Diffusers documentation
텍스트-이미지
텍스트-이미지
확산 모델(diffusion model)을 떠올리면 텍스트-이미지 생성이 가장 먼저 생각나는 경우가 많습니다. 텍스트-이미지 생성은 텍스트 설명(예: “Astronaut in a jungle, cold color palette, muted colors, detailed, 8k”)을 기반으로 이미지를 생성하며, 이 텍스트 설명을 프롬프트라고도 합니다.
매우 높은 수준에서 보면, diffusion 모델은 프롬프트와 무작위 초기 노이즈를 입력으로 받아 노이즈를 반복적으로 제거하여 이미지를 생성합니다. denoising 과정은 프롬프트에 의해 안내되며, 미리 정해진 시간 단계 수만큼 denoising 과정이 종료되면 이미지 표현이 이미지로 디코딩됩니다.
Stable Diffusion은 어떻게 작동하나요? 블로그 포스트를 읽어 잠재 공간 확산 모델의 작동 원리를 자세히 알아보세요.
🤗 Diffusers에서 프롬프트로 이미지를 생성하는 방법은 두 단계입니다:
- checkpoint을 AutoPipelineForText2Image 클래스에 로드합니다. 이 클래스는 체크포인트를 기반으로 사용할 적절한 파이프라인 클래스를 자동으로 감지합니다:
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda") # or "mps", "xpu", "cpu"- pipeline에 프롬프트를 전달하여 이미지를 생성합니다:
image = pipeline(
"stained glass of darth vader, backlight, centered composition, masterpiece, photorealistic, 8k"
).images[0]
image
인기 모델
가장 일반적인 텍스트-이미지 모델은 Stable Diffusion v1.5, Stable Diffusion XL (SDXL), Kandinsky 2.2입니다. 이미지 생성 시 더 직접적인 제어가 가능한 ControlNet 모델이나 어댑터도 텍스트-이미지 모델과 함께 사용할 수 있습니다. 각 모델은 아키텍처와 학습 과정이 다르기 때문에 결과가 약간씩 다릅니다. 하지만 어떤 모델을 선택하더라도 사용 방법은 거의 동일합니다. 각 모델에 동일한 프롬프트를 사용해 결과를 비교해 보겠습니다.
Stable Diffusion v1.5
Stable Diffusion v1.5는 Stable Diffusion v1-4에서 초기화되어 LAION-Aesthetics V2 데이터셋의 512x512 이미지로 595K 스텝 동안 파인튜닝된 잠재 확산 모델입니다. 이 모델을 다음과 같이 사용할 수 있습니다:
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda") # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
imageStable Diffusion XL
SDXL은 이전 Stable Diffusion 모델보다 훨씬 큰 버전으로, 이미지에 더 많은 세부 사항을 추가하는 2단계 모델 프로세스를 포함합니다. 또한 중심 주제를 중심으로 고품질 이미지를 생성하기 위한 추가적인 마이크로 컨디셔닝도 포함합니다. 사용법에 대해 자세히 알아보려면 보다 포괄적인 SDXL 가이드를 참고하세요. 일반적으로 SDXL은 다음과 같이 사용할 수 있습니다:
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16, variant="fp16"
).to("cuda") # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
imageKandinsky 2.2
Kandinsky 모델은 Stable Diffusion 모델과 약간 다르며, diffusion 모델에서 텍스트와 이미지를 더 잘 정렬하기 위해 사용되는 임베딩을 생성하는 데 이미지 사전 모델(image prior model)도 함께 사용합니다.
Kandinsky 2.2를 사용하는 가장 쉬운 방법은 다음과 같습니다:
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"kandinsky-community/kandinsky-2-2-decoder", dtype=torch.float16
).to("cuda") # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
imageControlNet
ControlNet 모델은 Stable Diffusion v1.5와 같은 텍스트-이미지 생성 모델 위에 파인튜닝된 보조 모델 또는 어댑터입니다. ControlNet 모델을 텍스트-이미지 생성 모델과 함께 사용하면 이미지를 생성하는 방식에 대해 보다 명시적인 제어를 위한 다양한 옵션을 제공합니다. ControlNet을 사용하면 모델에 추가적인 조건 입력 이미지를 추가할 수 있습니다. 예를 들어, 인간 자세 이미지(보통 스켈레톤으로 연결된 여러 개의 키포인트로 표현됨)를 조건 입력으로 제공하면, 모델은 해당 이미지의 자세를 따르는 이미지를 생성합니다. 다른 조건 입력과 사용 방법에 대해 자세히 알아보려면 더 심층적인 ControlNet 가이드를 확인해 보세요.
이 예제에서는 ControlNet을 human pose estimation 이미지로 조건화해 보겠습니다. human pose estimation으로 사전 학습된 ControlNet 모델을 로드합니다:
from diffusers import ControlNetModel, AutoPipelineForText2Image
from diffusers.utils import load_image
import torch
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/control_v11p_sd15_openpose", dtype=torch.float16, variant="fp16"
).to("cuda") # or "mps", "xpu", "cpu"
pose_image = load_image("https://huggingface.co/lllyasviel/control_v11p_sd15_openpose/resolve/main/images/control.png")controlnet을 AutoPipelineForText2Image에 전달하고 프롬프트와 포즈 추정 이미지를 제공합니다:
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, dtype=torch.float16, variant="fp16"
).to("cuda") # or "mps", "xpu", "cpu"
generator = torch.Generator("cuda").manual_seed(31)
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", image=pose_image, generator=generator).images[0]
image
파이프라인 매개변수 구성
pipeline에서 이미지가 생성되는 방식을 결정하는 여러 매개변수를 설정할 수 있습니다. 이미지의 출력 크기를 변경하거나, 이미지 품질을 개선하기 위해 negative prompt를 지정하는 등 다양한 설정이 가능합니다. 이 섹션에서는 이러한 매개변수를 사용하는 방법에 대해 자세히 살펴봅니다.
높이와 너비
height와 width 매개변수는 생성된 이미지의 높이와 너비(픽셀 단위)를 제어합니다. 기본적으로 Stable Diffusion v1.5 모델은 512x512 이미지를 출력하지만, 8의 배수인 어떤 크기로든 변경할 수 있습니다. 예를 들어, 직사각형 이미지를 생성하려면:
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16"
).to("cuda") # or "mps", "xpu", "cpu"
image = pipeline(
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", height=768, width=512
).images[0]
image
다른 모델은 학습 데이터셋의 이미지 크기에 따라 기본 이미지 크기가 다를 수 있습니다. 예를 들어, SDXL의 기본 이미지 크기는 1024x1024이며, 더 작은
height와width값을 사용하면 품질이 낮은 이미지가 생성될 수 있습니다. 먼저 해당 모델의 API 참고 문서를 확인하세요!
가이던스 스케일
guidance_scale 매개변수는 프롬프트가 이미지 생성에 미치는 영향을 결정합니다. 값이 낮을수록 모델은 프롬프트와 느슨하게 연관된 이미지를 생성하는 “창의성”을 발휘합니다. guidance_scale 값이 높을수록 모델은 프롬프트를 더 엄격하게 따르도록 유도되며, 이 값이 지나치게 높으면 생성된 이미지에서 일부 아티팩트가 관찰될 수 있습니다.
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda") # or "mps", "xpu", "cpu"
image = pipeline(
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", guidance_scale=3.5
).images[0]
image
부정 프롬프트
프롬프트가 생성을 안내하듯, negative prompt는 모델이 생성하지 않기를 원하는 요소로부터 모델을 이끌어냅니다. 이는 “low resolution”이나 “bad details”와 같은 저품질 또는 불량 이미지 특성을 제거하여 전반적인 이미지 품질을 향상시키는 데 일반적으로 사용됩니다. negative prompt를 사용하여 이미지의 콘텐츠와 스타일을 제거하거나 수정할 수도 있습니다.
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda") # or "mps", "xpu", "cpu"
image = pipeline(
prompt="Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
negative_prompt="ugly, deformed, disfigured, poor details, bad anatomy",
).images[0]
image
Generator
torch.Generator 객체는 수동 시드를 설정하여 파이프라인의 재현성을 보장합니다. Generator를 사용하여 이미지 배치 생성 및 시드로 생성된 이미지의 반복적 개선에 활용할 수 있으며, 자세한 내용은 결정론적 생성을 통한 이미지 품질 개선 가이드를 참고하세요.
시드와 Generator를 아래에 표시된 대로 설정할 수 있습니다. Generator를 사용하여 이미지를 생성하면 매번 무작위로 새로운 이미지를 생성하는 대신 동일한 결과가 반환되어야 합니다.
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda") # or "mps", "xpu", "cpu"
generator = torch.Generator(device="cuda").manual_seed(30)
image = pipeline(
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
generator=generator,
).images[0]
image이미지 생성 제어
pipeline의 매개변수를 설정하는 것 외에도 프롬프트 가중치나 ControlNet 모델 등을 통해 이미지 생성 방식을 더 세밀하게 제어하는 여러 가지 방법이 있습니다.
프롬프트 가중치
Prompt weighting은 프롬프트 내 개념의 중요도를 높이거나 낮추어 이미지에서 특정 특징을 강조하거나 최소화하는 기법입니다. 가중치 부여된 프롬프트 임베딩을 생성하는 데 도움이 되는 Compel 라이브러리 사용을 권장합니다.
Prompt weighting 가이드에서 프롬프트 임베딩을 생성하는 방법을 배울 수 있습니다. 이 예제는 파이프라인에서 프롬프트 임베딩을 사용하는 방법에 초점을 맞춥니다.
임베딩을 생성한 후에는 파이프라인의 prompt_embeds 매개변수(음성 프롬프트를 사용하는 경우 negative_prompt_embeds 포함)에 이를 전달할 수 있습니다.
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16
).to("cuda") # or "mps", "xpu", "cpu"
image = pipeline(
prompt_embeds=prompt_embeds, # generated from Compel
negative_prompt_embeds=negative_prompt_embeds, # generated from Compel
).images[0]ControlNet
ControlNet 섹션에서 보았듯이, 이러한 모델은 추가적인 조건 이미지 입력을 포함하여 이미지를 생성하는 더 유연하고 정확한 방법을 제공합니다. 각 ControlNet 모델은 특정 유형의 조건 이미지에 대해 사전 학습되어 해당 이미지와 유사한 새로운 이미지를 생성하도록 설계되었습니다. 예를 들어, 깊이 맵에 대해 사전 학습된 ControlNet 모델을 사용하면 깊이 맵을 조건 입력으로 제공하면 해당 깊이 맵의 공간 정보를 보존한 이미지를 생성할 수 있습니다. 이는 프롬프트에서 깊이 정보를 명시하는 것보다 빠르고 쉽습니다. Multi-ControlNet을 사용하면 여러 조건 입력을 결합할 수도 있습니다!
사용할 수 있는 조건 입력(conditioning input)의 종류는 다양하며, 🤗 Diffusers는 Stable Diffusion 및 SDXL 모델에 대한 ControlNet을 지원합니다. 이러한 모델을 어떻게 사용할 수 있는지 알아보려면 보다 포괄적인 ControlNet 가이드를 참고하세요.
최적화
Diffusion 모델은 크기가 크고, 이미지를 denoise하는 반복적인 과정은 계산 비용이 많이 들고 부하가 큽니다. 하지만 이를 사용하려면 강력한 GPU나 심지어 여러 개의 GPU가 필요하다는 뜻은 아닙니다. 소비자용 및 무료 티어 리소스에서 diffusion 모델을 실행하기 위한 최적화 기법이 많이 있습니다. 예를 들어, 모델 가중치를 half-precision으로 로드하여 GPU 메모리를 절약하고 속도를 높이거나, 전체 모델을 GPU로 offload하여 더 많은 메모리를 절약할 수 있습니다.
PyTorch 2.0은 scaled dot product attention라는 더 메모리 효율적인 attention 메커니즘도 지원하며, PyTorch 2.0을 사용 중이라면 자동으로 활성화됩니다. torch.compile와 함께 사용하면 코드를 더욱 빠르게 실행할 수 있습니다:
from diffusers import AutoPipelineForText2Image
import torch
pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16").to("cuda") # or "mps", "xpu", "cpu"
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)메모리를 절약하고 추론 속도를 높이기 위해 코드를 최적화하는 방법에 대한 추가 팁은 Accelerate inference 및 Reduce memory usage 가이드를 참고하세요.
Update on GitHub