# Stable Diffusion 3

  
  

Patrick Esser, Sumith Kulal, Andreas Blattmann, Rahim Entezari, Jonas Muller, Harry Saini, Yam Levi, Dominik Lorenz, Axel Sauer, Frederic Boesel, Dustin Podell, Tim Dockhorn, Zion English, Kyle Lacey, Alex Goodwin, Yannik Marek, Robin Rombach는 [Scaling Rectified Flow Transformers for High-Resolution Image Synthesis](https://huggingface.co/papers/2403.03206)에서 Stable Diffusion 3(SD3)를 제안했습니다.

해당 논문의 초록은 다음과 같습니다:

*Diffusion 모델은 데이터에서 노이즈로 향하는 전진 경로를 역전시켜 노이즈로부터 데이터를 생성하며, 이미지와 비디오와 같은 고차원 지각 데이터에 대한 강력한 생성 모델링 기법으로 부상했습니다. Rectified flow는 데이터와 노이즈를 직선으로 연결하는 최근의 생성 모델 형식입니다. 더 나은 이론적 속성과 개념적 단순성에도 불구하고, 아직 표준 관행으로 결정적으로 확립되지는 않았습니다. 본 연구에서는 지각적으로 관련 있는 스케일로 편향되도록 하여 rectified flow 모델 학습을 위한 기존 노이즈 샘플링 기법을 개선합니다. 대규모 연구를 통해, 이 접근법이 고해상도 텍스트-이미지 합성을 위한 확립된 diffusion 형식과 비교하여 우수한 성능을 보임을 입증합니다. 또한, 두 모달리티에 대해 별도의 가중치를 사용하고 이미지 및 텍스트 토큰 간의 양방향 정보 흐름을 가능하게 하여 텍스트 이해, 타이포그래피, 인간 선호도 평가를 개선하는 텍스트-이미지 생성을 위한 새로운 transformer 기반 아키텍처를 제시합니다. 이 아키텍처가 예측 가능한 스케일링 추세를 따르며, 다양한 지표와 인간 평가를 통해 측정된 텍스트-이미지 합성 개선과 검증 손실 감소가 상관관계가 있음을 입증합니다.*

## 사용 예시

_모델이 게이트가 설정되어 있으므로, diffusers와 함께 사용하기 전에 먼저 [Stable Diffusion 3 Medium Hugging Face 페이지](https://huggingface.co/stabilityai/stable-diffusion-3-medium-diffusers)에 접속하여 양식을 작성하고 게이트를 수락해야 합니다. 접근 권한이 부여된 후에는 시스템이 게이트 수락을 인식할 수 있도록 로그인해야 합니다._

아래 명령을 사용하여 로그인하세요:

```bash
hf auth login
```

> [!TIP]
> SD3 파이프라인은 이미지를 생성하기 위해 세 개의 텍스트 인코더를 사용합니다. 대부분의 범용 하드웨어에서 실행하려면 모델 오프로딩이 필요합니다. 추가적인 메모리 절약을 위해 `torch.float16` 데이터형을 사용하세요.

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained("stabilityai/stable-diffusion-3-medium-diffusers", dtype=torch.float16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world.png")
```

**참고:** Stable Diffusion 3.5는 SD3 파이프라인을 사용하여 실행할 수도 있으며, 언급된 모든 최적화 및 기법이 해당 파이프라인에도 적용됩니다. SD3 계열에는 공식 모델이 총 3가지 있습니다:
- [`stabilityai/stable-diffusion-3-medium-diffusers`](https://huggingface.co/stabilityai/stable-diffusion-3-medium-diffusers)
- [`stabilityai/stable-diffusion-3.5-large`](https://huggingface.co/stabilityai/stable-diffusion-3-5-large)
- [`stabilityai/stable-diffusion-3.5-large-turbo`](https://huggingface.co/stabilityai/stable-diffusion-3-5-large-turbo)

## IP-Adapters를 활용한 이미지 프롬프팅

IP-Adapter를 사용하면 텍스트 프롬프트 외에도 이미지로 SD3에 프롬프트를 전달할 수 있습니다. 이는 텍스트만으로 표현하기 어려운 복잡한 개념을 설명할 때 참고 이미지가 있는 경우 특히 유용합니다. IP-Adapter를 로드하고 사용하려면 다음이 필요합니다:

- `image_encoder`: 이미지 특징을 얻기 위해 사용되는 사전 학습된 비전 모델로, 일반적으로 CLIP 이미지 인코더입니다.
- `feature_extractor`: 선택한 `image_encoder`에 입력 이미지를 준비하는 이미지 프로세서입니다.
- `ip_adapter_id`: 이미지 크로스 어텐션 레이어와 이미지 투영의 매개변수를 포함하는 체크포인트.

IP-Adapter는 특정 모델 아키텍처를 대상으로 학습되므로, 기본 모델의 파인튜닝된 변형에서도 작동합니다. `~SD3IPAdapterMixin.set_ip_adapter_scale` 함수를 사용하여 출력 결과가 이미지 프롬프트와 얼마나 강하게 일치하는지 조정할 수 있습니다. 값이 높을수록 모델이 이미지 프롬프트를 더 밀접하게 따릅니다. 기본값인 0.5는 일반적으로 텍스트 프롬프트와 이미지 프롬프트를 동등하게 고려하도록 하는 좋은 균형점을 제공합니다.

```python
import torch
from PIL import Image

from diffusers import StableDiffusion3Pipeline
from transformers import SiglipVisionModel, SiglipImageProcessor

image_encoder_id = "google/siglip-so400m-patch14-384"
ip_adapter_id = "InstantX/SD3.5-Large-IP-Adapter"

feature_extractor = SiglipImageProcessor.from_pretrained(
    image_encoder_id,
    dtype=torch.float16
)
image_encoder = SiglipVisionModel.from_pretrained(
    image_encoder_id,
    dtype=torch.float16
).to( "cuda")  # or "mps", "xpu", "cpu"

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    dtype=torch.float16,
    feature_extractor=feature_extractor,
    image_encoder=image_encoder,
).to("cuda")

pipe.load_ip_adapter(ip_adapter_id)
pipe.set_ip_adapter_scale(0.6)

ref_img = Image.open("image.jpg").convert('RGB')

image = pipe(
    width=1024,
    height=1024,
    prompt="a cat",
    negative_prompt="lowres, low quality, worst quality",
    num_inference_steps=24,
    guidance_scale=5.0,
    ip_adapter_image=ref_img
).images[0]

image.save("result.jpg")
```

    
    프롬프트 "a cat"을 사용한 IP-Adapter 예시

> [!TIP]
> IP-Adapter의 작동 원리를 자세히 알아보려면 [IP-Adapter](../../../using-diffusers/ip_adapter)를 확인하세요.

## SD3의 메모리 최적화

SD3은 세 개의 텍스트 인코더를 사용하며, 그중 하나는 매우 큰 T5-XXL 모델입니다. 이로 인해 `fp16` 정밀도를 사용하더라도 VRAM이 24GB 미만인 GPU에서 모델을 실행하는 것이 어렵습니다. 다음 섹션에서는 리소스가 제한된 하드웨어에서 SD3을 실행하기 쉽게 만드는 Diffusers의 몇 가지 메모리 최적화 방법을 설명합니다.

### 모델 오프로딩을 통한 추론 실행

Diffusers에서 사용할 수 있는 가장 기본적인 메모리 최적화는 추론 중에 모델의 구성 요소를 CPU로 오프로드하여 메모리를 절약할 수 있게 해주며, 이로 인해 추론 지연 시간이 약간 증가합니다. 모델 오프로딩은 실행이 필요한 시점에 해당 모델 구성 요소만 GPU로 이동시키고, 나머지 구성 요소는 CPU에 유지합니다.

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained("stabilityai/stable-diffusion-3-medium-diffusers", dtype=torch.float16)
pipe.enable_model_cpu_offload()

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world.png")
```

### 추론 시 T5 텍스트 인코더 제거

추론 시 메모리 집약적인 4.7B 파라미터 T5-XXL 텍스트 인코더를 제거하면 성능 저하가 거의 없으면서도 SD3의 메모리 요구량을 크게 줄일 수 있습니다.

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    text_encoder_3=None,
    tokenizer_3=None,
    dtype=torch.float16
)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world-no-T5.png")
```

### 양자화된 T5 텍스트 인코더 사용

`bitsandbytes` 라이브러리를 활용하여 T5-XXL 텍스트 인코더를 8비트 정밀도로 로드하고 양자화할 수 있습니다. 이를 통해 세 가지 텍스트 인코더를 모두 계속 사용할 수 있으며, 성능에 미치는 영향은 미미합니다.

먼저 `bitsandbytes` 라이브러리를 설치하세요.

```shell
pip install bitsandbytes
```

그 다음 `BitsAndBytesConfig`를 사용하여 T5-XXL 모델을 로드합니다.

```python
import torch
from diffusers import StableDiffusion3Pipeline
from transformers import T5EncoderModel, BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_8bit=True)

model_id = "stabilityai/stable-diffusion-3-medium-diffusers"
text_encoder = T5EncoderModel.from_pretrained(
    model_id,
    subfolder="text_encoder_3",
    quantization_config=quantization_config,
)
pipe = StableDiffusion3Pipeline.from_pretrained(
    model_id,
    text_encoder_3=text_encoder,
    device_map="balanced",
    dtype=torch.float16
)

image = pipe(
    prompt="a photo of a cat holding a sign that says hello world",
    negative_prompt="",
    num_inference_steps=28,
    height=1024,
    width=1024,
    guidance_scale=7.0,
).images[0]

image.save("sd3_hello_world-8bit-T5.png")
```

엔드투엔드 스크립트는 [여기](https://gist.github.com/sayakpaul/82acb5976509851f2db1a83456e504f1)에서 찾을 수 있습니다.

## SD3 성능 최적화

### Torch Compile를 사용하여 추론 속도 향상

SD3 파이프라인에서 컴파일된 구성 요소를 사용하면 추론 속도가 최대 4배까지 빨라질 수 있습니다. 다음 코드 스니펫은 SD3 파이프라인의 Transformer 및 VAE 구성 요소를 컴파일하는 방법을 보여줍니다.

```python
import torch
from diffusers import StableDiffusion3Pipeline

torch.set_float32_matmul_precision("high")

torch._inductor.config.conv_1x1_as_mm = True
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.epilogue_fusion = False
torch._inductor.config.coordinate_descent_check_all_directions = True

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers",
    dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"
pipe.set_progress_bar_config(disable=True)

pipe.transformer.to(memory_format=torch.channels_last)
pipe.vae.to(memory_format=torch.channels_last)

pipe.transformer = torch.compile(pipe.transformer, mode="max-autotune", fullgraph=True)
pipe.vae.decode = torch.compile(pipe.vae.decode, mode="max-autotune", fullgraph=True)

# Warm Up
prompt = "a photo of a cat holding a sign that says hello world"
for _ in range(3):
    _ = pipe(prompt=prompt, generator=torch.manual_seed(1))

# Run Inference
image = pipe(prompt=prompt, generator=torch.manual_seed(1)).images[0]
image.save("sd3_hello_world.png")
```

전체 스크립트는 [여기](https://gist.github.com/sayakpaul/508d89d7aad4f454900813da5d42ca97)에서 확인하세요.

## 양자화

Quantization은 모델 가중치를 더 낮은 정밀도의 데이터 타입으로 저장하여 매우 큰 모델의 메모리 요구 사항을 줄이는 데 도움이 됩니다. 그러나 quantization은 비디오 모델에 따라 비디오 품질에 다양한 영향을 미칠 수 있습니다.

지원되는 양자화 백엔드와 사용 사례에 맞는 양자화 백엔드 선택에 대해 자세히 알아보려면 [Quantization](../../../quantization/overview) 개요를 참조하세요. 아래 예제는 bitsandbytes를 사용하여 양자화된 [StableDiffusion3Pipeline](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/stable_diffusion_3#diffusers.StableDiffusion3Pipeline)을 추론에 로드하는 방법을 보여줍니다.

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SD3Transformer2DModel, StableDiffusion3Pipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = T5EncoderModel.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    subfolder="text_encoder_3",
    quantization_config=quant_config,
    dtype=torch.float16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = SD3Transformer2DModel.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.float16,
)

pipeline = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    dtype=torch.float16,
    device_map="balanced",
)

prompt = "a tiny astronaut hatching from an egg on the moon"
image = pipeline(prompt, num_inference_steps=28, guidance_scale=7.0).images[0]
image.save("sd3.png")
```

## T5 텍스트 인코더를 사용하여 긴 프롬프트 사용

기본적으로 T5 Text Encoder 프롬프트는 최대 시퀀스 길이가 `256`입니다. `max_sequence_length`를 설정하여 더 적거나 더 많은 토큰을 허용하도록 조정할 수 있습니다. 더 긴 시퀀스는 추가 리소스가 필요하며 배치 추론과 같은 경우 생성 시간이 길어질 수 있다는 점을 유의하세요.

```python
prompt = "A whimsical and creative image depicting a hybrid creature that is a mix of a waffle and a hippopotamus, basking in a river of melted butter amidst a breakfast-themed landscape. It features the distinctive, bulky body shape of a hippo. However, instead of the usual grey skin, the creature’s body resembles a golden-brown, crispy waffle fresh off the griddle. The skin is textured with the familiar grid pattern of a waffle, each square filled with a glistening sheen of syrup. The environment combines the natural habitat of a hippo with elements of a breakfast table setting, a river of warm, melted butter, with oversized utensils or plates peeking out from the lush, pancake-like foliage in the background, a towering pepper mill standing in for a tree.  As the sun rises in this fantastical world, it casts a warm, buttery glow over the scene. The creature, content in its butter river, lets out a yawn. Nearby, a flock of birds take flight"

image = pipe(
    prompt=prompt,
    negative_prompt="",
    num_inference_steps=28,
    guidance_scale=4.5,
    max_sequence_length=512,
).images[0]
```

### T5 Text Encoder에 다른 프롬프트를 전송

CLIP Text Encoders와 T5 Text Encoder에 서로 다른 프롬프트를 보내면 CLIP Text Encoders에 의해 프롬프트가 잘리는 것을 방지하고 생성 품질을 개선할 수 있습니다.

> [!TIP]
> CLIP Text Encoders를 사용하는 프롬프트는 여전히 77 토큰 제한으로 잘립니다.

```python
prompt = "A whimsical and creative image depicting a hybrid creature that is a mix of a waffle and a hippopotamus, basking in a river of melted butter amidst a breakfast-themed landscape. A river of warm, melted butter, pancake-like foliage in the background, a towering pepper mill standing in for a tree."

prompt_3 = "A whimsical and creative image depicting a hybrid creature that is a mix of a waffle and a hippopotamus, basking in a river of melted butter amidst a breakfast-themed landscape. It features the distinctive, bulky body shape of a hippo. However, instead of the usual grey skin, the creature’s body resembles a golden-brown, crispy waffle fresh off the griddle. The skin is textured with the familiar grid pattern of a waffle, each square filled with a glistening sheen of syrup. The environment combines the natural habitat of a hippo with elements of a breakfast table setting, a river of warm, melted butter, with oversized utensils or plates peeking out from the lush, pancake-like foliage in the background, a towering pepper mill standing in for a tree.  As the sun rises in this fantastical world, it casts a warm, buttery glow over the scene. The creature, content in its butter river, lets out a yawn. Nearby, a flock of birds take flight"

image = pipe(
    prompt=prompt,
    prompt_3=prompt_3,
    negative_prompt="",
    num_inference_steps=28,
    guidance_scale=4.5,
    max_sequence_length=512,
).images[0]
```

## Stable Diffusion 3용 Tiny AutoEncoder

Stable Diffusion의 작은 AutoEncoder인 TAESD3는 [Ollin Boer Bohan](https://github.com/madebyollin/taesd)이 만든 Stable Diffusion 3 VAE의 작은 증류 버전으로, [StableDiffusion3Pipeline](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/stable_diffusion_3#diffusers.StableDiffusion3Pipeline)의 latents를 거의 즉시 디코딩할 수 있습니다.

Stable Diffusion 3와 함께 사용하려면:

```python
import torch
from diffusers import StableDiffusion3Pipeline, AutoencoderTiny

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3-medium-diffusers", dtype=torch.float16
)
pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd3", dtype=torch.float16)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "slice of delicious New York-style berry cheesecake"
image = pipe(prompt, num_inference_steps=25).images[0]
image.save("cheesecake.png")
```

## `from_single_file`를 통해 원래의 체크포인트를 로드

`SD3Transformer2DModel` 및 `StableDiffusion3Pipeline` 클래스는 `from_single_file` 메서드를 통해 원래의 체크포인트를 로드하는 것을 지원합니다. 이 메서드를 사용하면 모델을 학습하는 데 사용된 원래 체크포인트 파일을 로드할 수 있습니다.

## `SD3Transformer2DModel`의 원래 체크포인트를 로드합니다

```python
from diffusers import SD3Transformer2DModel

model = SD3Transformer2DModel.from_single_file("https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/sd3_medium.safetensors")
```

## `StableDiffusion3Pipeline`의 단일 체크포인트를 로드합니다

### T5 없이 단일 파일 체크포인트 로드

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/sd3_medium_incl_clips.safetensors",
    dtype=torch.float16,
    text_encoder_3=None
)
pipe.enable_model_cpu_offload()

image = pipe("a picture of a cat holding a sign that says hello world").images[0]
image.save('sd3-single-file.png')
```

### T5로 단일 파일 체크포인트 로드

> [!TIP]
> 다음 예제는 PyTorch 2.3 이상을 요구하는 8-bit 부동 소수점 형식으로 저장된 체크포인트를 로드합니다.

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-3-medium/blob/main/sd3_medium_incl_clips_t5xxlfp8.safetensors",
    dtype=torch.float16,
)
pipe.enable_model_cpu_offload()

image = pipe("a picture of a cat holding a sign that says hello world").images[0]
image.save('sd3-single-file-t5-fp8.png')
```

### Stable Diffusion 3.5 Transformer 모델의 단일 파일 체크포인트 로드

```python
import torch
from diffusers import SD3Transformer2DModel, StableDiffusion3Pipeline

transformer = SD3Transformer2DModel.from_single_file(
    "https://huggingface.co/stabilityai/stable-diffusion-3.5-large-turbo/blob/main/sd3.5_large.safetensors",
    dtype=torch.bfloat16,
)
pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    transformer=transformer,
    dtype=torch.bfloat16,
)
pipe.enable_model_cpu_offload()
image = pipe("a cat holding a sign that says hello world").images[0]
image.save("sd35.png")
```

## StableDiffusion3Pipeline[[diffusers.StableDiffusion3Pipeline]]

#### diffusers.StableDiffusion3Pipeline[[diffusers.StableDiffusion3Pipeline]]

```python
diffusers.StableDiffusion3Pipeline(transformer: SD3Transformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, text_encoder_2: CLIPTextModelWithProjection, tokenizer_2: CLIPTokenizer, text_encoder_3: T5EncoderModel, tokenizer_3: T5Tokenizer, image_encoder: SiglipVisionModel = None, feature_extractor: SiglipImageProcessorPil = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L148)

**매개변수:**

transformer ([SD3Transformer2DModel](/docs/diffusers/main/ko/api/models/sd3_transformer2d#diffusers.SD3Transformer2DModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer (MMDiT) 아키텍처.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`와 함께 사용하여 인코딩된 이미지 라텐트를 디노이즈하는 데 사용되는 스케줄러입니다.

vae ([AutoencoderKL](/docs/diffusers/main/ko/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다.

text_encoder (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), 구체적으로 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 변형이며, `hidden_size`를 차원으로 하는 대각 행렬로 초기화된 추가 투영 계층이 있습니다.

text_encoder_2 (`CLIPTextModelWithProjection`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection), 구체적으로 [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k) 변형입니다.

text_encoder_3 (`T5EncoderModel`) : 고정된 텍스트 인코더. Stable Diffusion 3은 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) 변형을 사용합니다.

tokenizer (`CLIPTokenizer`) : [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 클래스의 토크나이저.

tokenizer_2 (`CLIPTokenizer`) : [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 클래스의 두 번째 Tokenizer.

tokenizer_3 (`T5TokenizerFast`) : [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer) 클래스의 토크나이저.

image_encoder (`SiglipVisionModel`, *선택 사항*) : IP Adapter용 사전 학습된 Vision Model입니다.

feature_extractor (`SiglipImageProcessor`, *선택 사항*) : IP Adapter용 이미지 프로세서입니다.

#### __호출__[[diffusers.StableDiffusion3Pipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, prompt_3: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 256, skip_guidance_layers: list = None, skip_layer_guidance_scale: float = 2.8, skip_layer_guidance_stop: float = 0.2, skip_layer_guidance_start: float = 0.01, mu: float | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L772)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 대신 전달해야 합니다.

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2`와 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우 `prompt`가 대신 사용됩니다

prompt_3 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_3` 및 `text_encoder_3`에 전송할 프롬프트입니다. 정의되지 않은 경우 `prompt`가 대신 사용됩니다

height (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 높이입니다. 최적의 결과를 위해 기본값은 1024로 설정됩니다.

width (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 너비입니다. 최적의 결과를 위해 기본값은 1024로 설정됩니다.

num_inference_steps (`int`, *선택 사항*, 기본값 50) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.

sigmas (`list[float]`, *선택 사항*) : `set_timesteps` 메서드에 `sigmas` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다.

guidance_scale (`float`, *선택 사항*, 기본값 7.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)에서 정의한 가이던스 스케일입니다. `guidance_scale`은 [Imagen Paper](https://huggingface.co/papers/2205.11487)의 2번 식의 `w`로 정의됩니다. `guidance_scale > 1`을 설정하여 가이던스 스케일을 활성화합니다. 가이던스 스케일이 높을수록 `prompt` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.

negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).

negative_prompt_2 (`str` 또는 `list[str]`, *선택*) : `tokenizer_2`와 `text_encoder_2`에 전송할 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우 `negative_prompt`가 대신 사용됩니다

negative_prompt_3 (`str` 또는 `list[str]`, *선택*) : 이미지 생성을 유도하지 않기 위해 `tokenizer_3`와 `text_encoder_3`에 전송할 프롬프트입니다. 정의되지 않은 경우 `negative_prompt`가 대신 사용됩니다

num_images_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 이미지의 수.

generator (`torch.Generator` 또는 `list[torch.Generator]`, *선택 사항*) : 생성을 결정적으로 만들기 위한 [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) 하나 또는 목록.

latents (`torch.FloatTensor`, *선택 사항*) : 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈된 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 `generator`를 사용하여 샘플링하여 latents 텐서가 생성됩니다.

prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`torch.FloatTensor`, *선택*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

pooled_prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다.

negative_pooled_prompt_embeds (`torch.FloatTensor`, *선택*) : 미리 생성된 부정 풀링 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 pooled negative_prompt_embeds가 생성됩니다.

ip_adapter_image (`PipelineImageInput`, *선택 사항*) : IP Adapters와 함께 사용할 선택적 이미지 입력입니다.

ip_adapter_image_embeds (`torch.Tensor`, *선택 사항*) : IP-Adapter를 위한 사전 생성된 이미지 임베딩입니다. `(batch_size, num_images, emb_dim)` 형태의 텐서여야 합니다. `do_classifier_free_guidance`가 `True`로 설정된 경우, 음의 이미지 임베딩을 포함해야 합니다. 제공되지 않으면 `ip_adapter_image` 입력 인자로부터 임베딩이 계산됩니다.

output_type (`str`, *선택 사항*, 기본값 `"pil"`) : 이미지 생성의 출력 형식입니다. [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` 또는 `np.array` 중 하나를 선택합니다.

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`을 반환할지 여부.

joint_attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.

clip_skip (`int`, *선택 사항*) : 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어 수. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다.

callback_on_step_end (`Callable`, *선택 사항*) : 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs`에는 `callback_on_step_end_tensor_inputs`로 지정된 모든 텐서 목록이 포함됩니다.

callback_on_step_end_tensor_inputs (`list`, *선택 사항*) : `callback_on_step_end` 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 `callback_kwargs` 인수로 전달됩니다. 파이프라인 클래스의 `._callback_tensor_inputs` 속성에 나열된 변수만 포함할 수 있습니다.

max_sequence_length (`int` 기본값은 256) : `prompt`에 사용할 최대 시퀀스 길이입니다.

skip_guidance_layers (`list[int]`, *선택 사항*) : guidance 과정에서 건너뛸 레이어를 지정하는 정수 목록입니다. 제공되지 않으면 모든 레이어가 guidance에 사용됩니다. 제공된 경우, guidance는 목록에 지정된 레이어에만 적용됩니다. StabiltyAI가 Stable Diffusion 3.5 Medium에 대해 권장하는 값은 [7, 8, 9]입니다.

skip_layer_guidance_scale (`int`, *선택 사항*) : `skip_guidance_layers`에 지정된 레이어에 대한 가이던스의 스케일입니다. `skip_guidance_layers`에 지정된 레이어에는 `skip_layer_guidance_scale` 스케일로 가이던스가 적용되며, 나머지 레이어에는 `1` 스케일로 가이던스가 적용됩니다.

skip_layer_guidance_stop (`int`, *선택 사항*) : `skip_guidance_layers`에 지정된 레이어에 대한 가이던스가 중단되는 단계입니다. `skip_layer_guidance_stop`에 지정된 비율까지 `skip_guidance_layers`에 지정된 레이어에 가이던스가 적용됩니다. StabilityAI가 Stable Diffusion 3.5 Medium에 대해 권장하는 값은 0.2입니다.

skip_layer_guidance_start (`int`, *선택 사항*) : `skip_guidance_layers`에 지정된 레이어에 대한 가이던스가 시작되는 단계입니다. `skip_layer_guidance_start`에 지정된 비율부터 `skip_guidance_layers`에 지정된 레이어에 가이던스가 적용됩니다. StabilityAI가 Stable Diffusion 3.5 Medium에 대해 권장하는 값은 0.01입니다.

mu (`float`, *선택 사항*) : `dynamic_shifting`에 사용되는 `mu` 값.

**반환값:** `~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput` 또는 `tuple`

`return_dict`가 True인 경우 `~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`, 그렇지 않으면 `tuple`입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지의 목록입니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:
```py
>>> import torch
>>> from diffusers import StableDiffusion3Pipeline

>>> pipe = StableDiffusion3Pipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt).images[0]
>>> image.save("sd3.png")
```

#### encode_image[[diffusers.StableDiffusion3Pipeline.encode_image]]

```python
encode_image(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], device: device)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L696)

**매개변수:**

image (`PipelineImageInput`) : 인코딩할 입력 이미지.

device : (`torch.device`): Torch 장치.

**반환값:** `torch.Tensor`

인코딩된 이미지 특징 표현입니다.

사전 학습된 이미지 인코더를 사용하여 주어진 이미지를 특징 표현으로 인코딩합니다.

#### encode_prompt[[diffusers.StableDiffusion3Pipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], prompt_2: str | list[str], prompt_3: str | list[str], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, negative_prompt_3: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, clip_skip: int | None = None, max_sequence_length: int = 256, lora_scale: float | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L344)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2` 및 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우 모든 text-encoder에 `prompt`가 사용됩니다.

prompt_3 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_3` 및 `text_encoder_3`에 전송할 프롬프트입니다. 정의되지 않은 경우 모든 text-encoder에 `prompt`가 사용됩니다.

device : (`torch.device`): torch 디바이스

num_images_per_prompt (`int`) : 프롬프트당 생성할 이미지 수

do_classifier_free_guidance (`bool`) : classifier free guidance를 사용할지 여부

negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).

negative_prompt_2 (`str` 또는 `list[str]`, *선택*) : `tokenizer_2`와 `text_encoder_2`에 전송할 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우, 모든 text-encoder에서 `negative_prompt`가 사용됩니다.

negative_prompt_3 (`str` 또는 `list[str]`, *선택*) : `tokenizer_3`와 `text_encoder_3`에 전송할 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우, 모든 text-encoder에서 `negative_prompt`가 사용됩니다.

prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`torch.FloatTensor`, *선택*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

pooled_prompt_embeds (`torch.FloatTensor`, *선택 사항*) : 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다.

negative_pooled_prompt_embeds (`torch.FloatTensor`, *선택*) : 미리 생성된 부정 풀링 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 pooled negative_prompt_embeds가 생성됩니다.

clip_skip (`int`, *선택 사항*) : 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어 수. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다.

lora_scale (`float`, *선택 사항*) : LoRA 레이어가 로드된 경우, 텍스트 인코더의 모든 LoRA 레이어에 적용될 LoRA 스케일입니다.

#### prepare_ip_adapter_image_embeds[[diffusers.StableDiffusion3Pipeline.prepare_ip_adapter_image_embeds]]

```python
prepare_ip_adapter_image_embeds(ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: typing.Optional[torch.Tensor] = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py#L716)

**매개변수:**

ip_adapter_image (`PipelineImageInput`, *선택 사항*) : IP-Adapter에서 특징을 추출할 입력 이미지입니다.

ip_adapter_image_embeds (`torch.Tensor`, *선택 사항*) : 미리 계산된 이미지 임베딩.

device : (`torch.device`, *선택 사항*): Torch 장치.

num_images_per_prompt (`int`, 기본값 1) : 프롬프트당 생성할 이미지 수.

do_classifier_free_guidance (`bool`, 기본값 True) : classifier free guidance를 사용할지 여부.

IP-Adapter에서 사용할 이미지 임베딩을 준비합니다.

`ip_adapter_image` 또는 `ip_adapter_image_embeds` 중 하나는 전달되어야 합니다.

