[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,117 +1,193 @@
|
||||
---
|
||||
id: wiki-2026-0508-variational-autoencoders-vae
|
||||
title: Variational Autoencoders VAE
|
||||
title: Variational Autoencoders (VAE)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [VAE, Variational Autoencoder, β-VAE]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [auto-consolidated, technical-documentation]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [generative-model, deep-learning, latent-variable, variational-inference]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
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: PyTorch 2.x
|
||||
---
|
||||
|
||||
# [[Variational Autoencoders (VAE)|Variational Autoencoders (VAE)]]
|
||||
# Variational Autoencoders (VAE)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터를 구름 속에 가두고 다시 빚기: 현실의 데이터를 압축된 '잠재 공간(Latent Space)'이라는 확률 분포로 변환한 뒤, 그 구름에서 새로운 표본을 샘플링하여 현실에 존재한 적 없는 새로운 데이터를 창조해내는 생성의 정석."
|
||||
## 매 한 줄
|
||||
> **"매 encoder 가 input 의 latent distribution (μ, σ) 의 produce → reparameterization trick 으로 sample → decoder 의 reconstruct. 매 ELBO = reconstruction loss + KL(q(z|x) || p(z))"**. 매 Kingma & Welling 2013 (Auto-Encoding Variational Bayes). 매 2026 의 modern role: standalone generation 의 X (diffusion 의 우위) BUT 매 Stable Diffusion / FLUX / Sora 의 latent space 의 backbone — 매 image 의 8× downsampled latent 의 work.
|
||||
|
||||
---
|
||||
## 매 핵심
|
||||
|
||||
> "데이터를 확률 분포로 압축하여 무한한 변이를 생성하라" — 입력 데이터를 특정 수치가 아닌 '평균'과 '분산'을 가진 확률 분포로 인코딩함으로써, 잠재 공간(Latent Space)에서 새로운 데이터를 샘플링하여 생성할 수 있게 하는 모델.
|
||||
### 매 수학 (ELBO)
|
||||
- **Goal**: maximize log p(x). 매 intractable.
|
||||
- **Trick**: variational posterior q_φ(z|x) ≈ p(z|x). 매 ELBO 의 lower bound.
|
||||
- **ELBO** = E_{z~q}[log p_θ(x|z)] − D_KL(q_φ(z|x) || p(z))
|
||||
- 1번 term: reconstruction (decoder).
|
||||
- 2번 term: regularize latent 의 prior (보통 N(0,I)) 에 가깝게.
|
||||
- **Reparameterization**: z = μ + σ ⊙ ε, ε~N(0,I) — 매 backprop through stochastic sampling.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
변이형 오토인코더(Variational Autoencoder, VAE)는 데이터의 잠재적인 구조를 학습하여 새로운 유사 데이터를 생성해낼 수 있는 딥러닝 기반의 생성 모델입니다.
|
||||
### 매 vs 다른 generative
|
||||
- **GAN**: sharp, no likelihood, mode collapse. VAE: blurry, likelihood, stable training.
|
||||
- **Diffusion**: state-of-art quality. VAE: faster inference (single forward).
|
||||
- **2026 dominant role**: latent diffusion 의 frontend — 매 VAE 가 pixel space → latent space 압축, diffusion 이 latent 의 denoise.
|
||||
|
||||
1. **구조와 매커니즘**:
|
||||
* **Encoder**: 입력 데이터(이미지 등)를 저차원의 '잠재 변수(Latent Variable)' 분포(평균과 분산)로 압축.
|
||||
* **Latent Space**: 데이터를 하나의 점이 아닌 '확률 분포'의 영역으로 표현하여, 그 영역 내의 어떤 점에서도 그럴싸한 데이터가 나오게 함 (연속성 확보).
|
||||
* **Decoder**: 잠재 공간에서 샘플링한 벡터를 다시 원래의 고차원 데이터 형식으로 복원 및 생성.
|
||||
2. **핵심 기법 - Re[[Parameter|Parameter]]ization Trick**:
|
||||
* 샘플링 과정은 미분이 불가능하여 오차 역전파가 안 되는데, 이를 수학적 트릭으로 우회하여 신경망 전체가 학습 가능하게 만듦.
|
||||
3. **용도**:
|
||||
* 데이터 증강, 노이즈 제거(Denosing), 이미지 생성, 분자 구조 설계 등.
|
||||
### 매 변종
|
||||
- **β-VAE**: KL term 에 β 곱 → β>1 의 disentangled latent.
|
||||
- **VQ-VAE**: continuous latent → discrete codebook (Vector Quantization). 매 DALL-E, Sora 의 핵심.
|
||||
- **Hierarchical VAE / NVAE**: multi-scale latents.
|
||||
- **Conditional VAE (CVAE)**: conditional generation p(x|c).
|
||||
|
||||
---
|
||||
### 매 응용
|
||||
1. Latent diffusion (Stable Diffusion / FLUX / Sora) — 매 8×8 patch → 4-ch latent.
|
||||
2. Anomaly detection — high reconstruction error = anomaly.
|
||||
3. Molecular generation — 매 chemistry latent space exploration.
|
||||
|
||||
- **추출된 패턴:** 원시 데이터를 의미 있는 저차원 확률 분포로 요약(Encoder)하고, 이 분포로부터 샘플링된 값을 다시 원시 데이터 형태로 복원(Decoder)하는 생성적 추론 패턴.
|
||||
- **세부 내용:**
|
||||
- **Latent Space:** 데이터의 핵심 특징들이 압축된 다차원 공간. VAE는 이 공간이 정규 분포를 따르도록 강제함.
|
||||
- **Re[[Parameter|Parameter]]ization Trick:** 샘플링 과정에서 미분 가능성을 유지하여 역전파([[Backpropagation|Backpropagation]])가 가능하게 하는 핵심 수학적 기법.
|
||||
- **Kullback-Leibler (KL) Divergence:** 학습된 잠재 분포가 표준 정규 분포와 너무 멀어지지 않도록 규제하는 손실 함수 항.
|
||||
- **Applications:** 이미지 생성, 데이터 압축, 이상치 탐지(Anomaly Detection) 등.
|
||||
## 💻 패턴
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 초기 생성 모델 정책은 단순한 복원(Autoencoder)에 그치거나 GAN의 불안정한 학습에 고전했으나, VAE 정책은 수학적으로 안정적인 학습 기반을 제공하며 생성 AI 정책의 기틀을 닦음(RL Update).
|
||||
- **정책 변화(RL Update)**: 현대의 고품질 이미지 생성 정책(Stable Diffusion 등)에서, VAE는 이미지를 효율적인 잠재 공간으로 옮겨 연산 부하를 줄이는 'Latent Diffusion' 정책의 핵심 부품(Encoder/Decoder)으로 재배치되어 제2의 전성기를 누림.
|
||||
### Vanilla VAE (PyTorch 2.x)
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
---
|
||||
class VAE(nn.Module):
|
||||
def __init__(self, in_dim=784, hidden=400, z_dim=20):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(in_dim, hidden)
|
||||
self.fc_mu = nn.Linear(hidden, z_dim)
|
||||
self.fc_logvar = nn.Linear(hidden, z_dim)
|
||||
self.fc2 = nn.Linear(z_dim, hidden)
|
||||
self.fc3 = nn.Linear(hidden, in_dim)
|
||||
|
||||
- **과거 데이터와의 충돌:** 단순히 데이터를 복원만 하던 일반 오토인코더(AE)와 달리, 잠재 공간의 연속성을 확보함으로써 '새로운' 데이터를 생성할 수 있는 능력을 갖춤.
|
||||
- **정책 변화:** Antigravity 프로젝트는 위키 문서의 의미적 유사성 분석 및 문서 간 '누락된 연결 고리'를 생성적 추론으로 찾기 위해 VAE 기반의 잠재 공간 분석 기법을 활용함.
|
||||
def encode(self, x):
|
||||
h = F.relu(self.fc1(x))
|
||||
return self.fc_mu(h), self.fc_logvar(h)
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Self-Supervised Learning (SSL)|Self-Supervised Learning (SSL)]], Foundational Models, [[Straightening|Straightening]], [[Probability Theory|Probability Theory]], [[Style-Transfer|Style-Transfer]]
|
||||
- **Modern Tech/Tools**: Stable Diffusion VAE, Beta-VAE, PyTorch VAE, Keras Generative.
|
||||
---
|
||||
def reparameterize(self, mu, logvar):
|
||||
std = torch.exp(0.5 * logvar)
|
||||
eps = torch.randn_like(std)
|
||||
return mu + eps * std
|
||||
|
||||
---
|
||||
def decode(self, z):
|
||||
return torch.sigmoid(self.fc3(F.relu(self.fc2(z))))
|
||||
|
||||
- Autoencoder, [[Generative-Adversarial-Networks|Generative-Adversarial-Networks]]-GAN, [[Representation-Learning|Representation-Learning]], [[Uncertainty-Quantification|Uncertainty-Quantification]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Variational-Autoencoders-VAE.md
|
||||
def forward(self, x):
|
||||
mu, logvar = self.encode(x)
|
||||
z = self.reparameterize(mu, logvar)
|
||||
return self.decode(z), mu, logvar
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (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
|
||||
def vae_loss(recon, x, mu, logvar):
|
||||
bce = F.binary_cross_entropy(recon, x, reduction='sum')
|
||||
kld = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
|
||||
return bce + kld
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Training loop
|
||||
```python
|
||||
model = VAE().cuda()
|
||||
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
||||
for epoch in range(50):
|
||||
for x, _ in loader:
|
||||
x = x.view(-1, 784).cuda()
|
||||
recon, mu, logvar = model(x)
|
||||
loss = vae_loss(recon, x, mu, logvar)
|
||||
opt.zero_grad(); loss.backward(); opt.step()
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### β-VAE (disentanglement)
|
||||
```python
|
||||
def beta_vae_loss(recon, x, mu, logvar, beta=4.0):
|
||||
bce = F.binary_cross_entropy(recon, x, reduction='sum')
|
||||
kld = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
|
||||
return bce + beta * kld
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### VQ-VAE (vector quantization)
|
||||
```python
|
||||
class VectorQuantizer(nn.Module):
|
||||
def __init__(self, num_embeddings=512, embedding_dim=64, commitment=0.25):
|
||||
super().__init__()
|
||||
self.embed = nn.Embedding(num_embeddings, embedding_dim)
|
||||
self.embed.weight.data.uniform_(-1.0 / num_embeddings, 1.0 / num_embeddings)
|
||||
self.commitment = commitment
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
def forward(self, z_e): # z_e: (B, C, H, W)
|
||||
z_e_perm = z_e.permute(0, 2, 3, 1).contiguous()
|
||||
flat = z_e_perm.view(-1, z_e_perm.size(-1))
|
||||
# Nearest codebook vector
|
||||
d = (flat.pow(2).sum(1, keepdim=True)
|
||||
- 2 * flat @ self.embed.weight.t()
|
||||
+ self.embed.weight.pow(2).sum(1))
|
||||
idx = d.argmin(1)
|
||||
z_q = self.embed(idx).view(z_e_perm.shape).permute(0, 3, 1, 2)
|
||||
# Straight-through estimator
|
||||
loss = F.mse_loss(z_q.detach(), z_e) + self.commitment * F.mse_loss(z_q, z_e.detach())
|
||||
z_q = z_e + (z_q - z_e).detach()
|
||||
return z_q, loss, idx
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Sample / generate
|
||||
```python
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
z = torch.randn(64, 20).cuda()
|
||||
samples = model.decode(z).view(-1, 1, 28, 28).cpu()
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Latent diffusion VAE (SD-style — using diffusers)
|
||||
```python
|
||||
from diffusers import AutoencoderKL
|
||||
import torch
|
||||
|
||||
vae = AutoencoderKL.from_pretrained('stabilityai/sd-vae-ft-mse').cuda()
|
||||
# Encode 512x512 image → 4-ch 64x64 latent
|
||||
img = torch.randn(1, 3, 512, 512).cuda()
|
||||
latent = vae.encode(img).latent_dist.sample() * vae.config.scaling_factor
|
||||
# Diffusion happens in latent space, then decode
|
||||
recon = vae.decode(latent / vae.config.scaling_factor).sample
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 목적 | Choice |
|
||||
|---|---|
|
||||
| 2026 SOTA 이미지 생성 | Diffusion (FLUX, Stable Diffusion 3.5) — 매 VAE 의 frontend 만 |
|
||||
| Disentangled representation 연구 | β-VAE |
|
||||
| Discrete latent (LLM tokenize 유사) | VQ-VAE / VQ-GAN |
|
||||
| Anomaly detection | Vanilla VAE — reconstruction error |
|
||||
| Latent diffusion 학습 | Pre-trained KL-regularized VAE (e.g. SD VAE) reuse |
|
||||
| Molecular / structured generation | VAE (continuous latent) — 매 still competitive |
|
||||
|
||||
**기본값**: 매 image generation 의 directly 의 X — 매 latent diffusion 안 의 VAE 로 사용. 매 disentanglement / anomaly 의 standalone VAE.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Generative Models]] · [[Variational Inference]]
|
||||
- 변형: [[β-VAE]] · [[VQ-VAE]] · [[NVAE]] · [[Conditional VAE]]
|
||||
- 응용: [[Latent Diffusion]] · [[Stable Diffusion]] · [[FLUX]] · [[Sora]]
|
||||
- Adjacent: [[Diffusion Models]] · [[GAN]] · [[Normalizing Flows]] · [[Autoencoders]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 latent diffusion 의 VAE component 설명, 매 anomaly detection baseline 작성, 매 ELBO 수학 의 derivation, 매 reparameterization trick 의 implementation.
|
||||
**언제 X**: 매 standalone SOTA image generation (diffusion 우선), 매 sharp output 필수 (GAN/diffusion).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Posterior collapse**: q(z|x) → p(z) 의 무시 → KL=0, decoder 의 z 의 ignore. 매 KL annealing / β scheduling 필요.
|
||||
- **Pixel-space VAE 의 high-res 직접**: 매 blurry, 매 8× downsample latent + diffusion 으로 decouple.
|
||||
- **σ 의 직접 output**: 매 negative 가능. 매 logvar 의 output → σ = exp(0.5 * logvar).
|
||||
- **KL 의 mean reduction**: 매 batch mean 의 reconstruction 의 sum 과 mismatch — 매 두 term 의 same reduction.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Kingma & Welling 2013 ICLR, Stable Diffusion paper, NVIDIA NVAE, DeepMind β-VAE).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full VAE with ELBO, β-VAE, VQ-VAE, latent diffusion role, 6 patterns |
|
||||
|
||||
Reference in New Issue
Block a user