Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 20 min · revision 2

Reliability over Repeated Trials

Run every task of the lab 2 suite ten times with a seeded stochastic stand-in for the model, compute pass@k and pass^k with the unbiased estimators and the independence approximation, and report per-task spread, cost from token usage and simulated latency next to the success rate.

Contentsand lesson path

What you will learn

  • Measure reliability across repeated trials (pass@k versus pass^k) and report variance, cost and latency alongside success.

Prerequisites: AI Evaluation, Agent Loops & ReAct

01. Goal and setup

In lab 2 the fake agent behaved the same way every time, so one run per task told you everything. Real agents do not, for three kinds of reasons. The model samples its output, so it can pick another tool, argument or reading of a result. Tools and services answer with varying timing and sometimes time out, which changes what the model sees next. The environment varies too: a backend that is not fully reset, or a simulated user played by another model, adds its own randomness. One run of a suite is therefore one draw from a distribution.

You cannot simply switch this off. Recent Claude models do not accept a non-default temperature, and where a provider does accept temperature 0, identical outputs are still not guaranteed; tools and environment would vary anyway. Pin the model ID and prompt to remove drift between days, and run repeated trials, several runs of the same task, to measure what remains.

In this lab you run every task ten times with a seeded, stochastic stand-in for the model and report what a reader needs: success per task, pass@k and pass^k, the spread, cost and latency.

You need: the evalsuite folder from lab 2 with all its files, and Python 3.10 or later (tested with 3.12.13). No packages, no API key. Run every command inside evalsuite.

Files added in this lab
evalsuite/
├── ...                 everything from lab 2
├── noisy_client.py     step 1: seeded stochastic stand-in for the model
├── single_runs.py      step 2: one run per task, five times
├── reliability.py      step 3: pass@k and pass^k estimators
└── trials.py           step 4: n trials per task, with cost and latency
Terminal
cd evalsuite && ls fake_client.py runner.py tasks.py

02. Step 1: A stand-in that makes mistakes at fixed rates

NoisyClient keeps the correct v2 rules from lab 2 and adds three mistakes, each with a fixed probability: on a partial refund it sometimes refunds what is left on the order instead of the amount asked for, it sometimes treats a failed identity check as a pass, and after a failed cancellation it sometimes refunds the order instead. Each draw comes from its own random.Random(seed). The seed makes a trial repeatable, which is what lets this lesson print exact expected output. It does not make a real model repeatable: there you get the variation without the seed.

Python · evalsuite/noisy_client.py
"""A seeded, stochastic stand-in: the v2 rules plus mistakes at fixed rates.

Still NOT a model. The random draws play the part of sampling: the same
request can get a different trajectory on the next trial.
"""
import random

from fake_client import FakeClient


class NoisyClient(FakeClient):
    SLIP = 0.35       # partial refund: refunds what is left instead of the amount
    MISREAD = 0.25    # treats a failed identity check as a pass
    IMPROVISE = 0.15  # after a failed cancel, refunds the order instead

    def __init__(self, seed: str) -> None:
        super().__init__("v2")
        self.rng = random.Random(seed)  # same seed, same trajectory
        self.misread = None  # once misread, the mistake sticks for the whole run

    def decide(self, request: str, history: list) -> tuple:
        last = history[-1] if history else None
        order = next((r for n, _a, r, e in history if n == "get_order"
                      and not e), None)
        if last and last[0] == "verify_identity" and not last[2]["verified"]:
            self.misread = self.rng.random() < self.MISREAD
        if self.misread:
            history = [(n, a, {"verified": True} if n == "verify_identity" else r, e)
                       for n, a, r, e in history]
        if (last and last[0] == "cancel_order" and last[3]
                and self.rng.random() < self.IMPROVISE):
            left = order["total_pence"] - order["refunded_pence"]
            return ("tool", "issue_refund", {"order_id": order["order_id"],
                                             "amount_pence": left})
        action = super().decide(request, history)
        if (action[0] == "tool" and action[1] == "issue_refund" and "£" in request
                and self.rng.random() < self.SLIP):
            left = order["total_pence"] - order["refunded_pence"]
            action = ("tool", "issue_refund", {**action[2], "amount_pence": left})
        return action
Terminal
python3 - <<'EOF'
from noisy_client import NoisyClient
from runner import run_task
from tasks import TASKS
task = TASKS[2]  # partial-refund
marks = [run_task(task, NoisyClient(f"1-{task['id']}-{trial}"))["passed"]
         for trial in range(10)]
print(task["id"], " ".join("P" if m else "F" for m in marks))
a, b = (run_task(task, NoisyClient("1-partial-refund-3")) for _ in range(2))
print("same seed, same trajectory:", a["calls"] == b["calls"])
EOF
Expected output
partial-refund P P P P P P F F P F
same seed, same trajectory: True

03. Step 2: One run is a single draw

Now do what a team with one CI run per change does: run the whole suite once, with five different seeds, and look at the scores. Nothing changes between the five runs except the random draws.

Python · evalsuite/single_runs.py
"""Run the whole suite once per seed, as a single CI run would."""
from noisy_client import NoisyClient
from runner import run_task
from tasks import TASKS

for seed in range(1, 6):
    results = [run_task(t, NoisyClient(f"{seed}-{t['id']}-0")) for t in TASKS]
    failed = [r["id"] for r in results if not r["passed"]]
    passed = len(TASKS) - len(failed)
    print(f"seed {seed}: {passed}/{len(TASKS)} passed"
          f"  failed: {', '.join(failed) or '-'}")
Terminal
python3 single_runs.py
Expected output
seed 1: 6/6 passed  failed: -
seed 2: 5/6 passed  failed: partial-refund
seed 3: 4/6 passed  failed: partial-refund, wrong-code
seed 4: 5/6 passed  failed: cancel-delivered
seed 5: 6/6 passed  failed: -

The same agent scores between 4/6 and 6/6, and the failing tasks change from run to run. If seed 1 had been your only run, you would have reported a perfect agent; if seed 3 had been, you might have reverted a good change. Reporting the higher of two runs, or only the tasks that passed in both, makes this worse: both hide exactly the inconsistency you need to see.

04. Step 3: pass@k and pass^k

With several trials per task you can ask two different questions:

  • pass@k is the chance that at least one of k trials succeeds. It fits settings where failures can be retried or filtered out, such as a developer who generates several candidate patches and keeps one that passes the tests.
  • pass^k ("pass hat k") is the chance that all k trials succeed. It measures consistency, which matters for an agent that serves many users who each get one attempt. The tau-bench paper introduced it for this purpose.

At k = 1 both equal the success rate of one trial. As k grows, pass@k rises towards 1 and pass^k falls towards 0. If trials are independent with success probability p, pass@k = 1 − (1 − p)^k and pass^k = p^k. For p = 0.9 and k = 3, pass@3 = 1 − 0.1³ = 0.999 but pass^3 = 0.9³ = 0.729.

From real trials you do not know p; you know that c of n trials passed. The unbiased estimators use those counts. Choose k of the n trials at random, without replacement: the chance that all k are passes is C(c, k) / C(n, k), where C(n, k) counts the ways to choose k items from n. That is pass^k as tau-bench defines it. The chance that all k are failures is C(n − c, k) / C(n, k), so pass@k is 1 minus that, as defined for code generation by Chen and colleagues. Both need k ≤ n; a suite score is the mean over tasks.

Python · evalsuite/reliability.py
"""pass@k and pass^k from n trials with c successes (unbiased estimators)."""
from math import comb


def pass_at_k(n: int, c: int, k: int) -> float:
    """Chance that at least one of k trials, drawn from the n, passed."""
    return 1 - comb(n - c, k) / comb(n, k)


def pass_hat_k(n: int, c: int, k: int) -> float:
    """Chance that all k trials, drawn from the n, passed (tau-bench's pass^k)."""
    return comb(c, k) / comb(n, k)


def approx_at_k(p: float, k: int) -> float:
    return 1 - (1 - p) ** k  # assumes independent trials with known p


def approx_hat_k(p: float, k: int) -> float:
    return p ** k


if __name__ == "__main__":
    n, c = 10, 7
    p = c / n
    for k in (1, 3, 5):
        print(f"k={k}  pass@k {pass_at_k(n, c, k):.3f} (approx {approx_at_k(p, k):.3f})"
              f"  pass^k {pass_hat_k(n, c, k):.3f} (approx {approx_hat_k(p, k):.3f})")
Terminal
python3 reliability.py
Expected output
k=1  pass@k 0.700 (approx 0.700)  pass^k 0.700 (approx 0.700)
k=3  pass@k 0.992 (approx 0.973)  pass^k 0.292 (approx 0.343)
k=5  pass@k 1.000 (approx 0.998)  pass^k 0.083 (approx 0.168)

For 7 passes in 10, the methods agree at k = 1 and drift apart as k grows: pass^3 is 0.292 from the counts and 0.343 from the formula. The formula treats 0.7 as the true probability; the estimator asks what happens when you draw 3 of the 10 trials you actually have. Neither is the truth: with ten trials, the uncertainty about p is larger than the gap, as step 5 shows.

05. Step 4: Trials with cost and latency

trials.py runs every task n times, each trial with its own seed, and keeps three things per trial: pass or fail, cost and latency. Cost is the token counts from usage times a price per million tokens; the prices in the file are made-up examples, not a real price list. Latency is simulated from the seed: about 0.8 s per model call, a short time per tool call, and a 5% chance of a slow backend. For a real agent you would measure wall-clock time with time.perf_counter(), and it would differ on every run. Latency is reported as p50 (the median) and p95 (the time 95% of trials stay under), by nearest rank, because averages hide the slow tail that users notice.

Python · evalsuite/trials.py
"""Run every task n times; report reliability, cost and latency per task."""
import argparse
import json
import math
import random

from noisy_client import NoisyClient
from reliability import pass_at_k, pass_hat_k
from runner import run_task
from tasks import TASKS

# EXAMPLE prices in US dollars per million tokens, for the arithmetic only.
# They are not a real price list: use your provider's current prices.
EXAMPLE_PRICE = {"input": 2.00, "output": 10.00}


def cost(tokens: dict) -> float:
    return sum(tokens[kind] * EXAMPLE_PRICE[kind] for kind in tokens) / 1_000_000


def simulated_latency_ms(run: dict, rng: random.Random) -> int:
    """NOT measured: drawn from fixed distributions so that the output repeats."""
    model = sum(rng.lognormvariate(6.7, 0.3) for _ in range(len(run["calls"]) + 1))
    tools = sum(rng.uniform(2500, 4000) if rng.random() < 0.05  # a slow backend
                else rng.uniform(60, 150) for _ in run["calls"])
    return round(model + tools)


def nearest_rank(values: list, q: float) -> int:
    ordered = sorted(values)
    return ordered[max(0, math.ceil(q * len(ordered)) - 1)]


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--trials", type=int, default=10)
    parser.add_argument("--seed", default="1")
    parser.add_argument("--out", default="trials.json")
    args = parser.parse_args()
    n, rows = args.trials, []
    print(f"{'task':<17} {'c/n':>5} {'pass@1':>6} {'pass@3':>6} {'pass^3':>6}"
          f" {'pass^5':>6} {'cost/run':>9} {'p50 ms':>6} {'p95 ms':>6}")
    for task in TASKS:
        outcomes, costs, latencies = [], [], []
        for trial in range(n):
            seed = f"{args.seed}-{task['id']}-{trial}"  # one seed per task and trial
            result = run_task(task, NoisyClient(seed))
            outcomes.append(result["passed"])
            costs.append(cost(result["tokens"]))
            latencies.append(simulated_latency_ms(result, random.Random(seed)))
        c = sum(outcomes)
        row = {"id": task["id"], "n": n, "c": c, "outcomes": outcomes,
               "pass@1": c / n, "pass@3": pass_at_k(n, c, 3),
               "pass^3": pass_hat_k(n, c, 3), "pass^5": pass_hat_k(n, c, 5),
               "cost": sum(costs) / n, "p50": nearest_rank(latencies, 0.5),
               "p95": nearest_rank(latencies, 0.95)}
        rows.append(row)
        dollars = f"${row['cost']:.4f}"
        print(f"{task['id']:<17} {c:>2}/{n:<2} {row['pass@1']:>6.3f}"
              f" {row['pass@3']:>6.3f} {row['pass^3']:>6.3f} {row['pass^5']:>6.3f}"
              f" {dollars:>9} {row['p50']:>6} {row['p95']:>6}")
    mean = {m: sum(r[m] for r in rows) / len(rows) for m in ("pass@1", "pass@3",
                                                             "pass^3", "pass^5")}
    print(f"{'suite mean':<23} {mean['pass@1']:>6.3f} {mean['pass@3']:>6.3f}"
          f" {mean['pass^3']:>6.3f} {mean['pass^5']:>6.3f}")
    per_trial = [sum(r["outcomes"][t] for r in rows) for t in range(n)]
    total = sum(r["cost"] for r in rows) * n
    print(f"single-run scores across the {n} trials: {min(per_trial)}/{len(rows)}"
          f" to {max(per_trial)}/{len(rows)}")
    print(f"total cost of this report at the example prices: ${total:.2f}")
    with open(args.out, "w") as f:
        json.dump(rows, f, indent=1)


if __name__ == "__main__":
    main()
Terminal
python3 trials.py --trials 10 --seed 1
Expected output (latency is simulated from the seed, not measured)
task                c/n pass@1 pass@3 pass^3 pass^5  cost/run p50 ms p95 ms
refund-broken     10/10  1.000  1.000  1.000  1.000   $0.0055   5171   9440
cancel-pending    10/10  1.000  1.000  1.000  1.000   $0.0054   4416   6834
partial-refund     7/10  0.700  0.992  0.292  0.083   $0.0056   4620   6590
wrong-code         9/10  0.900  1.000  0.700  0.500   $0.0032   2760   7970
not-their-order   10/10  1.000  1.000  1.000  1.000   $0.0041   3895   4629
cancel-delivered   9/10  0.900  1.000  0.700  0.500   $0.0057   4465   8477
suite mean               0.917  0.999  0.782  0.681
single-run scores across the 10 trials: 4/6 to 6/6
total cost of this report at the example prices: $0.29

Read the table one column at a time:

  • c/n. Three tasks passed every trial; partial-refund passed 7 of 10, the same seven as in step 1.
  • pass@3 against pass^3. pass@3 is at least 0.992 everywhere, which would make the agent look ready. pass^3 says that three partial refunds in a row all come out right only 29% of the time. For a customer-facing agent, quote pass^3 = 0.782 and pass^5 = 0.681 for the suite, not pass@3 = 0.999.
  • Spread. A single run of the whole suite would have scored anywhere from 4/6 to 6/6. Put that range next to the mean.
  • Cost. It follows the trajectory: wrong-code is cheapest because a correct run stops after two calls. The report itself cost 60 runs.
  • Latency. p95 is 1.2 to 2.9 times p50, mostly because of the slow backend. One extra model call adds about 0.8 s to every run, which no pass rate shows.

06. Step 5: How much do ten trials tell you?

Run the same report with two other seeds and keep only the tasks that vary and the suite means:

Terminal
for seed in 2 3; do
  python3 trials.py --seed $seed --out trials-$seed.json | grep -E "partial|wrong|mean"
done
Expected output
partial-refund     9/10  0.900  1.000  0.700  0.500   $0.0056   4545   7547
wrong-code         7/10  0.700  0.992  0.292  0.083   $0.0037   2935   7377
suite mean               0.917  0.999  0.782  0.681
partial-refund     4/10  0.400  0.833  0.033  0.000   $0.0056   4498   7734
wrong-code         6/10  0.600  0.967  0.167  0.024   $0.0040   3036   6856
suite mean               0.800  0.967  0.611  0.541

The rates in noisy_client.py are fixed, so partial-refund truly succeeds 65% of the time. Ten trials measured it as 0.7, 0.9 and 0.4, and seeds 1 and 2 give the same suite mean with different tasks failing. Ten trials tell a reliable task from a shaky one, but do not measure a rate to a few points. More trials narrow each task's estimate; more tasks steady the suite mean, and usually matter more. To compare two versions, compare them task by task on the same tasks, as the CI regression gate lab does. Always state the number of tasks and trials, the model ID and the date.

Frameworks build this in. In Inspect, epochs sets the trials per sample, and reducers such as pass_at_{k} and pass_k_{k} compute the two metrics.

07. Check your understanding

Practice check · 3 questions

Repeated trials

Answer from the code and the tables in this lab.

Q1. Why does the seed-1 table show pass^3 = 0.292 for `partial-refund`, when 0.7³ = 0.343?
Q2. A manager sees pass@3 = 1.000 for `cancel-delivered` in the seed-1 table and concludes that this task never fails. What does its row show?
Q3. You run `python3 trials.py --seed 1` again on the same machine. What changes in the table?
Practice only: not graded, not saved, not evidence.

08. Apply it

For the practice project, run each task of your 25-task suite 5 times against your real agent and report, per task and for the suite: c/n, pass@1 and pass^5, cost per run at your provider's current prices, and p50 and p95 latency measured with time.perf_counter(). Mark the latency as measured, with the machine and date, because it will differ on the next run. Add the range of single-run scores, list the five least consistent tasks, and read their failing trajectories before changing anything.

09. Review prompt

Without looking back: name three sources of variation in agent runs, and say why temperature settings do not remove them. Define pass@k and pass^k, give the independence formulas and the unbiased estimators, and say which metric fits a customer-facing agent and why. Then list what a reliability report should include besides the success rate.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check