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 is a length.
Entropy: the shortest average description
Shannon introduced entropy to answer an engineering question: a source emits symbols ; 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,
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 ; the next section shows why). This is the meaning to keep: entropy is the average length of the best possible compression of . 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 : frequent symbols short, rare symbols long. That per-symbol length is the surprisal of — also called its self-information or information content; its unit (bit, nat) comes from the log base, below —, and entropy is its average,
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, .
Why , and not some other decreasing function? Two routes give the same answer.
- Axioms (Shannon 1948; made rigorous by Khinchin). Ask only that the information of an event depend on its probability, be continuous and decreasing, vanish for a certain event, and add over independent events: . Writing turns this into Cauchy’s equation , whose only continuous solutions are linear, so with . The constant is the choice of log base, i.e. the unit.
- Code length. An event of probability is “one of 8 equally likely cases”, which takes yes/no questions — 3 bits — to pin down. In general the next section shows that minimising expected length under the Kraft constraint gives exactly .
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 , of which Shannon’s is the limit . But once the question is “how many bits per symbol does lossless coding need?”, the answer 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 ; 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 base | unit | used by |
|---|---|---|
| 2 | bit (also shannon) | compression, bits per byte |
| nat | torch.log, every training loss | |
| 10 | hartley (ban, dit) | rarely |
bits, so a loss of nats is 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. , with equality only for a one-hot : a certain outcome needs no message. And over outcomes, with equality only for the uniform : a plain fixed-length code already spends bits, and only a uniform source leaves nothing to compress, because
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 a binary codeword of length 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:
Which lengths minimise the expected length ? Relax to real numbers and use a Lagrange multiplier on Kraft (with equality at the optimum):
Summing over fixes , so : the ideal codeword length is the surprisal, and the minimum expected length is . No prefix code beats it: for any lengths, with and ,
Now suppose we design the code from a model but the data come from . Rounding up, satisfies Kraft, and gives
The extra bit is a rounding artefact. Coding 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,
the cross-entropy is the unavoidable cost plus a penalty for the wrong model. KL is literally the extra bits per symbol paid for coding -data with a -code. Its non-negativity (Gibbs’ inequality) is the statement above that no code beats .
이 사이트의 손실은 거의 다 로그 확률이고, 정규화 항은 거의 다 KL divergence다. 사전학습은 cross-entropy를, SFT와 증류는 forward KL을 최소화하고, RLHF는 reverse KL에 벌점을 주며, 평가는 perplexity나 bits per byte로 보고한다. 정보 이론은 이것들을 잇는 몇 개의 항등식이다. 이 레슨은 그 항등식들을 압축에 대한 Shannon의 답, 엔트로피는 데이터의 가장 짧은 평균 설명이고 는 길이다에서 한 번에 유도한다.
엔트로피: 가장 짧은 평균 설명
Shannon은 공학적인 질문에 답하려고 엔트로피를 도입했다. 원천이 기호 를 내보낼 때, 이를 정확히 복원할 수 있게 적으려면 기호당 평균 몇 비트가 필요한가? 그의 원천 부호화 정리(source coding theorem)가 준 답이 이것이다.
어떤 무손실 부호도 평균적으로 이보다 적은 비트를 쓸 수 없고, 기호를 긴 블록으로 묶어 부호화하면 원하는 만큼 가까이 갈 수 있다(기호 하나만 볼 때 최적 접두 부호의 평균 길이는 에 들어간다. 이유는 다음 절에서 본다). 기억할 의미는 이것이다. 엔트로피는 를 가장 효율적으로 압축했을 때의 평균 길이다. 이 레슨의 나머지 양은 모두 다른 부호가 이 길이에서 얼마나 모자라는지를 잰다. cross-entropy는 모델의 부호로 실제로 내는 길이, KL은 그 초과분, perplexity와 bits per byte는 같은 길이를 다른 단위로 적은 것이다.
최적 부호는 각 기호에 길이가 대략 인 부호어를 준다. 자주 나오는 기호는 짧게, 드문 기호는 길게. 이 기호별 길이가 의 정보량(자기 정보량, self-information. 영어로는 surprisal이라고도 해서 이 레슨에서는 “놀라움”이라고도 쓴다. 단위 bit·nat은 아래처럼 로그의 밑이 정한다)이고, 엔트로피는 그 평균이다.
길이로 읽으면 놀라움의 익숙한 성질은 가정이 아니라 결과다. 확률 1인 사건은 보낼 것이 없어 길이 0이고, 드문 사건일수록 길며, 독립 사건은 부호어를 이어 붙여 보내므로 길이가 더해진다: .
왜 다른 감소 함수가 아니라 인가? 두 길이 같은 답에 닿는다.
- 공리 (Shannon 1948, Khinchin이 엄밀화). 사건의 정보량 에 확률에만 의존하고, 연속이고 감소하며, 확실한 사건에서 0이고, 독립 사건에 대해 더해진다 는 것만 요구하자. 로 두면 이는 Cauchy 함수방정식 가 되고, 연속 해는 일차함수뿐이므로 ()다. 상수 는 로그의 밑, 즉 단위를 고르는 것이다.
- 부호 길이. 확률 인 사건은 “동일 확률 8개 중 하나”이므로 예/아니오 질문 번, 즉 3비트로 지목된다. 일반적으로 다음 절에서 보듯 Kraft 제약 아래 기대 길이를 최소화하면 정확히 가 나온다.
공리는 식이 왜 로그여야 하는지를, 부호화 정리는 그 숫자가 무엇인지, 곧 최적 부호가 그 사건에 쓰는 비트 수를 알려 준다. 이를 평균한 것이 엔트로피다.
그러면 엔트로피는 사람이 고른 모델링인가, 유도된 사실인가? 층에 따라 둘 다다. 공리는 “정보”라는 말에 무엇을 바라는지에 대한 선택이고, 요구를 바꾸면 답도 바뀐다. 분포 전체에 대해 독립 원천의 덧셈성은 남기고 연쇄 법칙(grouping)을 빼면 Rényi 엔트로피 가족 전체가 허용되고, Shannon 엔트로피는 그 극한이다. 하지만 질문이 “무손실로 적으려면 기호당 몇 비트가 필요한가”가 되면 답 는 선택이 아니라 정리다. Shannon의 정의가 표준이 된 것은 그 정의가 이 조작적 한계와 정확히 일치하기 때문이다. 언어 모델의 cross-entropy 손실이 비유가 아니라 글자 그대로의 압축 길이인 것도 같은 일치 덕분이다.
이름과 단위를 구분해 두자. 정보량(자기 정보량) / self-information / information content / surprisal 은 모두 양 의 이름이고, bit와 nat은 그 양의 단위다. 미터가 길이의 단위인 것과 같다. 로그의 밑이 단위를 정한다.
| 로그의 밑 | 단위 | 쓰는 곳 |
|---|---|---|
| 2 | bit (shannon이라고도 함) | 압축, bits per byte |
| nat | torch.log, 모든 학습 손실 | |
| 10 | hartley (ban, dit) | 드묾 |
bit이므로 nat의 손실은 bit다. 프레임워크는 nat으로 계산하고(torch.log는 자연로그), 압축과 bits per byte는 bit로 말한다.
어디서나 쓰이는 사실 두 가지이고, 둘 다 부호 길이로 보면 당연하다. 이고 원-핫일 때만 0이다. 확실한 결과는 보낼 메시지가 없다. 그리고 결과가 개면 이고 균등분포 일 때만 등호다. 고정 길이 부호가 이미 비트를 쓰고, 균등한 원천만 더 압축할 여지가 없다. 왜냐하면
즉 정책의 “엔트로피”와 “균등분포까지의 KL”은 같은 손잡이를 양 끝에서 읽은 것이다. Track IX에서 엔트로피 보너스와 엔트로피 붕괴를 KL로 논할 수 있는 이유다.
부호화 관점: log-loss가 부호 길이인 이유
각 기호 에 길이 인 이진 부호어를 주되, 어떤 부호어도 다른 부호어의 접두사가 아니게 한다(복호기가 앞을 미리 볼 필요가 없다). 이런 접두 부호는 Kraft 부등식이 성립할 때, 그리고 그때만 존재한다.
기대 길이 를 최소화하는 길이는? 을 실수로 완화하고 Kraft(최적에서는 등호)에 라그랑주 승수를 건다.
에 대해 더하면 이므로 다. 이상적인 부호어 길이가 곧 놀라움이고, 최소 기대 길이는 다. 어떤 접두 부호도 이보다 짧을 수 없다. 임의의 길이에 대해 , 로 두면
이제 부호를 모델 로 설계했는데 데이터는 에서 온다고 하자. 올림한 길이 는 Kraft를 만족하고, 에서
남는 1비트는 올림 때문에 생긴 것이다. 기호 개를 한 블록으로 부호화하면 블록당 한 번만 내고, 산술 부호화(arithmetic coding) 는 메시지 전체에 2비트 남짓만 더 쓰므로, 기호당 비용은 정확히 cross-entropy로 수렴한다. 언어 모델의 학습 손실은 그대로 학습 텍스트를 압축하는 데 필요한 토큰당 비트 수다. 그리고 로그를 쪼개면
cross-entropy는 피할 수 없는 비용 에 틀린 모델의 벌점을 더한 것이다. KL은 글자 그대로 의 데이터를 의 부호로 적을 때 기호당 더 내는 비트다. KL이 음수가 아니라는 Gibbs 부등식은 위에서 본 “어떤 부호도 보다 짧을 수 없다”와 같은 말이다.
Three things to check in the figure. At τ = 1 the amber Shannon bar sits inside the dashed band 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.
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 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, , do the same for , and take the log ratio under :
Apply it times to an autoregressive policy , :
Two details matter in practice. The prefixes are drawn from the first argument, ; 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, (the estimator); summed along a sampled response it is unbiased for the sequence KL. The same chain rule gives for entropy and for NLL.
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
and integrate different functions. Write both as integrals over :
The first weights by : wherever and , the integrand , so must cover all of ‘s mass (mode covering). The second weights by : regions where contribute nothing, whatever does there, while where is infinitely expensive, so retreats into a region where is large (mode seeking). The gradients say the same thing and also say where the samples come from:
(The second uses and .) Forward KL needs samples from — data, a teacher’s outputs: that is MLE, SFT and classic distillation. Reverse KL needs samples from the model itself and on them — a policy-gradient with reward : 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 막대가 점선 띠 안에 들어가고 빨간 KL 조각이 사라진다. 과신(τ < 1)은 드문 기호에 긴 부호어를 주고, 그 기호가 나올 때마다 크게 치른다. 과소 확신(τ > 1)은 짧은 부호어를 드문 기호에 낭비한다. 둘 다 KL만큼 비싸다. 정확도가 아니라 log-loss에서 calibration이 중요한 이유다.
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})")블록 부호화 줄은 올림한 부호의 오버헤드가 블록이 커질수록 로 줄어들되 그 아래로는 내려가지 않음을 보여 준다. 마지막 두 줄은 KL 옆에 있는 세 divergence의 예고편이다(아래).
연쇄 법칙: 시퀀스 KL은 토큰 KL의 합
결합분포를 로 인수분해하고 도 같이 한 뒤, 아래에서 로그 비율의 기댓값을 취한다.
자기회귀 정책 , 에 이를 번 적용하면
실전에서 중요한 디테일 두 가지. 접두사 는 첫 번째 인자 에서 뽑는다. 다른 정책에서 뽑은 접두사는 다른 양을 추정하며, off-policy rollout에 importance weight가 필요한 이유다. 그리고 안쪽의 토큰 KL은 어휘 전체에 대해 정확히 계산할 수도, 샘플된 토큰 하나로 ( 추정량)처럼 추정할 수도 있다. 샘플된 응답을 따라 더하면 시퀀스 KL의 비편향 추정이다. 같은 연쇄 법칙이 엔트로피에는 , NLL에는 를 준다.
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, 점별로 보기
와 는 서로 다른 함수를 적분한다. 둘 다 에 대한 적분으로 쓰면
앞의 것은 로 가중한다. 인데 인 곳에서 피적분 함수가 로 가므로 는 의 질량을 모두 덮어야 한다(mode covering). 뒤의 것은 로 가중한다. 인 영역은 가 거기서 무엇을 하든 기여가 없고, 인 곳에 을 두면 무한히 비싸므로 는 가 큰 영역 안으로 숨는다(mode seeking). gradient도 같은 말을 하고, 샘플이 어디서 오는지까지 알려 준다.
(뒤의 식은 와 에서 나온다.) Forward KL에는 의 샘플 — 데이터, 교사의 출력 — 이 필요하다. MLE, SFT, 고전적 증류가 이것이다. Reverse KL에는 모델 자신의 샘플과 그 위에서의 가 필요하다. 보상이 인 policy gradient이고, RLHF의 KL 벌점과 on-policy 증류가 이것이다. 확률로 보는 손실 레슨이 최적 가우시안을 보여 줬다면, 아래 그림은 그 답을 만드는 피적분 함수를 보여 준다.
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 ,
It is symmetric and finite even when the supports differ, since bounds each log ratio by . It also has an information reading: draw a fair coin , sample from if heads and from if tails; then , the information a sample carries about which distribution produced it. At the optimal discriminator the original GAN objective equals . The generalised with interpolates between forward-like and reverse-like behaviour, and is the knob of GKD in distillation.
Total variation. , the largest disagreement on any event. For any with values in , . Speculative decoding accepts a draft token with probability exactly . TV and KL are tied by Pinsker’s inequality (KL in nats):
So a KL budget is also a budget on how much any bounded statistic — accuracy, a reward in , a refusal rate — can move.
χ². with : it is exactly the variance of importance weights, which is why it governs effective sample size in off-policy correction. By Jensen, , 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 , Taylor-expand to second order inside :
with the Fisher information . For a softmax over logits , . Consequences used later: a KL trust region is, to second order, an ellipsoid ; steepest descent inside it is the natural gradient (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 is the uncertainty left in after seeing , and the chain rule holds just as for KL. The mutual information is the reduction:
It is symmetric, zero exactly when and are independent, and — being a KL — invariant to relabelling either variable.
Data processing. If is a Markov chain ( depends on only through ), expand with the chain rule in two orders:
Processing cannot create information. The KL version is the one used most: pushing two distributions through the same channel can only shrink their divergence, (apply the chain rule to 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. 혼합 로
대칭이고, 지지집합이 달라도 유한하다. 라서 각 로그 비율이 로 묶이기 때문이다. 정보로도 읽힌다. 공정한 동전 를 던져 앞면이면 에서, 뒷면이면 에서 를 뽑으면 , 곧 샘플 하나가 “어느 분포에서 왔는가”에 대해 가진 정보다. 최적 판별기에서 원래 GAN의 목적함수는 와 같다. 로 일반화한 는 forward 같은 행동과 reverse 같은 행동 사이를 보간하며, 증류 레슨의 GKD가 돌리는 손잡이다.
Total variation. , 어떤 사건에서든 가장 큰 불일치다. 값이 인 모든 에 대해 다. Speculative decoding은 draft 토큰을 정확히 확률 로 받아들인다. TV와 KL은 Pinsker 부등식으로 묶인다(KL은 nat).
그러니 KL 예산은 어떤 유계 통계량 — 정확도, 의 보상, 거절률 — 이 움직일 수 있는 폭의 예산이기도 하다.
χ². , . 정확히 importance weight의 분산이고, 그래서 off-policy 보정에서 유효 표본 수를 결정한다. Jensen으로 이므로, KL이 크면 weight 분산은 반드시 거대하다(역은 아니다).
KL은 국소적으로 이차식: Fisher 계량
가족 의 가까운 두 원소에 대해 안의 를 2차까지 테일러 전개하면
여기서 Fisher 정보 다. logit 위의 softmax라면 다. 뒤에서 쓰이는 결과: KL trust region은 2차까지 타원체 이고, 그 안의 최급강하가 natural gradient (TRPO, PPO)이며, 연속한 정책 사이의 KL은 걸음 크기에 대해 이차로 자란다. 작은 staleness가 KL을 거의 쓰지 않는 이유다.
상호정보와 data-processing 부등식
두 확률변수에서 조건부 엔트로피 는 를 본 뒤 에 남은 불확실성이고, 연쇄 법칙 가 KL에서와 똑같이 성립한다. 상호정보(mutual information) 는 그 감소량이다.
대칭이고, 와 가 독립일 때 정확히 0이며, KL이므로 어느 변수의 이름을 바꿔도 변하지 않는다.
Data processing. 가 마르코프 연쇄라면(는 를 통해서만 에 의존), 를 연쇄 법칙으로 두 순서로 전개한다.
처리는 정보를 만들어 내지 못한다. 가장 많이 쓰이는 것은 KL 버전이다. 두 분포를 같은 채널 에 통과시키면 divergence는 줄어들 수만 있다: (에 연쇄 법칙을 두 순서로 적용). JS, TV, χ²도 마찬가지다.
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 and is at most the sequence KL, and with Pinsker the expected reward (in ) can move by at most . 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 tokens and bytes, with mean NLL nats/token,
Perplexity is the effective branching factor: a model that is uniformly unsure among tokens has PPL . But it is per token, and the tokenizer decides what a token is. The total code length 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.
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.
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: bits/token, and BPB. 0.175 forgets the nats→bits conversion; 1.01 is bits per token.
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 , and for , . 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 (source coding theorem); is the ideal code length per symbol, cross-entropy the length with a model’s code, and the extra bits. 1 nat 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 ) covers modes; reverse KL (samples from ) seeks them and has local minima.
- JS is bounded and symmetric, TV bounds any bounded statistic (Pinsker: ), χ² is importance-weight variance; locally KL .
- Mutual information is ; processing never increases MI or any of these divergences.
- Compare models across tokenizers in bits per byte, not perplexity.
Where this is used
- Losses through probability — MLE = forward KL, the optimal-Gaussian picture of KL’s asymmetry.
- Language modeling, Tokenization, Pre-training and scaling — NLL, perplexity, BPB, the entropy floor as “irreducible loss”.
- SFT and Distillation — forward vs reverse KL, on-policy distillation, generalised JSD.
- KL-regularised RL, Regularisation, DPO — sequence KL as a sum of token KLs, k1/k2/k3, entropy control, log-ratio rewards.
- Off-policy mismatch, Clipping and IS — χ² and ESS, TV-based trust-region masks.
- Inference, Speculative decoding — acceptance probability .
- PPO — trust regions and the natural gradient via the Fisher matrix.
- Report reviews that compare base models in BPB: OLMo 3, DeepSeek-V3, MAI-Base-2.
- Next: Numerics — computing these log-probabilities without overflow, underflow or cancellation.
사후학습에 대입하면 이렇다. 최종 답, 보상, 길이 — 응답의 어떤 함수든 응답에 적용한 “채널”이다. 그러니 와 의 답 분포 사이 KL은 시퀀스 KL 이하이고, Pinsker로 기대 보상()은 많아야 만큼 움직일 수 있다. 거꾸로 큰 시퀀스 KL이 변하지 않은 답 분포 뒤에 숨을 수도 있다. 모델이 같은 답을 내면서 추론 과정은 통째로 바꿨을 수 있다.
Perplexity와 bits per byte
토큰 개, 바이트 개인 평가 텍스트에서 평균 NLL이 토큰당 nat이면
Perplexity는 유효 분기 수다. 개 토큰 사이에서 균등하게 망설이는 모델의 PPL은 다. 하지만 토큰당 값이고, 무엇이 토큰인지는 토크나이저가 정한다. 텍스트 전체의 부호 길이 는 모델과 텍스트만의 성질이므로, 이것을 바이트(또는 글자, 단어) 수로 나누면 토크나이저가 달라도 비교할 수 있는 숫자가 된다. 토큰이 긴 토크나이저는 예측 횟수가 적고 각 예측이 어렵다. 토큰당 손실은 높아도 BPB는 더 낮을 수 있다.
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에 필요한 총 비트가 더 적다.
어떤 모델의 평가 손실이 토큰당 0.70 nat이고, 토크나이저는 토큰당 평균 4.0바이트다. bits per byte는?
비트로 바꾼 뒤 토큰당 바이트로 나눈다. bit/token, BPB. 0.175는 nat→bit 변환을 빠뜨린 값이고, 1.01은 토큰당 비트다.
어떤 RL 학습이 프롬프트당 시퀀스 KL(π‖π_ref)을 0.02 nat 이하로 유지한다. 보상은 [0,1]의 통과/실패다. 프롬프트당 기대 보상은 π와 π_ref 사이에서 얼마나 다를 수 있나?
보상은 응답의 함수이므로 data processing에 의해 보상 분포 사이의 KL은 0.02 이하다. Pinsker로 이고, 이면 이다. 작은 KL 예산은 정말로 모든 유계 지표가 움직일 폭을 묶는다.
정리
- 엔트로피는 를 가장 효율적으로 무손실 압축했을 때의 평균 길이다(원천 부호화 정리). 는 기호별 이상적인 부호 길이, cross-entropy는 모델의 부호로 잰 길이, 는 추가 비트다. 1 nat bit.
- 연쇄 법칙: 시퀀스의 KL·엔트로피·NLL은 토큰에 대한 합이고, 접두사는 첫 번째 인자에서 뽑는다.
- Forward KL(의 샘플)은 모드를 덮고, reverse KL(의 샘플)은 모드를 찾으며 국소 최소가 있다.
- JS는 유계·대칭, TV는 모든 유계 통계량을 묶고(Pinsker: ), χ²는 importance weight의 분산이다. 국소적으로 KL .
- 상호정보는 이고, 처리는 상호정보도 이 divergence들도 늘리지 못한다.
- 토크나이저가 다른 모델은 perplexity가 아니라 bits per byte로 비교한다.
이 사이트에서 쓰이는 곳
- 확률로 보는 손실 — MLE = forward KL, KL 비대칭의 최적 가우시안 그림.
- 언어 모델링, 토크나이저, 사전학습과 스케일링 — NLL, perplexity, BPB, “irreducible loss”로서의 엔트로피 하한.
- SFT와 증류 — forward vs reverse KL, on-policy 증류, 일반화 JSD.
- KL 정규화 RL, 정규화, DPO — 토큰 KL의 합으로서의 시퀀스 KL, k1/k2/k3, 엔트로피 제어, 로그 비율 보상.
- Off-policy 불일치, Clipping과 IS — χ²와 ESS, TV 기반 trust-region 마스크.
- 추론 최적화, Speculative decoding — 수락 확률 .
- PPO — trust region과 Fisher 행렬을 통한 natural gradient.
- base 모델을 BPB로 비교하는 보고서 리뷰: OLMo 3, DeepSeek-V3, MAI-Base-2.
- 다음: 수치 계산 — 이 로그 확률들을 overflow·underflow·상쇄 없이 계산하기.
더 읽을거리Further reading
- Cover & Thomas, Elements of Information Theory, 2nd ed. (Wiley, 2006), ch. 2, 5, 11 — 엔트로피·KL·상호정보의 연쇄 법칙과 data-processing 부등식(2장), Kraft 부등식과 부호 길이(5장), Pinsker(11장)의 표준 교재.The standard text — chain rules, KL, mutual information and the data-processing inequality (ch. 2), Kraft and code lengths (ch. 5), Pinsker (ch. 11).
- MacKay, Information Theory, Inference, and Learning Algorithms (CUP, 2003) — 무료 공개. 부호화와 추론을 한 언어로 묶는다. 4–6장의 압축 이야기가 이 레슨의 "부호 길이" 관점이다.Free online. Ties coding and inference together; chapters 4–6 on compression are this lesson's code-length view.
- Shannon, A Mathematical Theory of Communication (Bell System Technical Journal, 1948) — 엔트로피와 부호화 정리의 원전.The original source of entropy and the coding theorem.
- Lin, Divergence Measures Based on the Shannon Entropy (IEEE Trans. Inf. Theory, 1991) — Jensen–Shannon divergence의 정의와 성질.Definition and properties of the Jensen–Shannon divergence.
- Delétang et al., Language Modeling Is Compression (ICLR 2024) — 언어 모델의 log-loss가 곧 산술 부호화의 압축 길이라는 관점을 실제 모델로 보인다.Shows with real models that a language model's log-loss is its arithmetic-coding compression length.
- Schulman, Approximating KL Divergence (blog, 2020) — 샘플 하나로 KL을 추정하는 k1/k2/k3. RLHF의 KL 항이 쓰는 추정량.The k1/k2/k3 single-sample KL estimators used by the KL term in RLHF.