[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
+173 -39
View File
@@ -2,62 +2,196 @@
id: wiki-2026-0508-neural-style-transfer
title: Neural Style Transfer
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [AI-NST-001]
aliases: [NST, Style Transfer, Gatys Style Transfer, AdaIN]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [ai, Computer-Vision, neural-Style-Transfer, nst, generative-art, vgg]
confidence_score: 0.93
verification_status: applied
tags: [computer-vision, deep-learning, style-transfer, gatys, adain, diffusion, generative-art]
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: python, framework: pytorch }
---
# Neural Style Transfer (신경망 스타일 전이)
## 한 줄
## 📌 한 줄 통찰 (The Karpathy Summary)
> "원본의 '형체'는 유지하되 화가의 '붓 터치'를 덧입혀, 기계의 계산으로 예술의 영혼을 재현하라" — 콘텐츠 이미지의 구조적 정보와 스타일 이미지의 예술적 질감을 신경망 내부에서 분리하고 합성하여 새로운 이미지를 생성하는 기술.
Neural Style Transfer(NST)는 콘텐츠 이미지의 구조를 유지하면서 스타일 이미지의 텍스처/색감을 합성하기 위해, 사전학습 CNN의 feature와 Gram matrix를 활용해 입력 이미지를 최적화하거나 별도 네트워크로 학습하는 기법군이다.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Feature Disent[[ANGLE|ANGLE]]ment and Recomposition" — 미리 학습된 합성곱 신경망(주로 VGG-19)의 깊은 층에서는 사물의 형태를, 얕은 층에서는 색감과 질감을 추출한다는 점을 활용하여 두 특징 사이의 손실(Loss)을 최소화하며 픽셀을 최적화하는 패턴.
- **핵심 손실 함수:**
- **Content Loss:** 원본 이미지와 생성된 이미지의 특징 맵 차이 측정.
- **Style Loss:** 스타일 이미지의 특징들 사이의 상관관계(Gram Matrix)를 통해 예술적 패턴 복제.
- **Total Variation Loss:** 이미지의 노이즈를 줄이고 매끄럽게 만듦.
- **의의:** 딥러닝이 단순한 분류를 넘어 창의적인 예술 영역(Generative Art)에 발을 들이게 한 결정적인 사례이며, 필터 앱이나 영상 효과 등 실전 서비스에 널리 응용됨.
## 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 초기에는 한 장의 이미지를 생성하는 데 수천 번의 반복 연산이 필요했으나, 이제는 Fast Style Transfer나 AdaIN(Adaptive Instance [[Normalization|Normalization]]) 기법을 통해 실시간으로 스타일을 입히는 것이 가능해짐.
- **정책 변화:** Antigravity 프로젝트는 에이전트가 생성하는 시각적 리포트나 대시보드 테마에 사용자의 취향을 반영한 스타일 전이 기술을 적용하여 개인화된 UI 경험을 제공함.
### Gatys et al. 2015 (원형)
- 사전학습 VGG-19 사용.
- **Content loss**: 특정 layer (예: conv4_2) feature MSE.
- **Style loss**: 여러 layer Gram matrix MSE — 채널 간 상관관계가 텍스처를 표현.
- 입력 이미지 자체를 최적화 (수십 초~수 분).
- 총 손실: `L = α·L_content + β·L_style`.
## 🔗 지식 연결 (Graph)
- Computer-Vision-Foundations, [[Generative-Adversarial-Networks|Generative-Adversarial-Networks]]-GAN, [[Image-Segmentation|Image-Segmentation]], [[Convolutional-Neural-Networks|Convolutional-Neural-Networks]]-CNN
- **Raw Source:** 10_Wiki/Topics/AI/Neural-Style-Transfer.md
### Fast Neural Style (Johnson 2016)
- 한 번에 한 스타일을 학습한 transformation network.
- 추론 시 단일 forward pass — 실시간.
- 손실은 여전히 VGG perceptual + Gram.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Arbitrary Style Transfer
- **AdaIN** (Huang & Belongie 2017): 콘텐츠 feature의 평균/분산을 스타일에 맞춰 정규화.
- **WCT** (Whitening & Coloring Transform).
- 임의 스타일 한 번에 처리 (재학습 불필요).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 현대(2023-26)
- **Diffusion-based**: SDXL + IP-Adapter, ControlNet, Stable Diffusion Style LoRA.
- **InstantStyle (2024)**: 단일 참조 이미지로 스타일 추출, content leakage 차단.
- **StyleGAN inversion + edit**.
- 영상: AnimateDiff + style.
**언제 쓰면 안 되는가:**
- *(TODO)*
### 변형 / 응용
- Photorealistic style transfer (PhotoWCT, deep photo style transfer).
- 비디오 NST — temporal consistency loss.
- 3D NST (NeRF + style).
- 폰트, 음성 스타일 변환.
## 🧪 검증 상태 (Validation)
## 💻 패턴
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
```python
# 1. Gatys NST — VGG19 기반 (PyTorch)
import torch, torch.nn as nn, torch.optim as optim
from torchvision.models import vgg19
## 🧬 중복 검사 (Duplicate Check)
vgg = vgg19(weights="DEFAULT").features.eval().cuda()
for p in vgg.parameters(): p.requires_grad = False
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def gram(x):
b,c,h,w = x.shape
f = x.view(b,c,h*w)
return f @ f.transpose(1,2) / (c*h*w)
## 🕓 변경 이력 (Changelog)
content_layers = ["conv4_2"]
style_layers = ["conv1_1","conv2_1","conv3_1","conv4_1","conv5_1"]
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
```python
# 2. NST 최적화 루프
img = content.clone().requires_grad_(True)
opt = optim.LBFGS([img])
def closure():
opt.zero_grad()
feats = extract(vgg, img)
cl = sum(F.mse_loss(feats[l], target_content[l]) for l in content_layers)
sl = sum(F.mse_loss(gram(feats[l]), gram_style[l]) for l in style_layers)
loss = 1.0*cl + 1e6*sl
loss.backward()
return loss
for _ in range(300): opt.step(closure)
```
```python
# 3. Fast Style Transfer — transformer net
class TransformerNet(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
ConvBlock(3,32,9,1), ConvBlock(32,64,3,2), ConvBlock(64,128,3,2),
)
self.residual = nn.Sequential(*[ResBlock(128) for _ in range(5)])
self.decoder = nn.Sequential(
UpsampleConv(128,64), UpsampleConv(64,32), nn.Conv2d(32,3,9,padding=4),
)
def forward(self, x): return self.decoder(self.residual(self.encoder(x)))
```
```python
# 4. AdaIN — 임의 스타일
def adain(content_feat, style_feat, eps=1e-5):
c_mean, c_std = content_feat.mean([2,3], keepdim=True), content_feat.std([2,3], keepdim=True)+eps
s_mean, s_std = style_feat.mean([2,3], keepdim=True), style_feat.std([2,3], keepdim=True)+eps
return s_std * (content_feat - c_mean) / c_std + s_mean
```
```python
# 5. Total variation loss — 노이즈 억제
def tv_loss(img):
return ((img[:,:,1:,:] - img[:,:,:-1,:])**2).mean() + \
((img[:,:,:,1:] - img[:,:,:,:-1])**2).mean()
```
```python
# 6. Color preservation — luminance only NST
import cv2, numpy as np
yuv = cv2.cvtColor(stylized, cv2.COLOR_RGB2YUV)
yuv[:,:,1:] = cv2.cvtColor(content_orig, cv2.COLOR_RGB2YUV)[:,:,1:]
preserved = cv2.cvtColor(yuv, cv2.COLOR_YUV2RGB)
```
```python
# 7. Diffusion + IP-Adapter — 2024 표준
from diffusers import StableDiffusionXLPipeline
pipe = StableDiffusionXLPipeline.from_pretrained("...").to("cuda")
pipe.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models",
weight_name="ip-adapter_sdxl.safetensors")
pipe.set_ip_adapter_scale(0.7)
result = pipe(prompt="a cat", ip_adapter_image=style_img).images[0]
```
```python
# 8. Style LoRA + Stable Diffusion
pipe.load_lora_weights("path/to/style_lora.safetensors")
pipe.fuse_lora()
img = pipe(prompt="cyberpunk city <lora:style:0.8>").images[0]
```
```python
# 9. 비디오 NST — temporal consistency
def temporal_loss(stylized_t, stylized_t_prev, flow):
warped = warp(stylized_t_prev, flow)
return F.mse_loss(stylized_t, warped) * mask
```
```python
# 10. InstantStyle — content/style 분리
# IP-Adapter blocks 중 style-specific block만 활성화
pipe.set_ip_adapter_scale({"down": {"block_2": [0,1]}, "up": {"block_0": [0,1,1]}})
```
## 결정 기준
| 상황 | 추천 |
|---|---|
| 단일 결과, 최고 품질 | Gatys NST (LBFGS, VGG19) |
| 실시간 / 영상 | Fast NST 또는 AdaIN |
| 임의 스타일 | AdaIN, WCT |
| 사진 사실성 유지 | PhotoWCT, deep photo style |
| 텍스트 프롬프트 함께 | SDXL + IP-Adapter |
| 일관된 브랜드 스타일 | Style LoRA fine-tune |
| 비디오 | temporal loss + Fast NST 또는 AnimateDiff |
| 콘텐츠 누출 차단 | InstantStyle 블록 마스킹 |
기본값: 일회성 결과는 Gatys, 프로덕션은 SDXL+IP-Adapter.
## 🔗 Graph
- 부모: [[Computer-Vision]], [[Generative-AI]], [[Image-Generation]]
- 형제: [[GAN]], [[Diffusion-Models]], [[Stable-Diffusion]], [[CycleGAN]]
- 자식: [[AdaIN]], [[Fast-Style-Transfer]], [[IP-Adapter]], [[InstantStyle]]
- 응용: [[Generative-Art]], [[Photo-Filters]], [[Video-Stylization]]
## 🤖 LLM 활용
- VLM이 스타일 키워드 추출 ("Van Gogh, post-impressionist, swirling brushstrokes") → SD prompt 자동.
- LLM agent가 NST 파라미터(α/β, layer 선택) 자동 튜닝.
- 평가: CLIP score로 style 일치도 측정.
## ❌ 안티패턴
- Style/content weight 비율 무튜닝 — 결과 품질 좌우.
- VGG 외 backbone에서 동일 layer 가정.
- 영상에 frame별 NST만 적용 → 깜빡임.
- IP-Adapter scale=1.0 → content 누출.
## 🧪 검증 / 중복
- 정량: SSIM (content), Gram MSE (style), CLIP similarity.
- 정성: 사용자 평가.
- 중복: [[Style-Transfer]] 별칭 통합.
## 🕓 Changelog
- Phase 1 (2026-05-08): 초기 생성.
- Manual cleanup (2026-05-10): canonical 확정, Gatys → AdaIN → 확산 모델까지 흐름 정리, IP-Adapter/InstantStyle 추가.