Track 0 · Math Foundations · 07/10

정보 이론Information theory

엔트로피·cross-entropy·KL을 부호 길이로 읽고, KL의 두 방향, JS·TV·χ², 상호정보와 data-processing 부등식, 토큰 KL의 연쇄 법칙, perplexity와 bits-per-byte를 이 사이트의 손실·정규화·평가에 바로 쓸 수 있게 정리한다.Entropy, cross-entropy and KL read as code lengths; the two directions of KL; JS, TV and χ²; mutual information and the data-processing inequality; the chain rule that makes sequence KL a sum of token KLs; perplexity and bits per byte — the pieces this site's losses, regularisers and evaluations are built from.

45 분min entropy · cross-entropy · KL divergence · Jensen-Shannon · total variation · mutual information · data processing inequality · perplexity · bits per byte · Fisher information 먼저 볼 것:Before this: 확률Probability

Almost every loss on this site is a log-probability, and almost every regulariser is a KL divergence. Pre-training minimises cross-entropy, SFT and distillation minimise a forward KL, RLHF penalises a reverse KL, evaluation reports perplexity or bits per byte. Information theory is the small set of identities that connects them. This lesson derives those identities once, from Shannon’s answer to a compression question: entropy is the shortest average description of the data, and −log⁡p-\log p is a length.

Entropy: the shortest average description

Shannon introduced entropy to answer an engineering question: a source emits symbols x∼px \sim p; how many bits per symbol does it take, on average, to write them down so that they can be recovered exactly? His source coding theorem gives the answer,

H(p)=−∑xp(x)log⁡2p(x)bits per symbol.H(p) = -\sum_x p(x)\log_2 p(x) \quad \text{bits per symbol.}

No lossless code averages fewer bits than this, and coding the symbols in long blocks gets as close to it as you like (for a single symbol the best prefix code lands in [H,H+1)[H, H+1); the next section shows why). This is the meaning to keep: entropy is the average length of the best possible compression of pp. Every other quantity in this lesson measures how far some other code falls short of it — cross-entropy is the length you actually pay with a model’s code, KL is the excess, perplexity and bits per byte are the same length in other units.

The optimal code gives each symbol a codeword of length about −log⁡2p(x)-\log_2 p(x): frequent symbols short, rare symbols long. That per-symbol length is the surprisal of xx — also called its self-information or information content; its unit (bit, nat) comes from the log base, below —, and entropy is its average,

H(p)=Ex∼p[−log⁡p(x)].H(p) = \mathbb{E}_{x\sim p}[-\log p(x)].

Read as a length, the familiar properties of surprisal are forced rather than postulated: an event of probability 1 costs nothing to send, rarer events cost more, and independent events are sent by concatenating codewords, so their lengths add, −log⁡(p1p2)=−log⁡p1−log⁡p2-\log(p_1 p_2) = -\log p_1 - \log p_2.

Why −log⁡p-\log p, and not some other decreasing function? Two routes give the same answer.

  • Axioms (Shannon 1948; made rigorous by Khinchin). Ask only that the information I(p)I(p) of an event depend on its probability, be continuous and decreasing, vanish for a certain event, and add over independent events: I(p1p2)=I(p1)+I(p2)I(p_1 p_2) = I(p_1) + I(p_2). Writing f(t)=I(e−t)f(t) = I(e^{-t}) turns this into Cauchy’s equation f(t1+t2)=f(t1)+f(t2)f(t_1 + t_2) = f(t_1) + f(t_2), whose only continuous solutions are linear, so I(p)=−klog⁡pI(p) = -k\log p with k>0k > 0. The constant kk is the choice of log base, i.e. the unit.
  • Code length. An event of probability 1/81/8 is “one of 8 equally likely cases”, which takes log⁡28=3\log_2 8 = 3 yes/no questions — 3 bits — to pin down. In general the next section shows that minimising expected length under the Kraft constraint gives exactly ℓ⋆(x)=−log⁡2p(x)\ell^\star(x) = -\log_2 p(x).

The axioms say why the formula must be a log; the coding theorem says what the number is — the bits an optimal code spends on that event. Averaging it gives entropy.

So is entropy a modelling choice or a fact? Both, at different layers. The axioms are a choice of what we want “information” to mean, and changing them changes the answer: for whole distributions, keeping additivity over independent sources but dropping the chain rule (grouping) admits the whole Rényi family Hα(p)=11−αlog⁡∑xp(x)αH_\alpha(p) = \frac{1}{1-\alpha}\log\sum_x p(x)^\alpha, of which Shannon’s is the limit α→1\alpha \to 1. But once the question is “how many bits per symbol does lossless coding need?”, the answer H(p)H(p) is a theorem, not a choice. Shannon’s definition became the standard because it coincides exactly with that operational limit. The same coincidence is why a language model’s cross-entropy loss is a literal compression length rather than an analogy.

Keep the name and the unit apart. Surprisal / self-information / information content (Korean 정보량) name the quantity −log⁡p-\log p; bit and nat are units of it, the way a metre is a unit of length. The base of the log picks the unit:

log baseunitused by
2bit (also shannon)compression, bits per byte
eenattorch.log, every training loss
10hartley (ban, dit)rarely

1 nat=1/ln⁡2≈1.4431\ \text{nat} = 1/\ln 2 \approx 1.443 bits, so a loss of LL nats is L/ln⁡2L/\ln 2 bits. Frameworks compute in nats (torch.log is natural); compression and bits per byte speak in bits.

Two facts used everywhere, both obvious as code lengths. H(p)≥0H(p) \ge 0, with equality only for a one-hot pp: a certain outcome needs no message. And H(p)≤log⁡KH(p) \le \log K over KK outcomes, with equality only for the uniform uu: a plain fixed-length code already spends log⁡2K\log_2 K bits, and only a uniform source leaves nothing to compress, because

log⁡K−H(p)=∑xp(x)log⁡p(x)1/K=KL(p ∥ u)≥0.\log K - H(p) = \sum_x p(x)\log\frac{p(x)}{1/K} = \mathrm{KL}(p\,\|\,u) \ge 0 .

So “entropy” of a policy and “KL to uniform” are the same knob read from opposite ends. That is why entropy bonuses and entropy collapse (Track IX) can be discussed as a KL.

The coding view: why log-loss is a code length

Assign each symbol xx a binary codeword of length ℓ(x)\ell(x) so that no codeword is a prefix of another (the decoder never has to look ahead). Such codes exist exactly when the Kraft inequality holds:

∑x2−ℓ(x)≤1.\sum_x 2^{-\ell(x)} \le 1 .

Which lengths minimise the expected length ∑xp(x)ℓ(x)\sum_x p(x)\ell(x)? Relax ℓ\ell to real numbers and use a Lagrange multiplier on Kraft (with equality at the optimum):

∂∂ℓ(x)[∑xp(x)ℓ(x)+λ(∑x2−ℓ(x)−1)]=p(x)−λln⁡2  2−ℓ(x)=0  ⇒  2−ℓ(x)=p(x)λln⁡2.\frac{\partial}{\partial \ell(x)}\Big[\sum_x p(x)\ell(x) + \lambda\Big(\sum_x 2^{-\ell(x)} - 1\Big)\Big] = p(x) - \lambda \ln 2\; 2^{-\ell(x)} = 0 \;\Rightarrow\; 2^{-\ell(x)} = \frac{p(x)}{\lambda\ln 2}.

Summing over xx fixes λln⁡2=1\lambda \ln 2 = 1, so ℓ⋆(x)=−log⁡2p(x)\ell^\star(x) = -\log_2 p(x): the ideal codeword length is the surprisal, and the minimum expected length is H(p)H(p). No prefix code beats it: for any lengths, with r(x)=2−ℓ(x)/cr(x) = 2^{-\ell(x)}/c and c=∑2−ℓ≤1c = \sum 2^{-\ell} \le 1,

Ep[ℓ]−H(p)=∑xp(x)log⁡2p(x)2−ℓ(x)=KL(p ∥ r)+log⁡21c  ≥  0.\mathbb{E}_p[\ell] - H(p) = \sum_x p(x)\log_2\frac{p(x)}{2^{-\ell(x)}} = \mathrm{KL}(p\,\|\,r) + \log_2\tfrac1c \;\ge\; 0 .

Now suppose we design the code from a model qq but the data come from pp. Rounding up, ℓ(x)=⌈−log⁡2q(x)⌉\ell(x) = \lceil -\log_2 q(x)\rceil satisfies Kraft, and −log⁡2q≤ℓ<−log⁡2q+1-\log_2 q \le \ell < -\log_2 q + 1 gives

H(p,q)  ≤  Ep[ℓ]  <  H(p,q)+1,H(p,q)=−∑xp(x)log⁡q(x).H(p, q) \;\le\; \mathbb{E}_p[\ell] \;<\; H(p,q) + 1, \qquad H(p,q) = -\sum_x p(x)\log q(x).

The extra bit is a rounding artefact. Coding nn symbols as one block pays it once per block, and arithmetic coding pays about two bits for the whole message, so per symbol the cost tends to exactly the cross-entropy. A language model’s training loss is the number of bits per token it would need to compress the training text. And splitting the log,

H(p,q)=−∑xplog⁡p⏟H(p)+∑xplog⁡pq⏟KL(p∥q),H(p,q) = \underbrace{-\sum_x p\log p}_{H(p)} + \underbrace{\sum_x p\log\frac{p}{q}}_{\mathrm{KL}(p\|q)} ,

the cross-entropy is the unavoidable cost H(p)H(p) plus a penalty for the wrong model. KL is literally the extra bits per symbol paid for coding pp-data with a qq-code. Its non-negativity (Gibbs’ inequality) is the statement above that no code beats H(p)H(p).

이 사이트의 손실은 거의 다 로그 확률이고, 정규화 항은 거의 다 KL divergence다. 사전학습은 cross-entropy를, SFT와 증류는 forward KL을 최소화하고, RLHF는 reverse KL에 벌점을 주며, 평가는 perplexity나 bits per byte로 보고한다. 정보 이론은 이것들을 잇는 몇 개의 항등식이다. 이 레슨은 그 항등식들을 압축에 대한 Shannon의 답, 엔트로피는 데이터의 가장 짧은 평균 설명이고 −log⁡p-\log p는 길이다에서 한 번에 유도한다.

엔트로피: 가장 짧은 평균 설명

Shannon은 공학적인 질문에 답하려고 엔트로피를 도입했다. 원천이 기호 x∼px \sim p를 내보낼 때, 이를 정확히 복원할 수 있게 적으려면 기호당 평균 몇 비트가 필요한가? 그의 원천 부호화 정리(source coding theorem)가 준 답이 이것이다.

H(p)=−∑xp(x)log⁡2p(x)(기호당 bit).H(p) = -\sum_x p(x)\log_2 p(x) \quad \text{(기호당 bit).}

어떤 무손실 부호도 평균적으로 이보다 적은 비트를 쓸 수 없고, 기호를 긴 블록으로 묶어 부호화하면 원하는 만큼 가까이 갈 수 있다(기호 하나만 볼 때 최적 접두 부호의 평균 길이는 [H,H+1)[H, H+1)에 들어간다. 이유는 다음 절에서 본다). 기억할 의미는 이것이다. 엔트로피는 pp를 가장 효율적으로 압축했을 때의 평균 길이다. 이 레슨의 나머지 양은 모두 다른 부호가 이 길이에서 얼마나 모자라는지를 잰다. cross-entropy는 모델의 부호로 실제로 내는 길이, KL은 그 초과분, perplexity와 bits per byte는 같은 길이를 다른 단위로 적은 것이다.

최적 부호는 각 기호에 길이가 대략 −log⁡2p(x)-\log_2 p(x)인 부호어를 준다. 자주 나오는 기호는 짧게, 드문 기호는 길게. 이 기호별 길이가 xx의 정보량(자기 정보량, self-information. 영어로는 surprisal이라고도 해서 이 레슨에서는 “놀라움”이라고도 쓴다. 단위 bit·nat은 아래처럼 로그의 밑이 정한다)이고, 엔트로피는 그 평균이다.

H(p)=Ex∼p[−log⁡p(x)].H(p) = \mathbb{E}_{x\sim p}[-\log p(x)].

길이로 읽으면 놀라움의 익숙한 성질은 가정이 아니라 결과다. 확률 1인 사건은 보낼 것이 없어 길이 0이고, 드문 사건일수록 길며, 독립 사건은 부호어를 이어 붙여 보내므로 길이가 더해진다: −log⁡(p1p2)=−log⁡p1−log⁡p2-\log(p_1 p_2) = -\log p_1 - \log p_2.

왜 다른 감소 함수가 아니라 −log⁡p-\log p인가? 두 길이 같은 답에 닿는다.

  • 공리 (Shannon 1948, Khinchin이 엄밀화). 사건의 정보량 I(p)I(p)에 확률에만 의존하고, 연속이고 감소하며, 확실한 사건에서 0이고, 독립 사건에 대해 더해진다 I(p1p2)=I(p1)+I(p2)I(p_1 p_2) = I(p_1) + I(p_2)는 것만 요구하자. f(t)=I(e−t)f(t) = I(e^{-t})로 두면 이는 Cauchy 함수방정식 f(t1+t2)=f(t1)+f(t2)f(t_1 + t_2) = f(t_1) + f(t_2)가 되고, 연속 해는 일차함수뿐이므로 I(p)=−klog⁡pI(p) = -k\log p (k>0k > 0)다. 상수 kk는 로그의 밑, 즉 단위를 고르는 것이다.
  • 부호 길이. 확률 1/81/8인 사건은 “동일 확률 8개 중 하나”이므로 예/아니오 질문 log⁡28=3\log_2 8 = 3번, 즉 3비트로 지목된다. 일반적으로 다음 절에서 보듯 Kraft 제약 아래 기대 길이를 최소화하면 정확히 ℓ⋆(x)=−log⁡2p(x)\ell^\star(x) = -\log_2 p(x)가 나온다.

공리는 식이 왜 로그여야 하는지를, 부호화 정리는 그 숫자가 무엇인지, 곧 최적 부호가 그 사건에 쓰는 비트 수를 알려 준다. 이를 평균한 것이 엔트로피다.

그러면 엔트로피는 사람이 고른 모델링인가, 유도된 사실인가? 층에 따라 둘 다다. 공리는 “정보”라는 말에 무엇을 바라는지에 대한 선택이고, 요구를 바꾸면 답도 바뀐다. 분포 전체에 대해 독립 원천의 덧셈성은 남기고 연쇄 법칙(grouping)을 빼면 Rényi 엔트로피 가족 Hα(p)=11−αlog⁡∑xp(x)αH_\alpha(p) = \frac{1}{1-\alpha}\log\sum_x p(x)^\alpha 전체가 허용되고, Shannon 엔트로피는 그 α→1\alpha \to 1 극한이다. 하지만 질문이 “무손실로 적으려면 기호당 몇 비트가 필요한가”가 되면 답 H(p)H(p)는 선택이 아니라 정리다. Shannon의 정의가 표준이 된 것은 그 정의가 이 조작적 한계와 정확히 일치하기 때문이다. 언어 모델의 cross-entropy 손실이 비유가 아니라 글자 그대로의 압축 길이인 것도 같은 일치 덕분이다.

이름과 단위를 구분해 두자. 정보량(자기 정보량) / self-information / information content / surprisal 은 모두 양 −log⁡p-\log p의 이름이고, bit와 nat은 그 양의 단위다. 미터가 길이의 단위인 것과 같다. 로그의 밑이 단위를 정한다.

로그의 밑단위쓰는 곳
2bit (shannon이라고도 함)압축, bits per byte
eenattorch.log, 모든 학습 손실
10hartley (ban, dit)드묾

1 nat=1/ln⁡2≈1.4431\ \text{nat} = 1/\ln 2 \approx 1.443 bit이므로 LL nat의 손실은 L/ln⁡2L/\ln 2 bit다. 프레임워크는 nat으로 계산하고(torch.log는 자연로그), 압축과 bits per byte는 bit로 말한다.

어디서나 쓰이는 사실 두 가지이고, 둘 다 부호 길이로 보면 당연하다. H(p)≥0H(p) \ge 0이고 원-핫일 때만 0이다. 확실한 결과는 보낼 메시지가 없다. 그리고 결과가 KK개면 H(p)≤log⁡KH(p) \le \log K이고 균등분포 uu일 때만 등호다. 고정 길이 부호가 이미 log⁡2K\log_2 K 비트를 쓰고, 균등한 원천만 더 압축할 여지가 없다. 왜냐하면

log⁡K−H(p)=∑xp(x)log⁡p(x)1/K=KL(p ∥ u)≥0.\log K - H(p) = \sum_x p(x)\log\frac{p(x)}{1/K} = \mathrm{KL}(p\,\|\,u) \ge 0 .

즉 정책의 “엔트로피”와 “균등분포까지의 KL”은 같은 손잡이를 양 끝에서 읽은 것이다. Track IX에서 엔트로피 보너스와 엔트로피 붕괴를 KL로 논할 수 있는 이유다.

부호화 관점: log-loss가 부호 길이인 이유

각 기호 xx에 길이 ℓ(x)\ell(x)인 이진 부호어를 주되, 어떤 부호어도 다른 부호어의 접두사가 아니게 한다(복호기가 앞을 미리 볼 필요가 없다). 이런 접두 부호는 Kraft 부등식이 성립할 때, 그리고 그때만 존재한다.

∑x2−ℓ(x)≤1.\sum_x 2^{-\ell(x)} \le 1 .

기대 길이 ∑xp(x)ℓ(x)\sum_x p(x)\ell(x)를 최소화하는 길이는? ℓ\ell을 실수로 완화하고 Kraft(최적에서는 등호)에 라그랑주 승수를 건다.

∂∂ℓ(x)[∑xp(x)ℓ(x)+λ(∑x2−ℓ(x)−1)]=p(x)−λln⁡2  2−ℓ(x)=0  ⇒  2−ℓ(x)=p(x)λln⁡2.\frac{\partial}{\partial \ell(x)}\Big[\sum_x p(x)\ell(x) + \lambda\Big(\sum_x 2^{-\ell(x)} - 1\Big)\Big] = p(x) - \lambda \ln 2\; 2^{-\ell(x)} = 0 \;\Rightarrow\; 2^{-\ell(x)} = \frac{p(x)}{\lambda\ln 2}.

xx에 대해 더하면 λln⁡2=1\lambda \ln 2 = 1이므로 ℓ⋆(x)=−log⁡2p(x)\ell^\star(x) = -\log_2 p(x)다. 이상적인 부호어 길이가 곧 놀라움이고, 최소 기대 길이는 H(p)H(p)다. 어떤 접두 부호도 이보다 짧을 수 없다. 임의의 길이에 대해 r(x)=2−ℓ(x)/cr(x) = 2^{-\ell(x)}/c, c=∑2−ℓ≤1c = \sum 2^{-\ell} \le 1로 두면

Ep[ℓ]−H(p)=∑xp(x)log⁡2p(x)2−ℓ(x)=KL(p ∥ r)+log⁡21c  ≥  0.\mathbb{E}_p[\ell] - H(p) = \sum_x p(x)\log_2\frac{p(x)}{2^{-\ell(x)}} = \mathrm{KL}(p\,\|\,r) + \log_2\tfrac1c \;\ge\; 0 .

이제 부호를 모델 qq로 설계했는데 데이터는 pp에서 온다고 하자. 올림한 길이 ℓ(x)=⌈−log⁡2q(x)⌉\ell(x) = \lceil -\log_2 q(x)\rceil는 Kraft를 만족하고, −log⁡2q≤ℓ<−log⁡2q+1-\log_2 q \le \ell < -\log_2 q + 1에서

H(p,q)  ≤  Ep[ℓ]  <  H(p,q)+1,H(p,q)=−∑xp(x)log⁡q(x).H(p, q) \;\le\; \mathbb{E}_p[\ell] \;<\; H(p,q) + 1, \qquad H(p,q) = -\sum_x p(x)\log q(x).

남는 1비트는 올림 때문에 생긴 것이다. 기호 nn개를 한 블록으로 부호화하면 블록당 한 번만 내고, 산술 부호화(arithmetic coding) 는 메시지 전체에 2비트 남짓만 더 쓰므로, 기호당 비용은 정확히 cross-entropy로 수렴한다. 언어 모델의 학습 손실은 그대로 학습 텍스트를 압축하는 데 필요한 토큰당 비트 수다. 그리고 로그를 쪼개면

H(p,q)=−∑xplog⁡p⏟H(p)+∑xplog⁡pq⏟KL(p∥q),H(p,q) = \underbrace{-\sum_x p\log p}_{H(p)} + \underbrace{\sum_x p\log\frac{p}{q}}_{\mathrm{KL}(p\|q)} ,

cross-entropy는 피할 수 없는 비용 H(p)H(p)에 틀린 모델의 벌점을 더한 것이다. KL은 글자 그대로 pp의 데이터를 qq의 부호로 적을 때 기호당 더 내는 비트다. KL이 음수가 아니라는 Gibbs 부등식은 위에서 본 “어떤 부호도 H(p)H(p)보다 짧을 수 없다”와 같은 말이다.

H(p) – H(p,q) – KL(p‖q) – Ep[⌈−log₂q⌉] – Ep[ℓHuffman(q)] – perplexity –
Symbols arrive with frequencies p (blue, Zipf-like with exponent s). We design a binary code from a model q (red outline), here p sharpened or flattened by a temperature τ, and pay its code length on data from p. At τ = 1 the model is right: the expected length lands within one bit of H(p). Move τ away from 1 in either direction and every code built from q pays extra — the red KL slab on top of H(p). Set s = 0 (uniform source) and τ stops mattering. 기호는 빈도 p(파랑, 지수 s인 Zipf 꼴)로 나온다. 이진 부호를 모델 q(빨간 테두리)로 설계하고 — 여기서 q는 p를 온도 τ로 날카롭게/평평하게 한 것 — p에서 나온 데이터에 그 부호 길이를 낸다. τ = 1이면 모델이 맞고, 기대 길이가 H(p)에서 1비트 이내에 들어온다. τ를 1에서 어느 쪽으로든 움직이면 q로 만든 모든 부호가 추가 비용을 낸다. 그것이 H(p) 위에 얹힌 빨간 KL 조각이다. s = 0(균등한 원천)이면 τ는 아무 영향이 없다.

Three things to check in the figure. At τ = 1 the amber Shannon bar sits inside the dashed band [H(p,q),H(p,q)+1)[H(p,q), H(p,q)+1) and the red KL slab is gone. Over-confidence (τ < 1) gives rare symbols long codewords and pays heavily whenever they appear. Under-confidence (τ > 1) wastes short codewords on rare symbols. Both cost KL, which is why calibration matters for log-loss and not for accuracy.

NumPy Entropy, cross-entropy, KL — and code lengths that achieve them
import numpy as np

def H(p, base=2):
    """Entropy in the given base (2 -> bits, e -> nats)."""
    p = p[p > 0]
    return -(p * np.log(p)).sum() / np.log(base)

def CE(p, q, base=2):
    """Cross-entropy H(p, q): mean code length for data from p with a code built from q."""
    m = p > 0
    return -(p[m] * np.log(q[m])).sum() / np.log(base)

def KL(p, q, base=2):
    return CE(p, q, base) - H(p, base)

K = 8
p = 1 / np.arange(1, K + 1) ** 1.1; p /= p.sum()      # Zipf-like source
q = p ** (1 / 0.5); q /= q.sum()                      # an over-confident model (tau = 0.5)

print(f"H(p)     = {H(p):.4f} bits = {H(p, np.e):.4f} nats   (ratio = ln 2 = {H(p, np.e) / H(p):.4f})")
print(f"H(p,q)   = {CE(p, q):.4f} = H(p) + KL(p||q) = {H(p):.4f} + {KL(p, q):.4f}")
print(f"KL(q||p) = {KL(q, p):.4f}   (a different number: KL is not symmetric)")
u = np.full(K, 1 / K)
print(f"log2 K - H(p) = {np.log2(K) - H(p):.4f} = KL(p||uniform) = {KL(p, u):.4f} >= 0, so H(p) <= log2 K")

# Shannon code from q: lengths ceil(-log2 q) satisfy Kraft, so a prefix code with them exists
L = np.ceil(-np.log2(q))
print(f"\nKraft sum  sum 2^-l = {np.sum(2.0 ** -L):.4f} <= 1")
print(f"E_p[l] = {np.sum(p * L):.4f}  lies in [H(p,q), H(p,q)+1) = [{CE(p, q):.4f}, {CE(p, q) + 1:.4f})")

# code n symbols at once: the rounding overhead is paid once per block, < 1/n bit per symbol
for n in [1, 2, 4]:
    pn, qn = p, q
    for _ in range(n - 1):
        pn, qn = np.outer(pn, p).ravel(), np.outer(qn, q).ravel()
    Ln = np.ceil(-np.log2(qn))
    print(f"blocks of {n}: {np.sum(pn * Ln) / n:.4f} bits/symbol   (H(p,q) = {CE(p, q):.4f})")

# divergences that live next to KL
M = 0.5 * (p + q)
JS = 0.5 * KL(p, M) + 0.5 * KL(q, M)
TV = 0.5 * np.abs(p - q).sum()
chi2 = np.sum((p - q) ** 2 / q)
print(f"\nJS(p,q) = {JS:.4f} bits (<= 1)   TV = {TV:.4f} <= sqrt(KL_nats/2) = {np.sqrt(KL(p, q, np.e) / 2):.4f} (Pinsker)")
print(f"chi2(p||q) = {chi2:.4f} >= KL_nats = {KL(p, q, np.e):.4f}   (KL <= log(1 + chi2) = {np.log1p(chi2):.4f})")
 

The block-coding lines show the overhead of the rounded code shrinking towards H(p,q)H(p,q) as blocks grow, never below it. The last two lines preview three divergences that sit next to KL (below).

The chain rule: sequence KL is a sum of token KLs

Factor a joint distribution, p(x,y)=p(x) p(y∣x)p(x,y) = p(x)\,p(y\mid x), do the same for qq, and take the log ratio under pp:

KL(p(x,y) ∥ q(x,y))=KL(p(x) ∥ q(x))+Ex∼p[KL(p(y∣x) ∥ q(y∣x))].\mathrm{KL}\big(p(x,y)\,\|\,q(x,y)\big) = \mathrm{KL}\big(p(x)\,\|\,q(x)\big) + \mathbb{E}_{x\sim p}\Big[\mathrm{KL}\big(p(y\mid x)\,\|\,q(y\mid x)\big)\Big].

Apply it TT times to an autoregressive policy π(y∣x)=∏tπ(yt∣st)\pi(y\mid x) = \prod_t \pi(y_t\mid s_t), st=(x,y<t)s_t = (x, y_{<t}):

KL(πθ(⋅∣x) ∥ πref(⋅∣x))=∑t=1T Est∼πθ[KL(πθ(⋅∣st) ∥ πref(⋅∣st))].\mathrm{KL}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big) = \sum_{t=1}^{T}\ \mathbb{E}_{s_t\sim\pi_\theta}\Big[\mathrm{KL}\big(\pi_\theta(\cdot\mid s_t)\,\|\,\pi_{\text{ref}}(\cdot\mid s_t)\big)\Big].

Two details matter in practice. The prefixes sts_t are drawn from the first argument, πθ\pi_\theta; prefixes from any other policy estimate a different quantity, which is why off-policy rollouts need importance weights. And the inner token KL can be computed exactly over the vocabulary or estimated from the sampled token alone, log⁡πθ(yt∣st)πref(yt∣st)\log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)} (the k1k_1 estimator); summed along a sampled response it is unbiased for the sequence KL. The same chain rule gives H(y∣x)=∑tE[H(π(⋅∣st))]H(y\mid x) = \sum_t \mathbb{E}[H(\pi(\cdot\mid s_t))] for entropy and −log⁡π(y∣x)=∑t−log⁡π(yt∣st)-\log \pi(y\mid x) = \sum_t -\log\pi(y_t\mid s_t) for NLL.

NumPy Sequence KL = sum of expected token KLs (exact enumeration and Monte Carlo)
import numpy as np
import itertools

rs = np.random.default_rng(0)
V, T = 3, 5                                   # vocabulary, sequence length

def model(scale):
    """A toy autoregressive LM: next-token log-probs depend on position and previous token."""
    z = rs.normal(0, scale, (T, V, V))        # logits[t, prev, next]
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

LPpi, LPref = model(1.0), model(1.0)          # log pi(y_t | y_{t-1}), log pi_ref(...)

def seq_logp(LP, y):
    prev = [0] + list(y[:-1])                 # token 0 doubles as BOS
    return sum(LP[t, prev[t], y[t]] for t in range(T))

# 1) the definition: KL over all V^T whole sequences
seqs = list(itertools.product(range(V), repeat=T))
a = np.array([seq_logp(LPpi, y) for y in seqs])
b = np.array([seq_logp(LPref, y) for y in seqs])
kl_seq = np.sum(np.exp(a) * (a - b))

# 2) chain rule: sum over positions of E_{prefix ~ pi}[ KL of the next-token distributions ]
def chain(t=0, prev=0, w=1.0):
    if t == T:
        return 0.0
    lp, lr = LPpi[t, prev], LPref[t, prev]
    out = w * np.sum(np.exp(lp) * (lp - lr))  # this position's token KL, weighted by P(prefix)
    return out + sum(chain(t + 1, k, w * np.exp(lp[k])) for k in range(V))

print(f"sequence KL by enumeration ({V**T} sequences): {kl_seq:.6f} nats")
print(f"sum of expected per-token KLs (chain rule):  {chain():.6f} nats")

# 3) Monte Carlo, as in RLHF: sample y ~ pi, add up log-ratios of the sampled tokens (k1)
def sample(LP, n):
    Y = np.zeros((n, T), dtype=np.intp)
    prev = np.zeros(n, dtype=np.intp)
    for t in range(T):
        P = np.exp(LP[t, prev])               # (n, V)
        Y[:, t] = (rs.random((n, 1)) > np.cumsum(P, 1)).sum(1)
        prev = Y[:, t]
    return Y

def logratio(Y):
    prev = np.concatenate([np.zeros((len(Y), 1), dtype=np.intp), Y[:, :-1]], 1)
    t = np.arange(T)
    return (LPpi[t, prev, Y] - LPref[t, prev, Y]).sum(1)

n = 20000
k1 = logratio(sample(LPpi, n))
print(f"\nk1 on {n} samples from pi:   {k1.mean():.4f} +- {k1.std() / np.sqrt(n):.4f}")
wrong = logratio(sample(LPref, n))
kl_rev = np.sum(np.exp(b) * (b - a))
print(f"same estimator, samples from ref: {wrong.mean():.4f}   (exact -KL(ref||pi) = {-kl_rev:.4f})")
 

The last line is the warning: the very same sum of log-ratios, averaged over samples from the wrong policy, converges to a different number with the opposite sign.

Forward and reverse KL, pointwise

KL(p ∥ q)\mathrm{KL}(p\,\|\,q) and KL(q ∥ p)\mathrm{KL}(q\,\|\,p) integrate different functions. Write both as integrals over xx:

KL(p ∥ q)=∫p(x)log⁡p(x)q(x) dx,KL(q ∥ p)=∫q(x)log⁡q(x)p(x) dx.\mathrm{KL}(p\,\|\,q) = \int p(x)\log\frac{p(x)}{q(x)}\,dx, \qquad \mathrm{KL}(q\,\|\,p) = \int q(x)\log\frac{q(x)}{p(x)}\,dx .

The first weights by pp: wherever p>0p > 0 and q→0q \to 0, the integrand →∞\to \infty, so qq must cover all of pp‘s mass (mode covering). The second weights by qq: regions where q≈0q \approx 0 contribute nothing, whatever pp does there, while q>0q > 0 where p≈0p \approx 0 is infinitely expensive, so qq retreats into a region where pp is large (mode seeking). The gradients say the same thing and also say where the samples come from:

∇θKL(p ∥ qθ)=−Ex∼p[∇θlog⁡qθ(x)],∇θKL(qθ ∥ p)=Ex∼qθ[∇θlog⁡qθ(x) log⁡qθ(x)p(x)].\nabla_\theta \mathrm{KL}(p\,\|\,q_\theta) = -\mathbb{E}_{x\sim p}\big[\nabla_\theta\log q_\theta(x)\big], \qquad \nabla_\theta \mathrm{KL}(q_\theta\,\|\,p) = \mathbb{E}_{x\sim q_\theta}\Big[\nabla_\theta\log q_\theta(x)\,\log\frac{q_\theta(x)}{p(x)}\Big].

(The second uses ∇∫q(log⁡q−log⁡p)=∫∇q (log⁡q−log⁡p)+∫q ∇log⁡q\nabla\int q(\log q - \log p) = \int \nabla q\,(\log q - \log p) + \int q\,\nabla\log q and ∫q ∇log⁡q=∇∫q=0\int q\,\nabla\log q = \nabla\int q = 0.) Forward KL needs samples from pp — data, a teacher’s outputs: that is MLE, SFT and classic distillation. Reverse KL needs samples from the model itself and log⁡p\log p on them — a policy-gradient with reward −log⁡(q/p)-\log(q/p): that is the KL penalty in RLHF and on-policy distillation. Lesson Losses through probability shows the optimal Gaussians; the figure below shows the integrands that produce them.

그림에서 확인할 것 세 가지. τ = 1이면 주황 Shannon 막대가 점선 띠 [H(p,q),H(p,q)+1)[H(p,q), H(p,q)+1) 안에 들어가고 빨간 KL 조각이 사라진다. 과신(τ < 1)은 드문 기호에 긴 부호어를 주고, 그 기호가 나올 때마다 크게 치른다. 과소 확신(τ > 1)은 짧은 부호어를 드문 기호에 낭비한다. 둘 다 KL만큼 비싸다. 정확도가 아니라 log-loss에서 calibration이 중요한 이유다.

NumPy 엔트로피, cross-entropy, KL — 그리고 그 값을 달성하는 부호 길이
import numpy as np

def H(p, base=2):
    """밑 base의 엔트로피 (2 -> bit, e -> nat)."""
    p = p[p > 0]
    return -(p * np.log(p)).sum() / np.log(base)

def CE(p, q, base=2):
    """Cross-entropy H(p, q): q로 만든 부호로 p의 데이터를 적을 때의 평균 부호 길이."""
    m = p > 0
    return -(p[m] * np.log(q[m])).sum() / np.log(base)

def KL(p, q, base=2):
    return CE(p, q, base) - H(p, base)

K = 8
p = 1 / np.arange(1, K + 1) ** 1.1; p /= p.sum()      # Zipf 꼴 원천
q = p ** (1 / 0.5); q /= q.sum()                      # 과신하는 모델 (tau = 0.5)

print(f"H(p)     = {H(p):.4f} bits = {H(p, np.e):.4f} nats   (ratio = ln 2 = {H(p, np.e) / H(p):.4f})")
print(f"H(p,q)   = {CE(p, q):.4f} = H(p) + KL(p||q) = {H(p):.4f} + {KL(p, q):.4f}")
print(f"KL(q||p) = {KL(q, p):.4f}   (a different number: KL is not symmetric)")
u = np.full(K, 1 / K)
print(f"log2 K - H(p) = {np.log2(K) - H(p):.4f} = KL(p||uniform) = {KL(p, u):.4f} >= 0, so H(p) <= log2 K")

# q로 만든 Shannon 부호: 길이 ceil(-log2 q)는 Kraft를 만족하므로 그 길이의 접두 부호가 존재한다
L = np.ceil(-np.log2(q))
print(f"\nKraft sum  sum 2^-l = {np.sum(2.0 ** -L):.4f} <= 1")
print(f"E_p[l] = {np.sum(p * L):.4f}  lies in [H(p,q), H(p,q)+1) = [{CE(p, q):.4f}, {CE(p, q) + 1:.4f})")

# 기호 n개를 한 번에 부호화: 올림 오버헤드는 블록당 한 번, 기호당 1/n bit 미만
for n in [1, 2, 4]:
    pn, qn = p, q
    for _ in range(n - 1):
        pn, qn = np.outer(pn, p).ravel(), np.outer(qn, q).ravel()
    Ln = np.ceil(-np.log2(qn))
    print(f"blocks of {n}: {np.sum(pn * Ln) / n:.4f} bits/symbol   (H(p,q) = {CE(p, q):.4f})")

# KL 옆의 divergence들
M = 0.5 * (p + q)
JS = 0.5 * KL(p, M) + 0.5 * KL(q, M)
TV = 0.5 * np.abs(p - q).sum()
chi2 = np.sum((p - q) ** 2 / q)
print(f"\nJS(p,q) = {JS:.4f} bits (<= 1)   TV = {TV:.4f} <= sqrt(KL_nats/2) = {np.sqrt(KL(p, q, np.e) / 2):.4f} (Pinsker)")
print(f"chi2(p||q) = {chi2:.4f} >= KL_nats = {KL(p, q, np.e):.4f}   (KL <= log(1 + chi2) = {np.log1p(chi2):.4f})")
 

블록 부호화 줄은 올림한 부호의 오버헤드가 블록이 커질수록 H(p,q)H(p,q)로 줄어들되 그 아래로는 내려가지 않음을 보여 준다. 마지막 두 줄은 KL 옆에 있는 세 divergence의 예고편이다(아래).

연쇄 법칙: 시퀀스 KL은 토큰 KL의 합

결합분포를 p(x,y)=p(x) p(y∣x)p(x,y) = p(x)\,p(y\mid x)로 인수분해하고 qq도 같이 한 뒤, pp 아래에서 로그 비율의 기댓값을 취한다.

KL(p(x,y) ∥ q(x,y))=KL(p(x) ∥ q(x))+Ex∼p[KL(p(y∣x) ∥ q(y∣x))].\mathrm{KL}\big(p(x,y)\,\|\,q(x,y)\big) = \mathrm{KL}\big(p(x)\,\|\,q(x)\big) + \mathbb{E}_{x\sim p}\Big[\mathrm{KL}\big(p(y\mid x)\,\|\,q(y\mid x)\big)\Big].

자기회귀 정책 π(y∣x)=∏tπ(yt∣st)\pi(y\mid x) = \prod_t \pi(y_t\mid s_t), st=(x,y<t)s_t = (x, y_{<t})에 이를 TT번 적용하면

KL(πθ(⋅∣x) ∥ πref(⋅∣x))=∑t=1T Est∼πθ[KL(πθ(⋅∣st) ∥ πref(⋅∣st))].\mathrm{KL}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big) = \sum_{t=1}^{T}\ \mathbb{E}_{s_t\sim\pi_\theta}\Big[\mathrm{KL}\big(\pi_\theta(\cdot\mid s_t)\,\|\,\pi_{\text{ref}}(\cdot\mid s_t)\big)\Big].

실전에서 중요한 디테일 두 가지. 접두사 sts_t는 첫 번째 인자 πθ\pi_\theta에서 뽑는다. 다른 정책에서 뽑은 접두사는 다른 양을 추정하며, off-policy rollout에 importance weight가 필요한 이유다. 그리고 안쪽의 토큰 KL은 어휘 전체에 대해 정확히 계산할 수도, 샘플된 토큰 하나로 log⁡πθ(yt∣st)πref(yt∣st)\log\frac{\pi_\theta(y_t\mid s_t)}{\pi_{\text{ref}}(y_t\mid s_t)}(k1k_1 추정량)처럼 추정할 수도 있다. 샘플된 응답을 따라 더하면 시퀀스 KL의 비편향 추정이다. 같은 연쇄 법칙이 엔트로피에는 H(y∣x)=∑tE[H(π(⋅∣st))]H(y\mid x) = \sum_t \mathbb{E}[H(\pi(\cdot\mid s_t))], NLL에는 −log⁡π(y∣x)=∑t−log⁡π(yt∣st)-\log \pi(y\mid x) = \sum_t -\log\pi(y_t\mid s_t)를 준다.

NumPy 시퀀스 KL = 토큰 KL 기댓값의 합 (전수 열거와 몬테카를로)
import numpy as np
import itertools

rs = np.random.default_rng(0)
V, T = 3, 5                                   # 어휘 크기, 시퀀스 길이

def model(scale):
    """장난감 자기회귀 LM: 다음 토큰 log-prob이 위치와 이전 토큰에 의존한다."""
    z = rs.normal(0, scale, (T, V, V))        # logits[t, prev, next]
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

LPpi, LPref = model(1.0), model(1.0)          # log pi(y_t | y_{t-1}), log pi_ref(...)

def seq_logp(LP, y):
    prev = [0] + list(y[:-1])                 # 토큰 0이 BOS 역할도 한다
    return sum(LP[t, prev[t], y[t]] for t in range(T))

# 1) 정의 그대로: V^T개 전체 시퀀스에 대한 KL
seqs = list(itertools.product(range(V), repeat=T))
a = np.array([seq_logp(LPpi, y) for y in seqs])
b = np.array([seq_logp(LPref, y) for y in seqs])
kl_seq = np.sum(np.exp(a) * (a - b))

# 2) 연쇄 법칙: 위치마다 E_{접두사 ~ pi}[ 다음 토큰 분포의 KL ]을 더한다
def chain(t=0, prev=0, w=1.0):
    if t == T:
        return 0.0
    lp, lr = LPpi[t, prev], LPref[t, prev]
    out = w * np.sum(np.exp(lp) * (lp - lr))  # 이 위치의 토큰 KL, P(접두사)로 가중
    return out + sum(chain(t + 1, k, w * np.exp(lp[k])) for k in range(V))

print(f"sequence KL by enumeration ({V**T} sequences): {kl_seq:.6f} nats")
print(f"sum of expected per-token KLs (chain rule):  {chain():.6f} nats")

# 3) RLHF처럼 몬테카를로: y ~ pi를 뽑아 샘플된 토큰의 로그 비율을 더한다 (k1)
def sample(LP, n):
    Y = np.zeros((n, T), dtype=np.intp)
    prev = np.zeros(n, dtype=np.intp)
    for t in range(T):
        P = np.exp(LP[t, prev])               # (n, V)
        Y[:, t] = (rs.random((n, 1)) > np.cumsum(P, 1)).sum(1)
        prev = Y[:, t]
    return Y

def logratio(Y):
    prev = np.concatenate([np.zeros((len(Y), 1), dtype=np.intp), Y[:, :-1]], 1)
    t = np.arange(T)
    return (LPpi[t, prev, Y] - LPref[t, prev, Y]).sum(1)

n = 20000
k1 = logratio(sample(LPpi, n))
print(f"\nk1 on {n} samples from pi:   {k1.mean():.4f} +- {k1.std() / np.sqrt(n):.4f}")
wrong = logratio(sample(LPref, n))
kl_rev = np.sum(np.exp(b) * (b - a))
print(f"same estimator, samples from ref: {wrong.mean():.4f}   (exact -KL(ref||pi) = {-kl_rev:.4f})")
 

마지막 줄이 경고다. 똑같은 로그 비율의 합이라도 엉뚱한 정책의 샘플로 평균하면 부호까지 반대인 다른 값으로 수렴한다.

Forward KL과 reverse KL, 점별로 보기

KL(p ∥ q)\mathrm{KL}(p\,\|\,q)와 KL(q ∥ p)\mathrm{KL}(q\,\|\,p)는 서로 다른 함수를 적분한다. 둘 다 xx에 대한 적분으로 쓰면

KL(p ∥ q)=∫p(x)log⁡p(x)q(x) dx,KL(q ∥ p)=∫q(x)log⁡q(x)p(x) dx.\mathrm{KL}(p\,\|\,q) = \int p(x)\log\frac{p(x)}{q(x)}\,dx, \qquad \mathrm{KL}(q\,\|\,p) = \int q(x)\log\frac{q(x)}{p(x)}\,dx .

앞의 것은 pp로 가중한다. p>0p > 0인데 q→0q \to 0인 곳에서 피적분 함수가 ∞\infty로 가므로 qq는 pp의 질량을 모두 덮어야 한다(mode covering). 뒤의 것은 qq로 가중한다. q≈0q \approx 0인 영역은 pp가 거기서 무엇을 하든 기여가 없고, p≈0p \approx 0인 곳에 q>0q > 0을 두면 무한히 비싸므로 qq는 pp가 큰 영역 안으로 숨는다(mode seeking). gradient도 같은 말을 하고, 샘플이 어디서 오는지까지 알려 준다.

∇θKL(p ∥ qθ)=−Ex∼p[∇θlog⁡qθ(x)],∇θKL(qθ ∥ p)=Ex∼qθ[∇θlog⁡qθ(x) log⁡qθ(x)p(x)].\nabla_\theta \mathrm{KL}(p\,\|\,q_\theta) = -\mathbb{E}_{x\sim p}\big[\nabla_\theta\log q_\theta(x)\big], \qquad \nabla_\theta \mathrm{KL}(q_\theta\,\|\,p) = \mathbb{E}_{x\sim q_\theta}\Big[\nabla_\theta\log q_\theta(x)\,\log\frac{q_\theta(x)}{p(x)}\Big].

(뒤의 식은 ∇∫q(log⁡q−log⁡p)=∫∇q (log⁡q−log⁡p)+∫q ∇log⁡q\nabla\int q(\log q - \log p) = \int \nabla q\,(\log q - \log p) + \int q\,\nabla\log q와 ∫q ∇log⁡q=∇∫q=0\int q\,\nabla\log q = \nabla\int q = 0에서 나온다.) Forward KL에는 pp의 샘플 — 데이터, 교사의 출력 — 이 필요하다. MLE, SFT, 고전적 증류가 이것이다. Reverse KL에는 모델 자신의 샘플과 그 위에서의 log⁡p\log p가 필요하다. 보상이 −log⁡(q/p)-\log(q/p)인 policy gradient이고, RLHF의 KL 벌점과 on-policy 증류가 이것이다. 확률로 보는 손실 레슨이 최적 가우시안을 보여 줬다면, 아래 그림은 그 답을 만드는 피적분 함수를 보여 준다.

KL(p‖q) – KL(q‖p) – JS(p,q) – q = N(–, –²)
Drag the blue dots to move the two modes of p, and drag the red dot to move q (left–right is μ, up–down is the peak height, i.e. 1/σ). The lower panel shows what each KL integrates: blue p·log(p/q) explodes wherever p has mass and q does not; red q·log(q/p) explodes wherever q has mass and p does not. Then press a fit button: forward KL always ends between the modes, reverse KL ends in whichever mode q started nearer to. 파란 점을 끌어 p의 두 모드를 옮기고, 빨간 점을 끌어 q를 옮겨 보세요(좌우는 μ, 위아래는 봉우리 높이, 곧 1/σ). 아래 그림은 각 KL이 적분하는 것이다. 파란 p·log(p/q)는 p에 질량이 있는데 q에 없는 곳에서 폭발하고, 빨간 q·log(q/p)는 q에 질량이 있는데 p에 없는 곳에서 폭발한다. 그다음 맞추기 버튼을 누르면 forward KL은 언제나 두 모드 사이에서 끝나고, reverse KL은 q가 시작한 곳에서 가까운 모드에서 끝난다.

Try this: put q in the valley between the modes and look at the red curve — reverse KL is paying for every bit of q that sits where p is thin. Move q onto one mode and the red area collapses while the blue curve (forward KL) spikes on the abandoned mode. Then run fit reverse KL twice, starting q once left and once right of centre: two different answers, both local minima. Forward KL has a single answer (moment matching) whatever the start.

Divergences next to KL: JS, TV, χ²

Three more divergences appear on this site, each for a reason KL cannot serve.

Jensen–Shannon. With the mixture m=12(p+q)m = \tfrac12(p+q),

JS(p,q)=12KL(p ∥ m)+12KL(q ∥ m),0≤JS≤log⁡2.\mathrm{JS}(p,q) = \tfrac12\mathrm{KL}(p\,\|\,m) + \tfrac12\mathrm{KL}(q\,\|\,m), \qquad 0 \le \mathrm{JS} \le \log 2 .

It is symmetric and finite even when the supports differ, since m≥p/2m \ge p/2 bounds each log ratio by log⁡2\log 2. It also has an information reading: draw a fair coin ZZ, sample XX from pp if heads and from qq if tails; then JS(p,q)=I(X;Z)\mathrm{JS}(p,q) = I(X;Z), the information a sample carries about which distribution produced it. At the optimal discriminator the original GAN objective equals 2 JS−log⁡42\,\mathrm{JS} - \log 4. The generalised JSD(β)\mathrm{JSD}(\beta) with m=βp+(1−β)qm = \beta p + (1-\beta)q interpolates between forward-like and reverse-like behaviour, and is the knob of GKD in distillation.

Total variation. TV(p,q)=12∑x∣p(x)−q(x)∣=max⁡A∣p(A)−q(A)∣\mathrm{TV}(p,q) = \tfrac12\sum_x|p(x)-q(x)| = \max_A |p(A) - q(A)|, the largest disagreement on any event. For any ff with values in [0,1][0,1], ∣Epf−Eqf∣≤TV|\mathbb{E}_p f - \mathbb{E}_q f| \le \mathrm{TV}. Speculative decoding accepts a draft token with probability exactly 1−TV(p,q)1 - \mathrm{TV}(p,q). TV and KL are tied by Pinsker’s inequality (KL in nats):

TV(p,q)≤12 KL(p ∥ q).\mathrm{TV}(p,q) \le \sqrt{\tfrac12\,\mathrm{KL}(p\,\|\,q)} .

So a KL budget is also a budget on how much any bounded statistic — accuracy, a reward in [0,1][0,1], a refusal rate — can move.

χ². χ2(p ∥ q)=∑x(p−q)2q=Eq[w2]−1\chi^2(p\,\|\,q) = \sum_x \frac{(p-q)^2}{q} = \mathbb{E}_q[w^2] - 1 with w=p/qw = p/q: it is exactly the variance of importance weights, which is why it governs effective sample size in off-policy correction. By Jensen, KL(p ∥ q)=Ep[log⁡w]≤log⁡Ep[w]=log⁡(1+χ2)\mathrm{KL}(p\,\|\,q) = \mathbb{E}_p[\log w] \le \log\mathbb{E}_p[w] = \log(1+\chi^2), so a large KL forces a huge weight variance, never the reverse.

KL is locally a quadratic: the Fisher metric

For nearby members of a family pθp_\theta, Taylor-expand log⁡pθ+δ\log p_{\theta+\delta} to second order inside KL(pθ ∥ pθ+δ)=−Epθ[log⁡pθ+δ−log⁡pθ]\mathrm{KL}(p_\theta\,\|\,p_{\theta+\delta}) = -\mathbb{E}_{p_\theta}[\log p_{\theta+\delta} - \log p_\theta]:

KL(pθ ∥ pθ+δ)=−δ⊤E[∇log⁡pθ]⏟= 0−12 δ⊤ E[∇2log⁡pθ] δ+O(∥δ∥3)=12 δ⊤F(θ) δ+O(∥δ∥3),\mathrm{KL}(p_\theta\,\|\,p_{\theta+\delta}) = -\delta^\top\underbrace{\mathbb{E}[\nabla\log p_\theta]}_{=\,0} - \tfrac12\,\delta^\top\,\mathbb{E}[\nabla^2\log p_\theta]\,\delta + O(\|\delta\|^3) = \tfrac12\,\delta^\top F(\theta)\,\delta + O(\|\delta\|^3),

with the Fisher information F=−E[∇2log⁡pθ]=E[∇log⁡pθ ∇log⁡pθ⊤]F = -\mathbb{E}[\nabla^2\log p_\theta] = \mathbb{E}[\nabla\log p_\theta\,\nabla\log p_\theta^\top]. For a softmax over logits zz, F=diag(p)−pp⊤F = \mathrm{diag}(p) - pp^\top. Consequences used later: a KL trust region is, to second order, an ellipsoid 12δ⊤Fδ≤ϵ\tfrac12\delta^\top F\delta \le \epsilon; steepest descent inside it is the natural gradient F−1∇JF^{-1}\nabla J (TRPO, PPO); and KL between successive policies grows quadratically in the step, which is why small staleness costs so little KL.

Mutual information and the data-processing inequality

For two random variables, the conditional entropy H(X∣Y)=Ey[H(p(x∣y))]H(X\mid Y) = \mathbb{E}_y[H(p(x\mid y))] is the uncertainty left in XX after seeing YY, and the chain rule H(X,Y)=H(Y)+H(X∣Y)H(X,Y) = H(Y) + H(X\mid Y) holds just as for KL. The mutual information is the reduction:

I(X;Y)=H(X)−H(X∣Y)=H(X)+H(Y)−H(X,Y)=KL(p(x,y) ∥ p(x)p(y))≥0.I(X;Y) = H(X) - H(X\mid Y) = H(X) + H(Y) - H(X,Y) = \mathrm{KL}\big(p(x,y)\,\|\,p(x)p(y)\big) \ge 0 .

It is symmetric, zero exactly when XX and YY are independent, and — being a KL — invariant to relabelling either variable.

Data processing. If X→Y→ZX \to Y \to Z is a Markov chain (ZZ depends on XX only through YY), expand I(X;Y,Z)I(X; Y, Z) with the chain rule in two orders:

I(X;Y,Z)=I(X;Z)+I(X;Y∣Z)=I(X;Y)+I(X;Z∣Y)⏟= 0  ⇒  I(X;Z)≤I(X;Y).I(X;Y,Z) = I(X;Z) + I(X;Y\mid Z) = I(X;Y) + \underbrace{I(X;Z\mid Y)}_{=\,0} \;\Rightarrow\; I(X;Z) \le I(X;Y).

Processing cannot create information. The KL version is the one used most: pushing two distributions through the same channel KK can only shrink their divergence, KL(pK ∥ qK)≤KL(p ∥ q)\mathrm{KL}(pK\,\|\,qK) \le \mathrm{KL}(p\,\|\,q) (apply the chain rule to p(x)K(y∣x)p(x)K(y\mid x) in both orders). The same holds for JS, TV and χ².

이렇게 해 보자. q를 두 모드 사이의 골짜기에 두고 빨간 곡선을 보면, reverse KL이 p가 얇은 곳에 놓인 q의 모든 질량에 값을 치르고 있다. q를 한 모드 위로 옮기면 빨간 넓이는 무너지고 버려진 모드 위에서 파란 곡선(forward KL)이 솟는다. 그다음 reverse KL로 맞추기를 두 번, q를 한 번은 중앙 왼쪽에서, 한 번은 오른쪽에서 시작해 돌려 보라. 서로 다른 두 답이 나오고 둘 다 국소 최소다. Forward KL은 어디서 시작하든 답이 하나다(moment matching).

KL 옆의 divergence: JS, TV, χ²

이 사이트에는 divergence가 셋 더 나오고, 각각 KL이 해 주지 못하는 이유로 쓰인다.

Jensen–Shannon. 혼합 m=12(p+q)m = \tfrac12(p+q)로

JS(p,q)=12KL(p ∥ m)+12KL(q ∥ m),0≤JS≤log⁡2.\mathrm{JS}(p,q) = \tfrac12\mathrm{KL}(p\,\|\,m) + \tfrac12\mathrm{KL}(q\,\|\,m), \qquad 0 \le \mathrm{JS} \le \log 2 .

대칭이고, 지지집합이 달라도 유한하다. m≥p/2m \ge p/2라서 각 로그 비율이 log⁡2\log 2로 묶이기 때문이다. 정보로도 읽힌다. 공정한 동전 ZZ를 던져 앞면이면 pp에서, 뒷면이면 qq에서 XX를 뽑으면 JS(p,q)=I(X;Z)\mathrm{JS}(p,q) = I(X;Z), 곧 샘플 하나가 “어느 분포에서 왔는가”에 대해 가진 정보다. 최적 판별기에서 원래 GAN의 목적함수는 2 JS−log⁡42\,\mathrm{JS} - \log 4와 같다. m=βp+(1−β)qm = \beta p + (1-\beta)q로 일반화한 JSD(β)\mathrm{JSD}(\beta)는 forward 같은 행동과 reverse 같은 행동 사이를 보간하며, 증류 레슨의 GKD가 돌리는 손잡이다.

Total variation. TV(p,q)=12∑x∣p(x)−q(x)∣=max⁡A∣p(A)−q(A)∣\mathrm{TV}(p,q) = \tfrac12\sum_x|p(x)-q(x)| = \max_A |p(A) - q(A)|, 어떤 사건에서든 가장 큰 불일치다. 값이 [0,1][0,1]인 모든 ff에 대해 ∣Epf−Eqf∣≤TV|\mathbb{E}_p f - \mathbb{E}_q f| \le \mathrm{TV}다. Speculative decoding은 draft 토큰을 정확히 확률 1−TV(p,q)1 - \mathrm{TV}(p,q)로 받아들인다. TV와 KL은 Pinsker 부등식으로 묶인다(KL은 nat).

TV(p,q)≤12 KL(p ∥ q).\mathrm{TV}(p,q) \le \sqrt{\tfrac12\,\mathrm{KL}(p\,\|\,q)} .

그러니 KL 예산은 어떤 유계 통계량 — 정확도, [0,1][0,1]의 보상, 거절률 — 이 움직일 수 있는 폭의 예산이기도 하다.

χ². χ2(p ∥ q)=∑x(p−q)2q=Eq[w2]−1\chi^2(p\,\|\,q) = \sum_x \frac{(p-q)^2}{q} = \mathbb{E}_q[w^2] - 1, w=p/qw = p/q. 정확히 importance weight의 분산이고, 그래서 off-policy 보정에서 유효 표본 수를 결정한다. Jensen으로 KL(p ∥ q)=Ep[log⁡w]≤log⁡Ep[w]=log⁡(1+χ2)\mathrm{KL}(p\,\|\,q) = \mathbb{E}_p[\log w] \le \log\mathbb{E}_p[w] = \log(1+\chi^2)이므로, KL이 크면 weight 분산은 반드시 거대하다(역은 아니다).

KL은 국소적으로 이차식: Fisher 계량

가족 pθp_\theta의 가까운 두 원소에 대해 KL(pθ ∥ pθ+δ)=−Epθ[log⁡pθ+δ−log⁡pθ]\mathrm{KL}(p_\theta\,\|\,p_{\theta+\delta}) = -\mathbb{E}_{p_\theta}[\log p_{\theta+\delta} - \log p_\theta] 안의 log⁡pθ+δ\log p_{\theta+\delta}를 2차까지 테일러 전개하면

KL(pθ ∥ pθ+δ)=−δ⊤E[∇log⁡pθ]⏟= 0−12 δ⊤ E[∇2log⁡pθ] δ+O(∥δ∥3)=12 δ⊤F(θ) δ+O(∥δ∥3),\mathrm{KL}(p_\theta\,\|\,p_{\theta+\delta}) = -\delta^\top\underbrace{\mathbb{E}[\nabla\log p_\theta]}_{=\,0} - \tfrac12\,\delta^\top\,\mathbb{E}[\nabla^2\log p_\theta]\,\delta + O(\|\delta\|^3) = \tfrac12\,\delta^\top F(\theta)\,\delta + O(\|\delta\|^3),

여기서 Fisher 정보 F=−E[∇2log⁡pθ]=E[∇log⁡pθ ∇log⁡pθ⊤]F = -\mathbb{E}[\nabla^2\log p_\theta] = \mathbb{E}[\nabla\log p_\theta\,\nabla\log p_\theta^\top]다. logit zz 위의 softmax라면 F=diag(p)−pp⊤F = \mathrm{diag}(p) - pp^\top다. 뒤에서 쓰이는 결과: KL trust region은 2차까지 타원체 12δ⊤Fδ≤ϵ\tfrac12\delta^\top F\delta \le \epsilon이고, 그 안의 최급강하가 natural gradient F−1∇JF^{-1}\nabla J(TRPO, PPO)이며, 연속한 정책 사이의 KL은 걸음 크기에 대해 이차로 자란다. 작은 staleness가 KL을 거의 쓰지 않는 이유다.

상호정보와 data-processing 부등식

두 확률변수에서 조건부 엔트로피 H(X∣Y)=Ey[H(p(x∣y))]H(X\mid Y) = \mathbb{E}_y[H(p(x\mid y))]는 YY를 본 뒤 XX에 남은 불확실성이고, 연쇄 법칙 H(X,Y)=H(Y)+H(X∣Y)H(X,Y) = H(Y) + H(X\mid Y)가 KL에서와 똑같이 성립한다. 상호정보(mutual information) 는 그 감소량이다.

I(X;Y)=H(X)−H(X∣Y)=H(X)+H(Y)−H(X,Y)=KL(p(x,y) ∥ p(x)p(y))≥0.I(X;Y) = H(X) - H(X\mid Y) = H(X) + H(Y) - H(X,Y) = \mathrm{KL}\big(p(x,y)\,\|\,p(x)p(y)\big) \ge 0 .

대칭이고, XX와 YY가 독립일 때 정확히 0이며, KL이므로 어느 변수의 이름을 바꿔도 변하지 않는다.

Data processing. X→Y→ZX \to Y \to Z가 마르코프 연쇄라면(ZZ는 YY를 통해서만 XX에 의존), I(X;Y,Z)I(X; Y, Z)를 연쇄 법칙으로 두 순서로 전개한다.

I(X;Y,Z)=I(X;Z)+I(X;Y∣Z)=I(X;Y)+I(X;Z∣Y)⏟= 0  ⇒  I(X;Z)≤I(X;Y).I(X;Y,Z) = I(X;Z) + I(X;Y\mid Z) = I(X;Y) + \underbrace{I(X;Z\mid Y)}_{=\,0} \;\Rightarrow\; I(X;Z) \le I(X;Y).

처리는 정보를 만들어 내지 못한다. 가장 많이 쓰이는 것은 KL 버전이다. 두 분포를 같은 채널 KK에 통과시키면 divergence는 줄어들 수만 있다: KL(pK ∥ qK)≤KL(p ∥ q)\mathrm{KL}(pK\,\|\,qK) \le \mathrm{KL}(p\,\|\,q)(p(x)K(y∣x)p(x)K(y\mid x)에 연쇄 법칙을 두 순서로 적용). JS, TV, χ²도 마찬가지다.

H(X) – H(X|Y) – I(X;Y) – I(X;Z) –
A symbol X ∈ {0,1,2,3} goes through a noisy channel (kept with probability 1−ε, otherwise replaced by one of the other three) to give Y, and Y through a second channel to give Z. Raise ε₁: the joint p(x,y) loses its diagonal and the shared region I(X;Y) shrinks, reaching 0 at ε₁ = 0.75 where Y is independent of X. Now move ε₂: I(X;Z) is never above I(X;Y) — no processing of Y can recover information about X that Y does not carry. At ε₂ = 0 the two are equal. Units: bits. 기호 X ∈ {0,1,2,3}가 잡음 채널(확률 1−ε로 그대로, 아니면 나머지 셋 중 하나로 바뀜)을 지나 Y가 되고, Y가 두 번째 채널을 지나 Z가 된다. ε₁을 올리면 결합분포 p(x,y)의 대각선이 흐려지고 공유 영역 I(X;Y)가 줄어, ε₁ = 0.75에서 Y가 X와 독립이 되며 0이 된다. 이제 ε₂를 움직이면 I(X;Z)는 결코 I(X;Y)를 넘지 않는다. Y를 어떻게 처리해도 Y에 없는 X의 정보는 되살릴 수 없다. ε₂ = 0이면 둘이 같다. 단위: bit.

Concretely for post-training: the final answer, the reward, the length — any function of a response is a “channel” applied to it. So the KL between the answer distributions of πθ\pi_\theta and πref\pi_{\text{ref}} is at most the sequence KL, and with Pinsker the expected reward (in [0,1][0,1]) can move by at most KL/2\sqrt{\mathrm{KL}/2}. Conversely, a large sequence KL can hide behind an unchanged answer distribution: the model may rewrite its reasoning entirely while answering the same.

Perplexity and bits per byte

For a held-out text of TT tokens and NbytesN_{\text{bytes}} bytes, with mean NLL L\mathcal L nats/token,

PPL=eL=2L/ln⁡2,BPB=1Nbytes∑t=1T−log⁡2pθ(xt∣x<t)=TNbytes⋅Lln⁡2.\mathrm{PPL} = e^{\mathcal L} = 2^{\mathcal L/\ln 2}, \qquad \mathrm{BPB} = \frac{1}{N_{\text{bytes}}}\sum_{t=1}^{T} -\log_2 p_\theta(x_t\mid x_{<t}) = \frac{T}{N_{\text{bytes}}}\cdot\frac{\mathcal L}{\ln 2}.

Perplexity is the effective branching factor: a model that is uniformly unsure among kk tokens has PPL kk. But it is per token, and the tokenizer decides what a token is. The total code length ∑t−log⁡2pθ(xt∣x<t)\sum_t -\log_2 p_\theta(x_t\mid x_{<t}) of the text is a property of the model and the text only, so dividing it by bytes (or characters, or words) gives a number comparable across tokenizers. A tokenizer with longer tokens has fewer, harder predictions: higher per-token loss, possibly lower BPB.

NumPy Mutual information, data processing, the Fisher quadratic, and bits per byte
import numpy as np

def mi(Pxy):
    """Mutual information in bits = KL(p(x,y) || p(x)p(y))."""
    px, py = Pxy.sum(1), Pxy.sum(0)
    m = Pxy > 0
    return np.sum(Pxy[m] * np.log2(Pxy[m] / np.outer(px, py)[m]))

def channel(e, K=4):
    """Keep the symbol with probability 1-e, else switch to one of the other K-1."""
    return np.full((K, K), e / (K - 1)) + np.eye(K) * (1 - e - e / (K - 1))

px = np.exp(-0.4 * np.arange(4)); px /= px.sum()
T1, T2 = channel(0.15), channel(0.2)
Ixy, Ixz = mi(px[:, None] * T1), mi(px[:, None] * (T1 @ T2))
Hx = -np.sum(px * np.log2(px))
print(f"H(X) = {Hx:.4f}   I(X;Y) = {Ixy:.4f}   I(X;Z) = {Ixz:.4f} bits   DPI holds: {Ixz <= Ixy}")

# DPI for KL: send two distributions through the same channel; their KL can only shrink
kl = lambda p, q: np.sum(p * np.log(p / q))
p1, p2 = np.array([0.7, 0.1, 0.1, 0.1]), np.array([0.25, 0.25, 0.25, 0.25])
print(f"KL before channel {kl(p1, p2):.4f} nats, after {kl(p1 @ T1, p2 @ T1):.4f}, after two {kl(p1 @ T1 @ T2, p2 @ T1 @ T2):.4f}")

# Locally, KL is a quadratic form: KL(p_z || p_{z+d}) ~ 1/2 d^T F d, F = diag(p) - p p^T (softmax Fisher)
rs = np.random.default_rng(1)
z = rs.normal(0, 1, 6)
sm = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
p = sm(z)
F = np.diag(p) - np.outer(p, p)
for eps in [1e-1, 1e-2]:
    d = eps * rs.normal(0, 1, 6)
    print(f"|d| = {np.linalg.norm(d):.3f}:  KL = {kl(p, sm(z + d)):.3e}   1/2 d^T F d = {0.5 * d @ F @ d:.3e}")

# Perplexity is per token; bits per byte is per byte of text, so it survives a tokenizer change
n_bytes = 1_000_000                     # the same evaluation text for both models
for name, n_tok, nll in [("A", 250_000, 2.60), ("B", 300_000, 2.25)]:   # tokens, nats/token
    bits = n_tok * nll / np.log(2)      # total code length of the text under the model
    print(f"model {name}: {n_tok/1e3:.0f}K tokens, {nll} nats/token, PPL {np.exp(nll):6.2f}, "
          f"total {bits/8e3:.1f} KB, BPB {bits / n_bytes:.4f}")
 

Model A has the worse perplexity and the better compression: it needs fewer total bits for the same megabyte.

확인 문제Check yourself

A model's eval loss is 0.70 nats per token, and its tokenizer averages 4.0 bytes per token. What is its bits per byte?

Convert to bits, then divide by bytes per token: 0.70/ln⁡2=1.0100.70/\ln 2 = 1.010 bits/token, and 1.010/4.0≈0.251.010/4.0 \approx 0.25 BPB. 0.175 forgets the nats→bits conversion; 1.01 is bits per token.

확인 문제Check yourself

An RL run keeps the sequence-level KL(π‖π_ref) at most 0.02 nats per prompt. The reward is a pass/fail in [0,1]. How much can the expected reward per prompt differ between π and π_ref?

The reward is a function of the response, so by data processing the KL between the reward distributions is at most 0.02; Pinsker gives TV≤0.02/2=0.1\mathrm{TV} \le \sqrt{0.02/2} = 0.1, and for f∈[0,1]f \in [0,1], ∣Eπf−Ereff∣≤TV≤0.1|\mathbb{E}_\pi f - \mathbb{E}_{\text{ref}} f| \le \mathrm{TV} \le 0.1. A small KL budget really does cap how far any bounded metric can move.

Summary

  • Entropy is the average length of the best lossless compression of pp (source coding theorem); −log⁡2p-\log_2 p is the ideal code length per symbol, cross-entropy the length with a model’s code, and KL=H(p,q)−H(p)\mathrm{KL} = H(p,q) - H(p) the extra bits. 1 nat =1.443= 1.443 bits.
  • Chain rule: KL, entropy and NLL of a sequence are sums over tokens, with prefixes drawn from the first argument.
  • Forward KL (samples from pp) covers modes; reverse KL (samples from qq) seeks them and has local minima.
  • JS is bounded and symmetric, TV bounds any bounded statistic (Pinsker: TV≤KL/2\mathrm{TV} \le \sqrt{\mathrm{KL}/2}), χ² is importance-weight variance; locally KL ≈12δ⊤Fδ\approx \tfrac12\delta^\top F\delta.
  • Mutual information is KL(p(x,y)∥p(x)p(y))\mathrm{KL}(p(x,y)\|p(x)p(y)); processing never increases MI or any of these divergences.
  • Compare models across tokenizers in bits per byte, not perplexity.

Where this is used

사후학습에 대입하면 이렇다. 최종 답, 보상, 길이 — 응답의 어떤 함수든 응답에 적용한 “채널”이다. 그러니 πθ\pi_\theta와 πref\pi_{\text{ref}}의 답 분포 사이 KL은 시퀀스 KL 이하이고, Pinsker로 기대 보상([0,1][0,1])은 많아야 KL/2\sqrt{\mathrm{KL}/2}만큼 움직일 수 있다. 거꾸로 큰 시퀀스 KL이 변하지 않은 답 분포 뒤에 숨을 수도 있다. 모델이 같은 답을 내면서 추론 과정은 통째로 바꿨을 수 있다.

Perplexity와 bits per byte

토큰 TT개, 바이트 NbytesN_{\text{bytes}}개인 평가 텍스트에서 평균 NLL이 토큰당 L\mathcal L nat이면

PPL=eL=2L/ln⁡2,BPB=1Nbytes∑t=1T−log⁡2pθ(xt∣x<t)=TNbytes⋅Lln⁡2.\mathrm{PPL} = e^{\mathcal L} = 2^{\mathcal L/\ln 2}, \qquad \mathrm{BPB} = \frac{1}{N_{\text{bytes}}}\sum_{t=1}^{T} -\log_2 p_\theta(x_t\mid x_{<t}) = \frac{T}{N_{\text{bytes}}}\cdot\frac{\mathcal L}{\ln 2}.

Perplexity는 유효 분기 수다. kk개 토큰 사이에서 균등하게 망설이는 모델의 PPL은 kk다. 하지만 토큰당 값이고, 무엇이 토큰인지는 토크나이저가 정한다. 텍스트 전체의 부호 길이 ∑t−log⁡2pθ(xt∣x<t)\sum_t -\log_2 p_\theta(x_t\mid x_{<t})는 모델과 텍스트만의 성질이므로, 이것을 바이트(또는 글자, 단어) 수로 나누면 토크나이저가 달라도 비교할 수 있는 숫자가 된다. 토큰이 긴 토크나이저는 예측 횟수가 적고 각 예측이 어렵다. 토큰당 손실은 높아도 BPB는 더 낮을 수 있다.

NumPy 상호정보, data processing, Fisher 이차식, bits per byte
import numpy as np

def mi(Pxy):
    """상호정보(bit) = KL(p(x,y) || p(x)p(y))."""
    px, py = Pxy.sum(1), Pxy.sum(0)
    m = Pxy > 0
    return np.sum(Pxy[m] * np.log2(Pxy[m] / np.outer(px, py)[m]))

def channel(e, K=4):
    """확률 1-e로 기호를 유지하고, 아니면 나머지 K-1개 중 하나로 바꾼다."""
    return np.full((K, K), e / (K - 1)) + np.eye(K) * (1 - e - e / (K - 1))

px = np.exp(-0.4 * np.arange(4)); px /= px.sum()
T1, T2 = channel(0.15), channel(0.2)
Ixy, Ixz = mi(px[:, None] * T1), mi(px[:, None] * (T1 @ T2))
Hx = -np.sum(px * np.log2(px))
print(f"H(X) = {Hx:.4f}   I(X;Y) = {Ixy:.4f}   I(X;Z) = {Ixz:.4f} bits   DPI holds: {Ixz <= Ixy}")

# KL의 DPI: 두 분포를 같은 채널에 통과시키면 KL은 줄어들 수만 있다
kl = lambda p, q: np.sum(p * np.log(p / q))
p1, p2 = np.array([0.7, 0.1, 0.1, 0.1]), np.array([0.25, 0.25, 0.25, 0.25])
print(f"KL before channel {kl(p1, p2):.4f} nats, after {kl(p1 @ T1, p2 @ T1):.4f}, after two {kl(p1 @ T1 @ T2, p2 @ T1 @ T2):.4f}")

# 국소적으로 KL은 이차형식: KL(p_z || p_{z+d}) ~ 1/2 d^T F d, F = diag(p) - p p^T (softmax의 Fisher)
rs = np.random.default_rng(1)
z = rs.normal(0, 1, 6)
sm = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
p = sm(z)
F = np.diag(p) - np.outer(p, p)
for eps in [1e-1, 1e-2]:
    d = eps * rs.normal(0, 1, 6)
    print(f"|d| = {np.linalg.norm(d):.3f}:  KL = {kl(p, sm(z + d)):.3e}   1/2 d^T F d = {0.5 * d @ F @ d:.3e}")

# Perplexity는 토큰당, bits per byte는 텍스트 바이트당 -> 토크나이저가 바뀌어도 비교 가능
n_bytes = 1_000_000                     # 두 모델에 같은 평가 텍스트
for name, n_tok, nll in [("A", 250_000, 2.60), ("B", 300_000, 2.25)]:   # 토큰 수, 토큰당 nat
    bits = n_tok * nll / np.log(2)      # 모델로 잰 텍스트 전체의 부호 길이
    print(f"model {name}: {n_tok/1e3:.0f}K tokens, {nll} nats/token, PPL {np.exp(nll):6.2f}, "
          f"total {bits/8e3:.1f} KB, BPB {bits / n_bytes:.4f}")
 

모델 A는 perplexity가 더 나쁜데 압축은 더 잘한다. 같은 1MB에 필요한 총 비트가 더 적다.

확인 문제Check yourself

어떤 모델의 평가 손실이 토큰당 0.70 nat이고, 토크나이저는 토큰당 평균 4.0바이트다. bits per byte는?

비트로 바꾼 뒤 토큰당 바이트로 나눈다. 0.70/ln⁡2=1.0100.70/\ln 2 = 1.010 bit/token, 1.010/4.0≈0.251.010/4.0 \approx 0.25 BPB. 0.175는 nat→bit 변환을 빠뜨린 값이고, 1.01은 토큰당 비트다.

확인 문제Check yourself

어떤 RL 학습이 프롬프트당 시퀀스 KL(π‖π_ref)을 0.02 nat 이하로 유지한다. 보상은 [0,1]의 통과/실패다. 프롬프트당 기대 보상은 π와 π_ref 사이에서 얼마나 다를 수 있나?

보상은 응답의 함수이므로 data processing에 의해 보상 분포 사이의 KL은 0.02 이하다. Pinsker로 TV≤0.02/2=0.1\mathrm{TV} \le \sqrt{0.02/2} = 0.1이고, f∈[0,1]f \in [0,1]이면 ∣Eπf−Ereff∣≤TV≤0.1|\mathbb{E}_\pi f - \mathbb{E}_{\text{ref}} f| \le \mathrm{TV} \le 0.1이다. 작은 KL 예산은 정말로 모든 유계 지표가 움직일 폭을 묶는다.

정리

  • 엔트로피는 pp를 가장 효율적으로 무손실 압축했을 때의 평균 길이다(원천 부호화 정리). −log⁡2p-\log_2 p는 기호별 이상적인 부호 길이, cross-entropy는 모델의 부호로 잰 길이, KL=H(p,q)−H(p)\mathrm{KL} = H(p,q) - H(p)는 추가 비트다. 1 nat =1.443= 1.443 bit.
  • 연쇄 법칙: 시퀀스의 KL·엔트로피·NLL은 토큰에 대한 합이고, 접두사는 첫 번째 인자에서 뽑는다.
  • Forward KL(pp의 샘플)은 모드를 덮고, reverse KL(qq의 샘플)은 모드를 찾으며 국소 최소가 있다.
  • JS는 유계·대칭, TV는 모든 유계 통계량을 묶고(Pinsker: TV≤KL/2\mathrm{TV} \le \sqrt{\mathrm{KL}/2}), χ²는 importance weight의 분산이다. 국소적으로 KL ≈12δ⊤Fδ\approx \tfrac12\delta^\top F\delta.
  • 상호정보는 KL(p(x,y)∥p(x)p(y))\mathrm{KL}(p(x,y)\|p(x)p(y))이고, 처리는 상호정보도 이 divergence들도 늘리지 못한다.
  • 토크나이저가 다른 모델은 perplexity가 아니라 bits per byte로 비교한다.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading