Track I · ML Fundamentals · 03/09

확률로 보는 손실Losses through probability

MSE와 cross-entropy가 임의로 고른 손실이 아니라 최대우도에서 나온다는 것을 유도하고, entropy·cross-entropy·KL의 관계와 KL의 비대칭(mode-covering vs mode-seeking)이 LLM 사전학습과 RLHF에서 각각 무엇을 뜻하는지 설명할 수 있게 된다.Derive that MSE and cross-entropy are not arbitrary choices but come from maximum likelihood, and explain the relation between entropy, cross-entropy and KL, and what the asymmetry of KL (mode-covering vs mode-seeking) means for LLM pre-training and for RLHF.

35 분min MLE · negative log-likelihood · cross-entropy · entropy · KL divergence · forward KL · reverse KL 먼저 볼 것:Before this: 학습이란 무엇인가What is learning?

In the first lesson the loss ℓ\ell was “given”: squared error for regression, cross-entropy for classification. But why these in particular? The answer comes down to one principle: view the model as a probability distribution, and maximise the probability of the observed data. From this single viewpoint we derive MSE and cross-entropy, and the same line of reasoning explains why the LLM pre-training loss is “the −log⁡-\log probability of the next token” and why the RLHF KL penalty points the way it does.

Maximum likelihood estimation

Suppose the model outputs a conditional distribution pθ(y∣x)p_\theta(y \mid x) over outputs yy. If the data {(xi,yi)}i=1n\{(x_i, y_i)\}_{i=1}^n are i.i.d., the probability of seeing this data, the likelihood, is a product.

L(θ)=∏i=1npθ(yi∣xi)\mathcal{L}(\theta) = \prod_{i=1}^{n} p_\theta(y_i \mid x_i)

Maximum likelihood estimation (MLE) picks the θ\theta that maximises it. A product quickly underflows to 0 and is awkward to differentiate, so we take the log, flip the sign to make it a minimisation problem, and divide by nn. The log is monotonically increasing, so the optimum does not move.

θ^MLE=arg⁡min⁡θ  −1n∑i=1nlog⁡pθ(yi∣xi)⏟NLL (negative log-likelihood)\hat\theta_{\text{MLE}} = \arg\min_\theta \; \underbrace{-\frac1n \sum_{i=1}^n \log p_\theta(y_i \mid x_i)}_{\text{NLL (negative log-likelihood)}}

This is exactly the ERM of the first lesson with the loss ℓ=−log⁡pθ(y∣x)\ell = -\log p_\theta(y \mid x). Now we only need to choose the shape of pθp_\theta, and the loss follows automatically.

Gaussian → MSE

Assume the regression model fθ(x)f_\theta(x) outputs the mean and the noise is Gaussian with variance σ2\sigma^2. Since pθ(y∣x)=N(y; fθ(x),σ2)p_\theta(y \mid x) = \mathcal{N}(y;\, f_\theta(x), \sigma^2),

−log⁡pθ(y∣x)=(y−fθ(x))22σ2+12log⁡(2πσ2).-\log p_\theta(y \mid x) = \frac{(y - f_\theta(x))^2}{2\sigma^2} + \frac12 \log(2\pi\sigma^2).

If σ\sigma is fixed, the second term is a constant and the first is the squared error times a constant. MLE under Gaussian noise = least squares. Conversely, the moment you use MSE you have assumed that “the residuals are Gaussian with the same variance everywhere”. That is why MSE is fragile on data with many outliers: the Gaussian has thin tails, so it treats large residuals as extremely rare and pulls the model hard to get rid of them. Assuming a Laplace distribution, the same logic yields the absolute-error loss (MAE).

Bernoulli → binary cross-entropy

If y∈{0,1}y \in \{0, 1\} and the model outputs p=pθ(y=1∣x)p = p_\theta(y{=}1 \mid x), then pθ(y∣x)=py(1−p)1−yp_\theta(y \mid x) = p^{y}(1-p)^{1-y} and

−log⁡pθ(y∣x)=−[ ylog⁡p+(1−y)log⁡(1−p) ].-\log p_\theta(y \mid x) = -\big[\, y \log p + (1 - y)\log(1 - p) \,\big].

Categorical → cross-entropy

If y∈{1,…,K}y \in \{1, \dots, K\} and the model outputs a probability vector q=(q1,…,qK)q = (q_1, \dots, q_K), only the probability of the correct answer remains.

−log⁡pθ(y∣x)=−log⁡qy=−∑k=1K1[k=y]log⁡qk-\log p_\theta(y \mid x) = -\log q_y = -\sum_{k=1}^{K} \mathbb{1}[k = y] \log q_k

The last form is “the cross-entropy between the one-hot target distribution and qq”. The LLM next-token loss is exactly this; the vocabulary size is KK and the target is just the actual next token yty_t.

Information, entropy, cross-entropy, KL

The quantity −log⁡q-\log q has an information-theoretic name: the surprisal, or information content, of an event with probability qq. An event of probability 1 carries 0 nats, and the rarer the event, the larger it is (nats with base ee, bits with base 2).

  • Entropy H(p)=−∑kpklog⁡pkH(p) = -\sum_k p_k \log p_k: the average length of the best lossless compression of samples from pp (Shannon’s source coding theorem). The optimal code spends −log⁡pk-\log p_k on outcome kk, so this is also the average surprisal — the uncertainty of pp itself: 0 for a one-hot (nothing to send), maximal at log⁡K\log K for the uniform distribution (nothing to compress). See Information theory for the derivation.
  • Cross-entropy H(p,q)=−∑kpklog⁡qkH(p, q) = -\sum_k p_k \log q_k: the average surprisal when events actually come from pp but you believe qq. In compression terms, it is the average length when encoding samples of pp with a code fitted to qq.
  • KL divergence KL(p ∥ q)=∑kpklog⁡pkqk\mathrm{KL}(p \,\|\, q) = \sum_k p_k \log \frac{p_k}{q_k}: the difference — the extra surprisal caused by the wrong belief.
H(p,q)=H(p)+KL(p ∥ q)H(p, q) = H(p) + \mathrm{KL}(p \,\|\, q)

KL is always non-negative, and zero only when p=qp = q (Gibbs’ inequality). Since log⁡\log is concave, it follows directly from Jensen’s inequality.

−KL(p ∥ q)=∑kpklog⁡qkpk  ≤  log⁡∑kpkqkpk=log⁡∑k: pk>0qk  ≤  log⁡1=0-\mathrm{KL}(p\,\|\,q) = \sum_k p_k \log \frac{q_k}{p_k} \;\le\; \log \sum_k p_k \frac{q_k}{p_k} = \log \sum_{k:\,p_k>0} q_k \;\le\; \log 1 = 0

So cross-entropy is minimised at q=pq = p, and its minimum is H(p)H(p). This H(p)H(p) is exactly the “noise floor” of the first lesson: no model can reduce the uncertainty in the data itself.

첫 레슨에서 손실 ℓ\ell은 “주어진 것”이었다. 회귀에는 제곱 오차, 분류에는 cross-entropy. 그런데 왜 하필 이것들인가? 답은 하나의 원리로 정리된다. 모델을 확률분포로 보고, 관측된 데이터의 확률을 최대화하라. 이 관점 하나로 MSE와 cross-entropy가 유도되고, LLM 사전학습 손실이 왜 “다음 토큰의 −log⁡-\log 확률”인지, RLHF의 KL 페널티가 왜 그 방향인지까지 한 줄로 이어진다.

최대우도 추정

모델이 출력 yy에 대한 조건부 분포 pθ(y∣x)p_\theta(y \mid x)를 내놓는다고 하자. 데이터 {(xi,yi)}i=1n\{(x_i, y_i)\}_{i=1}^n가 i.i.d.라면 이 데이터가 나올 확률, 즉 우도(likelihood) 는 곱이다.

L(θ)=∏i=1npθ(yi∣xi)\mathcal{L}(\theta) = \prod_{i=1}^{n} p_\theta(y_i \mid x_i)

최대우도 추정(MLE, maximum likelihood estimation) 은 이것을 최대화하는 θ\theta를 고른다. 곱은 숫자가 금방 0으로 사라지고 미분도 불편하니 로그를 씌우고, 최소화 문제로 바꾸려 부호를 뒤집고, nn으로 나눈다. 로그는 단조증가라서 최적점은 그대로다.

θ^MLE=arg⁡min⁡θ  −1n∑i=1nlog⁡pθ(yi∣xi)⏟NLL (negative log-likelihood)\hat\theta_{\text{MLE}} = \arg\min_\theta \; \underbrace{-\frac1n \sum_{i=1}^n \log p_\theta(y_i \mid x_i)}_{\text{NLL (negative log-likelihood)}}

이것은 정확히 첫 레슨의 ERM에 손실 ℓ=−log⁡pθ(y∣x)\ell = -\log p_\theta(y \mid x)를 넣은 것이다. 이제 pθp_\theta의 모양만 정하면 손실이 저절로 나온다.

가우시안 → MSE

회귀 모델 fθ(x)f_\theta(x)가 평균을 내고 잡음은 분산 σ2\sigma^2의 가우시안이라고 가정하자. pθ(y∣x)=N(y; fθ(x),σ2)p_\theta(y \mid x) = \mathcal{N}(y;\, f_\theta(x), \sigma^2)이므로

−log⁡pθ(y∣x)=(y−fθ(x))22σ2+12log⁡(2πσ2).-\log p_\theta(y \mid x) = \frac{(y - f_\theta(x))^2}{2\sigma^2} + \frac12 \log(2\pi\sigma^2).

σ\sigma가 고정이면 둘째 항은 상수이고 첫째 항은 제곱 오차에 상수배다. 가우시안 잡음 가정 아래의 MLE = 최소제곱이다. 거꾸로 말하면, MSE를 쓰는 순간 “잔차는 가우시안이고 분산은 어디서나 같다”고 가정한 셈이다. 이상치가 많은 데이터에 MSE가 약한 이유가 이것이다. 가우시안은 꼬리가 얇아서 큰 잔차를 극도로 드물다고 보고, 그것을 없애려고 모델을 크게 끌어당긴다. 라플라스 분포를 가정하면 같은 논리로 절댓값 손실(MAE)이 나온다.

베르누이 → binary cross-entropy

y∈{0,1}y \in \{0, 1\}이고 모델이 p=pθ(y=1∣x)p = p_\theta(y{=}1 \mid x)를 낸다면 pθ(y∣x)=py(1−p)1−yp_\theta(y \mid x) = p^{y}(1-p)^{1-y}이고

−log⁡pθ(y∣x)=−[ ylog⁡p+(1−y)log⁡(1−p) ].-\log p_\theta(y \mid x) = -\big[\, y \log p + (1 - y)\log(1 - p) \,\big].

범주형 → cross-entropy

y∈{1,…,K}y \in \{1, \dots, K\}이고 모델이 확률 벡터 q=(q1,…,qK)q = (q_1, \dots, q_K)를 낸다면, 정답의 확률 하나만 남는다.

−log⁡pθ(y∣x)=−log⁡qy=−∑k=1K1[k=y]log⁡qk-\log p_\theta(y \mid x) = -\log q_y = -\sum_{k=1}^{K} \mathbb{1}[k = y] \log q_k

마지막 꼴이 “원-핫 정답 분포와 qq의 cross-entropy”다. LLM의 다음 토큰 손실이 정확히 이것이다. 어휘 크기가 KK이고 정답이 실제 다음 토큰 yty_t일 뿐이다.

정보량, entropy, cross-entropy, KL

−log⁡q-\log q라는 양에는 정보이론적인 이름이 있다. 확률 qq인 사건의 놀람(surprisal) 혹은 정보량이다. 확률 1인 사건은 0 nat, 드문 사건일수록 크다(밑이 ee면 nat, 2면 bit).

  • Entropy H(p)=−∑kpklog⁡pkH(p) = -\sum_k p_k \log p_k: pp의 표본을 가장 효율적으로 무손실 압축했을 때의 평균 길이(Shannon의 원천 부호화 정리). 최적 부호는 결과 kk에 −log⁡pk-\log p_k를 쓰므로 이는 평균 놀람이기도 하다. pp 자체의 불확실성이다. 원-핫이면 0(보낼 것이 없음), 균등이면 최대 log⁡K\log K(압축할 여지가 없음). 유도는 정보 이론에 있다.
  • Cross-entropy H(p,q)=−∑kpklog⁡qkH(p, q) = -\sum_k p_k \log q_k: 실제로는 pp에서 사건이 나오는데 qq라고 믿고 놀랄 때의 평균 놀람. 압축으로 말하면, qq에 맞춘 부호로 pp의 표본을 부호화할 때의 평균 길이다.
  • KL divergence KL(p ∥ q)=∑kpklog⁡pkqk\mathrm{KL}(p \,\|\, q) = \sum_k p_k \log \frac{p_k}{q_k}: 그 차이. 틀린 믿음 때문에 추가로 드는 놀람이다.
H(p,q)=H(p)+KL(p ∥ q)H(p, q) = H(p) + \mathrm{KL}(p \,\|\, q)

KL은 항상 0 이상이고, p=qp = q일 때만 0이다(Gibbs 부등식). log⁡\log가 오목하므로 Jensen 부등식으로 바로 나온다.

−KL(p ∥ q)=∑kpklog⁡qkpk  ≤  log⁡∑kpkqkpk=log⁡∑k: pk>0qk  ≤  log⁡1=0-\mathrm{KL}(p\,\|\,q) = \sum_k p_k \log \frac{q_k}{p_k} \;\le\; \log \sum_k p_k \frac{q_k}{p_k} = \log \sum_{k:\,p_k>0} q_k \;\le\; \log 1 = 0

따라서 cross-entropy는 q=pq = p에서 최소가 되고 그 최솟값은 H(p)H(p)다. 이 H(p)H(p)가 바로 첫 레슨의 “잡음 바닥”에 해당한다. 데이터 자체의 불확실성은 어떤 모델로도 줄일 수 없다.

H(p) – H(q) – H(p,q) – KL(p‖q) – KL(q‖p) – perplexity eH(p,q) –
Drag the bars up and down to change p (data, blue) and q (model, red). The other bars shrink or grow proportionally so the sum stays 1. The bars below stack H(p,q) = H(p) + KL(p‖q) literally (unit: nat). KL is 0 only when q = p, and the two directions of KL usually differ. Press "p = one-hot" and the cross-entropy reduces to −log q of the target token, while KL(q‖p) becomes ∞. 막대를 위아래로 끌어 p(데이터, 파랑)와 q(모델, 빨강)를 바꿔 보세요. 다른 막대는 합이 1이 되도록 비례해서 줄거나 늘어난다. 아래 막대는 H(p,q) = H(p) + KL(p‖q)를 그대로 쌓은 것이다(단위: nat). q = p일 때만 KL이 0이 되고, 두 방향의 KL은 대개 다르다. "p = 원-핫"을 누르면 cross-entropy가 정답 토큰의 −log q로 줄어들고, KL(q‖p)는 ∞가 된다.
  1. In the initial state KL(p‖q) ≈ 0.26 and KL(q‖p) ≈ 0.16 — they differ. q underestimates the tail of p (‘sat’, ‘ran’), and forward KL penalises that more heavily.
  2. Press “q misses a mode” and KL(p‖q) jumps. Where p puts a lot of probability and q is almost 0, pklog⁡(pk/qk)p_k \log(p_k/q_k) blows up.
  3. Press “p = one-hot” and H(p) = 0, so cross-entropy and KL(p‖q) become equal: both are the correct token’s −log⁡qcat-\log q_{\text{cat}}. KL(q‖p), on the other hand, is ∞, because q puts probability on tokens where p = 0.
  4. Perplexity eH(p,q)e^{H(p,q)} can be read as “how many tokens the model is, on average, hesitating between”. With q uniform it is exactly 6.

MLE is forward-KL minimisation

Consider the empirical distribution p^\hat p of the data (a distribution with mass 1/n1/n on each observed sample). The NLL can be written as an expectation under p^\hat p.

−1n∑i=1nlog⁡qθ(yi)=Ey∼p^[−log⁡qθ(y)]=H(p^,qθ)=H(p^)+KL(p^ ∥ qθ)-\frac1n\sum_{i=1}^n \log q_\theta(y_i) = \mathbb{E}_{y \sim \hat p}\big[-\log q_\theta(y)\big] = H(\hat p, q_\theta) = H(\hat p) + \mathrm{KL}(\hat p \,\|\, q_\theta)

H(p^)H(\hat p) does not depend on θ\theta, so minimising NLL = minimising KL(p^ ∥ qθ)\mathrm{KL}(\hat p \,\|\, q_\theta). This direction, with the data distribution first, is called forward KL. As n→∞n \to \infty, p^→pdata\hat p \to p_{\text{data}}, so MLE fits the model to the data distribution in forward KL.

The same holds for conditional models. A language model’s per-token loss is Ex∼data[H(pdata(⋅∣x), pθ(⋅∣x))]\mathbb{E}_{x \sim \text{data}}\big[H(p_{\text{data}}(\cdot \mid x),\, p_\theta(\cdot \mid x))\big], and its lower bound is the conditional entropy of the text itself. This is why pre-training loss curves converge towards some value rather than 0, and why scaling laws contain an “irreducible loss” term.

The asymmetry of KL: what goes on which side

KL is not a distance. KL(p ∥ q)≠KL(q ∥ p)\mathrm{KL}(p\,\|\,q) \ne \mathrm{KL}(q\,\|\,p), and when the shape of the approximating distribution qq is restricted (say, to a single Gaussian), which direction you minimise gives completely different answers.

  • Forward KL(p ∥ q)=Ep[log⁡p−log⁡q]\mathrm{KL}(p\,\|\,q) = \mathbb{E}_{p}[\log p - \log q]: the expectation is taken under pp. Where pp has mass and q≈0q \approx 0, −log⁡q→∞-\log q \to \infty, an infinite penalty. So qq spreads wide to cover every mode of pp. This is called mode-covering (or zero-avoiding).
  • Reverse KL(q ∥ p)=Eq[log⁡q−log⁡p]\mathrm{KL}(q\,\|\,p) = \mathbb{E}_{q}[\log q - \log p]: the expectation is taken under qq. Places where qq has no mass are never evaluated at all. Instead, if qq puts mass where p≈0p \approx 0, the penalty is infinite. So qq hides safely inside one mode. This is called mode-seeking (or zero-forcing).

Minimising forward KL with a Gaussian q=N(μ,σ2)q = \mathcal N(\mu, \sigma^2) has a closed-form answer. Differentiating −Ep[log⁡q]=12log⁡(2πσ2)+Ep[(x−μ)2]/(2σ2)-\mathbb{E}_p[\log q] = \tfrac12\log(2\pi\sigma^2) + \mathbb{E}_p[(x-\mu)^2]/(2\sigma^2) with respect to μ\mu and σ\sigma and setting it to 0 gives

μ⋆=Ep[x],σ⋆2=Var⁡p[x].\mu^\star = \mathbb{E}_p[x], \qquad \sigma^{\star 2} = \operatorname{Var}_p[x].

That is moment matching. For p=12N(−d,1)+12N(d,1)p = \tfrac12\mathcal N(-d, 1) + \tfrac12\mathcal N(d, 1), μ⋆=0\mu^\star = 0 and σ⋆2=1+d2\sigma^{\star 2} = 1 + d^2. The peak of qq lands in the valley between the two humps, where pp is almost 0.

Reverse KL has no closed-form solution, but the limit where the modes are far apart can be computed. Place q=N(d,1)q = \mathcal N(d, 1) exactly on top of the right mode; where qq has mass, p(x)≈(1−w) N(x;d,1)=(1−w) q(x)p(x) \approx (1-w)\,\mathcal N(x; d, 1) = (1-w)\,q(x), so

KL(q ∥ p)≈Eq[log⁡q(1−w) q]=−log⁡(1−w).\mathrm{KL}(q\,\|\,p) \approx \mathbb{E}_q\Big[\log \frac{q}{(1-w)\,q}\Big] = -\log(1 - w).

With w=1/2w = 1/2 this is log⁡2≈0.693\log 2 \approx 0.693. A wide qq pays a penalty for putting mass in the valley, so once the modes are far enough apart, hiding in one mode wins. Watch that transition in the figure below.

  1. 처음 상태에서 KL(p‖q) ≈ 0.26, KL(q‖p) ≈ 0.16으로 서로 다르다. q가 p의 꼬리(‘sat’, ‘ran’)를 과소평가하고 있고, forward KL은 이것을 더 무겁게 벌한다.
  2. “q가 모드를 놓침” 을 누르면 KL(p‖q)가 크게 뛴다. p가 확률을 많이 둔 곳에서 q가 거의 0이면 pklog⁡(pk/qk)p_k \log(p_k/q_k)가 폭발한다.
  3. “p = 원-핫” 을 누르면 H(p) = 0이 되고 cross-entropy와 KL(p‖q)가 같아진다. 둘 다 정답 토큰의 −log⁡qcat-\log q_{\text{cat}}이다. 반면 KL(q‖p)는 ∞다. q가 p=0인 토큰에 확률을 두기 때문이다.
  4. perplexity eH(p,q)e^{H(p,q)}는 “모델이 평균적으로 몇 개의 토큰 사이에서 고민하는가”로 읽을 수 있다. q = 균등이면 정확히 6이다.

MLE는 forward KL 최소화다

데이터의 경험분포 p^\hat p(관측된 표본마다 1/n1/n씩 질량을 둔 분포)를 생각하자. NLL은 p^\hat p에 대한 기댓값으로 쓸 수 있다.

−1n∑i=1nlog⁡qθ(yi)=Ey∼p^[−log⁡qθ(y)]=H(p^,qθ)=H(p^)+KL(p^ ∥ qθ)-\frac1n\sum_{i=1}^n \log q_\theta(y_i) = \mathbb{E}_{y \sim \hat p}\big[-\log q_\theta(y)\big] = H(\hat p, q_\theta) = H(\hat p) + \mathrm{KL}(\hat p \,\|\, q_\theta)

H(p^)H(\hat p)는 θ\theta와 무관하므로 NLL 최소화 = KL(p^ ∥ qθ)\mathrm{KL}(\hat p \,\|\, q_\theta) 최소화다. 데이터 분포가 앞에 오는 이 방향을 forward KL이라 부른다. n→∞n \to \infty이면 p^→pdata\hat p \to p_{\text{data}}이니 MLE는 모델을 데이터 분포에 forward KL로 맞추는 일이다.

조건부 모델도 마찬가지다. 언어 모델의 토큰당 손실은 Ex∼data[H(pdata(⋅∣x), pθ(⋅∣x))]\mathbb{E}_{x \sim \text{data}}\big[H(p_{\text{data}}(\cdot \mid x),\, p_\theta(\cdot \mid x))\big]이고, 그 하한은 텍스트 자체의 조건부 entropy다. 사전학습 loss 곡선이 0이 아니라 어떤 값으로 수렴해 가는 이유, 그리고 스케일링 법칙에 “줄일 수 없는 손실(irreducible loss)” 항이 들어가는 이유가 이것이다.

KL의 비대칭: 어느 쪽에 무엇을 놓는가

KL은 거리가 아니다. KL(p ∥ q)≠KL(q ∥ p)\mathrm{KL}(p\,\|\,q) \ne \mathrm{KL}(q\,\|\,p)이고, 근사 분포 qq의 모양이 제한되어 있을 때(예를 들어 가우시안 하나) 어느 방향을 최소화하느냐에 따라 전혀 다른 답이 나온다.

  • Forward KL(p ∥ q)=Ep[log⁡p−log⁡q]\mathrm{KL}(p\,\|\,q) = \mathbb{E}_{p}[\log p - \log q]: 기댓값을 pp로 잰다. pp가 질량을 둔 곳에서 q≈0q \approx 0이면 −log⁡q→∞-\log q \to \infty라 무한대 벌점이다. 그래서 qq는 pp의 모든 모드를 덮으려고 넓게 퍼진다. 이것을 mode-covering(혹은 zero-avoiding)이라 부른다.
  • Reverse KL(q ∥ p)=Eq[log⁡q−log⁡p]\mathrm{KL}(q\,\|\,p) = \mathbb{E}_{q}[\log q - \log p]: 기댓값을 qq로 잰다. qq가 질량을 두지 않은 곳은 아예 평가되지 않는다. 대신 p≈0p \approx 0인 곳에 qq가 질량을 두면 무한대 벌점이다. 그래서 qq는 한 모드 안에 안전하게 숨는다. 이것을 mode-seeking(혹은 zero-forcing)이라 부른다.

가우시안 q=N(μ,σ2)q = \mathcal N(\mu, \sigma^2)로 forward KL을 최소화하면 답이 닫힌 꼴로 나온다. −Ep[log⁡q]=12log⁡(2πσ2)+Ep[(x−μ)2]/(2σ2)-\mathbb{E}_p[\log q] = \tfrac12\log(2\pi\sigma^2) + \mathbb{E}_p[(x-\mu)^2]/(2\sigma^2)를 μ\mu, σ\sigma로 미분해 0으로 놓으면

μ⋆=Ep[x],σ⋆2=Var⁡p[x].\mu^\star = \mathbb{E}_p[x], \qquad \sigma^{\star 2} = \operatorname{Var}_p[x].

모멘트 매칭이다. p=12N(−d,1)+12N(d,1)p = \tfrac12\mathcal N(-d, 1) + \tfrac12\mathcal N(d, 1)이면 μ⋆=0\mu^\star = 0, σ⋆2=1+d2\sigma^{\star 2} = 1 + d^2. 두 봉우리 사이의 골짜기, 즉 pp가 거의 0인 곳에 qq의 꼭대기가 놓인다.

Reverse KL에는 닫힌 해가 없지만 모드가 멀리 떨어진 극한은 계산할 수 있다. q=N(d,1)q = \mathcal N(d, 1)을 오른쪽 모드에 정확히 겹쳐 놓으면, qq가 질량을 두는 곳에서는 p(x)≈(1−w) N(x;d,1)=(1−w) q(x)p(x) \approx (1-w)\,\mathcal N(x; d, 1) = (1-w)\,q(x)이므로

KL(q ∥ p)≈Eq[log⁡q(1−w) q]=−log⁡(1−w).\mathrm{KL}(q\,\|\,p) \approx \mathbb{E}_q\Big[\log \frac{q}{(1-w)\,q}\Big] = -\log(1 - w).

w=1/2w = 1/2이면 log⁡2≈0.693\log 2 \approx 0.693. 넓게 퍼진 qq는 골짜기에 질량을 두는 벌점을 받으므로, 모드가 충분히 떨어지면 한 모드에 숨는 쪽이 이긴다. 아래 그림에서 그 전환을 직접 보자.

forward 최적forward optimum μ=– σ=– reverse 최적reverse optimum μ=– σ=–
p (grey) is a mixture of two Gaussians; q is a single Gaussian. Blue is the q that minimises KL(p‖q), red the one that minimises KL(q‖p). As d grows, forward KL spreads wide to cover both humps (mode-covering), while reverse KL picks one hump and hides inside it (mode-seeking). The two maps below show the KL value over (μ, log σ) (darker = smaller). The reverse-KL map develops two valleys. Moving w changes which hump wins. Click a map to draw the q at that (μ, σ) in violet. p(회색)는 두 가우시안의 혼합, q는 가우시안 하나다. 파랑은 KL(p‖q)를, 빨강은 KL(q‖p)를 최소화한 q다. d를 키우면 forward KL은 두 봉우리를 모두 덮으려고 넓게 퍼지고(mode-covering), reverse KL은 한 봉우리를 골라 그 안에 숨는다(mode-seeking). 아래 두 지도는 (μ, log σ)에 대한 KL 값이다(어두울수록 작음). reverse KL 지도에는 골짜기가 두 개 생긴다. w를 움직이면 어느 봉우리가 이기는지 바뀐다. 지도를 클릭하면 그 (μ, σ)의 q가 보라색으로 그려진다.
  1. Raise d slowly from 0. While d is small the two solutions are almost the same (pp looks like a single hump).
  2. Around d ≈ 2.8 the reverse-KL solution (red) suddenly jumps to one of the humps. It is the moment the single valley in the right-hand map splits in two. Blue (forward) keeps widening continuously.
  3. Lower w to 0.4 and reverse KL picks the heavier right mode. Its KL value is close to −log⁡0.6≈0.51-\log 0.6 \approx 0.51.
  4. In the right-hand map, click the valley that was not chosen. It is also a local minimum. Minimising reverse KL by gradient descent gets stuck in one of the two depending on the initialisation.

Computing it

NumPy Entropy, cross-entropy, KL, and MLE
import numpy as np

def entropy(p):
    p = np.asarray(p, float)
    nz = p > 0                                  # 0 log 0 = 0
    return -np.sum(p[nz] * np.log(p[nz]))

def cross_entropy(p, q):
    p, q = np.asarray(p, float), np.asarray(q, float)
    nz = p > 0
    with np.errstate(divide="ignore"):
        return -np.sum(p[nz] * np.log(q[nz]))   # inf if p>0 where q=0

def kl(p, q):
    return cross_entropy(p, q) - entropy(p)

p = np.array([0.34, 0.22, 0.18, 0.12, 0.09, 0.05])
q = np.array([0.45, 0.30, 0.20, 0.03, 0.015, 0.005])
print(f"H(p)={entropy(p):.4f}  H(p,q)={cross_entropy(p, q):.4f}  H(p)+KL(p||q)={entropy(p) + kl(p, q):.4f}")
print(f"KL(p||q)={kl(p, q):.4f}   KL(q||p)={kl(q, p):.4f}   ← asymmetric")

onehot = np.eye(6)[2]                            # target token is 'cat' (index 2)
print(f"one-hot target: H(y,q)={cross_entropy(onehot, q):.4f} = -log q[2] = {-np.log(q[2]):.4f},"
      f"  KL(q||y)={kl(q, onehot)}")

# Checking MLE: the mean NLL of token samples equals the cross-entropy of the empirical p̂ and q
rng = np.random.default_rng(0)
tokens = rng.choice(6, size=10_000, p=p)
p_hat = np.bincount(tokens.astype(np.intp), minlength=6) / len(tokens)
print(f"\nmean NLL = {-np.log(q[tokens]).mean():.4f}   H(p̂, q) = {cross_entropy(p_hat, q):.4f}")
print(f"the MLE of q is p̂ itself: {np.round(p_hat, 3)}  → mean NLL = H(p̂) = {entropy(p_hat):.4f}")
 

Now we reproduce the figure’s experiment with a grid search: integrate both KLs numerically over a (μ,σ)(\mu, \sigma) grid and find each minimum.

NumPy Fitting one Gaussian to a bimodal distribution: forward vs reverse KL
def log_normal(x, mu, s):
    return -0.5 * ((x - mu) / s) ** 2 - np.log(s) - 0.5 * np.log(2 * np.pi)

x = np.linspace(-12, 12, 961); dx = x[1] - x[0]           # integration grid
mus = np.linspace(-6, 6, 121)
sigmas = np.exp(np.linspace(np.log(0.3), np.log(6), 120))

def kl_landscapes(d, w=0.5):
    logp = np.logaddexp(np.log(w) + log_normal(x, -d, 1), np.log(1 - w) + log_normal(x, d, 1))
    p_x = np.exp(logp)
    fwd = np.empty((len(mus), len(sigmas))); rev = np.empty_like(fwd)
    for j, s in enumerate(sigmas):
        logq = log_normal(x[None, :], mus[:, None], s)    # (number of μ, number of x)
        fwd[:, j] = np.sum(p_x * (logp - logq), axis=1) * dx            # KL(p||q)
        rev[:, j] = np.sum(np.exp(logq) * (logq - logp), axis=1) * dx   # KL(q||p)
    return fwd, rev

def argmin2(L):
    i, j = np.unravel_index(np.argmin(L), L.shape)
    return mus[i], sigmas[j], L[i, j]

for d, w in [(1.5, 0.5), (2.5, 0.5), (3.2, 0.5), (3.2, 0.4)]:
    fwd, rev = kl_landscapes(d, w)
    fm, fs, _ = argmin2(fwd)
    rm, rs, rk = argmin2(rev)
    mom_mu = (1 - 2 * w) * d
    mom_sd = np.sqrt(1 + d**2 - mom_mu**2)
    print(f"d={d} w={w}: forward μ={fm:+.2f} σ={fs:.2f} (moments {mom_mu:+.2f}, {mom_sd:.2f}) | "
          f"reverse μ={rm:+.2f} σ={rs:.2f} KL={rk:.3f}")
print(f"\n-log(0.5) = {-np.log(0.5):.3f},  -log(0.6) = {-np.log(0.6):.3f}")
 

At d = 1.5 and 2.5, reverse KL also places a wide Gaussian in the middle. At d = 3.2 it moves to one mode (σ ≈ 1), and the KL value is close to −log⁡(1−w)-\log(1-w). The forward-KL answer always agrees with moment matching.

확인 문제Check yourself

You approximate a multimodal distribution p with a model q of limited capacity. If the most important thing is 'never put near-zero probability on any mode of p', which should you minimise?

KL(p ∥ q)=Ep[log⁡p−log⁡q]\mathrm{KL}(p\,\|\,q) = \mathbb{E}_p[\log p - \log q] becomes infinite if q→0q \to 0 where p>0p > 0, so it forces qq to cover every mode (mode-covering). The price is that it also puts probability in the empty space between modes. MLE, i.e. pre-training, is this direction.

확인 문제Check yourself

You trained a regression model with MSE. Probabilistically, this is the same as MLE under which assumption?

−log⁡N(y;fθ(x),σ2)=(y−fθ(x))22σ2+const-\log \mathcal N(y; f_\theta(x), \sigma^2) = \frac{(y - f_\theta(x))^2}{2\sigma^2} + \text{const}. Only when σ\sigma is a constant independent of the input does the second term drop out, leaving exactly a constant multiple of MSE. If the noise differs per input (heteroscedastic), you need an NLL that also predicts σθ(x)\sigma_\theta(x). The Laplace assumption gives MAE.

Summary

  • MLE minimises the NLL −1n∑log⁡pθ(yi∣xi)-\frac1n\sum\log p_\theta(y_i|x_i). Gaussian → MSE, Bernoulli → BCE, categorical → cross-entropy.
  • H(p,q)=H(p)+KL(p∥q)H(p,q) = H(p) + \mathrm{KL}(p\|q), with KL≥0\mathrm{KL} \ge 0 (Jensen). The floor of cross-entropy is the entropy of the data.
  • MLE = forward-KL minimisation against the empirical distribution. The token cross-entropy of LLM pre-training is exactly this. Perplexity is eCEe^{\text{CE}}.
  • Forward KL is mode-covering (covers every mode; moment matching for a Gaussian); reverse KL is mode-seeking (hides in one mode, with several local minima).
  • The RLHF KL penalty is reverse KL over the model’s own samples, and its optimum is proportional to πref er/β\pi_{\text{ref}}\,e^{r/\beta}.
  1. d를 0에서 천천히 올리자. d가 작을 때는 두 해가 거의 같다(pp가 봉우리 하나처럼 생겼다).
  2. d ≈ 2.8 근처에서 reverse KL 해(빨강)가 갑자기 한쪽 봉우리로 점프한다. 오른쪽 지도에서 하나였던 골짜기가 둘로 갈라지는 순간이다. 파랑(forward)은 계속 연속적으로 넓어진다.
  3. w를 0.4로 내리면 reverse KL은 무거운 오른쪽 모드를 고른다. 그 KL 값은 −log⁡0.6≈0.51-\log 0.6 \approx 0.51에 가깝다.
  4. 오른쪽 지도에서 선택되지 않은 골짜기를 클릭해 보자. 그곳도 국소 최소다. 경사하강법으로 reverse KL을 최소화하면 초기화에 따라 둘 중 하나에 갇힌다.

직접 계산하기

NumPy entropy, cross-entropy, KL, 그리고 MLE
import numpy as np

def entropy(p):
    p = np.asarray(p, float)
    nz = p > 0                                  # 0 log 0 = 0
    return -np.sum(p[nz] * np.log(p[nz]))

def cross_entropy(p, q):
    p, q = np.asarray(p, float), np.asarray(q, float)
    nz = p > 0
    with np.errstate(divide="ignore"):
        return -np.sum(p[nz] * np.log(q[nz]))   # q=0 인 곳에 p>0 이면 inf

def kl(p, q):
    return cross_entropy(p, q) - entropy(p)

p = np.array([0.34, 0.22, 0.18, 0.12, 0.09, 0.05])
q = np.array([0.45, 0.30, 0.20, 0.03, 0.015, 0.005])
print(f"H(p)={entropy(p):.4f}  H(p,q)={cross_entropy(p, q):.4f}  H(p)+KL(p||q)={entropy(p) + kl(p, q):.4f}")
print(f"KL(p||q)={kl(p, q):.4f}   KL(q||p)={kl(q, p):.4f}   ← 비대칭")

onehot = np.eye(6)[2]                            # 정답 토큰이 'cat'(index 2)
print(f"원-핫 타깃: H(y,q)={cross_entropy(onehot, q):.4f} = -log q[2] = {-np.log(q[2]):.4f},"
      f"  KL(q||y)={kl(q, onehot)}")

# MLE 확인: 토큰 표본의 평균 NLL은 경험분포 p̂와 q의 cross-entropy와 같다
rng = np.random.default_rng(0)
tokens = rng.choice(6, size=10_000, p=p)
p_hat = np.bincount(tokens.astype(np.intp), minlength=6) / len(tokens)
print(f"\n평균 NLL = {-np.log(q[tokens]).mean():.4f}   H(p̂, q) = {cross_entropy(p_hat, q):.4f}")
print(f"q의 MLE는 p̂ 자체: {np.round(p_hat, 3)}  → 평균 NLL = H(p̂) = {entropy(p_hat):.4f}")
 

이제 그림의 실험을 격자 탐색으로 재현한다. (μ,σ)(\mu, \sigma) 격자 위에서 두 KL을 수치 적분하고 각각의 최소점을 찾는다.

NumPy 가우시안 하나를 쌍봉 분포에 맞추기: forward vs reverse KL
def log_normal(x, mu, s):
    return -0.5 * ((x - mu) / s) ** 2 - np.log(s) - 0.5 * np.log(2 * np.pi)

x = np.linspace(-12, 12, 961); dx = x[1] - x[0]           # 적분 격자
mus = np.linspace(-6, 6, 121)
sigmas = np.exp(np.linspace(np.log(0.3), np.log(6), 120))

def kl_landscapes(d, w=0.5):
    logp = np.logaddexp(np.log(w) + log_normal(x, -d, 1), np.log(1 - w) + log_normal(x, d, 1))
    p_x = np.exp(logp)
    fwd = np.empty((len(mus), len(sigmas))); rev = np.empty_like(fwd)
    for j, s in enumerate(sigmas):
        logq = log_normal(x[None, :], mus[:, None], s)    # (μ 개수, x 개수)
        fwd[:, j] = np.sum(p_x * (logp - logq), axis=1) * dx            # KL(p||q)
        rev[:, j] = np.sum(np.exp(logq) * (logq - logp), axis=1) * dx   # KL(q||p)
    return fwd, rev

def argmin2(L):
    i, j = np.unravel_index(np.argmin(L), L.shape)
    return mus[i], sigmas[j], L[i, j]

for d, w in [(1.5, 0.5), (2.5, 0.5), (3.2, 0.5), (3.2, 0.4)]:
    fwd, rev = kl_landscapes(d, w)
    fm, fs, _ = argmin2(fwd)
    rm, rs, rk = argmin2(rev)
    mom_mu = (1 - 2 * w) * d
    mom_sd = np.sqrt(1 + d**2 - mom_mu**2)
    print(f"d={d} w={w}: forward μ={fm:+.2f} σ={fs:.2f} (모멘트 {mom_mu:+.2f}, {mom_sd:.2f}) | "
          f"reverse μ={rm:+.2f} σ={rs:.2f} KL={rk:.3f}")
print(f"\n-log(0.5) = {-np.log(0.5):.3f},  -log(0.6) = {-np.log(0.6):.3f}")
 

d = 1.5, 2.5에서는 reverse KL도 가운데에 넓은 가우시안을 놓는다. d = 3.2에서는 한 모드로 옮겨 가고(σ ≈ 1), KL 값이 −log⁡(1−w)-\log(1-w)에 가깝다. forward KL의 답은 언제나 모멘트 매칭과 일치한다.

확인 문제Check yourself

표현력이 제한된 모델 q로 다봉(multimodal) 분포 p를 근사한다. 'p의 어떤 모드에도 확률을 거의 0으로 두지 않는 것'이 가장 중요하다면 어느 것을 최소화해야 하는가?

KL(p ∥ q)=Ep[log⁡p−log⁡q]\mathrm{KL}(p\,\|\,q) = \mathbb{E}_p[\log p - \log q]는 p>0p > 0인 곳에서 q→0q \to 0이면 무한대가 되므로 모든 모드를 덮게 만든다(mode-covering). 대가로 모드 사이의 빈 곳에도 확률을 둔다. MLE, 즉 사전학습이 이 방향이다.

확인 문제Check yourself

회귀 모델을 MSE로 학습했다. 이것은 확률적으로 어떤 가정 아래의 MLE와 같은가?

−log⁡N(y;fθ(x),σ2)=(y−fθ(x))22σ2+const-\log \mathcal N(y; f_\theta(x), \sigma^2) = \frac{(y - f_\theta(x))^2}{2\sigma^2} + \text{const}. σ\sigma가 입력과 무관한 상수일 때만 둘째 항이 사라지고 정확히 MSE의 상수배가 된다. 입력마다 잡음이 다르면(heteroscedastic) σθ(x)\sigma_\theta(x)도 함께 예측하는 NLL을 써야 한다. 라플라스 가정에서는 MAE가 나온다.

정리

  • MLE는 NLL −1n∑log⁡pθ(yi∣xi)-\frac1n\sum\log p_\theta(y_i|x_i)의 최소화다. 가우시안 → MSE, 베르누이 → BCE, 범주형 → cross-entropy.
  • H(p,q)=H(p)+KL(p∥q)H(p,q) = H(p) + \mathrm{KL}(p\|q), KL≥0\mathrm{KL} \ge 0(Jensen). cross-entropy의 바닥은 데이터의 entropy다.
  • MLE = 경험분포에 대한 forward KL 최소화. LLM 사전학습의 토큰 cross-entropy가 그대로 이것이다. perplexity는 eCEe^{\text{CE}}.
  • forward KL은 mode-covering(모든 모드를 덮음, 가우시안이면 모멘트 매칭), reverse KL은 mode-seeking(한 모드에 숨음, 국소 최소가 여러 개).
  • RLHF의 KL 페널티는 자기 표본 위의 reverse KL이고, 최적해는 πref er/β\pi_{\text{ref}}\,e^{r/\beta}에 비례한다.

더 읽을거리Further reading