A language model is a probability distribution over sequences; sampling from it is drawing a random variable; RL for LLMs differentiates an expectation over those samples; evaluation estimates a probability from a finite number of them. This lesson is the probability needed for all of that — the standard definitions done quickly, and the four results the later tracks use constantly: the chain rule, the Gumbel-max trick, the law of Monte Carlo, and the log-derivative trick.
Random variables and expectation
A random variable is a function of the outcome of an experiment; its distribution is given by a pmf (discrete) or a density with (continuous). The expectation is
with no need to find the distribution of first. Two facts carry most of the weight:
- Linearity — always, independent or not. The expected number of correct tokens in a response is the sum of per-position probabilities, however the positions depend on each other.
- Indicators — . Every probability is an expectation, so everything said about estimating expectations (Monte Carlo, below) applies to estimating probabilities: an accuracy is the mean of a 0/1 reward.
Variance and covariance
, and expanding the square of a sum,
For independent copies with variance the covariances vanish, so the mean has and standard deviation — the most important formula in this lesson and the next. With positive correlations the variance shrinks more slowly: tokens of one response, or responses in one group, are not independent samples, and averaging over them buys less than their count suggests.
For a random vector the covariance matrix is positive semidefinite, because . (That is the argument that made the log-sum-exp Hessian PSD in the optimisation lesson: it is the covariance of a one-hot sample from .) The same variance arithmetic, for independent zero-mean terms, is what sets the scale of Xavier and He initialisation (training deep nets).
Conditional probability and Bayes’ rule
. Rearranged, this is the product rule , and summing it over a partition gives the law of total probability . Writing the joint probability both ways and dividing gives Bayes’ rule:
The denominator is total probability. In odds the normaliser disappears and the rule becomes a product:
Concretely: = “the sampled answer is correct”, = “the verifier passed it”.
언어 모델은 시퀀스 위의 확률분포이고, 거기서 샘플링하는 것은 확률변수를 뽑는 일이며, LLM용 RL은 그 샘플에 대한 기댓값을 미분하고, 평가는 유한한 샘플로 확률을 추정한다. 이 레슨은 그 모두에 필요한 확률이다. 표준 정의는 빠르게 지나가고, 뒤 트랙이 끊임없이 쓰는 결과 넷, 즉 연쇄 법칙, Gumbel-max trick, 몬테카를로의 법칙, log-derivative trick에 시간을 쓴다.
확률변수와 기댓값
확률변수 는 실험 결과의 함수다. 분포는 pmf (이산) 또는 인 밀도 (연속)로 주어진다. 기댓값은
이고, 의 분포를 먼저 구할 필요가 없다. 대부분의 일을 두 사실이 한다.
- 선형성: 는 독립이든 아니든 항상 성립한다. 응답 안에서 맞힌 토큰 수의 기댓값은 위치별 확률의 합이다. 위치들이 서로 어떻게 의존하든 상관없다.
- 지시변수: . 모든 확률은 기댓값이므로, 기댓값 추정에 대한 모든 이야기(아래 몬테카를로)가 확률 추정에도 적용된다. 정확도는 0/1 보상의 평균이다.
분산과 공분산
이고, 합의 제곱을 전개하면
분산이 인 독립 사본 개면 공분산이 사라지므로 평균 은 , 표준편차 이다. 이 레슨과 다음 레슨에서 가장 중요한 식이다. 양의 상관이 있으면 분산이 더 느리게 줄어든다. 한 응답의 토큰들, 한 그룹의 응답들은 독립 샘플이 아니어서, 그 개수가 암시하는 만큼 평균의 이득이 나지 않는다.
확률 벡터 의 공분산 행렬 는 이므로 양의 준정부호다. (최적화 레슨에서 log-sum-exp Hessian 이 PSD였던 논리가 이것이다. 에서 뽑은 one-hot 샘플의 공분산이다.) 같은 분산 산수, 독립이고 평균 0인 항들에 대한 가 Xavier·He 초기화의 스케일을 정한다(깊은 망 학습).
조건부 확률과 베이즈 규칙
. 다시 쓰면 곱 규칙 이고, 분할 에 대해 더하면 전확률 법칙 이다. 결합확률을 두 방향으로 쓰고 나누면 베이즈 규칙이 나온다.
분모가 전확률이다. odds로 쓰면 정규화 상수가 사라지고 곱이 된다.
구체적으로 = “샘플한 답이 정답”, = “verifier가 통과시킴”으로 두자.
With a 5% base rate and a verifier that is “95% accurate” in both directions, : the likelihood ratio 19 only lifts prior odds of 1:19 to 1:1. On hard prompts, where the policy is rarely right, a small false-positive rate dominates the reward signal — and RL optimises exactly what passes. This is the probabilistic core of reward hacking against verifiers (rewards and environments, over-optimisation).
Two notions to keep apart: and are independent if ; they are conditionally independent given if . Two samples from the same prompt are conditionally independent given the prompt but correlated across prompts — which matters when computing error bars (statistics).
The chain rule is the autoregressive model
Applying the product rule repeatedly gives, for any joint distribution and with no assumptions,
An autoregressive language model is a parameterisation of each factor, ; because each factor is normalised, the product is automatically a normalised distribution over all sequences (the Py block checks this by brute force). Consequences used later:
- Training by maximum likelihood is a sum of per-token cross-entropies (language modelling).
- Sequence probabilities shrink exponentially with length (a typical per-token log-prob of gives for 1000 tokens), so everything is done in log space (numerics).
- A ratio of two sequence probabilities is a product of per-token ratios, . Products of many noisy factors have log-normal-like, heavy-tailed behaviour — the central difficulty of sequence-level importance sampling (off-policy mismatch, sequence vs token).
- Truncating the conditioning to the last tokens is the Markov assumption of an n-gram model.
Distributions you will meet
Bernoulli() — a 0/1 outcome, mean , variance , largest at . A verifiable reward is Bernoulli with = the policy’s success rate on that prompt. In a group of samples, all rewards are equal with probability , and then a group-relative advantage is zero — the reason for difficulty filtering in RLVR. GRPO divides by the observed group std, not the population one: with group success rate and ddof = 0 it is (some implementations use ddof = 1, a factor larger). For and , the group has std 0 while the population std is 0.5. Since estimates , the division reweights prompts by (a noisy estimate of) this variance (sequence vs token).
Binomial() — the number of successes in independent Bernoulli() trials: , mean , variance (a sum of independent variances). It is the count of correct answers among samples of one prompt — the input to the pass@k estimator (statistics) and to model comparisons in reports such as MiMo-7B.
Beta() — a distribution on with density and mean ; the natural model for a spread of per-prompt pass rates across a dataset (sequence vs token uses Beta(0.6, 1.2) for “mostly hard prompts”). It is conjugate to the binomial: a Beta() prior on plus successes in trials gives the posterior Beta(), whose mean adds pseudo-successes and pseudo-failures; only for a symmetric prior is it add- smoothing (: Laplace). And the maximum of independent uniforms is Beta(), which is how best-of-N gets the quantile of the chosen response.
Categorical() over classes — the next-token distribution; . One-hot encoding has mean and covariance .
Gaussian — density ; 68/95/99.7% of the mass within 1/2/3 σ. Closed under affine maps and under sums of independent Gaussians (means add, variances add), and it can be written as with — the reparameterisation used below. Multivariate: with .
Log-normal — if then is log-normal, and completing the square, , gives
This is the model for a sequence-level importance ratio. If the per-token log-ratios are roughly independent with variance , their sum over tokens has variance — its standard deviation grows like — and is approximately log-normal. A ratio that is correct on average needs , i.e. mean log-ratio ; then the median of is while explodes. Most sequences get tiny weights and a few get enormous ones — the variance and ESS collapse analysed in off-policy mismatch, mismatch engineering, verl rollout correction and statistics.
Gumbel(0, 1) — CDF , density , sampled as with . It is the limiting law of maxima, and it gives the Gumbel-max trick:
The proof (integrate the density of the winning perturbed logit against the CDFs of the others) and its companions — the maximum of perturbed logits is , a noisy log-sum-exp, and taking the top instead of the argmax samples without replacement (Gumbel-top-k) — are worked out in extreme values. Here we use the statement and check it by sampling; the figure doubles as a look at Monte Carlo error.
base rate 5%에 양방향 모두 “95% 정확한” verifier라면 다. 우도비 19가 1:19의 사전 odds를 1:1로 올릴 뿐이다. 정책이 좀처럼 맞히지 못하는 어려운 프롬프트에서는 작은 false-positive 비율이 보상 신호를 지배하고, RL은 정확히 통과하는 것을 최적화한다. verifier에 대한 reward hacking의 확률적 핵심이다(보상과 환경, 과최적화).
구별할 두 개념. 이면 와 는 독립이고, 이면 가 주어졌을 때 조건부 독립이다. 같은 프롬프트에서 뽑은 두 샘플은 프롬프트가 주어지면 조건부 독립이지만 프롬프트를 가로지르면 상관되어 있다. 오차 막대를 계산할 때 중요하다(통계).
연쇄 법칙이 곧 자기회귀 모델이다
곱 규칙을 반복 적용하면 어떤 결합분포에 대해서도, 아무 가정 없이
자기회귀 언어 모델은 각 인수를 로 매개변수화한 것이다. 인수마다 정규화되어 있으므로 곱은 자동으로 모든 시퀀스 위의 정규화된 분포가 된다(Py 블록이 전수 계산으로 확인한다). 뒤에서 쓰는 결과:
- 최대우도 학습은 토큰별 cross-entropy의 합이다(언어 모델링).
- 시퀀스 확률은 길이에 따라 지수적으로 작아진다(토큰당 log-prob이 면 1000 토큰에서 ). 그래서 모든 것을 로그 공간에서 한다(수치 계산).
- 두 시퀀스 확률의 비는 토큰별 비의 곱 다. 잡음 섞인 인수를 많이 곱하면 로그정규 비슷한 두꺼운 꼬리가 생긴다. 시퀀스 단위 importance sampling의 핵심 난점이다(off-policy 불일치, 시퀀스 vs 토큰).
- 조건을 마지막 개 토큰으로 자르는 것이 n-gram 모델의 Markov 가정이다.
자주 만나는 분포
Bernoulli(): 0/1 결과, 평균 , 분산 , 에서 최대. 검증 가능한 보상은 = 그 프롬프트에서 정책의 정답률인 Bernoulli다. 개 샘플의 그룹에서 보상이 모두 같을 확률은 이고, 그러면 그룹 상대 advantage가 0이다. RLVR에서 난이도 필터링을 하는 이유다. GRPO는 모집단 std가 아니라 관측된 그룹 std로 나눈다. 그룹 정답률 , ddof = 0이면 그 값은 이다(ddof = 1을 쓰는 구현도 있고, 그러면 배 크다). , 에서 그룹 의 std는 0이지만 모집단 std는 0.5다. 가 의 추정이므로, 이 나눗셈은 이 분산의 (잡음 섞인) 추정으로 프롬프트의 무게를 바꾼다(시퀀스 vs 토큰).
Binomial(): 독립인 Bernoulli() 시행 번의 성공 횟수. , 평균 , 분산 (독립 분산 개의 합). 프롬프트 하나에서 뽑은 개 샘플 중 정답 수이고, pass@k 추정량(통계)과 MiMo-7B 같은 보고서의 모델 비교에 들어가는 입력이다.
Beta(): 위의 분포로 밀도 , 평균 . 데이터셋 전체에 퍼진 프롬프트별 통과율의 자연스러운 모델이다(시퀀스 vs 토큰은 “대부분 어려운 프롬프트”를 Beta(0.6, 1.2)로 둔다). 이항분포와 켤레다. 에 대한 Beta() 사전분포에 번 중 번 성공을 더하면 사후분포는 Beta()이고, 그 평균 는 가상의 성공 번과 실패 번을 더한 것이다. 대칭 사전분포 일 때만 add- smoothing이다(이면 Laplace). 그리고 독립 균등분포 개의 최댓값은 Beta()이다. best-of-N이 고른 응답의 분위수를 구하는 방법이다.
Categorical(): 개 클래스 위. 다음 토큰 분포이고 다. one-hot 인코딩 의 평균은 , 공분산은 이다.
Gaussian : 밀도 . 질량의 68/95/99.7%가 1/2/3 σ 안에 있다. 아핀 사상과 독립 Gaussian의 합에 닫혀 있고(평균끼리, 분산끼리 더한다), 로 이라 쓸 수 있다. 아래에서 쓰는 reparameterisation이다. 다변량이면 인 로 .
로그정규(log-normal): 이면 는 로그정규이고, 완전제곱 에서
이 나온다. 시퀀스 단위 importance ratio의 모델이다. 토큰별 log-ratio 가 대략 독립이고 분산이 이면 개 토큰의 합은 분산 , 즉 표준편차가 로 자라고, 는 근사적으로 로그정규다. 평균적으로 맞는 ratio라면 , 곧 log-ratio 평균이 여야 한다. 그러면 의 중앙값은 인데 는 폭발한다. 대부분의 시퀀스는 아주 작은 가중치를, 몇 개는 거대한 가중치를 받는다. off-policy 불일치, 불일치 엔지니어링, verl rollout correction, 통계가 분석하는 분산·ESS 붕괴다.
Gumbel(0, 1): CDF , 밀도 , 로 로 뽑는다. 최댓값의 극한 분포이고, Gumbel-max trick을 준다.
증명(이긴 logit의 밀도를 나머지들의 CDF와 함께 적분한다)과 딸린 결과들, 즉 잡음 섞인 logit의 최댓값이 (잡음 섞인 log-sum-exp)이라는 것과 argmax 대신 상위 개를 고르면 비복원 추출이 된다는 것(Gumbel-top-k)은 극값 레슨에서 다룬다. 여기서는 명제만 쓰고 샘플링으로 확인한다. 그림은 몬테카를로 오차를 보는 창이기도 하다.
Where it shows up: the Bradley–Terry model is “add Gumbel noise to two utilities and pick the larger” — the difference of two independent Gumbels is logistic, whose CDF is the sigmoid (reward models); sampling engines use the same argmax-of-perturbed-scores form (vLLM divides probabilities by exponential noise, , which is Gumbel-max in disguise), so with the noise fixed a sampled token is a deterministic function of the logits — the setting of mismatch engineering, whose simulation samples exactly this way; and Gumbel-top-k, sampling without replacement, is how the MoE lesson simulates skewed top-k routing loads.
Monte Carlo estimation
To compute when the sum or integral is intractable, draw and average:
Unbiasedness is linearity of expectation; the standard deviation is the rule. Two things to notice. The error depends on and but not on the dimension of — this is why sampling works over sequences of a thousand tokens. And the rate is slow: each extra decimal digit costs 100× more samples. Variance reduction (baselines, control variates, importance sampling — next lesson) attacks instead of . The central limit theorem then says is approximately Gaussian, which turns into confidence intervals (statistics).
import numpy as np
rng = np.random.default_rng(0)
# Bernoulli rewards: mean p, variance p(1-p)
p = np.array([0.05, 0.3, 0.5, 0.9])
R = (rng.random((200_000, 4)) < p).astype(float)
print("Bernoulli mean ", np.round(R.mean(0), 4), " vs p ", p)
print("Bernoulli var ", np.round(R.var(0), 4), " vs p(1-p)", p * (1 - p))
# Var of a sum, and the sd of a mean of n iid samples
X = rng.normal(size=200_000); Y = 0.6 * X + 0.8 * rng.normal(size=200_000)
print(f"\nVar(X+Y) = {np.var(X + Y):.3f} Var X + Var Y + 2 Cov = {np.var(X) + np.var(Y) + 2*np.cov(X, Y)[0, 1]:.3f}")
for n in [1, 4, 16, 64]:
means = rng.normal(size=(20_000, n)).mean(1)
print(f"n={n:3d}: sd of the mean = {means.std():.4f} 1/sqrt(n) = {1/np.sqrt(n):.4f}")
# Bayes with a noisy verifier, checked by simulation
prior, tpr, fpr = 0.05, 0.95, 0.05
post = tpr * prior / (tpr * prior + fpr * (1 - prior))
C = rng.random(1_000_000) < prior # is the response correct?
passed = np.where(C, rng.random(C.size) < tpr, rng.random(C.size) < fpr)
print(f"\nBayes: P(C|pass) = {post:.4f} simulated = {C[passed].mean():.4f}")
# chain rule: a toy autoregressive model over V=3 tokens; the product of conditionals is a distribution
V, T = 3, 4
p0 = np.array([0.5, 0.3, 0.2]) # p(y1)
Pn = rng.dirichlet(np.ones(V), size=V) # p(y_t | y_{t-1})
def seq_logprob(y):
return np.log(p0[y[0]]) + sum(np.log(Pn[y[t-1], y[t]]) for t in range(1, len(y)))
seqs = np.array(np.meshgrid(*[range(V)] * T, indexing="ij")).reshape(T, -1).T
total = sum(np.exp(seq_logprob(s)) for s in seqs)
print(f"chain rule: sum over all {len(seqs)} sequences of prod_t p(y_t|y_<t) = {total:.12f}")
# Gumbel-max sampling reproduces softmax
z = np.array([2.0, 1.2, 0.6, 0.0, -0.8])
soft = np.exp(z - z.max()); soft /= soft.sum()
idx = np.argmax(z + rng.gumbel(size=(200_000, z.size)), axis=1)
freq = np.bincount(idx.astype(np.intp), minlength=z.size) / idx.size
print("\nsoftmax(z) ", np.round(soft, 4))
print("Gumbel-max freq ", np.round(freq, 4))
# Monte Carlo: RMSE * sqrt(N) is constant (= sd of f)
f = lambda x: np.cos(x) ** 2 # E[f(X)], X~N(0,1) = (1 + e^-2)/2
truth = 0.5 * (1 + np.exp(-2))
sd_f = f(rng.normal(size=10**6)).std()
for N in [10, 100, 1_000, 10_000]:
est = f(rng.normal(size=(400, N))).mean(1)
rmse = np.sqrt(np.mean((est - truth) ** 2))
print(f"N={N:6d}: RMSE = {rmse:.5f} RMSE*sqrt(N) = {rmse*np.sqrt(N):.3f} (sd of f = {sd_f:.3f})")
# log-normal: E[e^X] = exp(mu + sigma^2/2); a sum of T token log-ratios has sd ~ sqrt(T)
Xn = rng.normal(-0.3, 0.8, size=1_000_000)
print(f"\nE[e^X] = {np.exp(Xn).mean():.4f} exp(mu + sigma^2/2) = {np.exp(-0.3 + 0.32):.4f}")
s2 = 0.005
for T in [10, 100, 1000]:
logw = rng.normal(-s2 / 2, np.sqrt(s2), size=(2000, T)).sum(1)
print(f"T={T:5d}: sd of sum = {logw.std():.3f} (sqrt(T s2) = {np.sqrt(T*s2):.3f}) median w = {np.exp(np.median(logw)):.3f} mean w = {np.exp(logw).mean():.3f}")Gradients of expectations: score function versus reparameterisation
RL and variational methods need , where the parameters sit in the distribution being averaged over. There are two standard estimators.
Score function (log-derivative trick, REINFORCE). Differentiate under the sum and use :
It needs only samples and — can be a black box, discontinuous, a 0/1 verifier; can be a discrete token sequence (then by the chain rule). The score has mean zero, , so for any constant (or any that does not depend on the sample itself)
a baseline changes the variance but not the mean. A leave-one-out mean of the other samples in a batch qualifies (RLOO); a mean that includes the sample itself scales the expected gradient by .
Reparameterisation (pathwise). If with from a fixed distribution — for a Gaussian — move the gradient inside:
It uses the derivative of , which usually makes it much lower-variance — but it requires differentiable and continuous. For a step function the pathwise derivative is zero almost everywhere and the estimator is simply wrong. How each estimator becomes a loss that autograd can differentiate (surrogate losses, stop-gradient) is the subject of surrogate gradients.
쓰이는 곳: Bradley–Terry 모델은 “두 효용에 Gumbel 잡음을 더하고 큰 쪽을 고른다”이다. 독립인 두 Gumbel의 차는 로지스틱 분포이고 그 CDF가 시그모이드다(보상모델). 샘플링 엔진도 같은 “잡음 섞인 점수의 argmax” 꼴을 쓴다(vLLM은 확률을 지수분포 잡음으로 나눈 를 쓰는데, 모양만 다른 Gumbel-max다). 그래서 잡음을 고정하면 뽑힌 토큰은 logit의 결정적 함수가 된다. 불일치 엔지니어링의 상황이고, 그 레슨의 시뮬레이션이 정확히 이렇게 샘플링한다. 비복원 추출인 Gumbel-top-k는 MoE 레슨이 치우친 top-k 라우팅 부하를 시뮬레이션하는 방법이다.
몬테카를로 추정
합이나 적분을 계산할 수 없을 때 를 구하려면 를 뽑아 평균한다.
불편성은 기댓값의 선형성이고, 표준편차는 규칙이다. 주목할 점 둘. 오차는 와 에 의존하지만 의 차원에는 의존하지 않는다. 천 토큰짜리 시퀀스 위에서도 샘플링이 통하는 이유다. 그리고 속도가 느리다. 소수점 한 자리를 더 얻으려면 샘플이 100배 필요하다. 분산 감소(baseline, control variate, importance sampling, 다음 레슨)는 대신 를 공략한다. 중심극한정리는 이 근사적으로 Gaussian이라고 말해 주고, 그것이 을 신뢰구간으로 바꾼다(통계).
import numpy as np
rng = np.random.default_rng(0)
# Bernoulli 보상: 평균 p, 분산 p(1-p)
p = np.array([0.05, 0.3, 0.5, 0.9])
R = (rng.random((200_000, 4)) < p).astype(float)
print("Bernoulli 평균 ", np.round(R.mean(0), 4), " vs p ", p)
print("Bernoulli 분산 ", np.round(R.var(0), 4), " vs p(1-p)", p * (1 - p))
# 합의 분산, iid 표본 n개 평균의 표준편차
X = rng.normal(size=200_000); Y = 0.6 * X + 0.8 * rng.normal(size=200_000)
print(f"\nVar(X+Y) = {np.var(X + Y):.3f} Var X + Var Y + 2 Cov = {np.var(X) + np.var(Y) + 2*np.cov(X, Y)[0, 1]:.3f}")
for n in [1, 4, 16, 64]:
means = rng.normal(size=(20_000, n)).mean(1)
print(f"n={n:3d}: 평균의 표준편차 = {means.std():.4f} 1/sqrt(n) = {1/np.sqrt(n):.4f}")
# 잡음 섞인 verifier와 베이즈, 시뮬레이션으로 확인
prior, tpr, fpr = 0.05, 0.95, 0.05
post = tpr * prior / (tpr * prior + fpr * (1 - prior))
C = rng.random(1_000_000) < prior # 응답이 정답인가?
passed = np.where(C, rng.random(C.size) < tpr, rng.random(C.size) < fpr)
print(f"\n베이즈: P(C|pass) = {post:.4f} 시뮬레이션 = {C[passed].mean():.4f}")
# 연쇄 법칙: V=3 토큰 위의 장난감 자기회귀 모델; 조건부들의 곱은 분포다
V, T = 3, 4
p0 = np.array([0.5, 0.3, 0.2]) # p(y1)
Pn = rng.dirichlet(np.ones(V), size=V) # p(y_t | y_{t-1})
def seq_logprob(y):
return np.log(p0[y[0]]) + sum(np.log(Pn[y[t-1], y[t]]) for t in range(1, len(y)))
seqs = np.array(np.meshgrid(*[range(V)] * T, indexing="ij")).reshape(T, -1).T
total = sum(np.exp(seq_logprob(s)) for s in seqs)
print(f"연쇄 법칙: 시퀀스 {len(seqs)}개 전체에 대한 prod_t p(y_t|y_<t)의 합 = {total:.12f}")
# Gumbel-max 샘플링은 softmax를 재현한다
z = np.array([2.0, 1.2, 0.6, 0.0, -0.8])
soft = np.exp(z - z.max()); soft /= soft.sum()
idx = np.argmax(z + rng.gumbel(size=(200_000, z.size)), axis=1)
freq = np.bincount(idx.astype(np.intp), minlength=z.size) / idx.size
print("\nsoftmax(z) ", np.round(soft, 4))
print("Gumbel-max 빈도 ", np.round(freq, 4))
# 몬테카를로: RMSE * sqrt(N)은 일정 (= f의 표준편차)
f = lambda x: np.cos(x) ** 2 # E[f(X)], X~N(0,1) = (1 + e^-2)/2
truth = 0.5 * (1 + np.exp(-2))
sd_f = f(rng.normal(size=10**6)).std()
for N in [10, 100, 1_000, 10_000]:
est = f(rng.normal(size=(400, N))).mean(1)
rmse = np.sqrt(np.mean((est - truth) ** 2))
print(f"N={N:6d}: RMSE = {rmse:.5f} RMSE*sqrt(N) = {rmse*np.sqrt(N):.3f} (f의 표준편차 = {sd_f:.3f})")
# 로그정규: E[e^X] = exp(mu + sigma^2/2); 토큰 log-ratio T개 합의 표준편차 ~ sqrt(T)
Xn = rng.normal(-0.3, 0.8, size=1_000_000)
print(f"\nE[e^X] = {np.exp(Xn).mean():.4f} exp(mu + sigma^2/2) = {np.exp(-0.3 + 0.32):.4f}")
s2 = 0.005
for T in [10, 100, 1000]:
logw = rng.normal(-s2 / 2, np.sqrt(s2), size=(2000, T)).sum(1)
print(f"T={T:5d}: 합의 sd = {logw.std():.3f} (sqrt(T s2) = {np.sqrt(T*s2):.3f}) w 중앙값 = {np.exp(np.median(logw)):.3f} w 평균 = {np.exp(logw).mean():.3f}")기댓값의 gradient: score function과 reparameterisation
RL과 변분 방법은 가 필요하다. 매개변수가 평균을 취하는 분포 안에 있다. 표준 추정량은 둘이다.
Score function(log-derivative trick, REINFORCE). 합 안에서 미분하고 를 쓴다.
샘플과 만 있으면 된다. 는 블랙박스여도, 불연속이어도, 0/1 verifier여도 되고, 는 이산 토큰 시퀀스여도 된다(그러면 연쇄 법칙으로 ). score의 평균은 0이다. . 그러므로 어떤 상수 에 대해서도(또는 샘플 자신에 의존하지 않는 어떤 에 대해서도)
baseline은 분산을 바꾸지만 평균은 바꾸지 않는다. 배치의 다른 샘플들의 leave-one-out 평균은 조건을 만족한다(RLOO). 샘플 자신을 포함한 평균은 기대 gradient를 배로 줄인다.
Reparameterisation(pathwise). 고정된 분포의 으로 이라 쓸 수 있으면(Gaussian이면 ) gradient를 안으로 넣는다.
의 도함수를 쓰므로 보통 분산이 훨씬 작다. 하지만 가 미분 가능하고 가 연속이어야 한다. 계단 함수라면 pathwise 도함수가 거의 모든 곳에서 0이고, 추정량은 그냥 틀린다. 각 추정량을 autograd가 미분할 수 있는 손실로 바꾸는 방법(surrogate 손실, stop-gradient)은 surrogate gradient 레슨의 주제다.
import numpy as np
rng = np.random.default_rng(1)
mu, sigma, N = 0.5, 1.0, 16 # batches of 16 samples
eps = rng.normal(size=(20_000, N)); x = mu + sigma * eps
phi = lambda u: np.exp(-0.5 * u * u) / np.sqrt(2 * np.pi)
for name, fx, dfx, true in [("x^2", x**2, 2*x, 2*mu),
("1[x>0]", (x > 0).astype(float), np.zeros_like(x), phi(mu/sigma) / sigma)]:
score = fx * eps / sigma # f(x) * d/dmu log N(x; mu, sigma^2)
b = (fx.sum(1, keepdims=True) - fx) / (N - 1) # leave-one-out baseline
est = {"score": score.mean(1), "score+baseline": ((fx - b) * eps / sigma).mean(1), "reparam": dfx.mean(1)}
print(f"f = {name}: true gradient {true:.4f}")
for k, v in est.items():
print(f" {k:15s} mean {v.mean():+.4f} sd {v.std():.4f}")
print(f"\nE[score] = E[(x-mu)/sigma^2] = {(eps / sigma).mean():+.5f} (zero: baselines add no bias)")For all three are unbiased and the pathwise estimator has about half the standard deviation of the plain score function. For the 0/1 reward the pathwise estimator returns exactly 0 with zero variance — perfectly confident and wrong — while the score function remains unbiased. Tokens are discrete and verifiers are step functions, so LLM RL lives on the score-function side: policy gradients derive REINFORCE and baselines from exactly this identity, and GRPO/RLOO are choices of . (Gumbel-softmax is a continuous relaxation that makes discrete samples reparameterisable, at the cost of bias; it is not used for LLM policy gradients.)
In REINFORCE you subtract a baseline b from the reward. Which choice of b would bias the gradient?
Unbiasedness needs , which holds when does not depend on (it can depend on the prompt and on other, independent samples): then factors out and . If depends on , the product no longer averages to zero. Using the sample’s own reward as its baseline gives : no gradient at all.
Markov chains
A sequence of states is a Markov chain if the next state depends on the past only through the present: . With finitely many states the dynamics is a row-stochastic matrix , and a distribution (a row vector) evolves linearly:
A stationary distribution satisfies : it is a left eigenvector of with eigenvalue 1. If the chain is irreducible and aperiodic, from any start, at a rate set by the second-largest eigenvalue modulus (power iteration, eigen/SVD).
An MDP is a Markov chain whose transitions are chosen by actions: . Fix a policy and it collapses back to a Markov chain with — the object Bellman equations are written for (MDP). An LLM generating text is trivially Markov if the state is the whole prefix; agent RL keeps that by making the state the full interaction history (agent RL).
import numpy as np
P = np.array([[0.90, 0.08, 0.02],
[0.10, 0.80, 0.10],
[0.05, 0.15, 0.80]])
d = np.array([1.0, 0.0, 0.0])
for t in range(200): d = d @ P # d_{t+1} = d_t P
w, U = np.linalg.eig(P.T) # left eigenvectors of P
pi = np.real(U[:, np.argmin(np.abs(w - 1))]); pi /= pi.sum()
print("power iteration ", np.round(d, 6))
print("left eigenvector ", np.round(pi, 6), " check pi P = pi:", np.allclose(pi @ P, pi))
print("|eigenvalues| ", np.round(np.sort(np.abs(w))[::-1], 4), "-> mixing rate set by |lambda_2|")Summary
- is linear; ; for independent samples, more with positive correlation; covariance matrices are PSD.
- Bayes in odds: posterior odds = prior odds × likelihood ratio. Low base rates let small false-positive rates dominate.
- The chain rule holds for any distribution; an autoregressive LM parameterises its factors. Sequence ratios are products of token ratios.
- Bernoulli variance , Binomial , Beta–Binomial conjugacy; Gaussian ; log-normal , so a sum of token log-ratios gives sequence weights with ; Gumbel-max: .
- Monte Carlo error is , dimension-free.
- ; the score has mean zero, so baselines are free. Reparameterisation is lower-variance but needs differentiable and continuous .
- Markov chain: , stationary ; a fixed policy turns an MDP into one.
Where this is used
- Expectation, variance, the rule — SGD noise and batch size, initialisation, every error bar in statistics.
- Bayes, conditional independence — verifier errors in rewards and environments; Dirichlet smoothing in language modelling.
- Chain rule — language modelling, GPT from scratch, sequence-level ratios in off-policy mismatch and sequence vs token.
- Bernoulli rewards — group statistics in RLVR and GRPO, pass@k.
- Softmax sampling, Gumbel — decoding, Bradley–Terry, mismatch engineering, MoE.
- Binomial, Beta, log-normal — pass@k and model comparisons in statistics and MiMo-7B; pass-rate distributions in sequence vs token; the Beta(N, 1) quantile in best-of-N; sequence-level ratios in off-policy mismatch and verl rollout correction.
- Elsewhere in Track 0 — maxima, order statistics and Gumbel-top-k in extreme values; surrogate losses and stop-gradient for these estimators in surrogate gradients.
- Score function and baselines — policy gradient, actor-critic, KL-regularised RL, RLVR and GRPO, the frontier-RL landscape.
- Markov chains — MDP, TD and Q-learning.
import numpy as np
rng = np.random.default_rng(1)
mu, sigma, N = 0.5, 1.0, 16 # 표본 16개짜리 배치
eps = rng.normal(size=(20_000, N)); x = mu + sigma * eps
phi = lambda u: np.exp(-0.5 * u * u) / np.sqrt(2 * np.pi)
for name, fx, dfx, true in [("x^2", x**2, 2*x, 2*mu),
("1[x>0]", (x > 0).astype(float), np.zeros_like(x), phi(mu/sigma) / sigma)]:
score = fx * eps / sigma # f(x) * d/dmu log N(x; mu, sigma^2)
b = (fx.sum(1, keepdims=True) - fx) / (N - 1) # leave-one-out baseline
est = {"score": score.mean(1), "score+baseline": ((fx - b) * eps / sigma).mean(1), "reparam": dfx.mean(1)}
print(f"f = {name}: 참 gradient {true:.4f}")
for k, v in est.items():
print(f" {k:15s} 평균 {v.mean():+.4f} 표준편차 {v.std():.4f}")
print(f"\nE[score] = E[(x-mu)/sigma^2] = {(eps / sigma).mean():+.5f} (0: baseline은 편향을 더하지 않는다)")에서는 셋 다 불편이고 pathwise 추정량의 표준편차가 순수 score function의 절반쯤이다. 0/1 보상에서는 pathwise 추정량이 분산 0으로 정확히 0을 낸다. 완벽하게 확신하면서 틀린다. score function은 여전히 불편이다. 토큰은 이산이고 verifier는 계단 함수이므로 LLM RL은 score function 쪽에 산다. 정책 경사가 바로 이 항등식에서 REINFORCE와 baseline을 유도하고, GRPO/RLOO는 를 고르는 방식이다. (Gumbel-softmax는 이산 샘플을 reparameterise할 수 있게 만드는 연속 완화인데, 편향이 생긴다. LLM 정책 경사에는 쓰이지 않는다.)
REINFORCE에서 보상에서 baseline b를 뺀다. 어떤 b가 gradient를 편향시키는가?
불편이려면 이어야 하고, 이는 가 에 의존하지 않을 때 성립한다(프롬프트 나 다른 독립 샘플에는 의존해도 된다). 그러면 가 밖으로 나오고 이다. 가 에 의존하면 곱의 평균이 더는 0이 아니다. 샘플 자신의 보상을 baseline으로 쓰면 , gradient가 아예 없다.
마르코프 연쇄(Markov chain)
상태열 에서 다음 상태가 과거에 현재를 통해서만 의존하면, 즉 이면 Markov chain이다. 상태가 유한하면 동역학은 행 확률 행렬 이고, 분포 (행 벡터)는 선형으로 움직인다.
정상 분포(stationary distribution) 는 를 만족한다. 고유값 1인 의 왼쪽 고유벡터다. 체인이 기약(irreducible)이고 비주기적이면 어디서 출발해도 이고, 그 속도는 두 번째로 큰 고유값의 절댓값 가 정한다(거듭제곱법, 고유값·SVD).
MDP는 행동이 전이를 고르는 Markov chain이다: . 정책 를 고정하면 다시 Markov chain 가 된다. Bellman 방정식이 쓰이는 대상이다(MDP). 텍스트를 생성하는 LLM은 상태를 prefix 전체로 두면 자명하게 Markov다. agent RL은 상태를 상호작용 이력 전체로 두어 그 성질을 지킨다(agent RL).
import numpy as np
P = np.array([[0.90, 0.08, 0.02],
[0.10, 0.80, 0.10],
[0.05, 0.15, 0.80]])
d = np.array([1.0, 0.0, 0.0])
for t in range(200): d = d @ P # d_{t+1} = d_t P
w, U = np.linalg.eig(P.T) # P의 왼쪽 고유벡터
pi = np.real(U[:, np.argmin(np.abs(w - 1))]); pi /= pi.sum()
print("거듭제곱법 ", np.round(d, 6))
print("왼쪽 고유벡터 ", np.round(pi, 6), " pi P = pi 확인:", np.allclose(pi @ P, pi))
print("|고유값| ", np.round(np.sort(np.abs(w))[::-1], 4), "-> 섞이는 속도는 |lambda_2|가 정한다")정리
- 는 선형이다. . 독립 표본이면 , 양의 상관이 있으면 더 크다. 공분산 행렬은 PSD다.
- odds로 쓴 베이즈: 사후 odds = 사전 odds × 우도비. base rate가 낮으면 작은 false-positive 비율이 지배한다.
- 연쇄 법칙 는 어떤 분포에도 성립하고, 자기회귀 LM은 그 인수를 매개변수화한다. 시퀀스 비는 토큰 비의 곱이다.
- Bernoulli 분산 , Binomial , Beta–Binomial 켤레성. Gaussian . 로그정규 이므로 토큰 log-ratio 개의 합은 인 시퀀스 가중치를 준다. Gumbel-max: .
- 몬테카를로 오차는 이고 차원과 무관하다.
- . score의 평균이 0이라 baseline은 공짜다. reparameterisation은 분산이 작지만 미분 가능한 와 연속인 가 필요하다.
- Markov chain: , 정상 분포 . 정책을 고정하면 MDP가 Markov chain이 된다.
이 사이트에서 쓰이는 곳
- 기댓값, 분산, 규칙: SGD 잡음과 배치 크기, 초기화, 통계의 모든 오차 막대.
- 베이즈, 조건부 독립: 보상과 환경의 verifier 오류, 언어 모델링의 Dirichlet smoothing.
- 연쇄 법칙: 언어 모델링, GPT 바닥부터, off-policy 불일치와 시퀀스 vs 토큰의 시퀀스 단위 비.
- Bernoulli 보상: RLVR과 GRPO의 그룹 통계, pass@k.
- softmax 샘플링, Gumbel: 디코딩, Bradley–Terry, 불일치 엔지니어링, MoE.
- Binomial, Beta, 로그정규: 통계와 MiMo-7B의 pass@k와 모델 비교, 시퀀스 vs 토큰의 통과율 분포, best-of-N의 Beta(N, 1) 분위수, off-policy 불일치와 verl rollout correction의 시퀀스 단위 비.
- Track 0의 다른 레슨: 최댓값·순서통계량·Gumbel-top-k는 극값, 이 추정량들의 surrogate 손실과 stop-gradient는 surrogate gradient.
- score function과 baseline: 정책 경사, actor-critic, KL 정규화 RL, RLVR과 GRPO, frontier RL 지도.
- Markov chain: MDP, TD와 Q-learning.
더 읽을거리Further reading
- Blitzstein & Hwang, Introduction to Probability, 2nd ed. (CRC Press, 2019) — 조건부 확률, 기댓값의 선형성, 지시변수 기법, Markov chain을 직관적으로. Harvard Stat 110 교재.Conditional probability, linearity of expectation, indicator tricks and Markov chains, intuitively. The Harvard Stat 110 textbook.
- Bishop, Pattern Recognition and Machine Learning (Springer, 2006), ch. 1–2 — 확률 규칙, 베이즈, Gaussian의 성질(§2.3)을 ML 표기로.Probability rules, Bayes and properties of the Gaussian (§2.3) in ML notation.
- Goodfellow, Bengio, Courville, Deep Learning (MIT Press, 2016), ch. 3 — 딥러닝에 필요한 확률만 압축해서.Just the probability deep learning needs, compressed.
- Mohamed, Rosca, Figurnov, Mnih, Monte Carlo Gradient Estimation in Machine Learning (JMLR, 2020) — score function, pathwise(reparameterisation), measure-valued gradient의 성질과 분산을 정리한 서베이. 이 레슨 4부의 표준 참고.Survey of score-function, pathwise (reparameterisation) and measure-valued gradients, their properties and variances. The standard reference for this lesson's gradient section.
- Huijben, Kool, Paulus, van Sloun, A Review of the Gumbel-max Trick and its Extensions for Discrete Stochasticity in Machine Learning (IEEE TPAMI, 2022) — Gumbel-max, Gumbel-top-k, Gumbel-softmax의 유도와 응용.Derivations and uses of Gumbel-max, Gumbel-top-k and Gumbel-softmax.
- Williams, Simple statistical gradient-following algorithms for connectionist reinforcement learning (Machine Learning, 1992) — REINFORCE. score-function gradient와 baseline의 원 논문.REINFORCE — the original score-function gradient with a baseline.
- Kingma & Welling, Auto-Encoding Variational Bayes (ICLR 2014) — reparameterisation trick을 널리 알린 논문.The paper that popularised the reparameterisation trick.