[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,92 +1,142 @@
---
id: wiki-2026-0508-kullback-leibler-divergence
title: Kullback Leibler Divergence
title: Kullback-Leibler Divergence
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-KL-001]
aliases: [KL Divergence, Relative Entropy, KL-D]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, Statistics, kl-divergence, Information-Theory, loss-functions, ai]
confidence_score: 0.95
verification_status: applied
tags: [information-theory, divergence, ml, vae, rlhf]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: torch, scipy
---
# Kullback-Leibler Divergence (KL 발산)
# Kullback-Leibler Divergence
## 📌 한 줄 통찰 (The Karpathy Summary)
> "두 세상(확률 분포) 사이의 어긋남을 측정하여, 모델이 진실에 얼마나 도달했는지 수치로 증명하라" — 어떤 확률 분포 $P$를 다른 확률 분포 $Q$로 대체했을 때 발생하는 정보 손실의 양을 측정하는 비대칭적 지표.
## 한 줄
> **"매 distribution 간의 directed information loss"**. KL Divergence $D_{\text{KL}}(P \| Q) = \mathbb{E}_P[\log P/Q]$ 는 reference distribution $Q$ 로 $P$ encode 시 expected extra bits. Kullback & Leibler (1951) 가 정의했고, 2026 ML 에서는 VAE ELBO, RLHF (PPO/DPO), variational inference, distillation 의 매 core loss term.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Distribution [[Alignment|Alignment]]" — 모델의 출력 분포를 타겟 분포에 근사시키기 위해 정보 엔트로피의 차이를 최소화하며 지식의 왜곡을 줄여나가는 최적화 패턴.
- **핵심 성질:**
- **Non-negativity:** 항상 0 이상이며, 두 분포가 완벽히 같을 때만 0임 (Gibbs' In[[Equality|Equality]]).
- **Asymmetry:** $D_{KL}(P||Q) \neq D_{KL}(Q||P)$. 즉, 기준이 되는 분포에 따라 값이 달라짐 (거리 개념이 아님).
- **AI에서의 응용:**
- **VAE (Variational Autoencoder):** 잠재 공간의 분포를 가우시안 분포에 가깝게 강제.
- **PPO (Reinforcement Learning):** 새로운 정책이 이전 정책과 너무 급격하게 변하지 않도록 제약.
- **Knowledge [[Distillation|Distillation]]:** 스튜던트 모델이 티처 모델의 확률 분포를 따라가게 함.
- **의의:** AI 모델이 단순히 정답을 맞히는 것을 넘어, 데이터의 내재된 확률 구조 자체를 학습하게 만드는 수학적 나침반.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 대칭적인 거리 개념(Euclidean Distance)으로 접근하던 초기 방식을 넘어, 정보의 흐름과 소실 관점에서 확률 분포를 비교하는 정보 이론적 접근이 현대 AI의 표준이 됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 페르소나 미세 조정([[Fine-tuning|Fine-tuning]]) 시, 기존 모델과의 KL 발산을 모니터링하여 원래의 유용한 지능이 파괴되지 않도록 관리함.
### 매 Definition
- discrete: $D_{\text{KL}}(P\|Q) = \sum_x P(x) \log \frac{P(x)}{Q(x)}$
- continuous: $\int p(x) \log \frac{p(x)}{q(x)} dx$
- always $\ge 0$ (Gibbs inequality), $=0$ iff $P=Q$
- **NOT symmetric**, **NOT a metric** (no triangle inequality)
- $D_{\text{KL}}(P\|Q) = H(P, Q) - H(P)$ — cross-entropy minus entropy
## 🔗 지식 연결 (Graph)
- Probability-Theory, [[Kolmogorov-Complexity|Kolmogorov-Complexity]], [[Knowledge-Distillation|Knowledge-Distillation]], [[Reinforcement-Learning|Reinforcement-Learning]]
- **Raw Source:** 10_Wiki/Topics/AI/Kullback-Leibler-Divergence.md
### 매 Mode behavior
- **Forward $D_{\text{KL}}(P\|Q)$**: Q must cover all mass of P → "mode-covering"
- **Reverse $D_{\text{KL}}(Q\|P)$**: Q goes where P has mass → "mode-seeking"
- VAE 는 reverse, EP 는 forward
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **VAE ELBO**: $\mathbb{E}[\log p(x|z)] - D_{\text{KL}}(q(z|x) \| p(z))$.
2. **RLHF PPO**: $\beta \cdot D_{\text{KL}}(\pi \| \pi_{\text{ref}})$ penalty.
3. **Knowledge distillation**: $D_{\text{KL}}(p_T \| p_S)$ with temperature.
4. **Variational inference**: $\arg\min_q D_{\text{KL}}(q \| p)$.
5. **Mutual information**: $I(X;Y) = D_{\text{KL}}(p(x,y) \| p(x)p(y))$.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Discrete KL
```python
import numpy as np
def kl_div(p, q, eps=1e-12):
p, q = np.asarray(p), np.asarray(q)
return np.sum(p * (np.log(p + eps) - np.log(q + eps)))
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
p = np.array([0.5, 0.3, 0.2])
q = np.array([0.4, 0.4, 0.2])
print(kl_div(p, q))
```
## 🤔 의사결정 기준 (Decision Criteria)
### PyTorch KL (numerically stable)
```python
import torch
import torch.nn.functional as F
**선택 A를 써야 할 때:**
- *(TODO)*
# inputs MUST be log-probs for kl_div first arg
log_p = F.log_softmax(model_logits, dim=-1)
q = F.softmax(target_logits, dim=-1)
loss = F.kl_div(log_p, q, reduction="batchmean")
```
**선택 B를 써야 할 때:**
- *(TODO)*
### KL between Gaussians (closed form)
```python
def kl_gaussian(mu1, var1, mu2, var2):
return 0.5 * (
torch.log(var2 / var1) + (var1 + (mu1-mu2)**2) / var2 - 1
).sum()
**기본값:**
> *(TODO)*
# VAE: q ~ N(mu, sigma^2), prior N(0, 1)
def kl_to_standard_normal(mu, log_var):
return -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
```
## ❌ 안티패턴 (Anti-Patterns)
### Distillation loss with temperature
```python
def distill_kl(student_logits, teacher_logits, T=4.0):
log_p_s = F.log_softmax(student_logits / T, dim=-1)
p_t = F.softmax(teacher_logits / T, dim=-1)
return F.kl_div(log_p_s, p_t, reduction="batchmean") * (T*T)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### RLHF PPO KL penalty (per-token)
```python
def ppo_kl_penalty(logp_new, logp_ref, beta=0.05):
# token-level KL via log-prob difference
return beta * (logp_new - logp_ref) # used as reward shaping
```
### Forward vs reverse comparison
```python
# Approximate q (Gaussian) to bimodal p
# - reverse KL D(q||p): q picks one mode (mode-seeking)
# - forward KL D(p||q): q spans both modes (mode-covering, broader)
```
## 매 결정 기준
| Need | Form |
|---|---|
| variational posterior fit | reverse $D_{\text{KL}}(q\|p)$ |
| spread (cover all modes) | forward $D_{\text{KL}}(p\|q)$ |
| symmetric | JS divergence |
| bounded, metric | Wasserstein, Hellinger |
| RLHF stability | per-token reverse KL with $\beta$ schedule |
**기본값**: 매 problem 따라 — VAE 면 reverse, EP 면 forward.
## 🔗 Graph
- 부모: [[Information-Theory]] · [[Divergences]]
- 변형: [[Jensen-Shannon-Divergence]] · [[Wasserstein-Distance]] · [[f-Divergence]]
- 응용: [[VAE]] · [[RLHF]] · [[Knowledge-Distillation]] · [[Variational-Inference]]
- Adjacent: [[Cross-Entropy]] · [[Mutual-Information]]
## 🤖 LLM 활용
**언제**: 매 distribution-level loss 정의, RLHF 의 reference model anchoring, distillation.
**언제 X**: 매 distance metric 이 필요할 때 — KL 은 metric 이 X — Wasserstein 사용.
## ❌ 안티패턴
- **Symmetric 가정**: $D_{\text{KL}}(P\|Q) \ne D_{\text{KL}}(Q\|P)$.
- **Disjoint support**: $Q(x)=0, P(x)>0$ 이면 $\infty$ — smooth or use JS.
- **`F.kl_div` 의 input 순서 혼동**: 첫 arg 는 log-prob.
- **Distillation T 무시**: temperature $T$ 없이 sharp distribution 사용 → poor signal.
- **RLHF 에서 KL collapse**: $\beta$ 너무 작으면 reward hacking.
## 🧪 검증 / 중복
- Verified (Cover & Thomas 2006 textbook ch 2, MacKay 2003 ch 2, Kingma VAE 2013).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — KL definition, mode behavior, VAE/RLHF/distillation patterns |