Rigorous measurement of stochastic systems: variance, reliability and cost
Measure stochastic reasoning and agent systems by separating task and run variation, clustering uncertainty by task, comparing paired systems, planning sample sizes, and reporting reliability alongside cost-accuracy frontiers.
After this lesson you can
- Decompose success-rate variance into between-task and within-task sampling components.
- Calculate task-clustered standard errors and task bootstrap intervals for success rate.
- Compare two systems on paired tasks and estimate sample size for a given difference.
- Define and estimate pass^k without bias as a reliability measure and contrast it with pass@k.
- Build cost-accuracy Pareto frontiers with uncertainty and identify misleading comparisons.
Before you start
- 23Coverage under repeated samplingToken and compute accountingReproducible LLM call harness
- 05Nonparametric bootstrapBootstrap percentile and basic intervalsSample size calculation and minimum detectable effectPower and power functionPaired design and paired test
- 04Law of total variance
- 20pass@k and its unbiased estimator
Two sources of variation
Two systems score 52% and 54% on one hundred tasks. The observed two-point difference alone does not identify which is better across a task population: whether they solved the same problems, how often each ran, and the cost of each run all matter. Success rate estimation starts by defining the population, success criterion, and independent unit. Miller proposes treating evaluations as experiments and making uncertainty and design explicit.
Suppose independent tasks, each with success probability , and independent Bernoulli runs conditional on . The mean is . The evaluation variance decomposition follows from the law of total variance:
The first term expresses task heterogeneity and the second variation between runs of a task. With fixed budget , increasing reduces the number of tasks and may increase the first term, though fixed cost per task, run correlations, and task availability affect the practical decision. This formula describes a population model; if the task set is fixed and is not a sample, the formula alone does not turn it into a random sample.
For a balanced design, calculate mean per task and estimate clustered standard error as the sample standard deviation of those means divided by . A task bootstrap resamples the complete groups, keeping their runs together. Naive intervals treating the observations as independent ignore within-task correlation and may be too narrow. A Wilson interval can serve for a binomial proportion of independent observations; it does not automatically repair a clustered design.
For example, if one task is almost impossible and another is almost always solved, many runs of both may give a precise estimate for those two tasks, but do not reveal system behavior on others. Cluster bootstrap makes this task-selection uncertainty explicit assuming exchangeable groups. If tasks belong to related families or share a repository, the independent unit may be the family: clustering only by question may still underestimate uncertainty.
The percentile bootstrap interval sorts estimates from resampled tasks and takes the 2.5 and 97.5 percentiles. Across hypothetical repetitions of the procedure, 95% coverage means approximately 95% of intervals contain the fixed parameter under the design and assumptions. It does not mean each task has a 95% probability of being inside the interval, nor that the interval eliminates extraction bias or test-set contamination.
Comparing the same problems
Paired comparison calculates and analyzes its mean. Resample the same task indices for both systems in each bootstrap replicate. Difference variance is : positive covariance can improve precision; negative covariance can worsen it. Pairing does not guarantee a gain in every design.
With one binary run per system and task, McNemar uses discordant cases: , where A succeeds and B fails, and , where B succeeds and A fails. Under discordant-case symmetry, the exact test uses a binomial with trials and probability 0.5. It cannot be applied without adaptation to multiple correlated runs as though each pair were an independent task.
Suppose A and B both succeed on 70 tasks and both fail on another 20; ten are discordant. If B wins six and A four, the observed difference is two points out of one hundred, but paired evidence comes from those ten disagreements, not one hundred independent pairs of marginal successes. A difference interval retains its possible sign and magnitude. A result compatible with zero does not prove equivalence: an equivalence conclusion requires a prespecified acceptable difference margin and enough precision to rule out differences beyond it.
For sample size planning, a two-sided normal approximation to detect difference with per-task difference standard deviation is
With , , level 0.05, and power 0.8, using and gives approximately 283 tasks after rounding up. The approximation assumes is known and that the distribution and test permit approximation; simulation with actual tasks, repetitions, and decision criteria may change the required size. Reserving tasks for selection and evaluation limits bias from choosing the best of many prompts on the test set.
Power is the probability of rejecting the null when the specified alternative is true. It is not the probability that a hypothesis is true after observing data. A pilot may guide dispersion estimates, but a noisy estimate of also makes the size plan uncertain. Determine the minimum decision-relevant effect, include expected operational failure rate, and consider the cost of obtaining new tasks versus repeating existing ones. An experiment sensitive to five points may be inadequate for a one-point difference.
If you try twenty prompts and publish only the best, the same set has selected and evaluated it: the chosen result tends to benefit from favorable noise. In the idealized case of twenty independent null tests at level 0.05, the probability of at least one false positive is ; the expression need not hold for dependent tests. Bonferroni uses level per test and controls the probability of any false positive by a union bound without requiring independence, at a power cost. A held-out test not used for prompt selection addresses another part of the problem: it evaluates the fixed choice, although it does not itself correct all subsequent tests.
Coverage and reliability answer different questions
For a task with success probability per independent run, coverage of attempts is and pass^k reliability is : the probability that all attempts succeed. τ-bench uses pass^k to study agent consistency. With runs and successes, for the estimators without replacement are
An impossible combination is taken as zero. The second estimator averages the indicator that all elements of a subset of runs succeed; under Bernoulli independence each subset has expectation . A system with high coverage may be unreliable on each run. Dependence among runs changes the interpretation and must be reflected in the design.
With , , and , every subset of three contains at least one success, so estimated coverage is 1. In contrast only of the subsets contain three successes: estimated reliability is 0.4. Do not interpret the first figure as a promise that the next isolated attempt succeeds; it answers a question about a set of attempts. When averaging across tasks, calculate each estimator per task first to avoid unintentionally letting tasks with more records dominate.
Cost and frontier
The cost-accuracy Pareto frontier retains systems for which no other has lower or equal cost and higher or equal accuracy, with at least one strict inequality. Tokens, seconds, and approximate FLOPs answer different questions. Count input and output, candidate generation, and selection calls; include a simple baseline. A frontier of point estimates does not prove statistical dominance: errors correlate when tasks are shared, so compare paired differences. Kapoor and colleagues show why accuracy, cost, and evaluation set design must be considered together.
Changing the cost unit can change which option dominates: a system may process more tokens in parallel or take less time per batch while using more memory. Report measurement mode, device, version, concurrency, and whether time includes model loading. If accuracy comes from an extractor, report extraction failures and how they are counted; a format change can appear to improve reasoning without doing so. The frontier summarizes measured systems, not a guarantee about unevaluated ones.
Lab: a small library
The following functions operate on matrices with one row per task. You can also download the library to import it in later labs. The bootstrap interval uses percentiles and a fixed seed; for very small samples or extreme distributions it may have poor coverage. These methods do not themselves verify task independence or validity of the success criterion.
from statistics import mean, stdev
from random import Random
from math import comb, sqrt
def success_rate(matrix):
if len(matrix) < 2 or any(not row for row in matrix):
raise ValueError('Se necesitan al menos dos tareas con ejecuciones')
task_means = [mean(row) for row in matrix]
return mean(task_means), stdev(task_means)/sqrt(len(task_means))
def paired_bootstrap(a, b, n_boot=2000, seed=42):
if len(a) != len(b) or len(a) < 2 or n_boot < 40 or any(not x for x in a+b):
raise ValueError('Matrices o número de réplicas no válidos')
differences = [mean(y)-mean(x) for x,y in zip(a,b)]
rng = Random(seed)
means = sorted(mean(rng.choice(differences) for _ in differences) for _ in range(n_boot))
return means[int(.025*n_boot)], means[min(n_boot-1,int(.975*n_boot))]
def pass_at_k(n, c, k):
if not 0 <= c <= n or not 1 <= k <= n: raise ValueError('n, c o k no válidos')
return 1-(comb(n-c,k)/comb(n,k) if n-c>=k else 0)
def pass_hat_k(n, c, k):
if not 0 <= c <= n or not 1 <= k <= n: raise ValueError('n, c o k no válidos')
return comb(c,k)/comb(n,k) if c>=k else 0
def mcnemar_exact(a, b):
if len(a) != len(b) or not a or any(x not in (0,1) for x in a+b):
raise ValueError('Pares binarios no válidos')
b_only = sum(x == 0 and y == 1 for x,y in zip(a,b))
a_only = sum(x == 1 and y == 0 for x,y in zip(a,b))
n = a_only + b_only
return min(1.0, 2*sum(comb(n,i)*0.5**n for i in range(min(a_only,b_only)+1))) if n else 1.0
def pareto(points):
# Cada elemento es (nombre, coste, precisión).
return [a for a in points if not any(b[1] <= a[1] and b[2] >= a[2]
and (b[1] < a[1] or b[2] > a[2]) for b in points)]
a = [[1,1,0], [0,0,1], [1,1,1], [0,0,0], [1,0,1]]
b = [[1,1,1], [0,1,1], [1,1,1], [0,0,1], [1,1,1]]
print('A: media y error agrupado', success_rate(a))
print('Intervalo pareado B-A', paired_bootstrap(a,b))
print('Cuatro aciertos en cinco, k=3: cobertura', pass_at_k(5,4,3), 'fiabilidad', pass_hat_k(5,4,3))
print('Frontera', pareto([('A',10,.6),('B',12,.7),('C',14,.6)]))Also check by simulation whether the interval behaves as expected under a known model. The next experiment shows empirical coverage of the percentile interval and does not prove validity for every distribution. Power is calculated for a normal approximation with known standard deviation: this checks the planning calculation, not power of an actual binomial test.
from random import Random
from statistics import mean
from math import sqrt
rng = Random(8)
covered = 0
for experiment in range(120):
matrix = []
for task in range(40):
p = rng.betavariate(1, 2)
matrix.append([int(rng.random() < p) for _ in range(3)])
task_means = [mean(row) for row in matrix]
boot = sorted(sum(rng.choice(task_means) for _ in task_means)/len(task_means) for _ in range(400))
covered += boot[10] <= 1/3 <= boot[390]
print('Cobertura empírica de 120 intervalos:', covered/120)
delta, sigma, tareas = .05, .3, 283
rejected = 0
for _ in range(5000):
estimated = rng.gauss(delta, sigma/sqrt(tareas))
rejected += abs(estimated) > 1.96*sigma/sqrt(tareas)
print('Potencia normal simulada:', rejected/5000)Local lab: reanalyzing saved outputs
Keep files gsm8k_results.json and muestras_200x64.jsonl produced in lessons 2 and 3. The direct condition and both lesson 2 conditions have one run per task; do not present them as five repetitions. For voting and best-of-8, the first 40 samples are split into five disjoint groups of eight. This yields five results per problem for those selectors, not five independent runs of the entire generation system. Keep the extractor and problems the same and record failures.
import json, math
from pathlib import Path
from collections import Counter, defaultdict
from statistics import mean, stdev
from random import Random
from math import comb, sqrt
def success_rate(matrix):
task_means = [mean(row) for row in matrix]
return mean(task_means), stdev(task_means)/sqrt(len(task_means))
def paired_bootstrap(a, b, n_boot=2000):
differences = [mean(y)-mean(x) for x,y in zip(a,b)]
rng = Random(42)
means = sorted(mean(rng.choice(differences) for _ in differences) for _ in range(n_boot))
return means[int(.025*n_boot)], means[int(.975*n_boot)]
def mcnemar_exact(a, b):
x = sum(u==1 and v==0 for u,v in zip(a,b))
y = sum(u==0 and v==1 for u,v in zip(a,b))
n = x+y
return min(1.0, 2*sum(comb(n,i)*0.5**n for i in range(min(x,y)+1))) if n else 1.0
def pass_hat_k(n, c, k):
return comb(c,k)/comb(n,k) if c>=k else 0
previas = json.loads(Path('gsm8k_results.json').read_text(encoding='utf-8'))
por_modo = {modo:{r['indice']:r for r in previas if r['modo']==modo} for modo in ('directo','cero','ocho')}
assert all(set(range(200)) <= set(grupo) for grupo in por_modo.values())
def acierto(r):
return int(r['extraida'] is not None and r['extraida'] == r['referencia'])
for modo in ('cero', 'ocho'):
a = [[acierto(por_modo['directo'][i])] for i in range(200)]
b = [[acierto(por_modo[modo][i])] for i in range(200)]
print(modo, 'diferencia B-A', mean(mean(y)-mean(x) for x,y in zip(a,b)),
'IC pareado', paired_bootstrap(a,b),
'McNemar exacto', mcnemar_exact([x[0] for x in a], [x[0] for x in b]))
muestras = [json.loads(x) for x in Path('muestras_200x64.jsonl').read_text(encoding='utf-8').splitlines()]
grupos = defaultdict(list)
for r in muestras: grupos[r['problema']].append(r)
assert all(len(grupos[i]) == 64 for i in range(200))
resultados = {'voto':[], 'mejor':[]}
costes = {'voto':[], 'mejor':[]}
tiempos = {'voto':[], 'mejor':[]}
for indice in range(200):
grupo = sorted(grupos[indice], key=lambda r:r['muestra'])
reference = grupo[0]['referencia']
filas_voto, filas_mejor = [], []
for j in range(5):
subset = grupo[8*j:8*(j+1)]
counts = Counter(r['respuesta'] for r in subset)
maximo = max(counts.values())
# Desempate reproducible: primera respuesta en el orden de las muestras.
voto = next(r['respuesta'] for r in subset if counts[r['respuesta']]==maximo)
mejor = max(subset, key=lambda r:r['logp_modelo_base']/r['tokens_salida'])['respuesta']
filas_voto.append(int(voto is not None and voto == reference))
filas_mejor.append(int(mejor is not None and mejor == reference))
costo = sum(r['tokens_entrada']+r['tokens_salida'] for r in subset)
costes['voto'].append(costo); costes['mejor'].append(costo)
tiempo = sum(r['segundos_lote_generacion_y_puntuacion']/r['lote'] for r in subset)
tiempos['voto'].append(tiempo); tiempos['mejor'].append(tiempo)
resultados['voto'].append(filas_voto); resultados['mejor'].append(filas_mejor)
for modo, matrix in resultados.items():
print(modo, 'tasa y error agrupado', success_rate(matrix),
'IC frente a directo', paired_bootstrap(a,matrix), 'tokens medios', mean(costes[modo]))
print('pass^5 estimado', mean(pass_hat_k(5,sum(row),5) for row in matrix))
def intervalo_tareas(valores, seed):
rng = Random(seed)
boot = sorted(mean(rng.choice(valores) for _ in valores) for _ in range(2000))
return boot[50], boot[1950]
puntos = []
for seed, modo in enumerate(('directo', 'cero', 'ocho')):
filas = [por_modo[modo][i] for i in range(200)]
valores = [acierto(r) for r in filas]
puntos.append((modo, mean(r['tokens_entrada']+r['tokens_salida'] for r in filas),
mean(valores), intervalo_tareas(valores,700+seed),
mean(r['segundos_lote']/r['tamano_lote'] for r in filas)))
for seed, modo in enumerate(('voto','mejor'), start=3):
valores = [mean(row) for row in resultados[modo]]
puntos.append((modo, mean(costes[modo]), mean(valores), intervalo_tareas(valores,700+seed), mean(tiempos[modo])))
for punto in puntos: print('nombre, tokens, acierto, IC agrupado, segundos amortizados:', punto)
frontera = [a for a in puntos if not any(b[1] <= a[1] and b[2] >= a[2]
and (b[1] < a[1] or b[2] > a[2]) for b in puntos)]
print('Frontera puntual en tokens:', [p[0] for p in frontera])
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
for nombre, tokens, tasa, (lo, hi), _ in puntos:
ax.errorbar(tokens, tasa, yerr=[[tasa-lo], [hi-tasa]], fmt='o', capsize=3)
offset = (5, -15) if nombre in ('directo', 'voto') else (5, 5)
ax.annotate(nombre, (tokens, tasa), xytext=offset, textcoords='offset points')
ax.set(xlabel='Tokens medios de entrada y salida', ylabel='Acierto automático', xlim=(0,3000), ylim=(0,1))
fig.tight_layout()
plt.show()npm run lab and open the connection link.The best-of-8 selector uses base-model mean log probability, a weak uncalibrated score. Voting in this cell breaks ties by first appearance, unlike the random rule in lesson 3; fix the rule before comparing and do not mix figures without noting the change. Costs sum all eight generations; add any selection or verification call as well. Compare the cost of each earlier mode and calculate the point frontier; for uncertainty in dominance compare per-task differences, not just two marginal bars.
In the recorded run on the first 200 problems, direct succeeds on 44/200, zero-shot on 45/200, and eight-shot on 111/200. Five groups of eight yield per-task means of 0.175 for voting and 0.226 for best log probability; both use about 2619 tokens per group. Against direct, paired difference intervals are approximately [−0.104, 0.013] and [−0.050, 0.062]. Voting does not demonstrate improvement and extractor failures cannot be ruled out: the no-extraction condition participates in voting. These data do not make the first 200 problems representative, and amortized seconds are not a controlled latency comparison.
Exercises
Step 1 of 2. What is the conditional variance of a task mean?
Step 1 of 2. How many subsets of size k contain only successes?
def paired_bootstrap(a, b, n_boot):
pass