🤖 AI/ML

Diffusion

Diffusion Model

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

📖 Detailed Explanation

Diffusion is a generative modeling technique that gradually adds noise to data and then learns the reverse process to recover the original data from noise. Inspired by the physical phenomenon of diffusion, it began to attract attention in 2020 when the DDPM (Denoising Diffusion Probabilistic Models) paper showed performance surpassing GANs in image generation.

The historical origins of diffusion date back to Sohl-Dickstein's 2015 paper "Deep Unsupervised Learning using Nonequilibrium Thermodynamics," but practical image generation began with the DDPM of Ho et al. in 2020. After that, DALL-E 2 in 2021, Stable Diffusion in 2022, and DALL-E 3 and Midjourney V5 in 2023 were released in succession, opening the era of AI image generation.

The core principle consists of two stages. In the forward process (diffusion process), Gaussian noise is gradually added to the original image x0 over T steps, converting it into pure noise xT. In the reverse process (reverse diffusion process), a neural network predicts and removes the noise added at each step, recovering x0 from xT. The training objective is to minimize the MSE between the predicted noise and the actual noise.

In practice, diffusion is used as the core technology of Stable Diffusion, DALL-E 3, and Midjourney. Compared with GANs, it has higher training stability and no mode collapse problem, so it can generate diverse images. However, it has the drawback of slow inference because sampling requires tens to hundreds of steps, so research on fast samplers such as DDIM and DPM-Solver is active.

💻 Code Example

# 디퓨전 핵심 개념 구현 (간소화 버전)
import torch
import torch.nn as nn
import numpy as np

class SimpleDiffusion:
    """간단한 디퓨전 프로세스 구현"""
    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.alphas_cumprod = torch.cumprod(self.alphas, dim=0)

    def forward_process(self, x0, t):
        """Forward diffusion: x0에 노이즈 추가하여 xt 생성"""
        sqrt_alpha_cumprod = torch.sqrt(self.alphas_cumprod[t])
        sqrt_one_minus = torch.sqrt(1.0 - self.alphas_cumprod[t])
        noise = torch.randn_like(x0)
        xt = sqrt_alpha_cumprod * x0 + sqrt_one_minus * noise
        return xt, noise

    def reverse_step(self, xt, predicted_noise, t):
        """Reverse diffusion: 예측 노이즈로 xt-1 복원"""
        alpha = self.alphas[t]
        alpha_cumprod = self.alphas_cumprod[t]
        beta = self.betas[t]

        # 평균 계산
        mean = (1 / torch.sqrt(alpha)) * (
            xt - (beta / torch.sqrt(1 - alpha_cumprod)) * predicted_noise
        )
        # 노이즈 추가 (t > 0일 때)
        if t > 0:
            noise = torch.randn_like(xt)
            return mean + torch.sqrt(beta) * noise
        return mean

# 학습 루프 예시
diffusion = SimpleDiffusion()
model = nn.Sequential(nn.Linear(784, 512), nn.ReLU(), nn.Linear(512, 784))

for epoch in range(100):
    x0 = torch.randn(32, 784)  # 배치 데이터
    t = torch.randint(0, 1000, (32,))  # 랜덤 타임스텝
    xt, noise = diffusion.forward_process(x0, t[0])
    predicted_noise = model(xt)
    loss = nn.MSELoss()(predicted_noise, noise)
    # loss.backward() 및 optimizer.step()...

📊 Performance & Cost

This is a price comparison of major Diffusion-based image generation services as of January 2025.

Services Monthly subscription Cost per image Free option
DALL-E 3 $20/month (ChatGPT Plus) $0.016 ~ $0.04 (API) 3 free images per day
Midjourney $10 ~ $30/month ~$0.05 (Basic) None
Stable Diffusion Free (local) $0.002+ (cloud) Free self-hosting
Stability AI API - $0.01/credit Free under $1M

Selection guide: Midjourney for artistic quality, DALL-E 3 for API integration/diversity, and Stable Diffusion locally for cost efficiency/customization. Running SDXL locally requires an RTX 4090-class GPU ($1,600+).

🗣️ Say It Like This in Practice

At an AI technology seminar

"The key reason diffusion replaced GANs is training stability. It trains stably with a simple noise-prediction MSE loss, without the GAN's discriminator-generator balance problem or mode collapse. Instead, sampling is slow, so acceleration techniques like DDIM are essential."

In a technical interview

"Noise schedule design is important in diffusion. A cosine schedule is better than a linear one for generating high-quality images because it reduces information loss in the early steps. Stable Diffusion also uses a variant of the cosine schedule."

At a product planning meeting

"If real-time image generation is needed, we should consider distilled models that can generate in 1-4 steps, such as LCM (Latent Consistency Model) or SDXL Turbo. With the default diffusion's 20-50 steps, the wait time is too long for the user experience."

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

⚠️ Common Mistakes & Cautions

⚠️
Slow sampling speed

Basic DDPM requires 1000-step sampling, so generating a single image takes tens of seconds. In production, using DDIM (50 steps), DPM-Solver (20 steps), or a distillation model is essential.

⚠️
VRAM limits for high-resolution generation

Memory requirements surge when generating high-resolution images of 512x512 or larger. You need to compute in a compressed latent space like Latent Diffusion, or build a tiling/upscaling pipeline.

⚠️
CFG scale adjustment required

If the Classifier-Free Guidance strength (CFG scale) is too high, oversaturated, unnatural images result; if it is too low, the prompt is ignored. Start in the range of 7-12 and adjust from there.

🔗 Related Terms

📚 Learn More