[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,66 +1,255 @@
---
id: wiki-2026-0508-deep-convolutional-gans
title: Deep Convolutional GANs
id: wiki-2026-0508-dcgan
title: DCGAN (Deep Convolutional GAN)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-DCGN-001]
aliases: [DCGAN, GAN, generative adversarial network, StyleGAN, CycleGAN, Pix2Pix]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, dcgan, Generative-Adversarial-Networks, Computer-Vision, Deep-Learning, image-generation, cnn]
confidence_score: 0.88
verification_status: applied
tags: [gan, dcgan, generative-models, deep-learning, image-generation, stylegan, cyclegan, history]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: PyTorch
---
# [[Deep-Convolutional-GANs|Deep-Convolutional-GANs]]
# DCGAN
## 📌 한 줄 통찰 (The Karpathy Summary)
> "눈을 가진 생성기: 초기 GAN의 불안정성을 합성곱 신경망(CNN) 구조로 극복하여, AI가 픽셀의 단순 조합을 넘어 사물의 기하학적 형태와 질감을 이해하고 진짜 같은 이미지를 그려내게 만든 현대 생성 AI의 선조."
## 한 줄
> **"매 GAN first 의 stable architecture"** (Radford 2015). 매 stride conv + 매 batch norm + 매 specific activation. 매 generative AI 의 grandparent. 매 modern: 매 Diffusion 의 superseded 가, 매 fast inference / GAN-based super-res / image-to-image 의 still relevant.
## 📖 구조화된 지식 (Synthesized Content)
DCGAN(Deep-Convolutional-GANs)은 GAN 아키텍처에 CNN을 도입하여 이미지 생성 성능을 획기적으로 개선한 모델입니다. (Alec Radford 등이 2015년 발표)
## 매 핵심
1. **아키텍처 혁신**:
* **Strided Convolutions**: 풀링([[Pooling|Pooling]]) 대신 스트라이드 합성곱을 사용하여 공간 정보를 보존하면서 차원을 조절.
* **Batch [[Normalization|Normalization]]**: 생성자와 판별자 모두에 적용하여 학습 초기의 불안정성 해소. ([[Reliability|Reliability]]와 연결)
* **Activation Functions**: 생성자에는 ReLU와 Tanh 사용, 판별자에는 LeakyReLU 사용.
2. **의의**:
* 특징 공간(Feature Space) 상의 '벡터 산술 연산'을 통해 안경 쓴 남성 - 남성 + 여성 = 안경 쓴 여성 같은 고차원 개념 조작이 가능함을 증명함. ([[Representation-Learning|Representation-Learning]]와 연결)
### 매 GAN basics (Goodfellow 2014)
- **Generator**: 매 noise → 매 image.
- **Discriminator**: 매 real vs fake.
- **Min-max game**.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거 GAN 정책은 학습이 매우 어려워 '운'에 의존하는 경과 정책(Mode collapse)이 잦았으나, DCGAN 정책은 검증된 아키텍처 정책 가이드라인을 제시하여 누구나 안정적인 생성 정책이 가능하게 함(RL Update).
- **정책 변화(RL Update)**: 현재는 확산 모델(Diffusion Models) 정책에 밀려 주류에서 물러났으나, 실시간 이미지 변환 정책이나 특정 도메인 데이터 증강 정책 등에서는 여전히 효율적인 선택지로 쓰임.
### DCGAN (2015) 의 contribution
1. **Strided conv** (no pooling).
2. **BatchNorm** in both G and D.
3. **No fully-connected hidden** layer.
4. **ReLU in G** (Tanh output).
5. **LeakyReLU in D**.
## 🔗 지식 연결 (Graph)
- [[Representation-Learning|Representation-Learning]], [[Reliability|Reliability]], Deep Learning (DL), [[Feature-Engineering|Feature-Engineering]], [[Research|Research]]
- **Key Milestones**: Vector Arithmetic in Feature Space.
---
### 매 famous GAN evolution
- **DCGAN** (2015): 매 stable.
- **WGAN** (2017): 매 Wasserstein loss, 매 mode collapse 의 mitigate.
- **Pix2Pix** (2017): 매 image-to-image.
- **CycleGAN** (2017): 매 unpaired.
- **StyleGAN** (2018-2021): 매 face quality SOTA.
- **BigGAN** (2018): 매 large-scale.
- **GigaGAN** (2023): 매 text-to-image GAN.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 mode collapse
- 매 G 의 매 limited variety 의 generate.
- 매 mitigation: 매 minibatch discrimination, 매 spectral norm, 매 WGAN.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 evaluation
- **FID** (Fréchet Inception Distance): 매 generated vs real 의 distance.
- **IS** (Inception Score).
- **Precision / Recall** (Kynkäänniemi 2019).
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 modern relevance
- **Super-resolution** (ESRGAN, Real-ESRGAN).
- **Image-to-image** (CycleGAN 의 still useful).
- **Domain adaptation** (sim2real).
- **Implicit EBM**.
- **Fast generation** (vs slow diffusion).
## 🧪 검증 상태 (Validation)
### 매 vs Diffusion
| 측면 | GAN | Diffusion |
|---|---|---|
| Quality | High (StyleGAN) | Highest |
| Diversity | Mode collapse risk | High |
| Training stability | Tricky | Stable |
| Inference speed | Fast (single step) | Slow (multi-step) |
| Conditioning | Hard | Easy (CLIP) |
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 💻 패턴
## 🧬 중복 검사 (Duplicate Check)
### DCGAN (PyTorch)
```python
import torch.nn as nn
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
class Generator(nn.Module):
def __init__(self, nz=100, ngf=64, nc=3):
super().__init__()
self.main = nn.Sequential(
# 매 input: nz × 1 × 1
nn.ConvTranspose2d(nz, ngf*8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf*8),
nn.ReLU(True),
# 매 ngf*8 × 4 × 4
nn.ConvTranspose2d(ngf*8, ngf*4, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf*4),
nn.ReLU(True),
# 매 ... → 매 nc × 64 × 64
nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),
nn.Tanh(),
)
def forward(self, z):
return self.main(z)
## 🕓 변경 이력 (Changelog)
class Discriminator(nn.Module):
def __init__(self, ndf=64, nc=3):
super().__init__()
self.main = nn.Sequential(
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, True),
nn.Conv2d(ndf, ndf*2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf*2),
nn.LeakyReLU(0.2, True),
# 매 ...
nn.Conv2d(ndf*8, 1, 4, 1, 0, bias=False),
nn.Sigmoid(),
)
def forward(self, x):
return self.main(x).view(-1)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Training loop
```python
G = Generator().to('cuda')
D = Discriminator().to('cuda')
opt_g = torch.optim.Adam(G.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(D.parameters(), lr=2e-4, betas=(0.5, 0.999))
criterion = nn.BCELoss()
for real, _ in loader:
real = real.to('cuda')
bs = real.size(0)
# 매 D step
opt_d.zero_grad()
d_real = D(real)
loss_real = criterion(d_real, torch.ones(bs).to('cuda'))
z = torch.randn(bs, 100, 1, 1).to('cuda')
fake = G(z)
d_fake = D(fake.detach())
loss_fake = criterion(d_fake, torch.zeros(bs).to('cuda'))
(loss_real + loss_fake).backward()
opt_d.step()
# 매 G step
opt_g.zero_grad()
d_fake = D(fake)
loss_g = criterion(d_fake, torch.ones(bs).to('cuda'))
loss_g.backward()
opt_g.step()
```
### WGAN-GP (modern stable)
```python
def gradient_penalty(D, real, fake):
bs = real.size(0)
alpha = torch.rand(bs, 1, 1, 1).to(real.device)
interp = alpha * real + (1 - alpha) * fake
interp.requires_grad_()
d_interp = D(interp)
grads = torch.autograd.grad(d_interp.sum(), interp, create_graph=True)[0]
grad_norm = grads.view(bs, -1).norm(2, dim=1)
return ((grad_norm - 1) ** 2).mean()
# 매 D step
loss_d = D(fake).mean() - D(real).mean() + 10 * gradient_penalty(D, real, fake)
```
### Real-ESRGAN (super-resolution, modern application)
```python
from realesrgan import RealESRGAN
from PIL import Image
model = RealESRGAN(device='cuda', scale=4)
model.load_weights('weights/RealESRGAN_x4.pth', download=True)
img = Image.open('low_res.jpg')
sr_img = model.predict(img)
sr_img.save('high_res.jpg')
```
### CycleGAN (unpaired image-to-image)
```python
# 매 매 horse → 매 zebra (no pair)
# 매 G_ab: 매 A → B, 매 G_ba: 매 B → A
# 매 cycle loss: 매 G_ba(G_ab(a)) ≈ a
```
### StyleGAN inversion (modern)
```python
from stylegan2_pytorch import Trainer
# 매 매 image 의 latent z 의 find
def invert(image, generator, n_iters=1000):
z = torch.randn(1, 512, requires_grad=True)
for _ in range(n_iters):
gen = generator(z)
loss = (gen - image).pow(2).mean()
loss.backward()
z.data -= 0.01 * z.grad.data
z.grad.zero_()
return z
```
### FID evaluation
```python
from pytorch_fid import fid_score
fid = fid_score.calculate_fid_given_paths(
['./real_images/', './fake_images/'],
batch_size=50,
device='cuda',
dims=2048,
)
print(f'FID: {fid:.2f}') # 매 lower 의 better
```
## 매 결정 기준
| 응용 | Method |
|---|---|
| Photoreal generation | Diffusion (SDXL, Flux) |
| Face | StyleGAN3 |
| Super-resolution | Real-ESRGAN |
| Domain adapt (unpaired) | CycleGAN |
| Sim2Real | CycleGAN / paired |
| Fast inference | GAN > Diffusion |
| Quality + control | Diffusion + ControlNet |
**기본값**: 매 modern generation = Diffusion. 매 GAN = 매 SR / I2I 의 still.
## 🔗 Graph
- 부모: [[Generative-Models]] · [[Deep-Learning]]
- 변형: [[GAN]] · [[WGAN]] · [[StyleGAN]] · [[BigGAN]] · [[GigaGAN]] · [[Pix2Pix]] · [[CycleGAN]]
- 응용: [[Super-Resolution]] · [[Image-to-Image]] · [[Domain-Adaptation]] · [[CV_Synthesis]]
- Adjacent: [[Diffusion-Models]] · [[Auto-Encoding]] · [[Stable-Diffusion]] · [[Deepfake-Technology]]
## 🤖 LLM 활용
**언제**: 매 GAN history. 매 fast generation. 매 super-res. 매 image-to-image.
**언제 X**: 매 highest quality (use diffusion).
## ❌ 안티패턴
- **DCGAN 의 production 의 force**: 매 modern 의 diffusion 더 좋음.
- **No mode collapse check**: 매 single output.
- **WGAN-GP 없 의 unstable**: 매 training fail.
- **FID 만 의 trust**: 매 다른 metric 도.
## 🧪 검증 / 중복
- Verified (Goodfellow GAN, Radford DCGAN, Karras StyleGAN, Real-ESRGAN).
- 신뢰도 A.
- Related: [[Diffusion-Models]] · [[Auto-Encoding]] · [[Stable-Diffusion]] · [[Deepfake-Technology]] · [[CV_Synthesis]] · [[Bioenergetics]] (model collapse).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — DCGAN architecture + GAN evolution + 매 PyTorch / WGAN-GP / Real-ESRGAN code |