🤖 AI/ML

Diffusion Model

Diffusion Model

A model that generates images by progressively removing noise. The basis of Stable Diffusion and DALL-E 3.

📖 Detailed Explanation

A Diffusion Model is a generative model that learns the process of gradually adding noise to data, then reverses it to generate data from noise. Since the 2020 DDPM (Denoising Diffusion Probabilistic Model) paper, it has developed rapidly and has become the dominant architecture replacing GANs in the field of image generation. Most of today's state-of-the-art image generation AIs, such as Stable Diffusion, DALL-E 3, Midjourney, and Imagen, are diffusion-based.

The core principle of diffusion is divided into two processes. In the Forward Process (diffusion process), Gaussian noise is gradually added to the original image until it becomes pure random noise. In the Reverse Process (reverse diffusion process), a trained neural network removes the noise a little at a time at each step to restore the original data. The model is trained to predict "how much noise should be removed from the current noisy image."

As of 2024-2025, diffusion models have gone through several innovations. The Latent Diffusion Model (LDM) performs diffusion in a compressed latent space rather than pixel space, greatly reducing computational cost (the basis of Stable Diffusion). Classifier-Free Guidance dramatically improved the quality of conditional generation. Recently, techniques that generate high-quality images in few steps, such as Consistency Models and SDXL Turbo, have emerged, making real-time generation possible.

Diffusion models are expanding beyond images into various domains such as video (Sora, RunwayML), audio (AudioLDM), 3D (DreamFusion), and protein structures (RFdiffusion). In particular, in text-to-image generation, it has become standard to combine them with multimodal encoders such as CLIP to generate desired images from natural language prompts. In enterprise settings, they are actively used for product image generation, advertising creatives, game asset production, and more.

💻 Code Example

Image generation with Stable Diffusion (Diffusers library)

from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
import torch

# Stable Diffusion XL 파이프라인 로드
pipe = StableDiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
    use_safetensors=True
)
pipe = pipe.to("cuda")

# 빠른 스케줄러로 교체 (20스텝으로 고품질 생성)
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
    pipe.scheduler.config
)

# 텍스트-to-이미지 생성
prompt = "A futuristic city skyline at sunset, cyberpunk style, 8k, detailed"
negative_prompt = "blurry, low quality, distorted"

image = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=25,
    guidance_scale=7.5,  # Classifier-Free Guidance 강도
    height=1024,
    width=1024
).images[0]

image.save("generated_city.png")

# 이미지-to-이미지 변환 (기존 이미지 스타일 변경)
from diffusers import AutoPipelineForImage2Image
from PIL import Image

img2img_pipe = AutoPipelineForImage2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16
).to("cuda")

init_image = Image.open("input.jpg").resize((512, 512))
result = img2img_pipe(
    prompt="oil painting style",
    image=init_image,
    strength=0.7,  # 원본 유지 정도 (0=원본, 1=완전 새로 생성)
    num_inference_steps=4  # SDXL Turbo는 4스텝으로 충분
).images[0]

Implementing core DDPM concepts (for learning)

import torch
import torch.nn as nn
import torch.nn.functional as F

class SimpleDiffusion:
    """DDPM의 핵심 개념을 단순화한 구현"""
    def __init__(self, timesteps=1000, beta_start=1e-4, beta_end=0.02):
        self.timesteps = timesteps
        # 노이즈 스케줄 정의
        self.betas = torch.linspace(beta_start, beta_end, timesteps)
        self.alphas = 1.0 - self.betas
        self.alpha_cumprod = torch.cumprod(self.alphas, dim=0)

    def forward_diffusion(self, x0, t):
        """Forward process: 원본에 노이즈 추가"""
        noise = torch.randn_like(x0)
        sqrt_alpha_cumprod = self.alpha_cumprod[t].sqrt()
        sqrt_one_minus = (1 - self.alpha_cumprod[t]).sqrt()

        # x_t = sqrt(alpha_cumprod) * x_0 + sqrt(1-alpha_cumprod) * noise
        xt = sqrt_alpha_cumprod.view(-1, 1, 1, 1) * x0 + \
             sqrt_one_minus.view(-1, 1, 1, 1) * noise
        return xt, noise

    def training_step(self, model, x0, optimizer):
        """학습: 노이즈 예측"""
        batch_size = x0.shape[0]
        t = torch.randint(0, self.timesteps, (batch_size,))

        xt, noise = self.forward_diffusion(x0, t)
        predicted_noise = model(xt, t)

        loss = F.mse_loss(predicted_noise, noise)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        return loss.item()

    @torch.no_grad()
    def sample(self, model, shape, device):
        """Reverse process: 노이즈에서 이미지 생성"""
        x = torch.randn(shape, device=device)

        for t in reversed(range(self.timesteps)):
            t_batch = torch.full((shape[0],), t, device=device)
            predicted_noise = model(x, t_batch)

            alpha = self.alphas[t]
            alpha_cumprod = self.alpha_cumprod[t]
            beta = self.betas[t]

            if t > 0:
                noise = torch.randn_like(x)
            else:
                noise = 0

            # 노이즈 제거 스텝
            x = (1 / alpha.sqrt()) * (
                x - (beta / (1 - alpha_cumprod).sqrt()) * predicted_noise
            ) + beta.sqrt() * noise

        return x

📊 Performance & Cost

Model Generation time (per image) VRAM requirements API cost
Stable Diffusion 1.5 2-5 sec (A100) 6GB+ Free when self-hosted
SDXL Base 5-10 sec (A100) 12GB+ Free when self-hosted
SDXL Turbo 0.5-1 sec (A100) 8GB+ Free when self-hosted
DALL-E 3 (OpenAI) 10-20 sec API-based $0.04-0.12/image
Midjourney 30-60 sec Cloud-based $10-60/month

Practical guide: For prototyping, the DALL-E 3 or Midjourney API is convenient. For bulk generation or customization, self-host SDXL. For real-time applications (games, interactive), SDXL Turbo or LCM-LoRA enables generation in under 1 second.

🗣️ Say It Like This in Practice

In project planning:

"To build a feature that automatically changes product image backgrounds, you need a diffusion model with Inpainting capability. Using the SDXL Inpainting pipeline, you can regenerate only the masked area."

In technical discussions:

"To improve generation quality, you need to adjust the CFG Scale (Classifier-Free Guidance). Around 7-8 is the sweet spot; raising it makes outputs more faithful to the prompt but reduces diversity. Specifying unwanted elements with a Negative Prompt is also important."

In interviews:

"A diffusion model consists of two processes: adding noise (Forward) and removing noise (Reverse). The model is trained to predict the noise in a given noisy image, and at generation time it starts from pure noise and gradually removes it. Latent Diffusion improved efficiency by performing this process in a compressed latent space."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌ Mistake 1: Ignoring copyright and licensing

Stable Diffusion was trained on the LAION dataset and can be used commercially, but legal issues may arise if generated images imitate a specific artist's style or resemble copyrighted images. Do not include specific artist names in prompts for commercial projects.

❌ Mistake 2: Extreme settings for step count and CFG Scale

If Inference steps are too low (10 or fewer), quality degrades sharply, and if too high (100+), you just waste time. Raising CFG Scale above 15 also oversaturates colors and causes artifacts.

✅ The Right Approach

For standard SDXL, 25-30 steps and CFG 7-8 are optimal. Turbo models are sufficient with 4-8 steps. Invest in prompt engineering: specific descriptions, style keywords (cinematic, 8k, detailed), and use of Negative Prompts have a major impact on quality. For commercial use, consider the generative AI of Getty Images or Adobe Stock (copyright indemnification).

🔗 Related Terms

📚 Learn More