Probability goes from a model to data; statistics goes back. On this site that return trip happens constantly: a KL estimator from sampled tokens, a policy gradient from a batch of rollouts, an off-policy correction from importance weights, and every benchmark number in every report. This lesson collects the tools to judge such numbers: what makes an estimator good, how big its error is, how to put an interval around it, and how to make the error smaller without more samples.
Estimators: bias, variance, MSE
An estimator is a function of random data, so it is itself a random variable with a sampling distribution. Its error decomposes exactly:
because the cross term is zero. Unbiased means the first term vanishes; consistent means as the sample grows. Neither is the same as accurate.
Worked example: the sample variance. With iid, mean , variance , write and sum the squares:
One degree of freedom is spent estimating the mean, so dividing by is unbiased and dividing by is biased low by . For Gaussian data (mean , variance ), so has
minimised at : shrinking toward zero trades a little bias for a larger cut in variance.
확률은 모델에서 데이터로 가고, 통계는 데이터에서 모델로 돌아온다. 이 사이트에서는 그 귀로가 끊임없이 일어난다. 샘플한 토큰으로 KL을 추정하고, rollout 배치로 정책 경사를 추정하고, importance weight로 off-policy를 보정하고, 모든 보고서의 모든 벤치마크 숫자가 그렇다. 이 레슨은 그런 숫자를 판단하는 도구를 모은다. 좋은 추정량은 무엇인지, 그 오차는 얼마나 큰지, 구간을 어떻게 씌우는지, 샘플을 늘리지 않고 오차를 어떻게 줄이는지.
추정량: 편향, 분산, MSE
추정량 는 무작위 데이터의 함수이므로 그 자체로 표본분포를 가진 확률변수다. 그 오차는 정확히 분해된다.
교차항 가 0이기 때문이다. 불편(unbiased) 이면 첫 항이 사라지고, 일치(consistent) 이면 표본이 커질 때 다. 둘 다 정확하다는 뜻은 아니다.
풀어 보는 예: 표본분산. 가 iid, 평균 , 분산 이면 로 쓰고 제곱해 더한다.
평균을 추정하는 데 자유도 하나를 쓰므로 로 나누면 불편이고, 으로 나누면 만큼 낮게 편향된다. Gaussian 데이터면 (평균 , 분산 )이므로 는
이고, 에서 최소다. 0 쪽으로 줄이면 편향이 조금 생기는 대신 분산이 더 크게 준다.
The same trade appears all over post-training: the KL estimators (unbiased, high variance), (biased, low variance) and (unbiased, low variance near ) in KL-regularised RL; truncated importance weights (bias for bounded variance) in off-policy mismatch; GRPO’s std normalisation and length aggregation, which change what is estimated, in sequence vs token. (The bias–variance trade-off of generalisation is the same decomposition applied to a model’s prediction at a point, with the training set as the random data.)
Maximum likelihood
Given iid data and a model , the maximum likelihood estimate maximises . Equivalently it minimises the cross-entropy from the empirical distribution to the model — the reason training an LM with next-token cross-entropy is MLE (probability and losses, language modelling), and why a reward model trained on the Bradley–Terry log-loss is an MLE (reward models).
Bernoulli. successes in trials: , so gives , the accuracy.
Gaussian. . Setting gives ; setting gives — the biased, divide-by- estimator from the figure. MLE is not designed to be unbiased.
How accurate is it? Under regularity conditions the MLE is consistent and asymptotically normal,
where is the Fisher information — the expected curvature of the log-likelihood. Sharp likelihood peak, small error. For a Bernoulli , whose expectation is , so : the error bar of every accuracy. (The Fisher matrix is also the metric behind natural gradients and TRPO’s KL trust region, since .)
import numpy as np
rng = np.random.default_rng(0)
# three estimators of sigma^2 = 1 from n = 5 Gaussian samples
n, M = 5, 200_000
X = rng.normal(size=(M, n))
S = ((X - X.mean(1, keepdims=True)) ** 2).sum(1)
print(f"estimating sigma^2 = 1 from n = {n} Gaussian samples")
for D, name in [(n - 1, "n-1 (unbiased)"), (n, "n (MLE)"), (n + 1, "n+1")]:
est = S / D
bias, var = est.mean() - 1, est.var()
print(f" /{name:15s} bias {bias:+.4f} var {var:.4f} bias^2+var {bias**2 + var:.4f} MSE {np.mean((est - 1)**2):.4f}")
# Bernoulli MLE p_hat = k/n; Fisher information 1/(p(1-p)) -> se = sqrt(p(1-p)/n)
p, n = 0.3, 400
p_hat = rng.binomial(n, p, size=100_000) / n
print(f"\nBernoulli MLE: mean {p_hat.mean():.4f}, sd {p_hat.std():.5f}, 1/sqrt(n I(p)) = {np.sqrt(p*(1-p)/n):.5f}")
# the log-likelihood is maximised at k/n (check on a grid)
k = 123
grid = np.linspace(0.01, 0.99, 9801)
ll = k * np.log(grid) + (n - k) * np.log(1 - grid)
print(f"argmax of the log-likelihood on a grid = {grid[np.argmax(ll)]:.4f}, k/n = {k/n:.4f}")The central limit theorem and confidence intervals
For iid with mean and finite variance ,
whatever the distribution of . So is approximately Gaussian with standard error , estimated by , and
is an approximate 95% confidence interval. The 95% is a property of the procedure: over repeated experiments, 95% of the intervals so constructed contain ; any single interval either does or does not. For an accuracy this is the Wald interval . It fails when or is small — near-perfect scores on small benchmarks — because it plugs into the variance (zero width when ) and the binomial is skewed there. The Wilson interval inverts the test instead, solving for :
같은 trade-off가 사후학습 곳곳에 나온다. KL 정규화 RL의 KL 추정량 (불편, 고분산), (편향, 저분산), (불편, 근처에서 저분산), off-policy 불일치의 잘린 importance weight(유계 분산을 위한 편향), 무엇을 추정하는지를 바꾸는 GRPO의 std 정규화와 길이 집계(시퀀스 vs 토큰)가 그렇다. (일반화의 bias–variance trade-off는 같은 분해를 한 점에서의 모델 예측에 적용한 것이다. 거기서는 학습 데이터가 무작위 데이터다.)
최대우도 추정
iid 데이터와 모델 가 주어지면 최대우도 추정(MLE) 은 를 최대화한다. 동치로, 경험 분포에서 모델로의 cross-entropy를 최소화한다. 다음 토큰 cross-entropy로 LM을 학습하는 것이 곧 MLE인 이유이고(확률로 보는 손실, 언어 모델링), Bradley–Terry 로그 손실로 학습한 보상모델이 MLE인 이유다(보상모델).
Bernoulli. 번 중 번 성공: 이므로 에서 , 곧 정확도다.
Gaussian. . 에서 , 에서 . 그림의 으로 나누는 편향 추정량이다. MLE는 불편이 되도록 설계된 것이 아니다.
얼마나 정확한가? 정칙 조건 아래서 MLE는 일치 추정량이고 점근적으로 정규분포를 따른다.
는 Fisher 정보, 로그우도의 기대 곡률이다. 우도의 봉우리가 뾰족하면 오차가 작다. Bernoulli에서 이고 그 기댓값이 이므로 이다. 모든 정확도의 오차 막대다. (이므로 Fisher 행렬은 natural gradient와 TRPO KL trust region 뒤의 계량이기도 하다.)
import numpy as np
rng = np.random.default_rng(0)
# n = 5개 Gaussian 표본으로 sigma^2 = 1을 추정하는 세 추정량
n, M = 5, 200_000
X = rng.normal(size=(M, n))
S = ((X - X.mean(1, keepdims=True)) ** 2).sum(1)
print(f"n = {n}개 Gaussian 표본으로 sigma^2 = 1 추정")
for D, name in [(n - 1, "n-1 (불편)"), (n, "n (MLE)"), (n + 1, "n+1")]:
est = S / D
bias, var = est.mean() - 1, est.var()
print(f" /{name:12s} 편향 {bias:+.4f} 분산 {var:.4f} 편향^2+분산 {bias**2 + var:.4f} MSE {np.mean((est - 1)**2):.4f}")
# Bernoulli MLE p_hat = k/n; Fisher 정보 1/(p(1-p)) -> se = sqrt(p(1-p)/n)
p, n = 0.3, 400
p_hat = rng.binomial(n, p, size=100_000) / n
print(f"\nBernoulli MLE: 평균 {p_hat.mean():.4f}, 표준편차 {p_hat.std():.5f}, 1/sqrt(n I(p)) = {np.sqrt(p*(1-p)/n):.5f}")
# 로그우도는 k/n에서 최대 (격자에서 확인)
k = 123
grid = np.linspace(0.01, 0.99, 9801)
ll = k * np.log(grid) + (n - k) * np.log(1 - grid)
print(f"격자 위 로그우도의 argmax = {grid[np.argmax(ll)]:.4f}, k/n = {k/n:.4f}")중심극한정리와 신뢰구간
평균 , 유한 분산 인 iid 에 대해
이고, 의 분포가 무엇이든 그렇다. 그래서 는 표준오차 (추정은 )인 근사 Gaussian이고,
가 근사 95% 신뢰구간이다. 95%는 절차의 성질이다. 실험을 반복하면 이렇게 만든 구간의 95%가 를 포함한다. 구간 하나는 포함하거나 포함하지 않거나다. 정확도 에 대해서는 Wald 구간 이 된다. 나 가 작으면, 즉 작은 벤치마크에서 거의 만점이면 무너진다. 분산에 를 넣기 때문에(이면 폭 0) 그리고 그 근처에서 이항분포가 치우쳐 있기 때문이다. Wilson 구간은 대신 검정을 뒤집어 을 에 대해 푼다.
Concentration: Hoeffding and the union bound
The CLT is asymptotic. When a guarantee must hold at a finite , use a concentration inequality. For independent , Hoeffding’s inequality gives
the same scaling as the CLT but with no approximation and no variance estimate (it uses only the range, so it is loose when the variance is small). To make such statements hold simultaneously, the union bound multiplies the failure probability by , so suffices for all means to be within with probability . The price of comparisons is only . For a 0/1 accuracy, points, : one benchmark needs questions (the CLT’s worst case gives about 1,070); twenty benchmarks at once need about 3,700. The same two steps — Hoeffding for one hypothesis, a union bound over a finite hypothesis class — give the generalisation bound in learning as optimisation, and the union bound is the Bonferroni correction you owe when scanning many benchmarks for a significant difference.
The bootstrap
When the statistic is not a simple mean — a median, a ratio, a win rate against a reference, a correlation, an average of per-problem pass@k values — there may be no convenient formula for its standard error. The bootstrap substitutes computation: treat the empirical distribution as the population, draw resamples of size with replacement, recompute the statistic on each, and use the spread of the values as its sampling distribution. The standard deviation of the bootstrap replicates estimates the standard error; their 2.5th and 97.5th percentiles give a percentile interval. Two rules matter in practice: resample the unit that is independent (questions, not samples within a question; clusters of related questions, not single questions), and remember the bootstrap estimates variance, it does not remove bias.
import numpy as np
rng = np.random.default_rng(1)
def wald(k, n, z=1.96):
ph = k / n; h = z * np.sqrt(ph * (1 - ph) / n); return ph - h, ph + h
def wilson(k, n, z=1.96):
ph = k / n; den = 1 + z*z/n; c = (ph + z*z/(2*n)) / den
h = z / den * np.sqrt(ph*(1-ph)/n + z*z/(4*n*n)); return c - h, c + h
print("coverage of nominal 95% intervals (100k simulated benchmarks)")
for p, n in [(0.7, 200), (0.95, 20), (0.95, 100), (0.99, 50)]:
k = rng.binomial(n, p, size=100_000)
cov = [np.mean((lo <= p) & (p <= hi)) for lo, hi in (wald(k, n), wilson(k, n))]
print(f" p={p:.2f} n={n:4d}: Wald {cov[0]:.3f} Wilson {cov[1]:.3f}")
# bootstrap: a statistic without a simple formula (the median of per-question scores)
scores = rng.beta(2, 5, size=300) # e.g. per-question rubric scores in [0, 1]
B = 4000
idx = rng.integers(0, scores.size, size=(B, scores.size)).astype(np.intp)
boot_mean = scores[idx].mean(1)
boot_med = np.median(scores[idx], axis=1)
print(f"\nbootstrap se of the mean {boot_mean.std():.4f} vs s/sqrt(n) {scores.std(ddof=1)/np.sqrt(scores.size):.4f}")
lo, hi = np.percentile(boot_med, [2.5, 97.5])
print(f"median {np.median(scores):.4f}, 95% percentile-bootstrap CI [{lo:.4f}, {hi:.4f}]")Importance sampling and the effective sample size
To estimate with samples from a different distribution , reweight:
valid when wherever . The estimator is unbiased, but its variance is governed by the second moment of the weights, , which explodes wherever is much smaller than . A one-number summary is the effective sample size
which equals for equal weights and 1 when a single weight dominates. For a Gaussian shifted by standard deviations, : at fewer than 2% of the samples are effectively used. When is known only up to a constant (or to cut variance) one uses self-normalised IS , which is biased by but consistent.
집중 부등식: Hoeffding과 union bound
CLT는 점근적이다. 유한한 에서 보장이 필요하면 집중 부등식을 쓴다. 독립인 에 대해 Hoeffding 부등식은
을 준다. CLT와 같은 스케일이지만 근사도 분산 추정도 없다(범위만 쓰므로 분산이 작으면 느슨하다). 이런 명제 개가 동시에 성립하게 하려면 union bound 로 실패 확률에 를 곱한다. 그러면 이면 확률 로 개 평균이 모두 안에 든다. 비교 개의 대가는 뿐이다. 0/1 정확도, 포인트, 이면 벤치마크 하나에 문항이 필요하다(CLT의 최악 경우 는 약 1,070). 벤치마크 스무 개를 동시에 보장하려면 약 3,700문항이다. 같은 두 단계, 즉 가설 하나에 대한 Hoeffding과 유한 가설 집합 위의 union bound가 최적화로서의 학습의 일반화 bound를 주고, union bound는 여러 벤치마크를 훑으며 유의한 차이를 찾을 때 치러야 하는 Bonferroni 보정이다.
부트스트랩
통계량이 단순 평균이 아니면, 예를 들어 중앙값, 비율, 기준 모델 대비 승률, 상관계수, 문제별 pass@k의 평균이면, 표준오차를 구하는 편리한 공식이 없을 수 있다. 부트스트랩은 계산으로 대신한다. 경험 분포를 모집단으로 보고, 크기 의 재표본을 복원추출로 번 뽑아 각각에서 통계량을 다시 계산하고, 그 개 값의 퍼짐을 표본분포로 쓴다. 부트스트랩 복제값의 표준편차가 표준오차의 추정이고, 2.5·97.5 백분위가 백분위 구간이다. 실전에서 중요한 규칙 둘. 독립인 단위를 재추출하라(문항 안의 샘플이 아니라 문항을, 관련 문항들의 묶음이 있으면 개별 문항이 아니라 묶음을). 그리고 부트스트랩은 분산을 추정할 뿐 편향을 없애지 않는다.
import numpy as np
rng = np.random.default_rng(1)
def wald(k, n, z=1.96):
ph = k / n; h = z * np.sqrt(ph * (1 - ph) / n); return ph - h, ph + h
def wilson(k, n, z=1.96):
ph = k / n; den = 1 + z*z/n; c = (ph + z*z/(2*n)) / den
h = z / den * np.sqrt(ph*(1-ph)/n + z*z/(4*n*n)); return c - h, c + h
print("명목 95% 구간의 포함률 (시뮬레이션 벤치마크 10만 회)")
for p, n in [(0.7, 200), (0.95, 20), (0.95, 100), (0.99, 50)]:
k = rng.binomial(n, p, size=100_000)
cov = [np.mean((lo <= p) & (p <= hi)) for lo, hi in (wald(k, n), wilson(k, n))]
print(f" p={p:.2f} n={n:4d}: Wald {cov[0]:.3f} Wilson {cov[1]:.3f}")
# 부트스트랩: 단순한 공식이 없는 통계량 (문항별 점수의 중앙값)
scores = rng.beta(2, 5, size=300) # 예: [0, 1] 범위의 문항별 rubric 점수
B = 4000
idx = rng.integers(0, scores.size, size=(B, scores.size)).astype(np.intp)
boot_mean = scores[idx].mean(1)
boot_med = np.median(scores[idx], axis=1)
print(f"\n평균의 부트스트랩 se {boot_mean.std():.4f} vs s/sqrt(n) {scores.std(ddof=1)/np.sqrt(scores.size):.4f}")
lo, hi = np.percentile(boot_med, [2.5, 97.5])
print(f"중앙값 {np.median(scores):.4f}, 95% 백분위 부트스트랩 구간 [{lo:.4f}, {hi:.4f}]")Importance sampling과 유효 표본 크기
다른 분포 의 샘플로 를 추정하려면 가중치를 다시 매긴다.
인 곳에서 이면 성립한다. 추정량 는 불편이지만, 분산은 가중치의 2차 적률 가 좌우하고, 이것은 가 보다 훨씬 작은 곳에서 폭발한다. 한 숫자로 요약한 것이 유효 표본 크기(ESS) 다.
가중치가 모두 같으면 , 하나가 지배하면 1이다. 표준편차 개만큼 이동한 Gaussian이면 이다. 면 실질적으로 쓰이는 샘플이 2%도 안 된다. 를 상수배까지만 알 때(또는 분산을 줄이려고) self-normalised IS 를 쓴다. 만큼 편향되지만 일치 추정량이다.
Why this bites LLMs. For a sequence the weight is a product of per-token ratios, . If the per-token log-ratios are roughly independent with variance (and mean , so that ), then and
A per-token mismatch too small to notice () leaves 37% of the samples at and under 2% at . This exponential collapse is why sequence-level IS is impractical for long responses, why PPO uses per-token ratios with clipping, and why truncated or masked weights (TIS, IcePop, CISPO’s clipped IS weight) trade bias for bounded variance (off-policy mismatch, clipping and IS, verl rollout correction).
import numpy as np
rng = np.random.default_rng(2)
def ess_frac(logw):
w = np.exp(logw - logw.max()); return w.sum() ** 2 / (w ** 2).sum() / w.size
N = 10_000
x = rng.normal(size=N) # proposal q = N(0, 1)
print("target N(d,1), proposal N(0,1)")
for d in [0.0, 0.5, 1.0, 2.0]:
logw = -0.5 * (x - d) ** 2 + 0.5 * x ** 2 # log pi(x) - log q(x)
w = np.exp(logw)
is_est = np.mean(w * x) # unbiased
snis = np.sum(w * x) / np.sum(w) # self-normalised: biased, consistent
print(f" d={d}: ESS/N {ess_frac(logw):.4f} (theory e^-d^2 = {np.exp(-d*d):.4f}) IS {is_est:+.3f} SNIS {snis:+.3f} truth {d}")
# sequence-level weight = product of T per-token ratios
s2 = 0.005 # variance of one token's log-ratio
print(f"\nsequence-level IS, per-token log-ratio variance {s2}:")
for T in [10, 50, 200, 800]:
logw = rng.normal(-s2 / 2, np.sqrt(s2), size=(4000, T)).sum(1) # E[rho_t] = 1
print(f" T={T:4d}: ESS/N {ess_frac(logw):.3f} (theory exp(-T s2) = {np.exp(-T*s2):.3f})")At the largest shifts the empirical ESS is above the theory: a finite sample has not yet drawn the rare, huge weights that dominate , so it looks healthier than it is. Treat a moderate ESS from heavy-tailed weights with suspicion.
Control variates — what a baseline is
If is correlated with and is known, then has the same mean as for every , and variance
a parabola in minimised at , where it equals . A 0.9 correlation removes 81% of the variance.
Two control variates run through the RL tracks. The policy-gradient baseline: has known mean 0, and subtracting is a control variate with coefficient — unbiased for any that does not depend on , best near , usually approximated by the expected reward (value function, group mean, leave-one-out mean; policy gradient, RLVR and GRPO). And the KL estimator with : , so it is plus a control variate with fixed coefficient 1, which is close to optimal when (KL-regularised RL).
import numpy as np
rng = np.random.default_rng(3)
# estimate E[exp(U)], U ~ Unif(0,1); control variate h = U with known mean 1/2
U = rng.random(size=(5000, 32))
f, h = np.exp(U), U
c_star = np.cov(f.ravel(), h.ravel())[0, 1] / h.var()
plain = f.mean(1)
cv = (f - c_star * (h - 0.5)).mean(1)
rho = np.corrcoef(f.ravel(), h.ravel())[0, 1]
print(f"control variate: c* = {c_star:.3f}, variance ratio {cv.var()/plain.var():.4f} (theory 1 - rho^2 = {1 - rho**2:.4f})")
print(f" both unbiased: plain {plain.mean():.4f}, cv {cv.mean():.4f}, truth e-1 = {np.e - 1:.4f}")
# KL estimators: k3 = k1 + (r - 1), a zero-mean control variate with coefficient 1
z = rng.normal(size=50)
for name, scale in [("close", 0.1), ("far", 1.0)]:
pi = np.exp(z) / np.exp(z).sum()
zr = z + scale * rng.normal(size=50); ref = np.exp(zr) / np.exp(zr).sum()
y = rng.choice(50, size=200_000, p=pi).astype(np.intp)
r = ref[y] / pi[y]
k1, k3 = -np.log(r), r - 1 - np.log(r)
print(f"{name:5s}: KL {np.sum(pi*np.log(pi/ref)):.4f} | k1 mean {k1.mean():.4f} sd {k1.std():.3f} | k3 mean {k3.mean():.4f} sd {k3.std():.3f}")Near the reference, ‘s standard deviation is more than an order of magnitude below ‘s; far from it the fixed coefficient 1 is no longer optimal and the advantage shrinks (it can even reverse).
The statistics of evaluation
pass@k. For one problem with per-sample success probability , pass@k , the probability that at least one of independent samples is correct; a benchmark averages this over problems. The obvious estimator — draw samples, count correct, plug in — is biased low: is convex in , so by Jensen (optimisation). The unbiased estimator of Chen et al. (2021) instead asks: if we pick of the samples uniformly without replacement, what is the chance that all are wrong?
It is unbiased because a uniformly random -subset of iid samples is itself iid samples, so the probability that the subset is all-wrong has expectation . The product form avoids huge binomial coefficients. pass@1 estimated as the mean accuracy over samples per problem (as reasoning reports do) is the case.
How noisy is a benchmark score? With questions of varying difficulty and samples per question, the score’s variance has two parts (Miller, 2024):
Sampling more per question only shrinks the second term. If you ask “would I get the same number re-running this exact benchmark?”, only the second term applies; if you ask “is this model better at this kind of problem?”, both do. On a 30-question benchmark like AIME, a spread of per-question solve rates with standard deviation 0.3 alone gives points — no number of samples per question removes it.
How many questions to separate two models? Score both models on the same questions and analyse the per-question differences : . Pairing removes the shared difficulty: . To detect a true gap with 80% power at two-sided you need , i.e.
At accuracy around 70% with independent errors (), a 2-point gap needs about questions; a correlation of 0.5 between the models’ per-question correctness halves that. Most single-benchmark differences of a point or two in a report table are inside the noise.
import numpy as np
from math import comb
rng = np.random.default_rng(4)
def pass_at_k(n, c, k):
"""Unbiased pass@k from n samples with c correct (Chen et al., 2021), stable product form."""
if n - c < k: return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
n, k, p = 20, 5, 0.15 # 20 samples per problem, per-sample success 0.15
true = 1 - (1 - p) ** k
c = rng.binomial(n, p, size=200_000)
unb = np.array([pass_at_k(n, ci, k) for ci in range(n + 1)])[c.astype(np.intp)]
naive = 1 - (1 - c / n) ** k
print(f"pass@{k} with n={n}, p={p}: truth {true:.4f} unbiased {unb.mean():.4f} naive plug-in {naive.mean():.4f}")
print(f"product form == 1 - C(n-c,k)/C(n,k): {np.isclose(pass_at_k(20, 3, 5), 1 - comb(17, 5) / comb(20, 5))}")
# benchmark variance: questions differ in difficulty p_i; K samples per question
nq = 500
for K in [1, 4, 16]:
pq = rng.beta(0.6, 0.6, size=(2000, nq)) # a fresh question set per run
total = (rng.binomial(K, pq) / K).mean(1)
fixed = rng.beta(0.6, 0.6, size=nq) # one fixed question set, model re-run
rerun = (rng.binomial(K, fixed, size=(2000, nq)) / K).mean(1)
th_tot = np.sqrt((pq.var() + np.mean(pq * (1 - pq)) / K) / nq)
th_fix = np.sqrt(np.mean(fixed * (1 - fixed)) / K / nq)
print(f"K={K:2d}: new questions sd {total.std():.4f} (theory {th_tot:.4f}) | re-run sd {rerun.std():.4f} (theory {th_fix:.4f})")
# two models on the same 500 questions: B is ~3 points better on every question
pa = rng.beta(0.6, 0.6, size=nq); pb = np.clip(pa + 0.03, 0, 1)
a = (rng.random((2000, nq)) < pa).astype(float); b = (rng.random((2000, nq)) < pb).astype(float)
gap = b.mean(1) - a.mean(1)
se_paired = (b - a).std(1, ddof=1) / np.sqrt(nq)
pa_hat, pb_hat = a.mean(1), b.mean(1)
se_naive = np.sqrt((pa_hat*(1-pa_hat) + pb_hat*(1-pb_hat)) / nq)
print(f"\nmean observed gap {gap.mean():.4f}, its actual sd {gap.std():.4f}")
print(f" naive two-proportion se {se_naive.mean():.4f} paired se sd(d_i)/sqrt(n) {se_paired.mean():.4f}")
print(f" power at alpha=0.05: naive {np.mean(gap/se_naive > 1.96):.2f} paired {np.mean(gap/se_paired > 1.96):.2f}")The naive two-proportion standard error ignores that both models face the same questions and overstates the noise; the paired one matches the actual spread. Even paired, a 3-point gap on 500 questions is detected only a minority of the time — the minimum detectable difference here is about points.
A benchmark has 200 questions and model accuracy is about 60%. Roughly how many questions would you need for a 95% interval half as wide?
The half-width is , proportional to . Halving it needs the questions: 800. (Here about points at , at .) More samples per question shrink only the within-question part of the variance, not the part due to which questions were chosen.
You estimate pass@10 by sampling 10 responses per problem and scoring 1 if any is correct. Then you instead sample 50 per problem and plug c/50 into 1 − (1 − p)^10. Which statement is right?
With exactly samples, “any correct” is the unbiased estimator ( is 1 if and 0 otherwise). The plug-in applies the convex map to an unbiased , so and pass@10 is under-estimated. With 50 samples, use instead: unbiased and lower-variance than the 10-sample version.
Summary
- MSE = bias² + variance; unbiased is not the same as accurate (dividing by beats for Gaussian variance).
- MLE maximises = minimises cross-entropy; , , ; asymptotic variance , so .
- CLT: . For proportions near 0 or 1 or small , prefer Wilson to Wald. Width .
- Hoeffding: at any ; a union bound over statements costs only .
- Bootstrap: resample the independent unit with replacement; spread of replicates = standard error.
- IS: ; ; sequence weights give .
- Control variates: , variance at . Baselines and are control variates.
- Evaluation: unbiased pass@k ; score variance = question variance + sampling variance/, all over ; separate models with paired differences and .
Where this is used
- Bias and variance of estimators — in KL-regularised RL and regularisation; advantage normalisation and aggregation in sequence vs token; generalisation.
- Concentration and the union bound — the finite-class generalisation bound in learning as optimisation.
- MLE and Fisher information — probability and losses, language modelling, reward models, the KL trust region in PPO.
- Importance sampling and ESS — PPO, off-policy mismatch, clipping and IS, async staleness, verl rollout correction.
- Control variates and baselines — policy gradient, actor-critic, RLVR and GRPO, the frontier-RL landscape.
- Evaluation statistics — pass@k in RLVR and GRPO, MiMo-7B and DeepSeek-R1; best-of-N in rejection sampling; reading benchmark tables in how to read reports.
LLM에서 이것이 아픈 이유. 시퀀스의 가중치는 토큰별 비의 곱이다: . 토큰별 log-ratio가 대략 독립이고 분산 (평균 , 그래서 )이면 이고
눈치채기 어려울 만큼 작은 토큰별 불일치()도 에서는 샘플의 37%, 에서는 2% 미만만 남긴다. 이 지수적 붕괴가 긴 응답에서 시퀀스 단위 IS를 쓸 수 없는 이유이고, PPO가 토큰 단위 ratio에 clip을 쓰는 이유이며, 잘리거나 가려진 가중치(TIS, IcePop, CISPO의 clip된 IS 가중치)가 유계 분산을 위해 편향을 감수하는 이유다(off-policy 불일치, clipping과 IS, verl rollout correction).
import numpy as np
rng = np.random.default_rng(2)
def ess_frac(logw):
w = np.exp(logw - logw.max()); return w.sum() ** 2 / (w ** 2).sum() / w.size
N = 10_000
x = rng.normal(size=N) # 제안 분포 q = N(0, 1)
print("목표 N(d,1), 제안 N(0,1)")
for d in [0.0, 0.5, 1.0, 2.0]:
logw = -0.5 * (x - d) ** 2 + 0.5 * x ** 2 # log pi(x) - log q(x)
w = np.exp(logw)
is_est = np.mean(w * x) # 불편
snis = np.sum(w * x) / np.sum(w) # self-normalised: 편향, 일치
print(f" d={d}: ESS/N {ess_frac(logw):.4f} (이론 e^-d^2 = {np.exp(-d*d):.4f}) IS {is_est:+.3f} SNIS {snis:+.3f} 참값 {d}")
# 시퀀스 단위 가중치 = 토큰별 비 T개의 곱
s2 = 0.005 # 토큰 하나의 log-ratio 분산
print(f"\n시퀀스 단위 IS, 토큰별 log-ratio 분산 {s2}:")
for T in [10, 50, 200, 800]:
logw = rng.normal(-s2 / 2, np.sqrt(s2), size=(4000, T)).sum(1) # E[rho_t] = 1
print(f" T={T:4d}: ESS/N {ess_frac(logw):.3f} (이론 exp(-T s2) = {np.exp(-T*s2):.3f})")이동이 가장 클 때 경험 ESS가 이론보다 크다. 유한 표본은 를 지배하는 드물고 거대한 가중치를 아직 뽑지 못했기 때문에 실제보다 건강해 보인다. 꼬리가 두꺼운 가중치에서 나온 그럴듯한 ESS는 의심하라.
Control variate: baseline의 정체
가 와 상관되어 있고 를 안다면, 는 모든 에 대해 와 평균이 같고 분산은
이다. 에 대한 포물선이고 에서 최소이며, 그때 값은 다. 상관 0.9면 분산의 81%가 사라진다.
RL 트랙에는 control variate 두 개가 흐른다. 정책 경사의 baseline: 는 평균이 0으로 알려져 있고, 를 빼는 것은 계수 인 control variate다. 에 의존하지 않는 어떤 에 대해서도 불편이고, 최적값은 근처이며, 보통 기대 보상(value function, 그룹 평균, leave-one-out 평균)으로 근사한다(정책 경사, RLVR과 GRPO). 그리고 일 때 KL 추정량 : 이므로 에 계수 1로 고정된 control variate를 더한 것이고, 일 때 그 계수가 최적에 가깝다(KL 정규화 RL).
import numpy as np
rng = np.random.default_rng(3)
# E[exp(U)], U ~ Unif(0,1) 추정; 평균 1/2을 아는 control variate h = U
U = rng.random(size=(5000, 32))
f, h = np.exp(U), U
c_star = np.cov(f.ravel(), h.ravel())[0, 1] / h.var()
plain = f.mean(1)
cv = (f - c_star * (h - 0.5)).mean(1)
rho = np.corrcoef(f.ravel(), h.ravel())[0, 1]
print(f"control variate: c* = {c_star:.3f}, 분산 비 {cv.var()/plain.var():.4f} (이론 1 - rho^2 = {1 - rho**2:.4f})")
print(f" 둘 다 불편: 기본 {plain.mean():.4f}, cv {cv.mean():.4f}, 참값 e-1 = {np.e - 1:.4f}")
# KL 추정량: k3 = k1 + (r - 1), 계수 1인 평균 0의 control variate
z = rng.normal(size=50)
for name, scale in [("close", 0.1), ("far", 1.0)]:
pi = np.exp(z) / np.exp(z).sum()
zr = z + scale * rng.normal(size=50); ref = np.exp(zr) / np.exp(zr).sum()
y = rng.choice(50, size=200_000, p=pi).astype(np.intp)
r = ref[y] / pi[y]
k1, k3 = -np.log(r), r - 1 - np.log(r)
print(f"{name:5s}: KL {np.sum(pi*np.log(pi/ref)):.4f} | k1 평균 {k1.mean():.4f} sd {k1.std():.3f} | k3 평균 {k3.mean():.4f} sd {k3.std():.3f}")reference 근처에서 의 표준편차는 보다 한 자릿수 이상 작다. 멀어지면 고정 계수 1이 더는 최적이 아니라서 이점이 줄어든다(뒤집힐 수도 있다).
평가의 통계
pass@k. 샘플당 성공 확률이 인 문제 하나에서 pass@k , 독립 샘플 개 중 적어도 하나가 맞을 확률이다. 벤치마크는 이것을 문제들에 대해 평균한다. 당연해 보이는 추정량, 즉 개를 뽑아 맞은 수 를 세고 을 대입하는 것은 낮게 편향된다. 가 에 대해 볼록이므로 Jensen에 의해 이다(최적화). Chen et al.(2021)의 불편 추정량은 대신 이렇게 묻는다. 개 샘플 중 개를 비복원으로 균등하게 고르면 모두 틀릴 확률은?
iid 샘플 개 중 균등하게 고른 개 부분집합은 그 자체로 iid 샘플 개이므로, 부분집합이 모두 틀릴 확률의 기댓값이 이다. 그래서 불편이다. 곱 형태는 거대한 이항계수를 피한다. 추론 보고서들처럼 문제당 개 샘플의 평균 정확도로 추정한 pass@1은 인 경우다.
벤치마크 점수는 얼마나 흔들리는가? 난이도 가 제각각인 문항 개에서 문항당 개를 샘플하면 점수의 분산은 두 부분이다(Miller, 2024).
문항당 샘플을 늘리면 두 번째 항만 준다. “이 벤치마크를 그대로 다시 돌리면 같은 숫자가 나올까?”를 묻는다면 두 번째 항만 해당되고, “이 모델이 이런 종류의 문제를 더 잘 푸는가?”를 묻는다면 둘 다 해당된다. AIME처럼 30문항짜리 벤치마크에서 문항별 풀이율이 표준편차 0.3으로 퍼져 있다면 그것만으로 포인트다. 문항당 샘플을 아무리 늘려도 없어지지 않는다.
두 모델을 가르려면 문항이 몇 개 필요한가? 두 모델을 같은 문항으로 채점하고 문항별 차이 를 분석하라: . 쌍으로 묶으면 공통 난이도가 지워진다: . 양측 , 검정력 80%로 참 차이 를 검출하려면 , 즉
정확도 70% 근처에서 오류가 독립이면() 2포인트 차이에 약 문항이 필요하다. 두 모델의 문항별 정오 상관이 0.5면 절반이 된다. 보고서 표에서 벤치마크 하나의 1–2포인트 차이는 대부분 잡음 안에 있다.
import numpy as np
from math import comb
rng = np.random.default_rng(4)
def pass_at_k(n, c, k):
"""n개 중 c개 정답일 때 pass@k의 불편 추정량 (Chen et al., 2021), 안정한 곱 형태."""
if n - c < k: return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
n, k, p = 20, 5, 0.15 # 문제당 샘플 20개, 샘플당 성공률 0.15
true = 1 - (1 - p) ** k
c = rng.binomial(n, p, size=200_000)
unb = np.array([pass_at_k(n, ci, k) for ci in range(n + 1)])[c.astype(np.intp)]
naive = 1 - (1 - c / n) ** k
print(f"pass@{k}, n={n}, p={p}: 참값 {true:.4f} 불편 {unb.mean():.4f} 순진한 plug-in {naive.mean():.4f}")
print(f"곱 형태 == 1 - C(n-c,k)/C(n,k): {np.isclose(pass_at_k(20, 3, 5), 1 - comb(17, 5) / comb(20, 5))}")
# 벤치마크 분산: 문항마다 난이도 p_i가 다르다; 문항당 K개 샘플
nq = 500
for K in [1, 4, 16]:
pq = rng.beta(0.6, 0.6, size=(2000, nq)) # 실행마다 새 문항 집합
total = (rng.binomial(K, pq) / K).mean(1)
fixed = rng.beta(0.6, 0.6, size=nq) # 고정된 문항 집합, 모델만 다시 실행
rerun = (rng.binomial(K, fixed, size=(2000, nq)) / K).mean(1)
th_tot = np.sqrt((pq.var() + np.mean(pq * (1 - pq)) / K) / nq)
th_fix = np.sqrt(np.mean(fixed * (1 - fixed)) / K / nq)
print(f"K={K:2d}: 새 문항 sd {total.std():.4f} (이론 {th_tot:.4f}) | 재실행 sd {rerun.std():.4f} (이론 {th_fix:.4f})")
# 같은 500문항 위의 두 모델: B가 모든 문항에서 약 3포인트 더 낫다
pa = rng.beta(0.6, 0.6, size=nq); pb = np.clip(pa + 0.03, 0, 1)
a = (rng.random((2000, nq)) < pa).astype(float); b = (rng.random((2000, nq)) < pb).astype(float)
gap = b.mean(1) - a.mean(1)
se_paired = (b - a).std(1, ddof=1) / np.sqrt(nq)
pa_hat, pb_hat = a.mean(1), b.mean(1)
se_naive = np.sqrt((pa_hat*(1-pa_hat) + pb_hat*(1-pb_hat)) / nq)
print(f"\n관측 차이의 평균 {gap.mean():.4f}, 실제 표준편차 {gap.std():.4f}")
print(f" 순진한 두 비율 se {se_naive.mean():.4f} 쌍 se sd(d_i)/sqrt(n) {se_paired.mean():.4f}")
print(f" alpha=0.05 검정력: 순진 {np.mean(gap/se_naive > 1.96):.2f} 쌍 {np.mean(gap/se_paired > 1.96):.2f}")순진한 두 비율 표준오차는 두 모델이 같은 문항을 푼다는 점을 무시해 잡음을 과대평가한다. 쌍 표준오차는 실제 퍼짐과 맞는다. 쌍으로 분석해도 500문항에서 3포인트 차이는 소수의 경우에만 검출된다. 여기서 검출 가능한 최소 차이는 약 포인트다.
문항 200개짜리 벤치마크에서 모델 정확도가 약 60%다. 95% 구간의 폭을 절반으로 줄이려면 문항이 대략 몇 개 필요한가?
반폭은 , 에 비례한다. 절반으로 줄이려면 문항이 배, 800개 필요하다. (에서 약 포인트, 에서 포인트.) 문항당 샘플을 늘리면 분산 중 문항 내부 부분만 줄고, 어떤 문항을 골랐느냐에서 오는 부분은 줄지 않는다.
문제당 응답 10개를 뽑아 하나라도 맞으면 1점으로 pass@10을 추정했다. 이번에는 문제당 50개를 뽑아 c/50을 1 − (1 − p)^10에 대입했다. 옳은 것은?
정확히 개면 “하나라도 맞음”이 불편 추정량이다(은 이면 1, 아니면 0). plug-in 은 불편인 에 볼록 사상 을 적용하므로 이고 pass@10을 과소추정한다. 50개를 뽑았다면 대신 을 써라. 불편이고 10개짜리보다 분산이 작다.
정리
- MSE = 편향² + 분산. 불편이 정확하다는 뜻은 아니다(Gaussian 분산에서는 로 나누는 것이 보다 낫다).
- MLE는 를 최대화 = cross-entropy를 최소화. , , . 점근 분산 이므로 .
- CLT: . 비율이 0이나 1 근처이거나 이 작으면 Wald보다 Wilson. 폭 .
- Hoeffding: 어떤 에서든 . 명제 개에 대한 union bound의 대가는 뿐이다.
- 부트스트랩: 독립 단위를 복원추출하고, 복제값의 퍼짐이 표준오차다.
- IS: , . 시퀀스 가중치는 .
- Control variate: , 에서 분산 . baseline과 가 control variate다.
- 평가: 불편 pass@k . 점수 분산 = (문항 분산 + 샘플링 분산/)/. 모델은 쌍 차이로 가르고 .
이 사이트에서 쓰이는 곳
- 추정량의 편향과 분산: KL 정규화 RL과 정규화의 , 시퀀스 vs 토큰의 advantage 정규화와 집계, 일반화.
- 집중 부등식과 union bound: 최적화로서의 학습의 유한 가설 집합 일반화 bound.
- MLE와 Fisher 정보: 확률로 보는 손실, 언어 모델링, 보상모델, PPO의 KL trust region.
- Importance sampling과 ESS: PPO, off-policy 불일치, clipping과 IS, 비동기와 staleness, verl rollout correction.
- Control variate와 baseline: 정책 경사, actor-critic, RLVR과 GRPO, frontier RL 지도.
- 평가의 통계: RLVR과 GRPO, MiMo-7B, DeepSeek-R1의 pass@k, rejection sampling의 best-of-N, 보고서 읽는 법의 벤치마크 표 읽기.
더 읽을거리Further reading
- Wasserman, All of Statistics (Springer, 2004), ch. 5–9 — 추정량, MLE와 Fisher 정보, 신뢰구간, 부트스트랩을 ML 독자용으로 압축.Estimators, MLE and Fisher information, confidence intervals and the bootstrap, compressed for ML readers.
- Efron & Tibshirani, An Introduction to the Bootstrap (Chapman & Hall, 1993) — 부트스트랩의 원전 교과서. 백분위 구간과 그 한계.The original bootstrap textbook; percentile intervals and their limits.
- Brown, Cai, DasGupta, Interval Estimation for a Binomial Proportion (Statistical Science, 2001) — Wald 구간의 포함률이 작은 n과 극단적인 p에서 얼마나 나쁜지, Wilson 구간을 권하는 이유.How badly the Wald interval covers at small n and extreme p, and why Wilson is recommended.
- Owen, Monte Carlo Theory, Methods and Examples (2013), ch. 8–9 — control variate, importance sampling, self-normalised IS, effective sample size.Control variates, importance sampling, self-normalised IS and the effective sample size.
- Chen et al., Evaluating Large Language Models Trained on Code (2021) — pass@k의 불편 추정량과 수치적으로 안정한 계산법(§2.1).The unbiased pass@k estimator and its numerically stable form (§2.1).
- Miller, Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations (2024) — 벤치마크 점수의 표준오차, 문항 묶음(cluster), 문항당 여러 샘플, 쌍 비교와 검정력 분석.Standard errors of benchmark scores, clustered questions, multiple samples per question, paired comparisons and power analysis.