Latent Diffusion
Latent Diffusion Model
잠재 공간에서 디퓨전을 수행하는 효율적인 이미지 생성 모델. Stable Diffusion의 기반.
Latent Diffusion Model
잠재 공간에서 디퓨전을 수행하는 효율적인 이미지 생성 모델. Stable Diffusion의 기반.
Latent Diffusion Model(LDM)은 픽셀 공간이 아닌 잠재 공간(Latent Space)에서 디퓨전을 수행하는 생성 모델입니다. 2022년 Rombach 등이 제안했으며, Stable Diffusion, DALL-E 3, Midjourney의 핵심 기술입니다.
기존 Diffusion 모델(DDPM)은 512x512 이미지를 직접 처리해 계산량이 막대했습니다. LDM은 먼저 Autoencoder로 이미지를 64x64 잠재 벡터로 압축하고, 이 작은 공간에서 디퓨전을 수행해 연산량을 50배 이상 줄입니다.
구조: VAE Encoder(이미지→잠재공간), U-Net(노이즈 예측), VAE Decoder(잠재공간→이미지), Text Encoder(CLIP/T5로 텍스트 임베딩). 학습 시 잠재 벡터에 노이즈를 추가하고, U-Net이 이를 제거하는 방향으로 학습합니다.
실무 활용: Text-to-Image(프롬프트→이미지), Image-to-Image(이미지 편집), Inpainting(부분 수정), ControlNet(포즈/엣지 조건부 생성). SDXL, Stable Diffusion 3.5 등 최신 모델은 더 높은 품질과 프롬프트 이해력을 제공합니다.
# pip install diffusers transformers accelerate torch
from diffusers import StableDiffusionPipeline, StableDiffusionXLPipeline
from diffusers import StableDiffusionImg2ImgPipeline
import torch
# 1. Text-to-Image (기본 생성)
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
variant="fp16"
).to("cuda")
image = pipe(
prompt="A futuristic city at sunset, cyberpunk style, highly detailed",
negative_prompt="blurry, low quality, distorted",
num_inference_steps=30, # 스텝 수 (품질 vs 속도)
guidance_scale=7.5, # CFG scale (프롬프트 충실도)
width=1024, height=1024
).images[0]
image.save("generated.png")
# 2. Image-to-Image (이미지 변환)
img2img_pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16
).to("cuda")
from PIL import Image
init_image = Image.open("input.png").resize((512, 512))
result = img2img_pipe(
prompt="Same scene but in watercolor painting style",
image=init_image,
strength=0.75, # 0=원본 유지, 1=완전 새 이미지
guidance_scale=7.5
).images[0]
# 3. ControlNet (포즈 조건부 생성)
from diffusers import ControlNetModel, StableDiffusionControlNetPipeline
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/control_v11p_sd15_openpose", torch_dtype=torch.float16
)
cn_pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
controlnet=controlnet, torch_dtype=torch.float16
).to("cuda")
pose_image = Image.open("pose.png") # OpenPose 스켈레톤
result = cn_pipe(prompt="A dancer in red dress", image=pose_image).images[0]
"상품 썸네일 자동 생성에 SDXL 사용하겠습니다. ControlNet Canny로 제품 윤곽을 유지하면서 배경만 바꾸면 됩니다. A100 한 대로 초당 2장, 월 10만 장 처리 가능해요."
"Latent Diffusion의 핵심은 연산 효율성입니다. 512x512를 직접 처리하면 262K 픽셀인데, VAE로 64x64 latent(4K 요소)로 압축하면 50배 적은 연산으로 동일 품질을 얻습니다. Classifier-Free Guidance로 품질과 다양성 균형도 잡았어요."
"SD3의 Rectified Flow가 기존 DDPM보다 샘플링이 빨라요. 50스텝이 20스텝으로 줄고 품질은 유지됩니다. 하지만 텍스트 렌더링은 아직 DALL-E 3가 낫고, Midjourney는 미적 품질에서 앞서요."
CFG 15 이상은 이미지가 과포화되고 아티팩트 발생. 일반적으로 7-9가 적정 범위입니다.
특정 아티스트/캐릭터 스타일 학습은 법적 리스크. 상업용은 반드시 라이선스 확인하세요.
Negative prompt로 원치 않는 요소 제거. VRAM 부족 시 xformers나 torch.compile 사용. 상업용은 SDXL Turbo나 허가된 모델 사용.