# Stable Diffusion 2

Stable Diffusion 2는 원래 [Stable Diffusion](https://stability.ai/blog/stable-diffusion-public-release)의 연구를 기반으로 구축된 텍스트-이미지 _latent diffusion_ 모델이며, [Stability AI](https://stability.ai/)의 Robin Rombach와 [LAION](https://laion.ai/)의 Katherine Crowson이 주도적으로 개발했습니다.

*Stable Diffusion 2.0 릴리스에는 LAION이 Stability AI의 지원을 받아 개발한 새로운 텍스트 인코더(OpenCLIP)를 사용하여 학습된 강력한 텍스트-이미지 모델이 포함되어 있습니다. 이 모델은 이전 V1 릴리스와 비교하여 생성된 이미지의 품질을 크게 향상시킵니다. 이 릴리스의 텍스트-이미지 모델은 기본적으로 512x512 픽셀과 768x768 픽셀 해상도로 이미지를 생성할 수 있습니다. 이러한 모델은 Stability AI의 DeepFloyd 팀이 만든 [LAION-5B 데이터셋](https://laion.ai/blog/laion-5b/)의 미적 하위 집합으로 학습되었으며, 이후 [LAION의 NSFW 필터](https://openreview.net/forum?id=M3Y74vmsMcY)를 사용하여 성인 콘텐츠를 제거하도록 추가 필터링되었습니다.*

Stable Diffusion 2의 작동 방식과 기존 Stable Diffusion과의 차이점에 대한 자세한 내용은 공식 [공지 게시물](https://stability.ai/blog/stable-diffusion-v2-release)을 참고하세요.

Stable Diffusion 2의 아키텍처는 원래의 [Stable Diffusion 모델](./text2img)과 거의 동일하므로, Stable Diffusion 2 사용법은 해당 API 문서를 참고하세요. [DPMSolverMultistepScheduler](/docs/diffusers/main/ko/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler)를 사용하는 것을 권장하며, 이는 합리적인 속도/품질 트레이드오프를 제공하며 20단계로만 실행할 수 있습니다.

Stable Diffusion 2는 텍스트-이미지 생성, 인페인팅, 초해상도, 깊이-이미지 생성 등의 작업에 사용할 수 있습니다:

| 작업                    | 리포지토리                                                                                                    |
|-------------------------|---------------------------------------------------------------------------------------------------------------|
| 텍스트-이미지 (512x512) | [stabilityai/stable-diffusion-2-base](https://huggingface.co/stabilityai/stable-diffusion-2-base)             |
| 텍스트-이미지 (768x768) | [stabilityai/stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2)                       |
| 인페인팅              | [stabilityai/stable-diffusion-2-inpainting](https://huggingface.co/stabilityai/stable-diffusion-2-inpainting) |
| 초해상도        | [stable-diffusion-x4-upscaler](https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler)               |
| depth-to-image          | [stabilityai/stable-diffusion-2-depth](https://huggingface.co/stabilityai/stable-diffusion-2-depth)           |

각 작업별로 Stable Diffusion 2를 사용하는 방법에 대한 예시를 몇 가지 소개합니다:

> [!TIP]
> 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법과 파이프라인 구성 요소를 효율적으로 재사용하는 방법을 배우려면 Stable Diffusion [Tips](overview#tips) 섹션을 꼭 확인하세요!
>
> 특정 작업에 공식 체크포인트 중 하나를 사용하려는 경우, [CompVis](https://huggingface.co/CompVis) 및 [Stability AI](https://huggingface.co/stabilityai) Hub 조직을 탐색해 보세요!

## 텍스트-이미지

```py
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
import torch

repo_id = "stabilityai/stable-diffusion-2-base"
pipe = DiffusionPipeline.from_pretrained(repo_id, dtype=torch.float16, variant="fp16")

pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "High quality photo of an astronaut riding a horse in space"
image = pipe(prompt, num_inference_steps=25).images[0]
image
```

## 인페인팅

```py
import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
from diffusers.utils import load_image, make_image_grid

img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

init_image = load_image(img_url).resize((512, 512))
mask_image = load_image(mask_url).resize((512, 512))

repo_id = "stabilityai/stable-diffusion-2-inpainting"
pipe = DiffusionPipeline.from_pretrained(repo_id, dtype=torch.float16, variant="fp16")

pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
image = pipe(prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=25).images[0]
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
```

## 슈퍼 레졸루션

```py
from diffusers import StableDiffusionUpscalePipeline
from diffusers.utils import load_image, make_image_grid
import torch

# load model and scheduler
model_id = "stabilityai/stable-diffusion-x4-upscaler"
pipeline = StableDiffusionUpscalePipeline.from_pretrained(model_id, dtype=torch.float16)
pipeline = pipeline.to("cuda")  # or "mps", "xpu", "cpu"

# let's download an  image
url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
low_res_img = load_image(url)
low_res_img = low_res_img.resize((128, 128))
prompt = "a white cat"
upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
make_image_grid([low_res_img.resize((512, 512)), upscaled_image.resize((512, 512))], rows=1, cols=2)
```

## Depth-to-image

```py
import torch
from diffusers import StableDiffusionDepth2ImgPipeline
from diffusers.utils import load_image, make_image_grid

pipe = StableDiffusionDepth2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-2-depth",
    dtype=torch.float16,
).to("cuda")  # or "mps", "xpu", "cpu"

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
init_image = load_image(url)
prompt = "two tigers"
negative_prompt = "bad, deformed, ugly, bad anotomy"
image = pipe(prompt=prompt, image=init_image, negative_prompt=negative_prompt, strength=0.7).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
```

