Module contents
Lesson 4 of 31Core 110 min

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

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 TT independent tasks, each with success probability ptp_t, and RR independent Bernoulli runs conditional on ptp_t. The mean is μ^=(TR)−1∑t∑rXtr\hat\mu=(TR)^{-1}\sum_t\sum_r X_{tr}. The evaluation variance decomposition follows from the law of total variance:

Var⁡(μ^)=Var⁡(pt)T+E[pt(1−pt)]TR.\operatorname{Var}(\hat\mu)=\frac{\operatorname{Var}(p_t)}{T}+\frac{\mathbb E[p_t(1-p_t)]}{TR}.

The first term expresses task heterogeneity and the second variation between runs of a task. With fixed budget B=TRB=TR, increasing RR 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.

InteractiveMore tasks or more repetitions?
1.0
2.0
5
1000
Tasks200
Standard error0.0211
Approximate 95% width0.083
Between / within variance0.00028 / 0.00017
For a Beta distribution of success probabilities, the chart calculates hierarchical-model standard error under a maximum run budget. The approximate normal width assumes independent tasks.

For a balanced design, calculate mean Xˉt\bar X_t per task and estimate clustered standard error as the sample standard deviation of those TT means divided by T\sqrt T. A task bootstrap resamples the TT complete groups, keeping their runs together. Naive intervals treating the TRTR 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 Dt=XˉB,t−XˉA,tD_t=\bar X_{B,t}-\bar X_{A,t} and analyzes its mean. Resample the same task indices for both systems in each bootstrap replicate. Difference variance is Var⁡(B)+Var⁡(A)−2Cov⁡(A,B)\operatorname{Var}(B)+\operatorname{Var}(A)-2\operatorname{Cov}(A,B): 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: bb, where A succeeds and B fails, and cc, where B succeeds and A fails. Under discordant-case symmetry, the exact test uses a binomial with b+cb+c 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.

InteractiveThe power of pairing
  • Paired
  • Unpaired
0.05
0.60
200
3
Paired power0.698
Unpaired power0.473
Paired / unpaired standard error0.020 / 0.026
The synthetic normal model fixes between-task and between-run dispersion. Each power estimate uses 5000 simulations with known variances and a two-sided test; it does not directly represent Bernoulli outcomes.

For sample size planning, a two-sided normal approximation to detect difference Δ\Delta with per-task difference standard deviation σD\sigma_D is

T≈((z1−α/2+z1−β)σDΔ)2.T\approx\left(\frac{(z_{1-\alpha/2}+z_{1-\beta})\sigma_D}{\Delta}\right)^2.

With Δ=0.05\Delta=0.05, σD=0.3\sigma_D=0.3, level 0.05, and power 0.8, using z0.975≈1.96z_{0.975}\approx1.96 and z0.8≈0.842z_{0.8}\approx0.842 gives approximately 283 tasks after rounding up. The approximation assumes σD\sigma_D 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 σD\sigma_D 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 1−0.9520≈0.6421-0.95^{20}\approx0.642; the expression need not hold for dependent tests. Bonferroni uses level 0.05/200.05/20 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 pp per independent run, coverage of kk attempts is 1−(1−p)k1-(1-p)^k and pass^k reliability is pkp^k: the probability that all attempts succeed. τ-bench uses pass^k to study agent consistency. With nn runs and cc successes, for k≤nk\le n the estimators without replacement are

pass@k^=1−(n−ck)(nk),passk^=(ck)(nk).\widehat{\mathrm{pass@}k}=1-\frac{\binom{n-c}{k}}{\binom nk},\qquad \widehat{\mathrm{pass}^{k}}=\frac{\binom ck}{\binom nk}.

An impossible combination is taken as zero. The second estimator averages the indicator that all elements of a subset of kk runs succeed; under Bernoulli independence each subset has expectation pkp^k. A system with high coverage may be unreliable on each run. Dependence among runs changes the interpretation pkp^k and must be reflected in the design.

With n=5n=5, c=4c=4, and k=3k=3, every subset of three contains at least one success, so estimated coverage is 1. In contrast only (43)=4\binom43=4 of the (53)=10\binom53=10 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.

InteractiveCoverage versus reliability
  • pass@k
  • pass^k
8
Mean success per run0.50
Coverage0.785
Reliability0.215
The distributions are synthetic and have the same mean success per attempt. Under conditional independence, their probabilities of solving at least once and succeeding every time can differ greatly.

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.

InteractiveCost, accuracy, and uncertainty
00.20.40.60.81015003000Mean tokensAutomatic accuracyDirectZero-shotEight-shotVote of 8Best logprob of 8
Included systems
On the frontier3 systems
Data from the first 200 problems of lessons 2 and 3. Bootstrap intervals resample whole problems. Seconds are amortized batch time, not individual latency; batch size and shared load differ across runs.

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.

[ ]Clustered estimation and paired comparisonBrowser
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.

[ ]Simulated coverage and powerBrowser
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.

[ ]Paired comparison using recordsLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ProofTwo sources of variance
Prove: Independent tasks have probabilities p_t and each task has R Bernoulli runs independent conditional on p_t.
0
Write the mean as the average of task means and apply the law of total variance.

Step 1 of 2. What is the conditional variance of a task mean?

ProofA reliability estimator
Prove: If c is the number of successes in n independent Bernoulli trials, prove that C(c,k)/C(n,k) estimates p^k without bias.
0
Express the ratio as the average of indicators over all subsets of size k.

Step 1 of 2. How many subsets of size k contain only successes?

Numeric
Use the two-sided normal approximation with z=1.96 for α=0.05 and z=0.842 for power 0.8. If σ of per-task differences is 0.3 and the difference is 0.05, how many tasks are needed, rounding up?
Code
Implement paired_bootstrap(a,b,n_boot) for task-by-repetition matrices. Return the 2.5% and 97.5% percentiles of B−A when resampling complete tasks, with seed 42.
def paired_bootstrap(a, b, n_boot):
  pass
Shift+Enter to run
Quiz
An interval ignoring task clustering is much narrower than the clustered interval. Which conclusion is appropriate?
Key idea
Evaluate tasks as groups, compare systems pairwise, and report accuracy alongside cost and uncertainty.