Track 0 · Math Foundations · 05/10

확률Probability

확률변수·기댓값·분산·공분산, 조건부 확률과 베이즈 규칙, 연쇄 법칙이 곧 자기회귀 LM이라는 것, Bernoulli·categorical·Gaussian·Gumbel(Gumbel-max trick 유도), 몬테카를로 추정과 1/√N 오차, score function(log-derivative trick)과 reparameterisation gradient의 분산 비교, 그리고 MDP의 전제인 Markov chain까지.Random variables, expectation, variance and covariance; conditional probability and Bayes' rule; the chain rule as the autoregressive LM; Bernoulli, categorical, Gaussian and Gumbel distributions (with a derivation of the Gumbel-max trick); Monte Carlo estimation and its 1/√N error; the score-function (log-derivative) versus reparameterisation gradient and their variances; and Markov chains, the prerequisite for MDPs.

50 분min probability · expectation · variance · covariance · bayes · chain rule · gaussian · gumbel · monte carlo · score function · reparameterization · markov chain 먼저 볼 것:Before this: 미분·연쇄법칙·JacobianDerivatives, the chain rule and Jacobians

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 1/N1/\sqrt N law of Monte Carlo, and the log-derivative trick.

Random variables and expectation

A random variable XX is a function of the outcome of an experiment; its distribution is given by a pmf p(x)=P(X=x)p(x) = P(X = x) (discrete) or a density p(x)p(x) with P(X∈A)=∫Ap(x) dxP(X\in A) = \int_A p(x)\,dx (continuous). The expectation is

E[f(X)]=∑xp(x)f(x)or∫p(x)f(x) dx,\mathbb{E}[f(X)] = \sum_x p(x) f(x) \quad\text{or}\quad \int p(x) f(x)\,dx ,

with no need to find the distribution of f(X)f(X) first. Two facts carry most of the weight:

  • Linearity — E[aX+bY]=aEX+bEY\mathbb{E}[aX + bY] = a\mathbb{E}X + b\mathbb{E}Y 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 — E[1A]=P(A)\mathbb{E}[\mathbf{1}_A] = P(A). 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

Var(X)=E[(X−μ)2]=E[X2]−μ2,Cov(X,Y)=E[(X−μX)(Y−μY)].\mathrm{Var}(X) = \mathbb{E}\big[(X-\mu)^2\big] = \mathbb{E}[X^2] - \mu^2, \qquad \mathrm{Cov}(X,Y) = \mathbb{E}\big[(X-\mu_X)(Y-\mu_Y)\big].

Var(aX+b)=a2Var(X)\mathrm{Var}(aX + b) = a^2\mathrm{Var}(X), and expanding the square of a sum,

Var(∑iXi)=∑iVar(Xi)+2∑i<jCov(Xi,Xj).\mathrm{Var}\Big(\sum_i X_i\Big) = \sum_i \mathrm{Var}(X_i) + 2\sum_{i<j}\mathrm{Cov}(X_i, X_j).

For nn independent copies with variance σ2\sigma^2 the covariances vanish, so the mean Xˉn\bar X_n has Var(Xˉn)=σ2/n\mathrm{Var}(\bar X_n) = \sigma^2/n and standard deviation σ/n\sigma/\sqrt n — 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 xx the covariance matrix Σ=E[(x−μ)(x−μ)⊤]\Sigma = \mathbb{E}[(x-\mu)(x-\mu)^\top] is positive semidefinite, because v⊤Σv=Var(v⊤x)≥0v^\top\Sigma v = \mathrm{Var}(v^\top x) \ge 0. (That is the argument that made the log-sum-exp Hessian diag(p)−pp⊤\mathrm{diag}(p) - pp^\top PSD in the optimisation lesson: it is the covariance of a one-hot sample from pp.) The same variance arithmetic, Var(∑i=1nwixi)=n Var(w)Var(x)\mathrm{Var}(\sum_{i=1}^n w_i x_i) = n\,\mathrm{Var}(w)\mathrm{Var}(x) for independent zero-mean terms, is what sets the 1/n1/n scale of Xavier and He initialisation (training deep nets).

Conditional probability and Bayes’ rule

P(A∣B)=P(A∩B)/P(B)P(A\mid B) = P(A\cap B)/P(B). Rearranged, this is the product rule P(A∩B)=P(A∣B)P(B)P(A\cap B) = P(A\mid B)P(B), and summing it over a partition {Bk}\{B_k\} gives the law of total probability P(A)=∑kP(A∣Bk)P(Bk)P(A) = \sum_k P(A\mid B_k)P(B_k). Writing the joint probability both ways and dividing gives Bayes’ rule:

P(C∣E)=P(E∣C) P(C)P(E)=P(E∣C) P(C)P(E∣C)P(C)+P(E∣¬C)P(¬C).P(C\mid E) = \frac{P(E\mid C)\,P(C)}{P(E)} = \frac{P(E\mid C)\,P(C)}{P(E\mid C)P(C) + P(E\mid\neg C)P(\neg C)} .

The denominator is total probability. In odds the normaliser disappears and the rule becomes a product:

P(C∣E)P(¬C∣E)⏟posterior odds=P(C)P(¬C)⏟prior odds×P(E∣C)P(E∣¬C)⏟likelihood ratio.\underbrace{\frac{P(C\mid E)}{P(\neg C\mid E)}}_{\text{posterior odds}} = \underbrace{\frac{P(C)}{P(\neg C)}}_{\text{prior odds}} \times \underbrace{\frac{P(E\mid C)}{P(E\mid\neg C)}}_{\text{likelihood ratio}} .

Concretely: CC = “the sampled answer is correct”, EE = “the verifier passed it”.

언어 모델은 시퀀스 위의 확률분포이고, 거기서 샘플링하는 것은 확률변수를 뽑는 일이며, LLM용 RL은 그 샘플에 대한 기댓값을 미분하고, 평가는 유한한 샘플로 확률을 추정한다. 이 레슨은 그 모두에 필요한 확률이다. 표준 정의는 빠르게 지나가고, 뒤 트랙이 끊임없이 쓰는 결과 넷, 즉 연쇄 법칙, Gumbel-max trick, 몬테카를로의 1/N1/\sqrt N 법칙, log-derivative trick에 시간을 쓴다.

확률변수와 기댓값

확률변수 XX는 실험 결과의 함수다. 분포는 pmf p(x)=P(X=x)p(x) = P(X = x)(이산) 또는 P(X∈A)=∫Ap(x) dxP(X\in A) = \int_A p(x)\,dx인 밀도 p(x)p(x)(연속)로 주어진다. 기댓값은

E[f(X)]=∑xp(x)f(x)또는∫p(x)f(x) dx\mathbb{E}[f(X)] = \sum_x p(x) f(x) \quad\text{또는}\quad \int p(x) f(x)\,dx

이고, f(X)f(X)의 분포를 먼저 구할 필요가 없다. 대부분의 일을 두 사실이 한다.

  • 선형성: E[aX+bY]=aEX+bEY\mathbb{E}[aX + bY] = a\mathbb{E}X + b\mathbb{E}Y는 독립이든 아니든 항상 성립한다. 응답 안에서 맞힌 토큰 수의 기댓값은 위치별 확률의 합이다. 위치들이 서로 어떻게 의존하든 상관없다.
  • 지시변수: E[1A]=P(A)\mathbb{E}[\mathbf{1}_A] = P(A). 모든 확률은 기댓값이므로, 기댓값 추정에 대한 모든 이야기(아래 몬테카를로)가 확률 추정에도 적용된다. 정확도는 0/1 보상의 평균이다.

분산과 공분산

Var(X)=E[(X−μ)2]=E[X2]−μ2,Cov(X,Y)=E[(X−μX)(Y−μY)].\mathrm{Var}(X) = \mathbb{E}\big[(X-\mu)^2\big] = \mathbb{E}[X^2] - \mu^2, \qquad \mathrm{Cov}(X,Y) = \mathbb{E}\big[(X-\mu_X)(Y-\mu_Y)\big].

Var(aX+b)=a2Var(X)\mathrm{Var}(aX + b) = a^2\mathrm{Var}(X)이고, 합의 제곱을 전개하면

Var(∑iXi)=∑iVar(Xi)+2∑i<jCov(Xi,Xj).\mathrm{Var}\Big(\sum_i X_i\Big) = \sum_i \mathrm{Var}(X_i) + 2\sum_{i<j}\mathrm{Cov}(X_i, X_j).

분산이 σ2\sigma^2인 독립 사본 nn개면 공분산이 사라지므로 평균 Xˉn\bar X_n은 Var(Xˉn)=σ2/n\mathrm{Var}(\bar X_n) = \sigma^2/n, 표준편차 σ/n\sigma/\sqrt n이다. 이 레슨과 다음 레슨에서 가장 중요한 식이다. 양의 상관이 있으면 분산이 더 느리게 줄어든다. 한 응답의 토큰들, 한 그룹의 응답들은 독립 샘플이 아니어서, 그 개수가 암시하는 만큼 평균의 이득이 나지 않는다.

확률 벡터 xx의 공분산 행렬 Σ=E[(x−μ)(x−μ)⊤]\Sigma = \mathbb{E}[(x-\mu)(x-\mu)^\top]는 v⊤Σv=Var(v⊤x)≥0v^\top\Sigma v = \mathrm{Var}(v^\top x) \ge 0이므로 양의 준정부호다. (최적화 레슨에서 log-sum-exp Hessian diag(p)−pp⊤\mathrm{diag}(p) - pp^\top이 PSD였던 논리가 이것이다. pp에서 뽑은 one-hot 샘플의 공분산이다.) 같은 분산 산수, 독립이고 평균 0인 항들에 대한 Var(∑i=1nwixi)=n Var(w)Var(x)\mathrm{Var}(\sum_{i=1}^n w_i x_i) = n\,\mathrm{Var}(w)\mathrm{Var}(x)가 Xavier·He 초기화의 1/n1/n 스케일을 정한다(깊은 망 학습).

조건부 확률과 베이즈 규칙

P(A∣B)=P(A∩B)/P(B)P(A\mid B) = P(A\cap B)/P(B). 다시 쓰면 곱 규칙 P(A∩B)=P(A∣B)P(B)P(A\cap B) = P(A\mid B)P(B)이고, 분할 {Bk}\{B_k\}에 대해 더하면 전확률 법칙 P(A)=∑kP(A∣Bk)P(Bk)P(A) = \sum_k P(A\mid B_k)P(B_k)이다. 결합확률을 두 방향으로 쓰고 나누면 베이즈 규칙이 나온다.

P(C∣E)=P(E∣C) P(C)P(E)=P(E∣C) P(C)P(E∣C)P(C)+P(E∣¬C)P(¬C).P(C\mid E) = \frac{P(E\mid C)\,P(C)}{P(E)} = \frac{P(E\mid C)\,P(C)}{P(E\mid C)P(C) + P(E\mid\neg C)P(\neg C)} .

분모가 전확률이다. odds로 쓰면 정규화 상수가 사라지고 곱이 된다.

P(C∣E)P(¬C∣E)⏟사후 odds=P(C)P(¬C)⏟사전 odds×P(E∣C)P(E∣¬C)⏟우도비.\underbrace{\frac{P(C\mid E)}{P(\neg C\mid E)}}_{\text{사후 odds}} = \underbrace{\frac{P(C)}{P(\neg C)}}_{\text{사전 odds}} \times \underbrace{\frac{P(E\mid C)}{P(E\mid\neg C)}}_{\text{우도비}} .

구체적으로 CC = “샘플한 답이 정답”, EE = “verifier가 통과시킴”으로 두자.

P(pass) – P(C | pass) – 우도비likelihood ratio –
A thousand sampled responses to a hard problem; a fraction P(C) of them are correct. A verifier passes correct answers with probability P(pass | C) and wrong ones with P(pass | ¬C). Filled dots passed. Green filled = correct and passed, red filled = wrong but passed (false positives). Start at a 5% prior with a "95% accurate" verifier: half of what passes is wrong. Lower the prior and the false positives take over; that is the base-rate effect. Right: the posterior P(C | pass) as a function of the prior for the current verifier, which in odds form is just the prior odds times the likelihood ratio. 어려운 문제에 대해 샘플한 응답 1000개 중 P(C)의 비율이 정답이다. verifier는 정답을 P(pass | C), 오답을 P(pass | ¬C)의 확률로 통과시킨다. 채운 점이 통과한 것이다. 초록 채움 = 정답이고 통과, 빨강 채움 = 오답인데 통과(false positive). 사전확률 5%, "95% 정확한" verifier에서 시작하면 통과한 것의 절반이 오답이다. 사전확률을 낮추면 false positive가 대부분을 차지한다. base rate 효과다. 오른쪽: 현재 verifier에서 사전확률에 따른 사후확률 P(C | pass). odds로 쓰면 사전 odds × 우도비일 뿐이다.

With a 5% base rate and a verifier that is “95% accurate” in both directions, P(C∣pass)=0.5P(C\mid \text{pass}) = 0.5: 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: XX and YY are independent if p(x,y)=p(x)p(y)p(x,y) = p(x)p(y); they are conditionally independent given ZZ if p(x,y∣z)=p(x∣z)p(y∣z)p(x,y\mid z) = p(x\mid z)p(y\mid z). 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,

p(y1,…,yT∣x)=∏t=1Tp(yt∣x,y<t),log⁡p(y∣x)=∑t=1Tlog⁡p(yt∣x,y<t).p(y_1,\dots,y_T\mid x) = \prod_{t=1}^{T} p(y_t\mid x, y_{<t}), \qquad \log p(y\mid x) = \sum_{t=1}^T \log p(y_t\mid x, y_{<t}).

An autoregressive language model is a parameterisation of each factor, πθ(yt∣x,y<t)=softmax(logits)yt\pi_\theta(y_t\mid x, y_{<t}) = \mathrm{softmax}(\text{logits})_{y_t}; 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 −0.5-0.5 gives e−500e^{-500} for 1000 tokens), so everything is done in log space (numerics).
  • A ratio of two sequence probabilities is a product of per-token ratios, πθ(y)μ(y)=∏tρt\frac{\pi_\theta(y)}{\mu(y)} = \prod_t \rho_t. 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 n−1n-1 tokens is the Markov assumption of an n-gram model.

Distributions you will meet

Bernoulli(pp) — a 0/1 outcome, mean pp, variance p(1−p)p(1-p), largest at p=12p = \tfrac12. A verifiable reward is Bernoulli with pp = the policy’s success rate on that prompt. In a group of GG samples, all rewards are equal with probability pG+(1−p)Gp^G + (1-p)^G, 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 p^=1G∑iri\hat p = \frac1G\sum_i r_i and ddof = 0 it is p^(1−p^)\sqrt{\hat p(1-\hat p)} (some implementations use ddof = 1, a factor G/(G−1)\sqrt{G/(G-1)} larger). For G=4G = 4 and p=0.5p = 0.5, the group [1,1,1,1][1,1,1,1] has std 0 while the population std is 0.5. Since p^\hat p estimates pp, the division reweights prompts by (a noisy estimate of) this variance (sequence vs token).

Binomial(n,pn, p) — the number of successes in nn independent Bernoulli(pp) trials: P(c)=(nc)pc(1−p)n−cP(c) = \binom{n}{c}p^c(1-p)^{n-c}, mean npnp, variance np(1−p)np(1-p) (a sum of nn independent variances). It is the count of correct answers among nn samples of one prompt — the input to the pass@k estimator (statistics) and to model comparisons in reports such as MiMo-7B.

Beta(a,ba, b) — a distribution on [0,1][0, 1] with density ∝pa−1(1−p)b−1\propto p^{a-1}(1-p)^{b-1} and mean a/(a+b)a/(a+b); 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(a,ba, b) prior on pp plus cc successes in nn trials gives the posterior Beta(a+c, b+n−ca + c,\ b + n - c), whose mean (c+a)/(n+a+b)(c + a)/(n + a + b) adds aa pseudo-successes and bb pseudo-failures; only for a symmetric prior a=ba = b is it add-aa smoothing (a=b=1a = b = 1: Laplace). And the maximum of NN independent uniforms is Beta(N,1N, 1), which is how best-of-N gets the quantile of the chosen response.

Categorical(pp) over VV classes — the next-token distribution; p=softmax(z)p = \mathrm{softmax}(z). One-hot encoding eYe_Y has mean pp and covariance diag(p)−pp⊤\mathrm{diag}(p) - pp^\top.

Gaussian N(μ,σ2)\mathcal{N}(\mu, \sigma^2) — density 12πσe−(x−μ)2/2σ2\frac{1}{\sqrt{2\pi}\sigma}e^{-(x-\mu)^2/2\sigma^2}; 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 x=μ+σεx = \mu + \sigma\varepsilon with ε∼N(0,1)\varepsilon\sim\mathcal{N}(0,1) — the reparameterisation used below. Multivariate: x=μ+Lεx = \mu + L\varepsilon with LL⊤=ΣLL^\top = \Sigma.

Log-normal — if X∼N(μ,σ2)X\sim\mathcal{N}(\mu, \sigma^2) then eXe^X is log-normal, and completing the square, x−(x−μ)22σ2=−(x−μ−σ2)22σ2+μ+σ22x - \frac{(x-\mu)^2}{2\sigma^2} = -\frac{(x - \mu - \sigma^2)^2}{2\sigma^2} + \mu + \frac{\sigma^2}{2}, gives

E[eX]=eμ+σ2/2,E[e2X]=e2μ+2σ2.\mathbb{E}[e^X] = e^{\mu + \sigma^2/2}, \qquad \mathbb{E}[e^{2X}] = e^{2\mu + 2\sigma^2}.

This is the model for a sequence-level importance ratio. If the per-token log-ratios δt=log⁡πθ(yt∣⋅)μ(yt∣⋅)\delta_t = \log\frac{\pi_\theta(y_t\mid\cdot)}{\mu(y_t\mid\cdot)} are roughly independent with variance s2s^2, their sum over TT tokens has variance Ts2Ts^2 — its standard deviation grows like T\sqrt T — and w=e∑tδtw = e^{\sum_t\delta_t} is approximately log-normal. A ratio that is correct on average needs E[w]=1\mathbb{E}[w] = 1, i.e. mean log-ratio −Ts2/2-Ts^2/2; then the median of ww is e−Ts2/2→0e^{-Ts^2/2} \to 0 while E[w2]=eTs2\mathbb{E}[w^2] = e^{Ts^2} 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 F(g)=exp⁡(−e−g)F(g) = \exp(-e^{-g}), density e−gexp⁡(−e−g)e^{-g}\exp(-e^{-g}), sampled as g=−log⁡(−log⁡U)g = -\log(-\log U) with U∼Uniform(0,1)U\sim\mathrm{Uniform}(0,1). It is the limiting law of maxima, and it gives the Gumbel-max trick:

arg⁡max⁡i (zi+gi)  ∼  softmax(z),gi∼iidGumbel(0,1).\arg\max_i\,(z_i + g_i) \;\sim\; \mathrm{softmax}(z), \qquad g_i \overset{\text{iid}}{\sim}\mathrm{Gumbel}(0,1).

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 Gumbel(log⁡Z,1)\mathrm{Gumbel}(\log Z, 1), a noisy log-sum-exp, and taking the top kk 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라면 P(C∣pass)=0.5P(C\mid \text{pass}) = 0.5다. 우도비 19가 1:19의 사전 odds를 1:1로 올릴 뿐이다. 정책이 좀처럼 맞히지 못하는 어려운 프롬프트에서는 작은 false-positive 비율이 보상 신호를 지배하고, RL은 정확히 통과하는 것을 최적화한다. verifier에 대한 reward hacking의 확률적 핵심이다(보상과 환경, 과최적화).

구별할 두 개념. p(x,y)=p(x)p(y)p(x,y) = p(x)p(y)이면 XX와 YY는 독립이고, p(x,y∣z)=p(x∣z)p(y∣z)p(x,y\mid z) = p(x\mid z)p(y\mid z)이면 ZZ가 주어졌을 때 조건부 독립이다. 같은 프롬프트에서 뽑은 두 샘플은 프롬프트가 주어지면 조건부 독립이지만 프롬프트를 가로지르면 상관되어 있다. 오차 막대를 계산할 때 중요하다(통계).

연쇄 법칙이 곧 자기회귀 모델이다

곱 규칙을 반복 적용하면 어떤 결합분포에 대해서도, 아무 가정 없이

p(y1,…,yT∣x)=∏t=1Tp(yt∣x,y<t),log⁡p(y∣x)=∑t=1Tlog⁡p(yt∣x,y<t).p(y_1,\dots,y_T\mid x) = \prod_{t=1}^{T} p(y_t\mid x, y_{<t}), \qquad \log p(y\mid x) = \sum_{t=1}^T \log p(y_t\mid x, y_{<t}).

자기회귀 언어 모델은 각 인수를 πθ(yt∣x,y<t)=softmax(logits)yt\pi_\theta(y_t\mid x, y_{<t}) = \mathrm{softmax}(\text{logits})_{y_t}로 매개변수화한 것이다. 인수마다 정규화되어 있으므로 곱은 자동으로 모든 시퀀스 위의 정규화된 분포가 된다(Py 블록이 전수 계산으로 확인한다). 뒤에서 쓰는 결과:

  • 최대우도 학습은 토큰별 cross-entropy의 합이다(언어 모델링).
  • 시퀀스 확률은 길이에 따라 지수적으로 작아진다(토큰당 log-prob이 −0.5-0.5면 1000 토큰에서 e−500e^{-500}). 그래서 모든 것을 로그 공간에서 한다(수치 계산).
  • 두 시퀀스 확률의 비는 토큰별 비의 곱 πθ(y)μ(y)=∏tρt\frac{\pi_\theta(y)}{\mu(y)} = \prod_t \rho_t다. 잡음 섞인 인수를 많이 곱하면 로그정규 비슷한 두꺼운 꼬리가 생긴다. 시퀀스 단위 importance sampling의 핵심 난점이다(off-policy 불일치, 시퀀스 vs 토큰).
  • 조건을 마지막 n−1n-1개 토큰으로 자르는 것이 n-gram 모델의 Markov 가정이다.

자주 만나는 분포

Bernoulli(pp): 0/1 결과, 평균 pp, 분산 p(1−p)p(1-p), p=12p = \tfrac12에서 최대. 검증 가능한 보상은 pp = 그 프롬프트에서 정책의 정답률인 Bernoulli다. GG개 샘플의 그룹에서 보상이 모두 같을 확률은 pG+(1−p)Gp^G + (1-p)^G이고, 그러면 그룹 상대 advantage가 0이다. RLVR에서 난이도 필터링을 하는 이유다. GRPO는 모집단 std가 아니라 관측된 그룹 std로 나눈다. 그룹 정답률 p^=1G∑iri\hat p = \frac1G\sum_i r_i, ddof = 0이면 그 값은 p^(1−p^)\sqrt{\hat p(1-\hat p)}이다(ddof = 1을 쓰는 구현도 있고, 그러면 G/(G−1)\sqrt{G/(G-1)}배 크다). G=4G = 4, p=0.5p = 0.5에서 그룹 [1,1,1,1][1,1,1,1]의 std는 0이지만 모집단 std는 0.5다. p^\hat p가 pp의 추정이므로, 이 나눗셈은 이 분산의 (잡음 섞인) 추정으로 프롬프트의 무게를 바꾼다(시퀀스 vs 토큰).

Binomial(n,pn, p): 독립인 Bernoulli(pp) 시행 nn번의 성공 횟수. P(c)=(nc)pc(1−p)n−cP(c) = \binom{n}{c}p^c(1-p)^{n-c}, 평균 npnp, 분산 np(1−p)np(1-p)(독립 분산 nn개의 합). 프롬프트 하나에서 뽑은 nn개 샘플 중 정답 수이고, pass@k 추정량(통계)과 MiMo-7B 같은 보고서의 모델 비교에 들어가는 입력이다.

Beta(a,ba, b): [0,1][0, 1] 위의 분포로 밀도 ∝pa−1(1−p)b−1\propto p^{a-1}(1-p)^{b-1}, 평균 a/(a+b)a/(a+b). 데이터셋 전체에 퍼진 프롬프트별 통과율의 자연스러운 모델이다(시퀀스 vs 토큰은 “대부분 어려운 프롬프트”를 Beta(0.6, 1.2)로 둔다). 이항분포와 켤레다. pp에 대한 Beta(a,ba, b) 사전분포에 nn번 중 cc번 성공을 더하면 사후분포는 Beta(a+c, b+n−ca + c,\ b + n - c)이고, 그 평균 (c+a)/(n+a+b)(c + a)/(n + a + b)는 가상의 성공 aa번과 실패 bb번을 더한 것이다. 대칭 사전분포 a=ba = b일 때만 add-aa smoothing이다(a=b=1a = b = 1이면 Laplace). 그리고 독립 균등분포 NN개의 최댓값은 Beta(N,1N, 1)이다. best-of-N이 고른 응답의 분위수를 구하는 방법이다.

Categorical(pp): VV개 클래스 위. 다음 토큰 분포이고 p=softmax(z)p = \mathrm{softmax}(z)다. one-hot 인코딩 eYe_Y의 평균은 pp, 공분산은 diag(p)−pp⊤\mathrm{diag}(p) - pp^\top이다.

Gaussian N(μ,σ2)\mathcal{N}(\mu, \sigma^2): 밀도 12πσe−(x−μ)2/2σ2\frac{1}{\sqrt{2\pi}\sigma}e^{-(x-\mu)^2/2\sigma^2}. 질량의 68/95/99.7%가 1/2/3 σ 안에 있다. 아핀 사상과 독립 Gaussian의 합에 닫혀 있고(평균끼리, 분산끼리 더한다), ε∼N(0,1)\varepsilon\sim\mathcal{N}(0,1)로 x=μ+σεx = \mu + \sigma\varepsilon이라 쓸 수 있다. 아래에서 쓰는 reparameterisation이다. 다변량이면 LL⊤=ΣLL^\top = \Sigma인 LL로 x=μ+Lεx = \mu + L\varepsilon.

로그정규(log-normal): X∼N(μ,σ2)X\sim\mathcal{N}(\mu, \sigma^2)이면 eXe^X는 로그정규이고, 완전제곱 x−(x−μ)22σ2=−(x−μ−σ2)22σ2+μ+σ22x - \frac{(x-\mu)^2}{2\sigma^2} = -\frac{(x - \mu - \sigma^2)^2}{2\sigma^2} + \mu + \frac{\sigma^2}{2}에서

E[eX]=eμ+σ2/2,E[e2X]=e2μ+2σ2\mathbb{E}[e^X] = e^{\mu + \sigma^2/2}, \qquad \mathbb{E}[e^{2X}] = e^{2\mu + 2\sigma^2}

이 나온다. 시퀀스 단위 importance ratio의 모델이다. 토큰별 log-ratio δt=log⁡πθ(yt∣⋅)μ(yt∣⋅)\delta_t = \log\frac{\pi_\theta(y_t\mid\cdot)}{\mu(y_t\mid\cdot)}가 대략 독립이고 분산이 s2s^2이면 TT개 토큰의 합은 분산 Ts2Ts^2, 즉 표준편차가 T\sqrt T로 자라고, w=e∑tδtw = e^{\sum_t\delta_t}는 근사적으로 로그정규다. 평균적으로 맞는 ratio라면 E[w]=1\mathbb{E}[w] = 1, 곧 log-ratio 평균이 −Ts2/2-Ts^2/2여야 한다. 그러면 ww의 중앙값은 e−Ts2/2→0e^{-Ts^2/2} \to 0인데 E[w2]=eTs2\mathbb{E}[w^2] = e^{Ts^2}는 폭발한다. 대부분의 시퀀스는 아주 작은 가중치를, 몇 개는 거대한 가중치를 받는다. off-policy 불일치, 불일치 엔지니어링, verl rollout correction, 통계가 분석하는 분산·ESS 붕괴다.

Gumbel(0, 1): CDF F(g)=exp⁡(−e−g)F(g) = \exp(-e^{-g}), 밀도 e−gexp⁡(−e−g)e^{-g}\exp(-e^{-g}), U∼Uniform(0,1)U\sim\mathrm{Uniform}(0,1)로 g=−log⁡(−log⁡U)g = -\log(-\log U)로 뽑는다. 최댓값의 극한 분포이고, Gumbel-max trick을 준다.

arg⁡max⁡i (zi+gi)  ∼  softmax(z),gi∼iidGumbel(0,1).\arg\max_i\,(z_i + g_i) \;\sim\; \mathrm{softmax}(z), \qquad g_i \overset{\text{iid}}{\sim}\mathrm{Gumbel}(0,1).

증명(이긴 logit의 밀도를 나머지들의 CDF와 함께 적분한다)과 딸린 결과들, 즉 잡음 섞인 logit의 최댓값이 Gumbel(log⁡Z,1)\mathrm{Gumbel}(\log Z, 1)(잡음 섞인 log-sum-exp)이라는 것과 argmax 대신 상위 kk개를 고르면 비복원 추출이 된다는 것(Gumbel-top-k)은 극값 레슨에서 다룬다. 여기서는 명제만 쓰고 샘플링으로 확인한다. 그림은 몬테카를로 오차를 보는 창이기도 하다.

N 0 TV(경험empirical, softmax) – TV·√N –
Five tokens with fixed logits z. Each draw adds independent Gumbel(0,1) noise to z/τ and takes the argmax (top: grey = z/τ, coloured = after noise, red = winner). Press +100 a few times: the empirical frequencies (bars) converge to softmax(z/τ) (outlines) — no exponentials, no normalisation, no cumulative sums. Right: the Monte Carlo error falls like 1/√N (dashed line = theory), so TV·√N stays roughly constant; 100× more samples buy one more decimal digit. Change τ to reset and sample a flatter or sharper softmax. logit z가 고정된 토큰 다섯 개. 매 추출은 z/τ에 독립인 Gumbel(0,1) 잡음을 더하고 argmax를 고른다(위: 회색 = z/τ, 색 = 잡음을 더한 값, 빨강 = 승자). +100을 몇 번 눌러 보면 경험 빈도(막대)가 softmax(z/τ)(테두리)로 수렴한다. 지수도, 정규화도, 누적합도 없다. 오른쪽: Monte Carlo 오차는 1/√N으로 줄어들어(점선 = 이론) TV·√N이 대략 일정하다. 샘플을 100배 늘려야 자릿수 하나를 얻는다. τ를 바꾸면 초기화되고 더 평평하거나 뾰족한 softmax를 뽑는다.

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, arg⁡max⁡ipi/Ei\arg\max_i p_i/E_i, 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 μ=Ep[f(X)]\mu = \mathbb{E}_p[f(X)] when the sum or integral is intractable, draw x1,…,xN∼iidpx_1,\dots,x_N \overset{\text{iid}}{\sim} p and average:

μ^N=1N∑i=1Nf(xi),E[μ^N]=μ,sd(μ^N)=σfN.\hat\mu_N = \frac1N\sum_{i=1}^N f(x_i), \qquad \mathbb{E}[\hat\mu_N] = \mu, \qquad \mathrm{sd}(\hat\mu_N) = \frac{\sigma_f}{\sqrt N}.

Unbiasedness is linearity of expectation; the standard deviation is the σ2/n\sigma^2/n rule. Two things to notice. The error depends on σf\sigma_f and NN but not on the dimension of xx — 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 σf\sigma_f instead of NN. The central limit theorem then says μ^N\hat\mu_N is approximately Gaussian, which turns σf/N\sigma_f/\sqrt N into confidence intervals (statistics).

NumPy Moments, Bayes, the chain rule, Gumbel-max, the 1/√N law, log-normal sums
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 ∇θ Ex∼pθ[f(x)]\nabla_\theta\,\mathbb{E}_{x\sim p_\theta}[f(x)], 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 ∇pθ=pθ∇log⁡pθ\nabla p_\theta = p_\theta\nabla\log p_\theta:

∇θ∑xpθ(x)f(x)=∑xpθ(x) ∇θlog⁡pθ(x) f(x)=Ex∼pθ[f(x) ∇θlog⁡pθ(x)].\nabla_\theta\sum_x p_\theta(x) f(x) = \sum_x p_\theta(x)\,\nabla_\theta\log p_\theta(x)\, f(x) = \mathbb{E}_{x\sim p_\theta}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big].

It needs only samples and ∇log⁡pθ\nabla\log p_\theta — ff can be a black box, discontinuous, a 0/1 verifier; xx can be a discrete token sequence (then ∇log⁡pθ(y)=∑t∇log⁡πθ(yt∣y<t)\nabla\log p_\theta(y) = \sum_t\nabla\log\pi_\theta(y_t\mid y_{<t}) by the chain rule). The score has mean zero, E[∇log⁡pθ]=∑x∇pθ(x)=∇1=0\mathbb{E}[\nabla\log p_\theta] = \sum_x\nabla p_\theta(x) = \nabla 1 = 0, so for any constant bb (or any bb that does not depend on the sample itself)

E[(f(x)−b) ∇θlog⁡pθ(x)]=E[f(x) ∇θlog⁡pθ(x)]:\mathbb{E}\big[(f(x) - b)\,\nabla_\theta\log p_\theta(x)\big] = \mathbb{E}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big] :

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 (G−1)/G(G-1)/G.

Reparameterisation (pathwise). If x=gθ(ε)x = g_\theta(\varepsilon) with ε\varepsilon from a fixed distribution — x=μ+σεx = \mu + \sigma\varepsilon for a Gaussian — move the gradient inside:

∇θ Eε[f(gθ(ε))]=Eε[∇xf(x)∣x=gθ(ε) ∇θgθ(ε)].\nabla_\theta\,\mathbb{E}_\varepsilon\big[f(g_\theta(\varepsilon))\big] = \mathbb{E}_\varepsilon\big[\nabla_x f(x)\big|_{x = g_\theta(\varepsilon)}\,\nabla_\theta g_\theta(\varepsilon)\big].

It uses the derivative of ff, which usually makes it much lower-variance — but it requires ff differentiable and xx 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은 확률을 지수분포 잡음으로 나눈 arg⁡max⁡ipi/Ei\arg\max_i p_i/E_i를 쓰는데, 모양만 다른 Gumbel-max다). 그래서 잡음을 고정하면 뽑힌 토큰은 logit의 결정적 함수가 된다. 불일치 엔지니어링의 상황이고, 그 레슨의 시뮬레이션이 정확히 이렇게 샘플링한다. 비복원 추출인 Gumbel-top-k는 MoE 레슨이 치우친 top-k 라우팅 부하를 시뮬레이션하는 방법이다.

몬테카를로 추정

합이나 적분을 계산할 수 없을 때 μ=Ep[f(X)]\mu = \mathbb{E}_p[f(X)]를 구하려면 x1,…,xN∼iidpx_1,\dots,x_N \overset{\text{iid}}{\sim} p를 뽑아 평균한다.

μ^N=1N∑i=1Nf(xi),E[μ^N]=μ,sd(μ^N)=σfN.\hat\mu_N = \frac1N\sum_{i=1}^N f(x_i), \qquad \mathbb{E}[\hat\mu_N] = \mu, \qquad \mathrm{sd}(\hat\mu_N) = \frac{\sigma_f}{\sqrt N}.

불편성은 기댓값의 선형성이고, 표준편차는 σ2/n\sigma^2/n 규칙이다. 주목할 점 둘. 오차는 σf\sigma_f와 NN에 의존하지만 xx의 차원에는 의존하지 않는다. 천 토큰짜리 시퀀스 위에서도 샘플링이 통하는 이유다. 그리고 속도가 느리다. 소수점 한 자리를 더 얻으려면 샘플이 100배 필요하다. 분산 감소(baseline, control variate, importance sampling, 다음 레슨)는 NN 대신 σf\sigma_f를 공략한다. 중심극한정리는 μ^N\hat\mu_N이 근사적으로 Gaussian이라고 말해 주고, 그것이 σf/N\sigma_f/\sqrt N을 신뢰구간으로 바꾼다(통계).

NumPy 적률, 베이즈, 연쇄 법칙, Gumbel-max, 1/√N 법칙, 로그정규 합
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과 변분 방법은 ∇θ Ex∼pθ[f(x)]\nabla_\theta\,\mathbb{E}_{x\sim p_\theta}[f(x)]가 필요하다. 매개변수가 평균을 취하는 분포 안에 있다. 표준 추정량은 둘이다.

Score function(log-derivative trick, REINFORCE). 합 안에서 미분하고 ∇pθ=pθ∇log⁡pθ\nabla p_\theta = p_\theta\nabla\log p_\theta를 쓴다.

∇θ∑xpθ(x)f(x)=∑xpθ(x) ∇θlog⁡pθ(x) f(x)=Ex∼pθ[f(x) ∇θlog⁡pθ(x)].\nabla_\theta\sum_x p_\theta(x) f(x) = \sum_x p_\theta(x)\,\nabla_\theta\log p_\theta(x)\, f(x) = \mathbb{E}_{x\sim p_\theta}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big].

샘플과 ∇log⁡pθ\nabla\log p_\theta만 있으면 된다. ff는 블랙박스여도, 불연속이어도, 0/1 verifier여도 되고, xx는 이산 토큰 시퀀스여도 된다(그러면 연쇄 법칙으로 ∇log⁡pθ(y)=∑t∇log⁡πθ(yt∣y<t)\nabla\log p_\theta(y) = \sum_t\nabla\log\pi_\theta(y_t\mid y_{<t})). score의 평균은 0이다. E[∇log⁡pθ]=∑x∇pθ(x)=∇1=0\mathbb{E}[\nabla\log p_\theta] = \sum_x\nabla p_\theta(x) = \nabla 1 = 0. 그러므로 어떤 상수 bb에 대해서도(또는 샘플 자신에 의존하지 않는 어떤 bb에 대해서도)

E[(f(x)−b) ∇θlog⁡pθ(x)]=E[f(x) ∇θlog⁡pθ(x)].\mathbb{E}\big[(f(x) - b)\,\nabla_\theta\log p_\theta(x)\big] = \mathbb{E}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big] .

baseline은 분산을 바꾸지만 평균은 바꾸지 않는다. 배치의 다른 샘플들의 leave-one-out 평균은 조건을 만족한다(RLOO). 샘플 자신을 포함한 평균은 기대 gradient를 (G−1)/G(G-1)/G배로 줄인다.

Reparameterisation(pathwise). 고정된 분포의 ε\varepsilon으로 x=gθ(ε)x = g_\theta(\varepsilon)이라 쓸 수 있으면(Gaussian이면 x=μ+σεx = \mu + \sigma\varepsilon) gradient를 안으로 넣는다.

∇θ Eε[f(gθ(ε))]=Eε[∇xf(x)∣x=gθ(ε) ∇θgθ(ε)].\nabla_\theta\,\mathbb{E}_\varepsilon\big[f(g_\theta(\varepsilon))\big] = \mathbb{E}_\varepsilon\big[\nabla_x f(x)\big|_{x = g_\theta(\varepsilon)}\,\nabla_\theta g_\theta(\varepsilon)\big].

ff의 도함수를 쓰므로 보통 분산이 훨씬 작다. 하지만 ff가 미분 가능하고 xx가 연속이어야 한다. 계단 함수라면 pathwise 도함수가 거의 모든 곳에서 0이고, 추정량은 그냥 틀린다. 각 추정량을 autograd가 미분할 수 있는 손실로 바꾸는 방법(surrogate 손실, stop-gradient)은 surrogate gradient 레슨의 주제다.

f(x):
참 gradienttrue gradient –
Each histogram is the spread of one estimator across 1500 independent batches of 16 samples (same random numbers for all three). For the smooth x² the reparameterisation gradient (green) is far tighter than the score-function estimator (red), and a baseline (blue) recovers much of the gap. Move μ away from 0 with f = x²: the score estimator's spread grows with f's magnitude, the baseline removes most of that. Now pick 1[x > 0], a 0/1 reward like a verifier: its derivative is 0 almost everywhere, so the reparameterisation estimator collapses to 0 — confidently wrong — while the score function stays unbiased. That is why LLM RL, with discrete tokens and non-differentiable rewards, uses the score function. 각 히스토그램은 표본 16개짜리 독립 배치 1500개에 걸친 추정량 하나의 퍼짐이다(셋 모두 같은 난수). 매끄러운 x²에서는 reparameterisation gradient(초록)가 score-function 추정량(빨강)보다 훨씬 좁고, baseline(파랑)이 그 차이를 상당 부분 메운다. f = x²에서 μ를 0에서 멀리 옮겨 보라. score 추정량의 퍼짐이 f의 크기를 따라 커지고, baseline이 그 대부분을 지운다. 이제 verifier 같은 0/1 보상 1[x > 0]을 고르면, 그 도함수는 거의 모든 곳에서 0이라 reparameterisation 추정량은 0으로 무너진다. 확신에 찬 오답이다. score function은 여전히 불편이다. 이산 토큰과 미분 불가능한 보상을 다루는 LLM RL이 score function을 쓰는 이유다.
NumPy Score function vs reparameterisation: bias and variance
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 x2x^2 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 bb. (Gumbel-softmax is a continuous relaxation that makes discrete samples reparameterisable, at the cost of bias; it is not used for LLM policy gradients.)

확인 문제Check yourself

In REINFORCE you subtract a baseline b from the reward. Which choice of b would bias the gradient?

Unbiasedness needs E[b ∇log⁡pθ(y)]=0\mathbb{E}[b\,\nabla\log p_\theta(y)] = 0, which holds when bb does not depend on yy (it can depend on the prompt xx and on other, independent samples): then bb factors out and E[∇log⁡pθ]=0\mathbb{E}[\nabla\log p_\theta] = 0. If bb depends on yy, the product no longer averages to zero. Using the sample’s own reward as its baseline gives f−f=0f - f = 0: no gradient at all.

Markov chains

A sequence of states s0,s1,…s_0, s_1, \dots is a Markov chain if the next state depends on the past only through the present: P(st+1∣st,st−1,… )=P(st+1∣st)P(s_{t+1}\mid s_t, s_{t-1},\dots) = P(s_{t+1}\mid s_t). With finitely many states the dynamics is a row-stochastic matrix Pij=P(st+1=j∣st=i)P_{ij} = P(s_{t+1} = j\mid s_t = i), and a distribution dtd_t (a row vector) evolves linearly:

dt+1=dtP,dt=d0Pt.d_{t+1} = d_t P, \qquad d_t = d_0 P^t .

A stationary distribution satisfies dP=dd P = d: it is a left eigenvector of PP with eigenvalue 1. If the chain is irreducible and aperiodic, dt→dd_t \to d from any start, at a rate set by the second-largest eigenvalue modulus ∣λ2∣|\lambda_2| (power iteration, eigen/SVD).

An MDP is a Markov chain whose transitions are chosen by actions: P(s′∣s,a)P(s'\mid s, a). Fix a policy π(a∣s)\pi(a\mid s) and it collapses back to a Markov chain with Pπ(s′∣s)=∑aπ(a∣s)P(s′∣s,a)P_\pi(s'\mid s) = \sum_a \pi(a\mid s)P(s'\mid s,a) — 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).

NumPy A Markov chain's stationary distribution
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

  • E\mathbb{E} is linear; E[1A]=P(A)\mathbb{E}[\mathbf 1_A] = P(A); Var(Xˉn)=σ2/n\mathrm{Var}(\bar X_n) = \sigma^2/n 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 p(y)=∏tp(yt∣y<t)p(y) = \prod_t p(y_t\mid y_{<t}) holds for any distribution; an autoregressive LM parameterises its factors. Sequence ratios are products of token ratios.
  • Bernoulli variance p(1−p)p(1-p), Binomial np(1−p)np(1-p), Beta–Binomial conjugacy; Gaussian x=μ+σεx = \mu + \sigma\varepsilon; log-normal EeX=eμ+σ2/2\mathbb{E}e^X = e^{\mu+\sigma^2/2}, so a sum of TT token log-ratios gives sequence weights with Ew2=eTs2\mathbb{E}w^2 = e^{Ts^2}; Gumbel-max: arg⁡max⁡(z+g)∼softmax(z)\arg\max(z + g) \sim \mathrm{softmax}(z).
  • Monte Carlo error is σf/N\sigma_f/\sqrt N, dimension-free.
  • ∇Epθ[f]=E[f∇log⁡pθ]\nabla\mathbb{E}_{p_\theta}[f] = \mathbb{E}[f\nabla\log p_\theta]; the score has mean zero, so baselines are free. Reparameterisation is lower-variance but needs differentiable ff and continuous xx.
  • Markov chain: dt+1=dtPd_{t+1} = d_tP, stationary dP=ddP = d; a fixed policy turns an MDP into one.

Where this is used

NumPy Score function vs reparameterisation: 편향과 분산
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은 편향을 더하지 않는다)")
 

x2x^2에서는 셋 다 불편이고 pathwise 추정량의 표준편차가 순수 score function의 절반쯤이다. 0/1 보상에서는 pathwise 추정량이 분산 0으로 정확히 0을 낸다. 완벽하게 확신하면서 틀린다. score function은 여전히 불편이다. 토큰은 이산이고 verifier는 계단 함수이므로 LLM RL은 score function 쪽에 산다. 정책 경사가 바로 이 항등식에서 REINFORCE와 baseline을 유도하고, GRPO/RLOO는 bb를 고르는 방식이다. (Gumbel-softmax는 이산 샘플을 reparameterise할 수 있게 만드는 연속 완화인데, 편향이 생긴다. LLM 정책 경사에는 쓰이지 않는다.)

확인 문제Check yourself

REINFORCE에서 보상에서 baseline b를 뺀다. 어떤 b가 gradient를 편향시키는가?

불편이려면 E[b ∇log⁡pθ(y)]=0\mathbb{E}[b\,\nabla\log p_\theta(y)] = 0이어야 하고, 이는 bb가 yy에 의존하지 않을 때 성립한다(프롬프트 xx나 다른 독립 샘플에는 의존해도 된다). 그러면 bb가 밖으로 나오고 E[∇log⁡pθ]=0\mathbb{E}[\nabla\log p_\theta] = 0이다. bb가 yy에 의존하면 곱의 평균이 더는 0이 아니다. 샘플 자신의 보상을 baseline으로 쓰면 f−f=0f - f = 0, gradient가 아예 없다.

마르코프 연쇄(Markov chain)

상태열 s0,s1,…s_0, s_1, \dots에서 다음 상태가 과거에 현재를 통해서만 의존하면, 즉 P(st+1∣st,st−1,… )=P(st+1∣st)P(s_{t+1}\mid s_t, s_{t-1},\dots) = P(s_{t+1}\mid s_t)이면 Markov chain이다. 상태가 유한하면 동역학은 행 확률 행렬 Pij=P(st+1=j∣st=i)P_{ij} = P(s_{t+1} = j\mid s_t = i)이고, 분포 dtd_t(행 벡터)는 선형으로 움직인다.

dt+1=dtP,dt=d0Pt.d_{t+1} = d_t P, \qquad d_t = d_0 P^t .

정상 분포(stationary distribution) 는 dP=dd P = d를 만족한다. 고유값 1인 PP의 왼쪽 고유벡터다. 체인이 기약(irreducible)이고 비주기적이면 어디서 출발해도 dt→dd_t \to d이고, 그 속도는 두 번째로 큰 고유값의 절댓값 ∣λ2∣|\lambda_2|가 정한다(거듭제곱법, 고유값·SVD).

MDP는 행동이 전이를 고르는 Markov chain이다: P(s′∣s,a)P(s'\mid s, a). 정책 π(a∣s)\pi(a\mid s)를 고정하면 다시 Markov chain Pπ(s′∣s)=∑aπ(a∣s)P(s′∣s,a)P_\pi(s'\mid s) = \sum_a \pi(a\mid s)P(s'\mid s,a)가 된다. Bellman 방정식이 쓰이는 대상이다(MDP). 텍스트를 생성하는 LLM은 상태를 prefix 전체로 두면 자명하게 Markov다. agent RL은 상태를 상호작용 이력 전체로 두어 그 성질을 지킨다(agent RL).

NumPy Markov chain의 정상 분포
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|가 정한다")
 

정리

  • E\mathbb{E}는 선형이다. E[1A]=P(A)\mathbb{E}[\mathbf 1_A] = P(A). 독립 표본이면 Var(Xˉn)=σ2/n\mathrm{Var}(\bar X_n) = \sigma^2/n, 양의 상관이 있으면 더 크다. 공분산 행렬은 PSD다.
  • odds로 쓴 베이즈: 사후 odds = 사전 odds × 우도비. base rate가 낮으면 작은 false-positive 비율이 지배한다.
  • 연쇄 법칙 p(y)=∏tp(yt∣y<t)p(y) = \prod_t p(y_t\mid y_{<t})는 어떤 분포에도 성립하고, 자기회귀 LM은 그 인수를 매개변수화한다. 시퀀스 비는 토큰 비의 곱이다.
  • Bernoulli 분산 p(1−p)p(1-p), Binomial np(1−p)np(1-p), Beta–Binomial 켤레성. Gaussian x=μ+σεx = \mu + \sigma\varepsilon. 로그정규 EeX=eμ+σ2/2\mathbb{E}e^X = e^{\mu+\sigma^2/2}이므로 토큰 log-ratio TT개의 합은 Ew2=eTs2\mathbb{E}w^2 = e^{Ts^2}인 시퀀스 가중치를 준다. Gumbel-max: arg⁡max⁡(z+g)∼softmax(z)\arg\max(z + g) \sim \mathrm{softmax}(z).
  • 몬테카를로 오차는 σf/N\sigma_f/\sqrt N이고 차원과 무관하다.
  • ∇Epθ[f]=E[f∇log⁡pθ]\nabla\mathbb{E}_{p_\theta}[f] = \mathbb{E}[f\nabla\log p_\theta]. score의 평균이 0이라 baseline은 공짜다. reparameterisation은 분산이 작지만 미분 가능한 ff와 연속인 xx가 필요하다.
  • Markov chain: dt+1=dtPd_{t+1} = d_tP, 정상 분포 dP=ddP = d. 정책을 고정하면 MDP가 Markov chain이 된다.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading