# Perturbed-Attention Guidance

  

[Perturbed-Attention Guidance (PAG)](https://ku-cvlab.github.io/Perturbed-Attention-Guidance/)는 무조건적 및 조건적 설정 모두에서 샘플 품질을 향상시키는 새로운 diffusion sampling guidance입니다. 추가 학습이나 외부 모듈 통합 없이 이를 달성합니다.

PAG는 Donghoon Ahn, Hyoungwon Cho, Jaewon Min, Wooseok Jang, Jungwoo Kim, SeonHwa Kim, Hyun Hee Park, Kyong Hwan Jin, Seungryong Kim이 발표한 [Self-Rectifying Diffusion Sampling with Perturbed-Attention Guidance](https://huggingface.co/papers/2403.17377)에서 소개되었습니다.

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

*최근 연구들은 diffusion 모델이 고품질 샘플을 생성할 수 있음을 입증했지만, 그 품질은 classifier guidance(CG)와 classifier-free guidance(CFG)와 같은 샘플링 guidance 기법에 크게 의존합니다. 이러한 기법은 unconditional generation이나 이미지 복원 등 다양한 downstream task에는 적용하기 어렵습니다. 본 논문에서는 추가적인 학습이나 외부 모듈의 통합 없이 unconditional 및 conditional 설정 모두에서 diffusion 샘플 품질을 향상시키는 새로운 샘플링 guidance인 Perturbed-Attention Guidance(PAG)를 제안합니다. PAG는 denoising 과정 전반에 걸쳐 샘플의 구조를 점진적으로 강화하도록 설계되었습니다. 이는 self-attention 메커니즘이 구조 정보를 포착할 수 있는 능력을 고려하여, diffusion U-Net의 선택된 self-attention 맵을 identity matrix로 대체함으로써 구조가 열화된 중간 샘플을 생성하고, denoising 과정을 이러한 열화된 샘플에서 벗어나도록 유도하는 방식으로 작동합니다. ADM과 Stable Diffusion 모두에서 PAG는 conditional 시나리오는 물론 unconditional 시나리오에서도 놀랍게도 샘플 품질을 향상시킵니다. 또한, PAG는 ControlNet의 empty prompt 사용이나 inpainting, deblurring과 같은 이미지 복원 등 기존 guidance인 CG나 CFG를 완전히 활용하기 어려운 다양한 downstream task에서 baseline 성능을 크게 향상시킵니다.*

PAG는 PAG 파이프라인을 인스턴스화할 때 `pag_applied_layers`를 매개변수로 지정하여 사용할 수 있습니다. 단일 문자열 또는 문자열 목록일 수 있습니다. 각 문자열은 고유한 레이어 식별자이거나, 하나 이상의 레이어를 식별하기 위한 정규식일 수 있습니다.

- 일반 문자열로 된 전체 식별자: `down_blocks.2.attentions.0.transformer_blocks.0.attn1.processor`
- RegEx로 표현한 전체 식별자: `down_blocks.2.(attentions|motion_modules).0.transformer_blocks.0.attn1.processor`
- RegEx로 부분 식별자: `down_blocks.2` 또는 `attn1`
- 식별자 목록(문자열과 ReGex의 조합 가능): `["blocks.1", "blocks.(14|20)", r"down_blocks\.(2,3)"]`

> [!WARNING]
> RegEx가 레이어 식별자 매칭 방식으로 지원되므로, 올바르게 사용하지 않으면 예상치 못한 동작이 발생할 수 있습니다. PAG를 사용하는 권장 방법은 레이어를 `blocks.{layer_index}` 및 `blocks.({layer_index_1|layer_index_2|...})` 형식으로 지정하는 것입니다. 다른 방식으로 사용하는 것도 가능하지만, 기본 검증 검사를 우회하여 예상치 못한 결과를 초래할 수 있습니다.

## 일반 작업

PAG는 텍스트-이미지 생성, 이미지-이미지 변환, 인페인팅과 같은 작업을 위해 [StableDiffusionXLPipeline](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline)에 적용할 수 있습니다. 특정 작업에 PAG를 활성화하려면 `enable_pag=True` 플래그와 `pag_applied_layers` 인수를 사용하여 [AutoPipeline](./auto_pipeline) API로 파이프라인을 로드합니다.

> [!TIP]
> 🤗 Diffusers는 현재 선택된 SDXL 파이프라인과 [PixArtSigmaPAGPipeline](/docs/diffusers/main/ko/api/pipelines/pag#diffusers.PixArtSigmaPAGPipeline)에서만 PAG를 사용할 수 있습니다. 새로운 파이프라인에 PAG 지원을 추가하고 싶다면 [기능 요청](https://github.com/huggingface/diffusers/issues/new/choose)을 자유롭게 열어 주세요!

```py
from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    enable_pag=True,
    pag_applied_layers=["mid"],
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

> [!TIP]
> `pag_applied_layers` 인수를 사용하면 PAG가 적용될 레이어를 지정할 수 있습니다. 또한 파이프라인 생성 후 `set_pag_applied_layers` 메서드를 사용해 해당 레이어를 업데이트할 수 있습니다. PAG를 다른 레이어에 적용하는 방법에 대해서는 [pag_applied_layers](#pagappliedlayers) 섹션을 참고하세요.

이미 생성되고 로드된 파이프라인이 있는 경우, `enable_pag` 플래그를 사용하여 `from_pipe` API로 PAG를 활성화할 수 있습니다. 내부적으로 지정된 파이프라인과 작업을 기반으로 PAG 파이프라인이 생성됩니다. 아래 예시에서는 `AutoPipelineForText2Image`를 사용하고 `StableDiffusionXLPipeline`을 전달했으므로, 이에 따라 `StableDiffusionXLPAGPipeline`이 생성됩니다. 추가 메모리가 필요하지 않으며, `StableDiffusionXLPipeline`과 `StableDiffusionXLPAGPipeline`이 모두 로드되어 사용 준비가 된 상태가 됩니다. `from_pipe` API와 파이프라인 재사용 방법에 대해 diffuser [여기](https://huggingface.co/docs/diffusers/using-diffusers/loading#reusing-models-in-multiple-pipelines)에서 자세히 알아볼 수 있습니다.

```py
pipeline_sdxl = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForText2Image.from_pipe(pipeline_sdxl, enable_pag=True)
```

이미지를 생성하려면 `pag_scale`도 전달해야 합니다. `pag_scale`이 증가하면 이미지는 더 의미론적으로 일관된 구조를 가지게 되고 아티팩트가 줄어듭니다. 그러나 과도하게 큰 guidance scale은 CFG와 유사하게 이미지의 텍스처가 더 매끄러워지고 약간 과포화되는 결과를 초래할 수 있습니다. 공식 데모에서는 `pag_scale=3.0`이 사용되며 대부분의 사용 사례에서 잘 작동하지만, 필요에 따라 실험하여 적절한 값을 선택해 보세요. `pag_scale=0`이면 PAG가 비활성화됩니다.

```py
prompt = "an insect robot preparing a delicious meal, anime style"

for pag_scale in [0.0, 3.0]:
    generator = torch.Generator(device="cpu").manual_seed(0)
    images = pipeline(
        prompt=prompt,
        num_inference_steps=25,
        guidance_scale=7.0,
        generator=generator,
        pag_scale=pag_scale,
    ).images
```

  
    
    PAG가 없는 생성 이미지
  
  
    
    PAG로 생성된 이미지
  

PAG는 이미지-이미지 파이프라인과 함께 사용할 수 있습니다.

```py
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image
import torch

pipeline = AutoPipelineForImage2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    enable_pag=True,
    pag_applied_layers=["mid"],
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

이미지-이미지 파이프라인이 이미 있고 PAG를 활성화하려면 다음을 실행할 수 있습니다

```py
pipeline_t2i = AutoPipelineForImage2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_t2i, enable_pag=True)
```

텍스트-이미지 파이프라인에서 PAG가 활성화된 이미지-이미지 파이프라인으로 직접 전환하는 것도 매우 쉽습니다

```py
pipeline_pag = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_t2i, enable_pag=True)
```

PAG가 활성화된 텍스트-이미지 생성 파이프라인을 보유하고 있다면, PAG가 여전히 활성화된 상태로 이미지-이미지 생성 파이프라인으로 직접 전환할 수 있습니다.

```py
pipeline_pag = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", enable_pag=True, dtype=torch.float16)
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline_t2i)
```

이제 이미지를 생성해 보겠습니다!

```py
pag_scales =  4.0
guidance_scales = 7.0

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
init_image = load_image(url)
prompt = "a dog catching a frisbee in the jungle"

generator = torch.Generator(device="cpu").manual_seed(0)
image = pipeline(
    prompt,
    image=init_image,
    strength=0.8,
    guidance_scale=guidance_scale,
    pag_scale=pag_scale,
    generator=generator).images[0]
```

```py
from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image
import torch

pipeline = AutoPipelineForInpainting.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    enable_pag=True,
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

기존 inpainting 파이프라인에서 PAG를 다음과 같이 활성화할 수 있습니다

```py
pipeline_inpaint = AutoPipelineForInpainting.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForInpainting.from_pipe(pipeline_inpaint, enable_pag=True)
```

파이프라인의 작업이 다른 경우에도 여전히 작동합니다:

```py
pipeline_t2i = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", dtype=torch.float16)
pipeline = AutoPipelineForInpaiting.from_pipe(pipeline_t2i, enable_pag=True)
```

이미지를 생성해 보겠습니다!

```py
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).convert("RGB")
mask_image = load_image(mask_url).convert("RGB")

prompt = "A majestic tiger sitting on a bench"

pag_scales =  3.0
guidance_scales = 7.5

generator = torch.Generator(device="cpu").manual_seed(1)
images = pipeline(
    prompt=prompt,
    image=init_image,
    mask_image=mask_image,
    strength=0.8,
    num_inference_steps=50,
    guidance_scale=guidance_scale,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]
```

## ControlNet을 사용한 PAG

PAG를 ControlNet과 함께 사용하려면 먼저 `controlnet`을 생성합니다. 그런 다음, `controlnet`과 다른 PAG 인수를 지정된 작업의 AutoPipeline의 `from_pretrained` 메서드에 전달합니다.

```py
from diffusers import AutoPipelineForText2Image, ControlNetModel
import torch

controlnet = ControlNetModel.from_pretrained(
    "diffusers/controlnet-canny-sdxl-1.0", dtype=torch.float16
)

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet=controlnet,
    enable_pag=True,
    pag_applied_layers="mid",
    dtype=torch.float16
)
pipeline.enable_model_cpu_offload()
```

> [!TIP]
> 이미 controlnet 파이프라인이 있고 PAG를 활성화하려면 `from_pipe` API를 사용할 수 있습니다: `AutoPipelineForText2Image.from_pipe(pipeline_controlnet, enable_pag=True)`

`pag_scale` 매개변수를 지정할 수 있는 추가 옵션을 제외하면, ControlNet 파이프라인을 평소와 동일한 방식으로 사용할 수 있습니다. PAG는 조건 없는 생성에 잘 작동합니다. 이 예시에서는 프롬프트 없이 이미지를 생성합니다.

```py
from diffusers.utils import load_image
canny_image = load_image(
    "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/pag_control_input.png"
)

for pag_scale in [0.0, 3.0]:
    generator = torch.Generator(device="cpu").manual_seed(1)
    images = pipeline(
        prompt="",
        controlnet_conditioning_scale=controlnet_conditioning_scale,
        image=canny_image,
        num_inference_steps=50,
        guidance_scale=0,
        generator=generator,
        pag_scale=pag_scale,
    ).images
    images[0]
```

  
    
    PAG가 없는 생성 이미지
  
  
    
    PAG로 생성된 이미지
  

## IP-Adapter를 사용한 PAG

[IP-Adapter](https://hf.co/papers/2308.06721)는 기존 모델 구조를 변경하지 않고 이미지 프롬프팅을 가능하게 하는 확산 모델에 적용할 수 있는 인기 있는 모델입니다. IP-Adapter가 로드된 파이프라인에서 PAG를 활성화할 수 있습니다.

```py
from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image
from transformers import CLIPVisionModelWithProjection
import torch

image_encoder = CLIPVisionModelWithProjection.from_pretrained(
    "h94/IP-Adapter",
    subfolder="models/image_encoder",
    dtype=torch.float16
)

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    image_encoder=image_encoder,
    enable_pag=True,
    dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

pipeline.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter-plus_sdxl_vit-h.bin")

pag_scales = 5.0
ip_adapter_scales = 0.8

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_diner.png")

pipeline.set_ip_adapter_scale(ip_adapter_scale)
generator = torch.Generator(device="cpu").manual_seed(0)
images = pipeline(
    prompt="a polar bear sitting in a chair drinking a milkshake",
    ip_adapter_image=image,
    negative_prompt="deformed, ugly, wrong proportion, low res, bad anatomy, worst quality, low quality",
    num_inference_steps=25,
    guidance_scale=3.0,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]

```

PAG는 아티팩트를 줄이고 전반적인 구성을 개선합니다.

  
    
    PAG가 없는 생성 이미지
  
  
    
    PAG로 생성된 이미지
  

## 매개변수 구성

### pag_applied_layers

`pag_applied_layers` 인수를 사용하면 PAG가 적용될 레이어를 지정할 수 있습니다. 기본적으로 중간 블록에만 적용됩니다. 이 설정을 변경하면 출력에 상당한 영향을 미칩니다. 파이프라인 생성 후 `set_pag_applied_layers` 메서드를 사용하여 PAG 레이어를 조정하여 모델에 최적의 레이어를 찾을 수 있습니다.

예를 들어, `pag_layers = ["down.block_2"]`와 `pag_layers = ["down.block_2", "up.block_1.attentions_0"]`를 사용하여 생성된 이미지는 다음과 같습니다.

```py
prompt = "an insect robot preparing a delicious meal, anime style"
pipeline.set_pag_applied_layers(pag_layers)
generator = torch.Generator(device="cpu").manual_seed(0)
images = pipeline(
    prompt=prompt,
    num_inference_steps=25,
    guidance_scale=guidance_scale,
    generator=generator,
    pag_scale=pag_scale,
).images
images[0]
```

  
    
    down.block_2 + up.block1.attentions_0
  
  
    
    down.block_2
  

## AnimateDiffPAGPipeline[[diffusers.AnimateDiffPAGPipeline]]

#### diffusers.AnimateDiffPAGPipeline[[diffusers.AnimateDiffPAGPipeline]]

```python
diffusers.AnimateDiffPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModel, motion_adapter: MotionAdapter, scheduler: KarrasDiffusionSchedulers, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None, pag_applied_layers: str | list[str] = 'mid_block.*attn1')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py#L89)

**매개변수:**

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

text_encoder (`CLIPTextModel`) : 고정된 텍스트 인코더 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer (`CLIPTokenizer`) : 텍스트를 토큰화하기 위한 [CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)입니다.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 비디오 latents의 노이즈를 제거하기 위해 UNetMotionModel을 생성하는 데 사용되는 [UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)입니다.

motion_adapter (`MotionAdapter`) : `unet`와 함께 사용되어 인코딩된 비디오 latents의 노이즈를 제거하는 `MotionAdapter`입니다.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

[AnimateDiff](https://huggingface.co/docs/diffusers/en/api/pipelines/animatediff)와 [Perturbed Attention Guidance](https://huggingface.co/docs/diffusers/en/using-diffusers/pag)를 활용한 텍스트-비디오 생성 파이프라인.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] | None = None, num_frames: int | None = 16, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_videos_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_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'], decode_chunk_size: int = 16, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py#L575)

**매개변수:**

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

height (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 비디오의 픽셀 단위 높이.

width (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 비디오의 픽셀 단위 너비입니다.

num_frames (`int`, *선택 사항*, 기본값 16) : 생성되는 비디오 프레임의 수입니다. 기본값은 16프레임이며, 초당 8프레임 기준 2초 분량의 비디오에 해당합니다.

num_inference_steps (`int`, *선택 사항*, 기본값 50) : 디노이징 단계의 수입니다. 디노이징 단계를 늘리면 일반적으로 더 높은 품질의 비디오를 얻을 수 있지만, 추론 속도가 느려집니다.

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

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

num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수입니다.

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

output_type (`str`, *선택 사항*, 기본값 `"pil"`) : 생성된 비디오의 출력 형식입니다. `torch.Tensor`, `PIL.Image` 또는 `np.array` 중 하나를 선택합니다.

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

cross_attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)에서 정의된 `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` 속성에 나열된 변수만 포함할 수 있습니다.

decode_chunk_size (`int`, *선택 사항*, 기본값 16) : `decode_latents` 메서드를 호출할 때 한 번에 디코딩할 프레임 수입니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [AnimateDiffPipelineOutput](/docs/diffusers/main/ko/api/pipelines/animatediff#diffusers.pipelines.animatediff.AnimateDiffPipelineOutput) 또는 `tuple`

`return_dict`가 `True`인 경우 [AnimateDiffPipelineOutput](/docs/diffusers/main/ko/api/pipelines/animatediff#diffusers.pipelines.animatediff.AnimateDiffPipelineOutput)가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 프레임 목록인 `tuple`이 반환됩니다.

생성을 위한 pipeline의 호출 함수.

예:
```py
>>> import torch
>>> from diffusers import AnimateDiffPAGPipeline, MotionAdapter, DDIMScheduler
>>> from diffusers.utils import export_to_gif

>>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
>>> motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-2"
>>> motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id)
>>> scheduler = DDIMScheduler.from_pretrained(
...     model_id, subfolder="scheduler", beta_schedule="linear", steps_offset=1, clip_sample=False
... )
>>> pipe = AnimateDiffPAGPipeline.from_pretrained(
...     model_id,
...     motion_adapter=motion_adapter,
...     scheduler=scheduler,
...     pag_applied_layers=["mid"],
...     torch_dtype=torch.float16,
... ).to("cuda")

>>> video = pipe(
...     prompt="car, futuristic cityscape with neon lights, street, no human",
...     negative_prompt="low quality, bad quality",
...     num_inference_steps=25,
...     guidance_scale=6.0,
...     pag_scale=3.0,
...     generator=torch.Generator().manual_seed(42),
... ).frames[0]

>>> export_to_gif(video, "animatediff_pag.gif")
```

#### encode_prompt[[diffusers.AnimateDiffPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py#L165)

**매개변수:**

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

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`보다 작은 경우 무시됩니다).

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

## HunyuanDiTPAGPipeline[[diffusers.HunyuanDiTPAGPipeline]]

#### diffusers.HunyuanDiTPAGPipeline[[diffusers.HunyuanDiTPAGPipeline]]

```python
diffusers.HunyuanDiTPAGPipeline(vae: AutoencoderKL, text_encoder: BertModel, tokenizer: BertTokenizer, transformer: HunyuanDiT2DModel, scheduler: DDPMScheduler, safety_checker: diffusers.pipelines.stable_diffusion.safety_checker.StableDiffusionSafetyChecker | None = None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, requires_safety_checker: bool = True, text_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = None, tokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = None, pag_applied_layers: str | list[str] = 'blocks.1')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_hunyuandit.py#L152)

**매개변수:**

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

text_encoder (`~transformers.BertModel`, `~transformers.CLIPTextModel` | None) : 동결된 텍스트 인코더([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). HunyuanDiT는 fine-tuning된 [bilingual CLIP]를 사용합니다.

tokenizer (`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer` | None) : 텍스트를 토큰화할 `BertTokenizer` 또는 `CLIPTokenizer`.

transformer ([HunyuanDiT2DModel](/docs/diffusers/main/ko/api/models/hunyuan_transformer2d#diffusers.HunyuanDiT2DModel)) : Tencent Hunyuan에서 설계한 HunyuanDiT 모델입니다.

text_encoder_2 (`T5EncoderModel`) : mT5 임베더입니다. 구체적으로 't5-v1_1-xxl'입니다.

tokenizer_2 (`T5Tokenizer`) : mT5 임베더에 사용되는 토크나이저입니다.

scheduler ([DDPMScheduler](/docs/diffusers/main/ko/api/schedulers/ddpm#diffusers.DDPMScheduler)) : HunyuanDiT와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러입니다.

HunyuanDiT와 [Perturbed Attention Guidance](https://huggingface.co/docs/diffusers/en/using-diffusers/pag)를 사용하여 영어/중국어에서 이미지로 생성하는 Pipeline

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

HunyuanDiT는 두 개의 텍스트 인코더를 사용합니다: [mT5](https://huggingface.co/google/mt5-base)와 [이중 언어 CLIP](자체적으로 미세 조정함)

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

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_2: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_2: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, output_type: str = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int, dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], guidance_rescale: float = 0.0, original_size: tuple = (1024, 1024), target_size: tuple = None, crops_coords_top_left: tuple = (0, 0), use_resolution_binning: bool = True, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_hunyuandit.py#L579)

**매개변수:**

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

height (`int`) : 생성된 이미지의 픽셀 단위 높이.

width (`int`) : 생성된 이미지의 픽셀 단위 너비.

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

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

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

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

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

prompt_embeds_2 (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.

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

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

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 프롬프트에 사용할 어텐션 마스크입니다. `prompt_embeds`를 직접 전달하는 경우 필수입니다.

prompt_attention_mask_2 (`torch.Tensor`, *선택 사항*) : 프롬프트에 사용할 어텐션 마스크입니다. `prompt_embeds_2`를 직접 전달하는 경우 필수입니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택*) : negative prompt에 사용할 attention mask입니다. `negative_prompt_embeds`가 직접 전달될 때 필수입니다.

negative_prompt_attention_mask_2 (`torch.Tensor`, *선택 사항*) : negative prompt에 사용할 attention mask입니다. `negative_prompt_embeds_2`가 직접 전달되는 경우 필수입니다.

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

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

callback_on_step_end (`Callable[[int, int], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *선택 사항*) : 각 노이즈 제거 단계의 끝에서 호출될 콜백 함수 또는 콜백 함수 목록.

callback_on_step_end_tensor_inputs (`list[str]`, *선택 사항*) : 콜백 함수에 전달해야 하는 텐서 입력 목록입니다. 정의되지 않으면 모든 텐서 입력이 전달됩니다.

guidance_rescale (`float`, *optional*, defaults to 0.0) : Rescale the noise_cfg according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). See Section 3.4

original_size (`tuple[int, int]`, *선택 사항*, 기본값 `(1024, 1024)`) : 이미지의 원래 크기입니다. time ids를 계산하는 데 사용됩니다.

target_size (`tuple[int, int]`, *선택 사항*) : 이미지의 대상 크기. time ids를 계산하는 데 사용됩니다.

crops_coords_top_left (`tuple[int, int]`, *선택 사항*, 기본값 `(0, 0)`) : 크롭의 왼쪽 위 좌표입니다. time ids를 계산하는 데 사용됩니다.

use_resolution_binning (`bool`, *선택 사항*, 기본값 `True`) : 해상도 바인닝(resolution binning)을 사용할지 여부입니다. `True`인 경우, 입력 해상도가 가장 가까운 표준 해상도로 매핑됩니다. 지원되는 해상도는 1024x1024, 1280x1280, 1024x768, 1152x864, 1280x960, 768x1024, 864x1152, 960x1280, 1280x768, 768x1280입니다. 이 값을 `True`로 설정하는 것이 권장됩니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

HunyuanDiT로 생성을 위한 pipeline에 대한 호출 함수입니다.

예:
```python
>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=[14],
... ).to("cuda")

>>> # prompt = "an astronaut riding a horse"
>>> prompt = "一个宇航员在骑马"
>>> image = pipe(prompt, guidance_scale=4, pag_scale=3).images[0]
```

#### encode_prompt[[diffusers.HunyuanDiTPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, device: device = None, dtype: dtype = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int | None = None, text_encoder_index: int = 0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_hunyuandit.py#L258)

**매개변수:**

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

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

dtype (`torch.dtype`) : torch dtype

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

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

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

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

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

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 프롬프트에 사용할 어텐션 마스크입니다. `prompt_embeds`를 직접 전달하는 경우 필수입니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택*) : negative prompt에 사용할 attention mask입니다. `negative_prompt_embeds`가 직접 전달될 때 필수입니다.

max_sequence_length (`int`, *선택 사항*) : 프롬프트에 사용할 최대 시퀀스 길이.

text_encoder_index (`int`, *선택 사항*) : 사용할 텍스트 인코더의 인덱스입니다. `0`은 clip, `1`은 T5를 나타냅니다.

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

## KolorsPAGPipeline[[diffusers.KolorsPAGPipeline]]

#### diffusers.KolorsPAGPipeline[[diffusers.KolorsPAGPipeline]]

```python
diffusers.KolorsPAGPipeline(vae: AutoencoderKL, text_encoder: ChatGLMModel, tokenizer: ChatGLMTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, force_zeros_for_empty_prompt: bool = False, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L128)

**매개변수:**

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

text_encoder (`ChatGLMModel`) : 고정된 텍스트 인코더. Kolors는 [ChatGLM3-6B](https://huggingface.co/THUDM/chatglm3-6b)를 사용합니다.

tokenizer (`ChatGLMTokenizer`) : [ChatGLMTokenizer](https://huggingface.co/THUDM/chatglm3-6b/blob/main/tokenization_chatglm.py) 클래스의 토크나이저.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 U-Net 아키텍처.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

force_zeros_for_empty_prompt (`bool`, *선택 사항*, 기본값 `"False"`) : 부정 프롬프트 임베딩을 항상 0으로 설정하도록 강제할지 여부입니다. 또한 `Kwai-Kolors/Kolors-diffusers`의 구성을 참고하세요.

pag_applied_layers (`str` or `list[str]``, *optional*, defaults to `"mid"`) : 교란된 어텐션 가이던스를 적용할 트랜스포머 어텐션 레이어를 설정합니다. "down", "mid", "up", 트랜스포머 블록 전체 또는 특정 트랜스포머 블록의 어텐션 레이어를 나타내는 문자열 또는 문자열 목록일 수 있습니다. 예: ["mid"] ["down", "mid"] ["down", "mid", "up.block_1"] ["down", "mid", "up.block_1.attentions_0", "up.block_1.attentions_1"]

Kolors를 사용한 텍스트-이미지 생성을 위한 Pipeline

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, original_size: tuple[int, int] | None = None, crops_coords_top_left: tuple = (0, 0), target_size: tuple[int, int] | None = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple = (0, 0), negative_target_size: tuple[int, int] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0, max_sequence_length: int = 256)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L665)

**매개변수:**

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

height (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 높이입니다. 최적의 결과를 위해 기본값은 1024로 설정되어 있습니다. [Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers)와 저해상도에 대해 특별히 파인튜닝되지 않은 체크포인트의 경우 512픽셀 미만에서는 제대로 작동하지 않습니다.

width (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 너비입니다. 최적의 결과를 위해 기본값은 1024로 설정되어 있습니다. [Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers)와 저해상도에 대해 특별히 파인튜닝되지 않은 체크포인트의 경우 512픽셀 미만에서는 제대로 작동하지 않습니다.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

denoising_end (`float`, *선택 사항*) : 지정된 경우, 전체 디노이징 과정 중 의도적으로 조기 종료되기 전에 완료될 비율(0.0에서 1.0 사이)을 결정합니다. 그 결과, 스케줄러가 선택한 이산 시간 단계에 따라 반환되는 샘플에는 상당한 양의 노이즈가 여전히 남아 있게 됩니다. [**이미지 출력 개선**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)에서 자세히 설명된 바와 같이, 이 파이프라인이 "Mixture of Denoisers" 멀티 파이프라인 구성의 일부로 사용되는 경우 denoising_end 매개변수를 이상적으로 활용해야 합니다.

guidance_scale (`float`, *선택 사항*, 기본값 5.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`보다 작은 경우 무시됩니다).

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

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 논문(https://huggingface.co/papers/2010.02502)의 파라미터 eta (η)에 해당합니다. [schedulers.DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

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

ip_adapter_image_embeds (`list[torch.Tensor]`, *선택*) : IP-Adapter를 위한 사전 생성된 이미지 임베딩입니다. 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.kolors.KolorsPipelineOutput`를 반환할지 여부.

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

original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : `original_size`가 `target_size`와 같지 않으면 이미지가 다운샘플링 또는 업샘플링된 것처럼 보입니다. `original_size`는 지정되지 않은 경우 기본값이 `(height, width)`입니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디셔닝(micro-conditioning)의 일부입니다.

crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : `crops_coords_top_left`를 사용하면 `crops_coords_top_left` 위치에서 아래쪽으로 "잘린" 것처럼 보이는 이미지를 생성할 수 있습니다. (0, 0)으로 `crops_coords_top_left`를 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대부분의 경우 `target_size`는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정되지 않으면 기본값으로 `(height, width)`가 사용됩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다.

negative_original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 특정 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : 특정 crop 좌표를 기반으로 생성 과정을 부정적으로 조건부화합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대상 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. 대부분의 경우 `target_size`와 동일해야 합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션잉(micro-conditioning)의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

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

**반환값:** `~pipelines.kolors.KolorsPipelineOutput` 또는 `tuple`

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

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

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

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Kwai-Kolors/Kolors-diffusers",
...     variant="fp16",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["down.block_2.attentions_1", "up.block_0.attentions_1"],
... )
>>> pipe = pipe.to("cuda")

>>> prompt = (
...     "A photo of a ladybug, macro, zoom, high quality, film, holding a wooden sign with the text 'KOLORS'"
... )
>>> image = pipe(prompt, guidance_scale=5.5, pag_scale=1.5).images[0]
```

#### encode_prompt[[diffusers.KolorsPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 256)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L216)

**매개변수:**

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

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`보다 작은 경우 무시됩니다).

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

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.KolorsPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_kolors.py#L608)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionPAGInpaintPipeline[[diffusers.StableDiffusionPAGInpaintPipeline]]

#### diffusers.StableDiffusionPAGInpaintPipeline[[diffusers.StableDiffusionPAGInpaintPipeline]]

```python
diffusers.StableDiffusionPAGInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L184)

**매개변수:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)) : 고정된 텍스트 인코더 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)) : 텍스트를 토큰화하기 위한 `CLIPTokenizer`입니다.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 latents의 노이즈를 제거하기 위한 `UNet2DConditionModel`.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

safety_checker (`StableDiffusionSafetyChecker`) : 생성된 이미지가 offensive하거나 유해한 것으로 간주될 수 있는지 추정하는 분류 모듈입니다. 모델의 잠재적 유해성에 대한 자세한 내용은 [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)를 참고하세요.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 생성된 이미지에서 특징을 추출하기 위한 `CLIPImageProcessor`. `safety_checker`의 입력으로 사용됩니다.

Stable Diffusion을 사용한 텍스트-이미지 생성을 위한 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: Tensor = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 0.9999, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, 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'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L910)

**매개변수:**

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

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : `Image`, numpy 배열 또는 텐서로 표현된 inpaint 대상 이미지 배치입니다. (`mask_image`로 마스킹할 이미지 영역과 `prompt`에 따라 다시 그릴 영역을 지정합니다.)

mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : `image`를 마스킹할 이미지 배치(`Image`, numpy 배열 또는 텐서)를 나타냅니다. 마스크의 흰색 픽셀은 다시 채워지고 검은색 픽셀은 유지됩니다. `mask_image`가 PIL 이미지인 경우, 사용 전에 단일 채널(명도)로 변환됩니다. numpy 배열 또는 pytorch 텐서인 경우 3개 대신 하나의 색상 채널(L)을 포함해야 하므로, pytorch 텐서의 예상 shape은 `(B, 1, H, W)`, `(B, H, W)`, `(1, H, W)`, `(H, W)`입니다. numpy 배열의 경우 `(B, H, W, 1)`, `(B, H, W)`, `(H, W, 1)`, 또는 `(H, W)`입니다.

masked_image_latents (`torch.Tensor`, *선택 사항*) : 인페인팅을 위한 마스킹된 이미지의 사전 인코딩된 잠재 변수(latent).

height (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 높이.

width (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 너비.

padding_mask_crop (`int`, *선택 사항*, 기본값 `None`) : 이미지와 마스킹에 적용할 크롭의 마진 크기입니다. `None`인 경우 이미지와 mask_image에 크롭이 적용되지 않습니다. `padding_mask_crop`이 `None`이 아닌 경우, 먼저 이미지의 종횡비와 동일하고 모든 마스킹 영역을 포함하는 직사각형 영역을 찾은 다음, `padding_mask_crop`을 기반으로 해당 영역을 확장합니다. 이후 인페인팅을 위해 원래 이미지 크기로 리사이즈하기 전에 확장된 영역을 기준으로 이미지와 mask_image가 크롭됩니다. 이는 마스킹 영역이 작고 이미지가 크며 배경과 같이 인페인팅에 관련 없는 정보를 포함하는 경우에 유용합니다.

strength (`float`, *선택 사항*, 기본값 0.9999) : 참조 `image`를 변환할 정도를 나타냅니다. 0과 1 사이여야 합니다. `image`는 시작점으로 사용되며, `strength` 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되며, `num_inference_steps`에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 1이라는 값은 사실상 `image`를 무시하는 것과 같습니다.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

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

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

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

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

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

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

guidance_rescale (`float`, *선택 사항*, 기본값 0.0) : [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891)에서 제시한 Guidance rescale factor입니다. zero terminal SNR을 사용할 때 과노출 문제를 해결하기 위해 Guidance rescale factor를 사용해야 합니다.

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

생성을 위한 pipeline의 호출 함수.

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

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")
>>> 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).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")
>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     strength=0.8,
...     num_inference_steps=50,
...     guidance_scale=guidance_scale,
...     generator=generator,
...     pag_scale=pag_scale,
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionPAGInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L334)

**매개변수:**

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

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`보다 작은 경우 무시됩니다).

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionPAGInpaintPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py#L849)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionPAGPipeline[[diffusers.StableDiffusionPAGPipeline]]

#### diffusers.StableDiffusionPAGPipeline[[diffusers.StableDiffusionPAGPipeline]]

```python
diffusers.StableDiffusionPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L157)

**매개변수:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)) : 고정된 텍스트 인코더 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)) : 텍스트를 토큰화하기 위한 `CLIPTokenizer`입니다.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 latents의 노이즈를 제거하기 위한 `UNet2DConditionModel`.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

safety_checker (`StableDiffusionSafetyChecker`) : 생성된 이미지가 offensive하거나 유해한 것으로 간주될 수 있는지 추정하는 분류 모듈입니다. 모델의 잠재적 유해성에 대한 자세한 내용은 [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)를 참고하세요.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 생성된 이미지에서 특징을 추출하기 위한 `CLIPImageProcessor`. `safety_checker`의 입력으로 사용됩니다.

Stable Diffusion을 사용한 텍스트-이미지 생성을 위한 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, 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'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L745)

**매개변수:**

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

height (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 높이.

width (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 너비.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

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

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

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

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

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

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

guidance_rescale (`float`, *선택 사항*, 기본값 0.0) : [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891)에서 제시한 Guidance rescale factor입니다. zero terminal SNR을 사용할 때 과노출 문제를 해결하기 위해 Guidance rescale factor를 사용해야 합니다.

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

생성을 위한 pipeline의 호출 함수.

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

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L304)

**매개변수:**

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

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`보다 작은 경우 무시됩니다).

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd.py#L684)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionPAGImg2ImgPipeline[[diffusers.StableDiffusionPAGImg2ImgPipeline]]

#### diffusers.StableDiffusionPAGImg2ImgPipeline[[diffusers.StableDiffusionPAGImg2ImgPipeline]]

```python
diffusers.StableDiffusionPAGImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L152)

**매개변수:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)) : 고정된 텍스트 인코더 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)) : 텍스트를 토큰화하기 위한 `CLIPTokenizer`입니다.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 latents의 노이즈를 제거하기 위한 `UNet2DConditionModel`.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

safety_checker (`StableDiffusionSafetyChecker`) : 생성된 이미지가 offensive하거나 유해한 것으로 간주될 수 있는지 추정하는 분류 모듈입니다. 모델의 잠재적 유해성에 대한 자세한 내용은 [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)를 참고하세요.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 생성된 이미지에서 특징을 추출하기 위한 `CLIPImageProcessor`. `safety_checker`의 입력으로 사용됩니다.

Stable Diffusion을 사용한 텍스트 기반 이미지-이미지 생성을 위한 Pipeline

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.8, num_inference_steps: int | None = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float | None = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L782)

**매개변수:**

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

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : 시작점으로 사용할 이미지 배치의 `Image`, numpy 배열 또는 텐서를 나타냅니다. numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는 `[0, 1]`입니다. 텐서 또는 텐서 목록인 경우, 예상 shape은 `(B, C, H, W)` 또는 `(C, H, W)`여야 합니다. numpy 배열 또는 배열 목록인 경우, 예상 shape은 `(B, H, W, C)` 또는 `(H, W, C)`여야 합니다. `image`로 이미지 latents도 받을 수 있지만, latents를 직접 전달하는 경우 다시 인코딩되지 않습니다.

strength (`float`, *선택 사항*, 기본값 0.8) : 참조 `image`를 변환할 정도를 나타냅니다. 0과 1 사이여야 합니다. `image`는 시작점으로 사용되며, `strength` 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되며, `num_inference_steps`에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 1이라는 값은 사실상 `image`를 무시하는 것과 같습니다.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

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

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

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

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

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

생성을 위한 pipeline의 호출 함수.

예:
```py
>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionPAGImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L299)

**매개변수:**

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

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`보다 작은 경우 무시됩니다).

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionPAGImg2ImgPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_img2img.py#L725)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionControlNetPAGPipeline[[diffusers.StableDiffusionControlNetPAGPipeline]]

#### diffusers.StableDiffusionControlNetPAGPipeline[[diffusers.StableDiffusionControlNetPAGPipeline]]

```python
diffusers.StableDiffusionControlNetPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py#L168)

**매개변수:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)) : 고정된 텍스트 인코더 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)) : 텍스트를 토큰화하기 위한 `CLIPTokenizer`입니다.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 latents의 노이즈를 제거하기 위한 `UNet2DConditionModel`.

controlnet ([ControlNetModel](/docs/diffusers/main/ko/api/models/controlnet#diffusers.ControlNetModel) 또는 `list[ControlNetModel]`) : 노이즈 제거 과정에서 `unet`에 추가 조건을 제공합니다. 여러 ControlNet을 리스트로 설정하면 각 ControlNet의 출력을 합산하여 하나의 통합된 추가 조건을 생성합니다.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

safety_checker (`StableDiffusionSafetyChecker`) : 생성된 이미지가 offensive하거나 유해한 것으로 간주될 수 있는지 추정하는 분류 모듈입니다. 모델의 잠재적 유해성에 대한 자세한 내용은 [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)를 참고하세요.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 생성된 이미지에서 특징을 추출하기 위한 `CLIPImageProcessor`. `safety_checker`의 입력으로 사용됩니다.

ControlNet 가이던스를 사용하여 Stable Diffusion으로 텍스트-이미지 생성을 수행하는 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

#### encode_prompt[[diffusers.StableDiffusionControlNetPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py#L275)

**매개변수:**

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

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`보다 작은 경우 무시됩니다).

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionControlNetPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py#L810)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionControlNetPAGInpaintPipeline[[diffusers.StableDiffusionControlNetPAGInpaintPipeline]]

#### diffusers.StableDiffusionControlNetPAGInpaintPipeline[[diffusers.StableDiffusionControlNetPAGInpaintPipeline]]

```python
diffusers.StableDiffusionControlNetPAGInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L134)

**매개변수:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)) : 고정된 텍스트 인코더 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)) : 텍스트를 토큰화하기 위한 `CLIPTokenizer`입니다.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 latents의 노이즈를 제거하기 위한 `UNet2DConditionModel`.

controlnet ([ControlNetModel](/docs/diffusers/main/ko/api/models/controlnet#diffusers.ControlNetModel) 또는 `list[ControlNetModel]`) : 노이즈 제거 과정에서 `unet`에 추가 조건을 제공합니다. 여러 ControlNet을 리스트로 설정하면 각 ControlNet의 출력을 합산하여 하나의 통합된 추가 조건을 생성합니다.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

safety_checker (`StableDiffusionSafetyChecker`) : 생성된 이미지가 offensive하거나 유해한 것으로 간주될 수 있는지 추정하는 분류 모듈입니다. 모델의 잠재적 유해성에 대한 자세한 내용은 [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)를 참고하세요.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 생성된 이미지에서 특징을 추출하기 위한 `CLIPImageProcessor`. `safety_checker`의 입력으로 사용됩니다.

ControlNet 가이던스를 사용하여 Stable Diffusion으로 이미지 인페인팅을 수행하는 파이프라인.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

> [!TIP] > 이 파이프라인은 인페인팅을 위해 특별히 파인튜닝된 체크포인트와 함께 사용할 수 있습니다 >
([stable-diffusion-v1-5/stable-diffusion-inpainting](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting))와 기본 텍스트-이미지 Stable Diffusion 체크포인트인 ([stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5))를 사용합니다. 해당 체크포인트로 파인튜닝된 ControlNet, 예: [lllyasviel/control_v11p_sd15_inpaint](https://huggingface.co/lllyasviel/control_v11p_sd15_inpaint)의 경우 기본 텍스트-이미지 Stable Diffusion 체크포인트를 사용하는 것이 더 적합할 수 있습니다.

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

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 1.0, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 0.5, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L972)

**매개변수:**

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

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, : `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`): 시작점으로 사용할 이미지 배치의 `Image`, NumPy 배열 또는 텐서. NumPy 배열과 PyTorch 텐서 모두에서 예상 값 범위는 `[0, 1]` 사이입니다. 텐서 또는 텐서 목록인 경우, 예상 형상은 `(B, C, H, W)` 또는 `(C, H, W)`여야 합니다. NumPy 배열 또는 배열 목록인 경우, 예상 형상은 `(B, H, W, C)` 또는 `(H, W, C)`여야 합니다. `image`로 이미지 라텐트를 전달할 수도 있으며, 라텐트를 직접 전달하는 경우 다시 인코딩되지 않습니다.

mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, : `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`): `image`를 마스킹할 이미지 배치(`Image`, NumPy 배열 또는 텐서)를 나타냅니다. 마스크의 흰색 픽셀은 다시 채워지고 검은색 픽셀은 유지됩니다. `mask_image`가 PIL 이미지인 경우, 사용 전에 단일 채널(명도)로 변환됩니다. NumPy 배열 또는 PyTorch 텐서인 경우 3개 대신 하나의 색상 채널(L)을 포함해야 하므로, PyTorch 텐서의 예상 형상은 `(B, 1, H, W)`, `(B, H, W)`, `(1, H, W)`, `(H, W)`입니다. NumPy 배열의 경우 `(B, H, W, 1)`, `(B, H, W)`, `(H, W, 1)`, 또는 `(H, W)`입니다.

control_image (`torch.Tensor`, `PIL.Image.Image`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, : `list[list[torch.Tensor]]`, 또는 `list[list[PIL.Image.Image]]`): 생성 시 `unet`에 가이드를 제공하기 위한 ControlNet 입력 조건입니다. 타입이 `torch.Tensor`로 지정된 경우, ControlNet에 그대로 전달됩니다. `PIL.Image.Image`도 이미지로 허용됩니다. 출력 이미지의 차원은 기본적으로 `image`의 차원을 따릅니다. height와/또는 width가 전달되면, `image`는 이에 맞게 리사이즈됩니다. `init`에서 여러 ControlNet이 지정된 경우, 각 ControlNet에 대한 입력이 올바르게 배치(batch)될 수 있도록 리스트의 각 요소가 이미지가 되도록 리스트로 전달해야 합니다.

height (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 높이.

width (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 너비.

padding_mask_crop (`int`, *선택 사항*, 기본값 `None`) : 이미지와 마스킹에 적용할 크롭의 마진 크기입니다. `None`인 경우 이미지와 mask_image에 크롭이 적용되지 않습니다. `padding_mask_crop`이 `None`이 아닌 경우, 먼저 이미지의 종횡비와 동일하고 모든 마스킹 영역을 포함하는 직사각형 영역을 찾은 다음, `padding_mask_crop`을 기반으로 해당 영역을 확장합니다. 이후 인페인팅을 위해 원래 이미지 크기로 리사이즈하기 전에 확장된 영역을 기준으로 이미지와 mask_image가 크롭됩니다. 이는 마스킹 영역이 작고 이미지가 크며 배경과 같이 인페인팅에 관련 없는 정보를 포함하는 경우에 유용합니다.

strength (`float`, *선택 사항*, 기본값 1.0) : 참조 `image`를 변환할 정도를 나타냅니다. 0과 1 사이여야 합니다. `image`는 시작점으로 사용되며, `strength` 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되며, `num_inference_steps`에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 1이라는 값은 기본적으로 `image`를 무시하는 것과 같습니다.

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

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

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

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

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

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

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

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

controlnet_conditioning_scale (`float` 또는 `list[float]`, *선택 사항*, 기본값 0.5) : ControlNet의 출력은 원래 `unet`의 잔차에 더해지기 전에 `controlnet_conditioning_scale`과 곱해집니다. `init`에 여러 ControlNet이 지정된 경우, 해당 스케일을 리스트로 설정할 수 있습니다.

control_guidance_start (`float` 또는 `list[float]`, *선택 사항*, 기본값 0.0) : ControlNet이 적용을 시작하는 전체 스텝의 비율입니다.

control_guidance_end (`float` 또는 `list[float]`, *선택 사항*, 기본값 1.0) : ControlNet이 적용을 중단하는 전체 스텝의 비율입니다.

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

생성을 위한 pipeline의 호출 함수.

예:
```py
>>> # !pip install transformers accelerate
>>> import cv2
>>> from diffusers import AutoPipelineForInpainting, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> from PIL import Image
>>> import torch

>>> init_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))

>>> generator = torch.Generator(device="cpu").manual_seed(1)

>>> mask_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))

>>> def make_canny_condition(image):
...     image = np.array(image)
...     image = cv2.Canny(image, 100, 200)
...     image = image[:, :, None]
...     image = np.concatenate([image, image, image], axis=2)
...     image = Image.fromarray(image)
...     return image

>>> control_image = make_canny_condition(init_image)

>>> controlnet = ControlNetModel.from_pretrained(
...     "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     controlnet=controlnet,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )

>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> image = pipe(
...     "a handsome man with ray-ban sunglasses",
...     num_inference_steps=20,
...     generator=generator,
...     eta=1.0,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
...     pag_scale=0.3,
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionControlNetPAGInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L251)

**매개변수:**

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

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`보다 작은 경우 무시됩니다).

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionControlNetPAGInpaintPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py#L919)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionXLPAGPipeline[[diffusers.StableDiffusionXLPAGPipeline]]

#### diffusers.StableDiffusionXLPAGPipeline[[diffusers.StableDiffusionXLPAGPipeline]]

```python
diffusers.StableDiffusionXLPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L172)

**매개변수:**

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

text_encoder (`CLIPTextModel`) : 고정된 텍스트 인코더입니다. Stable Diffusion XL은 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)의 텍스트 부분을 사용하며, 구체적으로 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 변형을 사용합니다.

text_encoder_2 (` CLIPTextModelWithProjection`) : 두 번째 고정된 텍스트 인코더입니다. Stable Diffusion XL은 [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) 변형을 사용합니다.

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.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 U-Net 아키텍처.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

force_zeros_for_empty_prompt (`bool`, *선택 사항*, 기본값 `"True"`) : negative prompt embeddings가 항상 0으로 설정되도록 강제할지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-base-1-0`의 config를 참고하세요.

add_watermarker (`bool`, *선택 사항*) : 출력 이미지에 워터마크를 적용하기 위해 [invisible_watermark 라이브러리](https://github.com/ShieldMnt/invisible-watermark/)를 사용할지 여부입니다. 정의되지 않은 경우, 해당 패키지가 설치되어 있으면 기본값으로 True가 적용되고, 그렇지 않으면 워터마커가 사용되지 않습니다.

Stable Diffusion XL을 사용한 텍스트-이미지 생성을 위한 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple[int, int] | None = None, crops_coords_top_left: tuple = (0, 0), target_size: tuple[int, int] | None = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple = (0, 0), negative_target_size: tuple[int, int] | 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'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L836)

**매개변수:**

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

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

height (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 높이입니다. 최적의 결과를 위해 기본값은 1024로 설정되어 있습니다. [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 및 낮은 해상도로 특별히 미세 조정되지 않은 체크포인트의 경우 512픽셀 미만에서는 제대로 작동하지 않습니다.

width (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 너비입니다. 최적의 결과를 위해 기본값은 1024로 설정되어 있습니다. [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)와 저해상도에 대해 특별히 파인튜닝되지 않은 체크포인트의 경우 512픽셀 미만에서는 제대로 작동하지 않습니다.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

denoising_end (`float`, *선택 사항*) : 지정된 경우, 전체 디노이징 과정 중 의도적으로 조기 종료되기 전에 완료될 비율(0.0에서 1.0 사이)을 결정합니다. 그 결과, 스케줄러가 선택한 이산 시간 단계에 따라 반환되는 샘플에는 상당한 양의 노이즈가 여전히 남아 있게 됩니다. [**이미지 출력 개선**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)에서 자세히 설명된 바와 같이, 이 파이프라인이 "Mixture of Denoisers" 멀티 파이프라인 구성의 일부로 사용되는 경우 denoising_end 매개변수를 이상적으로 활용해야 합니다.

guidance_scale (`float`, *선택 사항*, 기본값 5.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`가 두 텍스트 인코더 모두에 사용됩니다.

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

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 논문(https://huggingface.co/papers/2010.02502)의 파라미터 eta (η)에 해당합니다. [schedulers.DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

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

ip_adapter_image_embeds (`list[torch.Tensor]`, *선택*) : IP-Adapter를 위한 사전 생성된 이미지 임베딩입니다. 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_xl.StableDiffusionXLPipelineOutput`을 반환할지 여부.

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

guidance_rescale (`float`, *선택 사항*, 기본값 0.0) : [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891)에서 제안한 Guidance rescale factor입니다. `guidance_scale`은 [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891)의 16번 식에서 `φ`로 정의됩니다. Guidance rescale factor는 zero terminal SNR을 사용할 때 과노출 문제를 해결해야 합니다.

original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : `original_size`가 `target_size`와 같지 않으면 이미지가 다운샘플링 또는 업샘플링된 것처럼 보입니다. `original_size`는 지정되지 않은 경우 기본값이 `(height, width)`입니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디셔닝(micro-conditioning)의 일부입니다.

crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : `crops_coords_top_left`를 사용하면 `crops_coords_top_left` 위치에서 아래쪽으로 "잘린" 것처럼 보이는 이미지를 생성할 수 있습니다. (0, 0)으로 `crops_coords_top_left`를 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대부분의 경우 `target_size`는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정되지 않으면 기본값으로 `(height, width)`가 사용됩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다.

negative_original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 특정 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : 특정 crop 좌표를 기반으로 생성 과정을 부정적으로 조건부화합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대상 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. 대부분의 경우 `target_size`와 동일해야 합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션잉(micro-conditioning)의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** `~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput` 또는 `tuple`

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

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

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

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLPAGPipeline.encode_prompt]]

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

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L293)

**매개변수:**

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

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2` 및 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우, 두 텍스트 인코더 모두에 `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`에 전송할 프롬프트입니다. 정의되지 않은 경우, `negative_prompt`가 두 텍스트 인코더 모두에 사용됩니다.

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

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

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl.py#L771)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionXLPAGImg2ImgPipeline[[diffusers.StableDiffusionXLPAGImg2ImgPipeline]]

#### diffusers.StableDiffusionXLPAGImg2ImgPipeline[[diffusers.StableDiffusionXLPAGImg2ImgPipeline]]

```python
diffusers.StableDiffusionXLPAGImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L191)

**매개변수:**

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

text_encoder (`CLIPTextModel`) : 고정된 텍스트 인코더입니다. Stable Diffusion XL은 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)의 텍스트 부분을 사용하며, 구체적으로 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 변형을 사용합니다.

text_encoder_2 (` CLIPTextModelWithProjection`) : 두 번째 고정된 텍스트 인코더입니다. Stable Diffusion XL은 [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) 변형을 사용합니다.

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.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 U-Net 아키텍처.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

requires_aesthetics_score (`bool`, *선택 사항*, 기본값 `"False"`) : 추론 시 `unet`에 `aesthetic_score` 조건을 전달해야 하는지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-refiner-1-0`의 config를 참고하세요.

force_zeros_for_empty_prompt (`bool`, *선택 사항*, 기본값 `"True"`) : negative prompt embeddings가 항상 0으로 설정되도록 강제할지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-base-1-0`의 config를 참고하세요.

add_watermarker (`bool`, *선택 사항*) : 출력 이미지에 워터마크를 적용하기 위해 [invisible_watermark 라이브러리](https://github.com/ShieldMnt/invisible-watermark/)를 사용할지 여부입니다. 정의되지 않은 경우, 해당 패키지가 설치되어 있으면 기본값으로 True가 적용되고, 그렇지 않으면 워터마커가 사용되지 않습니다.

Stable Diffusion XL을 사용한 텍스트-이미지 생성을 위한 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.3, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, denoising_start: float | None = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple = None, crops_coords_top_left: tuple = (0, 0), target_size: tuple = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L989)

**매개변수:**

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

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

image (`torch.Tensor` 또는 `PIL.Image.Image` 또는 `np.ndarray` 또는 `list[torch.Tensor]` 또는 `list[PIL.Image.Image]` 또는 `list[np.ndarray]`) : 파이프라인으로 수정할 이미지(들).

strength (`float`, *선택 사항*, 기본값 0.3) : 개념적으로 참조 `image`를 얼마나 변환할지를 나타냅니다. 0과 1 사이여야 합니다. `image`는 시작점으로 사용되며, `strength` 값이 클수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되고, 디노이징 프로세스는 `num_inference_steps`에 지정된 전체 반복 횟수 동안 실행됩니다. 따라서 1이라는 값은 기본적으로 `image`를 무시하는 것과 같습니다. `denoising_start`가 정수로 선언된 경우, `strength`의 값은 무시됩니다.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

denoising_start (`float`, *선택 사항*) : 지정된 경우, 디노이징 프로세스가 시작되기 전에 전체 디노이징 프로세스의 어느 비율(0.0에서 1.0 사이)을 우회할지를 나타냅니다. 따라서 디노이징 프로세스의 초기 부분이 건너뛰어지고, 전달된 `image`가 부분적으로 디노이징된 이미지라고 가정합니다. 이 값이 지정되면 strength는 무시됩니다. `denoising_start` 매개변수는 [**이미지 품질 개선**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality)에 자세히 설명된 "Mixture of Denoisers" 멀티 파이프라인 설정에 이 파이프라인이 통합될 때 특히 유용합니다.

denoising_end (`float`, *선택 사항*) : 지정된 경우, 전체 노이즈 제거 과정 중 의도적으로 조기 종료되기 전에 완료될 비율(0.0에서 1.0 사이)을 결정합니다. 그 결과, 반환되는 샘플에는 여전히 상당한 양의 노이즈(대략 최종 20%의 타임스텝이 여전히 필요)가 남아 있으며, `denoising_start`가 0.8로 설정되어 스케줄러의 최종 20%만 노이즈 제거하도록 하는 후속 파이프라인으로 노이즈 제거해야 합니다. [**이미지 품질 개선**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality)에 자세히 설명된 "Mixture of Denoisers" 멀티 파이프라인 구성의 일부로 이 파이프라인이 사용되는 경우, denoising_end 매개변수를 이상적으로 활용해야 합니다.

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : [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`가 두 텍스트 인코더 모두에 사용됩니다.

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

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 논문(https://huggingface.co/papers/2010.02502)의 파라미터 eta (η)에 해당합니다. [schedulers.DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

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

ip_adapter_image_embeds (`list[torch.Tensor]`, *선택*) : IP-Adapter를 위한 사전 생성된 이미지 임베딩입니다. 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.StableDiffusionXLPipelineOutput`을 반환할지 여부.

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

guidance_rescale (`float`, *선택 사항*, 기본값 0.0) : [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891)에서 제안한 Guidance rescale factor입니다. `guidance_scale`은 [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891)의 16번 식에서 `φ`로 정의됩니다. Guidance rescale factor는 zero terminal SNR을 사용할 때 과노출 문제를 해결해야 합니다.

original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : `original_size`가 `target_size`와 같지 않으면 이미지가 다운샘플링 또는 업샘플링된 것처럼 보입니다. `original_size`는 지정되지 않은 경우 기본값이 `(height, width)`입니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디셔닝(micro-conditioning)의 일부입니다.

crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : `crops_coords_top_left`를 사용하면 `crops_coords_top_left` 위치에서 아래쪽으로 "잘린" 것처럼 보이는 이미지를 생성할 수 있습니다. (0, 0)으로 `crops_coords_top_left`를 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대부분의 경우 `target_size`는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정되지 않으면 기본값으로 `(height, width)`가 사용됩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다.

negative_original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 특정 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : 특정 crop 좌표를 기반으로 생성 과정을 부정적으로 조건부화합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대상 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. 대부분의 경우 `target_size`와 동일해야 합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션잉(micro-conditioning)의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

aesthetic_score (`float`, *선택 사항*, 기본값 6.0) : 생성된 이미지의 미적 점수를 시뮬레이션하기 위해 긍정 텍스트 조건에 영향을 미칩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

negative_aesthetic_score (`float`, *선택 사항*, 기본값 2.5) : [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. negative text condition에 영향을 주어 생성된 이미지의 aesthetic score를 시뮬레이션하는 데 사용할 수 있습니다.

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` 또는 `tuple`

`return_dict`가 True인 경우 `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`, 그렇지 않으면 `tuple`을 반환합니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지의 리스트입니다.

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

예:
```py
>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-refiner-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLPAGImg2ImgPipeline.encode_prompt]]

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

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L311)

**매개변수:**

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

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2` 및 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우, 두 텍스트 인코더 모두에 `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`에 전송할 프롬프트입니다. 정의되지 않은 경우, `negative_prompt`가 두 텍스트 인코더 모두에 사용됩니다.

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

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

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLPAGImg2ImgPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py#L920)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionXLPAGInpaintPipeline[[diffusers.StableDiffusionXLPAGInpaintPipeline]]

#### diffusers.StableDiffusionXLPAGInpaintPipeline[[diffusers.StableDiffusionXLPAGInpaintPipeline]]

```python
diffusers.StableDiffusionXLPAGInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L204)

**매개변수:**

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

text_encoder (`CLIPTextModel`) : 고정된 텍스트 인코더입니다. Stable Diffusion XL은 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)의 텍스트 부분을 사용하며, 구체적으로 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 변형을 사용합니다.

text_encoder_2 (` CLIPTextModelWithProjection`) : 두 번째 고정된 텍스트 인코더입니다. Stable Diffusion XL은 [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) 변형을 사용합니다.

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.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 U-Net 아키텍처.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

requires_aesthetics_score (`bool`, *선택 사항*, 기본값 `"False"`) : 추론 시 `unet`에 aesthetic_score 조건을 전달해야 하는지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-refiner-1-0`의 config를 참고하세요.

force_zeros_for_empty_prompt (`bool`, *선택 사항*, 기본값 `"True"`) : negative prompt embeddings가 항상 0으로 설정되도록 강제할지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-base-1-0`의 config를 참고하세요.

add_watermarker (`bool`, *선택 사항*) : 출력 이미지에 워터마크를 적용하기 위해 [invisible_watermark 라이브러리](https://github.com/ShieldMnt/invisible-watermark/)를 사용할지 여부입니다. 정의되지 않은 경우, 해당 패키지가 설치되어 있으면 기본값으로 True가 적용되고, 그렇지 않으면 워터마커가 사용되지 않습니다.

Stable Diffusion XL을 사용한 텍스트-이미지 생성을 위한 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: Tensor = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 0.9999, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, denoising_start: float | None = None, denoising_end: float | None = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple = None, crops_coords_top_left: tuple = (0, 0), target_size: tuple = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L1080)

**매개변수:**

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

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

image (`PIL.Image.Image`) : `Image` 또는 inpaint 대상인 이미지 배치의 텐서, *즉* 이미지의 일부가 `mask_image`로 마스킹되고 `prompt`에 따라 다시 채워집니다.

mask_image (`PIL.Image.Image`) : `Image` 또는 이미지 배치 텐서. `image`에 적용할 마스크입니다. 마스크의 흰색 픽셀은 다시 채워지고, 검은색 픽셀은 유지됩니다. `mask_image`가 PIL 이미지인 경우, 사용 전에 단일 채널(휘도)로 변환됩니다. 텐서인 경우 3개 대신 하나의 색상 채널(L)을 포함해야 하므로, 예상되는 모양은 `(B, H, W, 1)`입니다.

masked_image_latents (`torch.Tensor`, *선택 사항*) : 인페인팅을 위한 마스킹된 이미지의 사전 인코딩된 잠재 변수(latent).

height (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 높이입니다. 최적의 결과를 위해 기본값은 1024로 설정되어 있습니다. [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 및 낮은 해상도로 특별히 미세 조정되지 않은 체크포인트의 경우 512픽셀 미만에서는 제대로 작동하지 않습니다.

width (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size * self.vae_scale_factor) : 생성된 이미지의 픽셀 단위 너비입니다. 최적의 결과를 위해 기본값은 1024로 설정되어 있습니다. [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)와 저해상도에 대해 특별히 파인튜닝되지 않은 체크포인트의 경우 512픽셀 미만에서는 제대로 작동하지 않습니다.

padding_mask_crop (`int`, *선택 사항*, 기본값 `None`) : 이미지와 마스킹에 적용할 크롭의 마진 크기입니다. `None`인 경우 이미지와 mask_image에 크롭이 적용되지 않습니다. `padding_mask_crop`이 `None`이 아닌 경우, 먼저 이미지의 종횡비와 동일하고 모든 마스킹 영역을 포함하는 직사각형 영역을 찾은 다음, `padding_mask_crop`을 기반으로 해당 영역을 확장합니다. 이후 인페인팅을 위해 원래 이미지 크기로 리사이즈하기 전에 확장된 영역을 기준으로 이미지와 mask_image가 크롭됩니다. 이는 마스킹 영역이 작고 이미지가 크며 배경과 같이 인페인팅에 관련 없는 정보를 포함하는 경우에 유용합니다.

strength (`float`, *선택 사항*, 기본값 0.9999) : 개념적으로, 참조 `image`의 마스킹된 부분을 얼마나 변환할지를 나타냅니다. 0과 1 사이여야 합니다. `image`가 시작점으로 사용되며, `strength` 값이 클수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되고, `num_inference_steps`에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 따라서 1이라는 값은 기본적으로 참조 `image`의 마스킹된 부분을 무시하는 것과 같습니다. `denoising_start`가 정수로 선언된 경우, `strength`의 값은 무시됩니다.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

denoising_start (`float`, *선택 사항*) : 지정된 경우, 디노이징 프로세스가 시작되기 전에 전체 디노이징 프로세스의 어느 비율(0.0에서 1.0 사이)을 우회할지를 나타냅니다. 따라서 디노이징 프로세스의 초기 부분이 건너뛰어지고, 전달된 `image`가 부분적으로 디노이징된 이미지라고 가정합니다. 이 값이 지정되면 strength는 무시됩니다. `denoising_start` 매개변수는 [**이미지 출력 개선**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)에 자세히 설명된 "Mixture of Denoisers" 멀티 파이프라인 설정에 이 파이프라인이 통합될 때 특히 유용합니다.

denoising_end (`float`, *optional*) : When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be completed before it is intentionally prematurely terminated. As a result, the returned sample will still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : [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`가 두 텍스트 인코더 모두에 사용됩니다.

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

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

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

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

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

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

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

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 논문(https://huggingface.co/papers/2010.02502)의 파라미터 eta (η)에 해당합니다. [schedulers.DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

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

original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : `original_size`가 `target_size`와 같지 않으면 이미지가 다운샘플링 또는 업샘플링된 것처럼 보입니다. `original_size`는 지정되지 않은 경우 기본값이 `(height, width)`입니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디셔닝(micro-conditioning)의 일부입니다.

crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : `crops_coords_top_left`를 사용하면 `crops_coords_top_left` 위치에서 아래쪽으로 "잘린" 것처럼 보이는 이미지를 생성할 수 있습니다. (0, 0)으로 `crops_coords_top_left`를 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대부분의 경우 `target_size`는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정되지 않으면 기본값으로 `(height, width)`가 사용됩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다.

negative_original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 특정 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : 특정 crop 좌표를 기반으로 생성 과정을 부정적으로 조건부화합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대상 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. 대부분의 경우 `target_size`와 동일해야 합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션잉(micro-conditioning)의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

aesthetic_score (`float`, *선택 사항*, 기본값 6.0) : 생성된 이미지의 미적 점수를 시뮬레이션하기 위해 긍정 텍스트 조건에 영향을 미칩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

negative_aesthetic_score (`float`, *선택 사항*, 기본값 2.5) : [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. negative text condition에 영향을 주어 생성된 이미지의 aesthetic score를 시뮬레이션하는 데 사용할 수 있습니다.

guidance_rescale (`float`, *선택 사항*, 기본값 0.0) : [일반적인 디퓨전 노이즈 스케줄과 샘플 단계의 결함](https://arxiv.org/pdf/2305.08891.pdf)에 따른 가이드런스 리스케일 팩터입니다.

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` 또는 `tuple`

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

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

예:
```py
>>> import torch
>>> from diffusers import AutoPipelineForInpainting
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     variant="fp16",
...     enable_pag=True,
... )
>>> pipe.to("cuda")

>>> 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).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")

>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     num_inference_steps=50,
...     strength=0.80,
...     pag_scale=0.3,
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLPAGInpaintPipeline.encode_prompt]]

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

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L401)

**매개변수:**

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

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2` 및 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우, 두 텍스트 인코더 모두에 `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`에 전송할 프롬프트입니다. 정의되지 않은 경우, `negative_prompt`가 두 텍스트 인코더 모두에 사용됩니다.

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

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

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLPAGInpaintPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py#L1011)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionXLControlNetPAGPipeline[[diffusers.StableDiffusionXLControlNetPAGPipeline]]

#### diffusers.StableDiffusionXLControlNetPAGPipeline[[diffusers.StableDiffusionXLControlNetPAGPipeline]]

```python
diffusers.StableDiffusionXLControlNetPAGPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L185)

**매개변수:**

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

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)) : 고정된 텍스트 인코더 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).

text_encoder_2 ([CLIPTextModelWithProjection](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModelWithProjection)) : 두 번째 고정된 텍스트 인코더 ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)) : 텍스트를 토큰화하기 위한 `CLIPTokenizer`입니다.

tokenizer_2 ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)) : 텍스트를 토큰화하기 위한 `CLIPTokenizer`입니다.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 latents의 노이즈를 제거하기 위한 `UNet2DConditionModel`.

controlnet ([ControlNetModel](/docs/diffusers/main/ko/api/models/controlnet#diffusers.ControlNetModel) 또는 `list[ControlNetModel]`) : 노이즈 제거 과정에서 `unet`에 추가 조건을 제공합니다. 여러 ControlNet을 리스트로 설정하면 각 ControlNet의 출력을 합산하여 하나의 통합된 추가 조건을 생성합니다.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

force_zeros_for_empty_prompt (`bool`, *선택 사항*, 기본값 `"True"`) : negative prompt embeddings를 항상 0으로 설정할지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-base-1-0`의 config를 참고하세요.

add_watermarker (`bool`, *선택 사항*) : 출력 이미지에 워터마크를 적용하기 위해 [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) 라이브러리를 사용할지 여부입니다. 정의되지 않은 경우, 해당 패키지가 설치되어 있으면 기본값은 `True`이며, 그렇지 않으면 워터마커가 사용되지 않습니다.

ControlNet 가이던스를 사용하여 Stable Diffusion XL로 텍스트-이미지 생성을 수행하는 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 1.0, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, original_size: tuple = None, crops_coords_top_left: tuple = (0, 0), target_size: tuple = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple = (0, 0), negative_target_size: tuple[int, int] | None = None, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L1003)

**매개변수:**

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

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

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` 또는 `list[list[PIL.Image.Image]]`): 생성 시 `unet`에 가이드를 제공하기 위한 ControlNet 입력 조건입니다. 타입이 `torch.Tensor`로 지정된 경우, ControlNet에 그대로 전달됩니다. `PIL.Image.Image`도 이미지로 허용됩니다. 출력 이미지의 차원은 기본적으로 `image`의 차원을 따릅니다. height와/또는 width가 전달되면, `image`는 이에 맞게 리사이즈됩니다. `init`에서 여러 ControlNet이 지정된 경우, 각 ControlNet에 대한 입력이 올바르게 배치(batch)될 수 있도록 리스트의 각 요소가 이미지가 되도록 리스트로 전달해야 합니다.

height (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 높이. 512픽셀 미만은 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 및 낮은 해상도에 대해 특별히 fine-tuning되지 않은 checkpoint에서 잘 작동하지 않습니다.

width (`int`, *선택 사항*, 기본값은 `self.unet.config.sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 너비입니다. 512픽셀 미만은 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 및 낮은 해상도에 대해 특별히 fine-tuning되지 않은 checkpoint에서 잘 작동하지 않습니다.

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

denoising_end (`float`, *선택 사항*) : 지정된 경우, 전체 디노이징 과정 중 의도적으로 조기 종료되기 전에 완료될 비율(0.0에서 1.0 사이)을 결정합니다. 그 결과, 스케줄러가 선택한 이산 시간 단계에 따라 반환되는 샘플에는 상당한 양의 노이즈가 여전히 남아 있게 됩니다. [**이미지 출력 개선**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)에서 자세히 설명된 바와 같이, 이 파이프라인이 "Mixture of Denoisers" 멀티 파이프라인 구성의 일부로 사용되는 경우 denoising_end 매개변수를 이상적으로 활용해야 합니다.

guidance_scale (`float`, *선택 사항*, 기본값 5.0) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

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

negative_prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성에서 포함하지 않을 내용을 안내하는 프롬프트입니다. 이 값은 `tokenizer_2`와 `text_encoder_2`에 전달됩니다. 정의되지 않은 경우, `negative_prompt`가 두 텍스트 인코더 모두에 사용됩니다.

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

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

negative_pooled_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인자에서 `negative_prompt_embeds`가 생성됩니다.

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

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

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

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

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

controlnet_conditioning_scale (`float` 또는 `list[float]`, *선택 사항*, 기본값 1.0) : ControlNet의 출력은 원래 `unet`의 잔차에 더해지기 전에 `controlnet_conditioning_scale`과 곱해집니다. `init`에 여러 ControlNet이 지정된 경우, 해당 스케일을 리스트로 설정할 수 있습니다.

control_guidance_start (`float` 또는 `list[float]`, *선택 사항*, 기본값 0.0) : ControlNet이 적용을 시작하는 전체 스텝의 비율입니다.

control_guidance_end (`float` 또는 `list[float]`, *선택 사항*, 기본값 1.0) : ControlNet이 적용을 중단하는 전체 스텝의 비율입니다.

original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : `original_size`가 `target_size`와 같지 않으면 이미지가 다운샘플링 또는 업샘플링된 것처럼 보입니다. `original_size`는 지정되지 않은 경우 기본값이 `(height, width)`입니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디셔닝(micro-conditioning)의 일부입니다.

crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : `crops_coords_top_left`를 사용하면 `crops_coords_top_left` 위치에서 아래쪽으로 "잘린" 것처럼 보이는 이미지를 생성할 수 있습니다. (0, 0)으로 `crops_coords_top_left`를 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대부분의 경우 `target_size`는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정되지 않으면 기본값으로 `(height, width)`가 사용됩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다.

negative_original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 특정 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : 특정 crop 좌표를 기반으로 생성 과정을 부정적으로 조건부화합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대상 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. 대부분의 경우 `target_size`와 동일해야 합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션잉(micro-conditioning)의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

`return_dict`가 `True`인 경우 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)가 반환되고, 그렇지 않으면 출력 이미지를 포함하는 `tuple`이 반환됩니다.

생성을 위한 pipeline의 호출 함수.

예:
```py
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import AutoPipelineForText2Image, ControlNetModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"

>>> # download an image
>>> image = load_image(
...     "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )

>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()

>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)

>>> # generate image
>>> image = pipe(
...     prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image, pag_scale=0.3
... ).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLControlNetPAGPipeline.encode_prompt]]

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

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L306)

**매개변수:**

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

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2` 및 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우, 두 텍스트 인코더 모두에 `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`에 전송할 프롬프트입니다. 정의되지 않은 경우, `negative_prompt`가 두 텍스트 인코더 모두에 사용됩니다.

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

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

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLControlNetPAGPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py#L946)

**매개변수:**

w (`torch.Tensor`) : 지정된 guidance scale을 사용하여 임베딩 벡터를 생성하고, 이를 통해 timestep 임베딩을 풍부하게 만듭니다.

embedding_dim (`int`, *선택 사항*, 기본값 512) : 생성할 임베딩의 차원.

dtype (`torch.dtype`, *선택 사항*, 기본값 `torch.float32`) : 생성된 임베딩의 데이터 유형입니다.

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

`(len(w), embedding_dim)` 형태의 임베딩 벡터.

https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 를 참조하세요.

## StableDiffusionXLControlNetPAGImg2ImgPipeline[[diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline]]

#### diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline[[diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline]]

```python
diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModel, scheduler: KarrasDiffusionSchedulers, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None, pag_applied_layers: str | list[str] = 'mid')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py#L164)

**매개변수:**

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

text_encoder (`CLIPTextModel`) : 고정된 텍스트 인코더입니다. Stable Diffusion은 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)의 텍스트 부분을 사용하며, 구체적으로 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 변형을 사용합니다.

text_encoder_2 (` CLIPTextModelWithProjection`) : 두 번째 고정된 텍스트 인코더입니다. Stable Diffusion XL은 [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) 변형을 사용합니다.

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.

unet ([UNet2DConditionModel](/docs/diffusers/main/ko/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 U-Net 아키텍처.

controlnet ([ControlNetModel](/docs/diffusers/main/ko/api/models/controlnet#diffusers.ControlNetModel) 또는 `list[ControlNetModel]`) : 디노이징 과정에서 unet에 추가 조건을 제공합니다. 여러 ControlNet을 리스트로 설정하면 각 ControlNet의 출력을 합산하여 하나의 결합된 추가 조건을 생성합니다.

scheduler ([SchedulerMixin](/docs/diffusers/main/ko/api/schedulers/overview#diffusers.SchedulerMixin)) : `unet`와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 스케줄러입니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler), [LMSDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler), 또는 [PNDMScheduler](/docs/diffusers/main/ko/api/schedulers/pndm#diffusers.PNDMScheduler) 중 하나일 수 있습니다.

requires_aesthetics_score (`bool`, *선택 사항*, 기본값 `"False"`) : 추론 시 `unet`에 `aesthetic_score` 조건을 전달해야 하는지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-refiner-1-0`의 config를 참고하세요.

force_zeros_for_empty_prompt (`bool`, *선택 사항*, 기본값 `"True"`) : negative prompt embeddings가 항상 0으로 설정되도록 강제할지 여부입니다. 또한 `stabilityai/stable-diffusion-xl-base-1-0`의 config를 참고하세요.

add_watermarker (`bool`, *선택 사항*) : 출력 이미지에 워터마크를 적용하기 위해 [invisible_watermark 라이브러리](https://github.com/ShieldMnt/invisible-watermark/)를 사용할지 여부입니다. 정의되지 않은 경우, 해당 패키지가 설치되어 있으면 기본값으로 True가 적용되고, 그렇지 않으면 워터마커가 사용되지 않습니다.

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor)) : 생성된 이미지에서 특징을 추출하기 위한 `CLIPImageProcessor`. `safety_checker`의 입력으로 사용됩니다.

ControlNet 가이던스를 사용하여 Stable Diffusion XL로 이미지-이미지 생성을 수행하는 Pipeline입니다.

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 [load_textual_inversion()](/docs/diffusers/main/ko/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- LoRA 가중치를 저장하는 [save_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)
- IP Adapter를 로드하기 위한 [load_ip_adapter()](/docs/diffusers/main/ko/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.8, num_inference_steps: int = 50, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = 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: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, controlnet_conditioning_scale: float | list[float] = 0.8, guess_mode: bool = False, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, original_size: tuple = None, crops_coords_top_left: tuple = (0, 0), target_size: tuple = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple = (0, 0), negative_target_size: tuple[int, int] | None = None, aesthetic_score: float = 6.0, negative_aesthetic_score: float = 2.5, clip_skip: int | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py#L1080)

**매개변수:**

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

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

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` 또는 `list[list[PIL.Image.Image]]`): 초기 이미지는 이미지 생성 과정의 시작점으로 사용됩니다. `image`로 이미지 latents를 직접 전달할 수도 있으며, 이 경우 다시 인코딩되지 않습니다.

control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` 또는 `list[list[PIL.Image.Image]]`): ControlNet 입력 조건입니다. ControlNet은 이 입력 조건을 사용하여 Unet에 가이던스를 생성합니다. 타입이 `torch.Tensor`로 지정된 경우, ControlNet에 그대로 전달됩니다. `PIL.Image.Image`도 이미지로 허용됩니다. 출력 이미지의 차원은 기본적으로 `image`의 차원을 따릅니다. height와/또는 width가 전달되면, `image`는 해당 값에 따라 리사이즈됩니다. init에서 여러 ControlNet이 지정된 경우, 각 ControlNet에 대한 입력이 올바르게 배치되도록 각 요소가 올바르게 배치될 수 있는 리스트로 이미지를 전달해야 합니다.

height (`int`, *선택 사항*, 기본값은 control_image의 크기) : 생성된 이미지의 픽셀 단위 높이입니다. 512픽셀 미만은 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 및 낮은 해상도에 대해 특별히 미세 조정되지 않은 체크포인트에서 잘 작동하지 않습니다.

width (`int`, *선택 사항*, 기본값은 control_image의 크기) : 생성된 이미지의 픽셀 단위 너비입니다. [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 및 낮은 해상도에 대해 특별히 미세 조정되지 않은 체크포인트의 경우 512픽셀 미만은 제대로 작동하지 않습니다.

strength (`float`, *선택 사항*, 기본값 0.8) : 참조 `image`를 변환할 정도를 나타냅니다. 0과 1 사이여야 합니다. `image`는 시작점으로 사용되며, `strength` 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되며, `num_inference_steps`에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 1이라는 값은 사실상 `image`를 무시하는 것과 같습니다.

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

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : [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`가 두 텍스트 인코더 모두에 사용됩니다.

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

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 논문(https://huggingface.co/papers/2010.02502)의 파라미터 eta (η)에 해당합니다. [schedulers.DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

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

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

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

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

ip_adapter_image_embeds (`list[torch.Tensor]`, *선택*) : IP-Adapter를 위한 사전 생성된 이미지 임베딩입니다. 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`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

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

controlnet_conditioning_scale (`float` 또는 `list[float]`, *선택 사항*, 기본값 1.0) : Controlnet의 출력은 원래 unet의 residual에 추가되기 전에 `controlnet_conditioning_scale`로 곱해집니다. init에서 여러 ControlNet을 지정하는 경우, 해당 scale을 리스트로 설정할 수 있습니다.

guess_mode (`bool`, *선택 사항*, 기본값 `False`) : 이 모드에서는 모든 프롬프트를 제거하더라도 ControlNet 인코더가 입력 이미지의 내용을 최대한 인식하도록 시도합니다. `guidance_scale`은 3.0에서 5.0 사이 값을 권장합니다.

control_guidance_start (`float` 또는 `list[float]`, *선택 사항*, 기본값 0.0) : 전체 스텝 중 controlnet이 적용을 시작하는 비율입니다.

control_guidance_end (`float` 또는 `list[float]`, *선택 사항*, 기본값 1.0) : controlnet이 적용을 중단하는 전체 스텝의 비율입니다.

original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : `original_size`가 `target_size`와 같지 않으면 이미지가 다운샘플링 또는 업샘플링된 것처럼 보입니다. `original_size`는 지정되지 않은 경우 기본값이 `(height, width)`입니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디셔닝(micro-conditioning)의 일부입니다.

crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : `crops_coords_top_left`를 사용하면 `crops_coords_top_left` 위치에서 아래쪽으로 "잘린" 것처럼 보이는 이미지를 생성할 수 있습니다. (0, 0)으로 `crops_coords_top_left`를 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대부분의 경우 `target_size`는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정되지 않으면 기본값으로 `(height, width)`가 사용됩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다.

negative_original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 특정 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_crops_coords_top_left (`tuple[int]`, *선택 사항*, 기본값 (0, 0)) : 특정 crop 좌표를 기반으로 생성 과정을 부정적으로 조건부화합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

negative_target_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : 대상 이미지 해상도를 기반으로 생성 과정을 부정적으로 조건부 설정합니다. 대부분의 경우 `target_size`와 동일해야 합니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션잉(micro-conditioning)의 일부입니다. 자세한 내용은 이 이슈 스레드를 참조하세요: https://github.com/huggingface/diffusers/issues/4208.

aesthetic_score (`float`, *선택 사항*, 기본값 6.0) : 생성된 이미지의 미적 점수를 시뮬레이션하기 위해 긍정 텍스트 조건에 영향을 미칩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다.

negative_aesthetic_score (`float`, *선택 사항*, 기본값 2.5) : [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. negative text condition에 영향을 주어 생성된 이미지의 aesthetic score를 시뮬레이션하는 데 사용할 수 있습니다.

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

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : 추론 중 각 denoising 단계의 끝에서 호출되는 함수 또는 `PipelineCallback` 또는 `MultiPipelineCallbacks`의 하위 클래스입니다. 다음 인수를 가집니다: `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` 속성에 나열된 변수만 포함할 수 있습니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` 또는 `tuple`

`return_dict`가 True인 경우 `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`, 그렇지 않으면 출력 이미지를 포함하는 `tuple`

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

예:
```py
>>> # pip install accelerate transformers safetensors diffusers

>>> import torch
>>> import numpy as np
>>> from PIL import Image

>>> from transformers import DPTFeatureExtractor, DPTForDepthEstimation
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetPAGImg2ImgPipeline, AutoencoderKL
>>> from diffusers.utils import load_image

>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
>>> feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas")
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-depth-sdxl-1.0-small",
...     variant="fp16",
...     use_safetensors="True",
...     torch_dtype=torch.float16,
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetPAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     variant="fp16",
...     use_safetensors=True,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()

>>> def get_depth_map(image):
...     image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
...     with torch.no_grad(), torch.autocast("cuda"):
...         depth_map = depth_estimator(image).predicted_depth

...     depth_map = torch.nn.functional.interpolate(
...         depth_map.unsqueeze(1),
...         size=(1024, 1024),
...         mode="bicubic",
...         align_corners=False,
...     )
...     depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_map = (depth_map - depth_min) / (depth_max - depth_min)
...     image = torch.cat([depth_map] * 3, dim=1)
...     image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
...     image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
...     return image

>>> prompt = "A robot, 4k photo"
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
...     "/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> depth_image = get_depth_map(image)

>>> images = pipe(
...     prompt,
...     image=image,
...     control_image=depth_image,
...     strength=0.99,
...     num_inference_steps=50,
...     controlnet_conditioning_scale=controlnet_conditioning_scale,
... ).images
>>> images[0].save(f"robot_cat.png")
```

#### encode_prompt[[diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline.encode_prompt]]

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

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py#L297)

**매개변수:**

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

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2` 및 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우, 두 텍스트 인코더 모두에 `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`에 전송할 프롬프트입니다. 정의되지 않은 경우, `negative_prompt`가 두 텍스트 인코더 모두에 사용됩니다.

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

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

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

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

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

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

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

## StableDiffusion3PAGPipeline[[diffusers.StableDiffusion3PAGPipeline]]

#### diffusers.StableDiffusion3PAGPipeline[[diffusers.StableDiffusion3PAGPipeline]]

```python
diffusers.StableDiffusion3PAGPipeline(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, pag_applied_layers: str | list[str] = 'blocks.1')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_3.py#L136)

**매개변수:**

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) 클래스의 토크나이저.

Stable Diffusion 3을 사용한 텍스트-이미지 생성을 위한 [PAG pipeline](https://huggingface.co/docs/diffusers/main/en/using-diffusers/pag).

#### __호출__[[diffusers.StableDiffusion3PAGPipeline.__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, 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, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_3.py#L684)

**매개변수:**

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가 생성됩니다.

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

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

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`에 사용할 최대 시퀀스 길이입니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

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

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

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

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

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt, guidance_scale=5.0, pag_scale=0.7).images[0]
>>> image.save("sd3_pag.png")
```

#### encode_prompt[[diffusers.StableDiffusion3PAGPipeline.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/pag/pipeline_pag_sd_3.py#L335)

**매개변수:**

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 스케일입니다.

## StableDiffusion3PAGImg2ImgPipeline[[diffusers.StableDiffusion3PAGImg2ImgPipeline]]

#### diffusers.StableDiffusion3PAGImg2ImgPipeline[[diffusers.StableDiffusion3PAGImg2ImgPipeline]]

```python
diffusers.StableDiffusion3PAGImg2ImgPipeline(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, pag_applied_layers: str | list[str] = 'blocks.1')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py#L152)

**매개변수:**

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) 클래스의 토크나이저.

Stable Diffusion 3을 사용한 이미지-이미지 생성을 위한 [PAG pipeline](https://huggingface.co/docs/diffusers/main/en/using-diffusers/pag).

#### __호출__[[diffusers.StableDiffusion3PAGImg2ImgPipeline.__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, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.6, num_inference_steps: int = 50, 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, 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, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py#L735)

**매개변수:**

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.default_sample_size * self.vae_scale_factor`) : 생성된 이미지의 픽셀 단위 높이입니다. 최적의 결과를 위해 기본값은 1024로 설정되어 있습니다.

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

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : 시작점으로 사용할 이미지 배치의 `Image`, numpy 배열 또는 텐서를 나타냅니다. numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는 `[0, 1]`입니다. 텐서 또는 텐서 목록인 경우, 예상 shape은 `(B, C, H, W)` 또는 `(C, H, W)`여야 합니다. numpy 배열 또는 배열 목록인 경우, 예상 shape은 `(B, H, W, C)` 또는 `(H, W, C)`여야 합니다. `image`로 이미지 latents도 받을 수 있지만, latents를 직접 전달하는 경우 다시 인코딩되지 않습니다.

strength (`float`, *선택 사항*, 기본값 0.8) : 참조 `image`를 변환할 정도를 나타냅니다. 0과 1 사이여야 합니다. `image`는 시작점으로 사용되며, `strength` 값이 높을수록 더 많은 노이즈가 추가됩니다. 디노이징 단계의 수는 초기에 추가된 노이즈의 양에 따라 결정됩니다. `strength`가 1이면 추가되는 노이즈가 최대가 되며, `num_inference_steps`에 지정된 전체 반복 횟수만큼 디노이징 프로세스가 실행됩니다. 1이라는 값은 사실상 `image`를 무시하는 것과 같습니다.

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가 생성됩니다.

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

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

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`에 사용할 최대 시퀀스 길이입니다.

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

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

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

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

예:
```py
>>> import torch
>>> from diffusers import StableDiffusion3PAGImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> pipe = StableDiffusion3PAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
>>> init_image = load_image(url).convert("RGB")
>>> image = pipe(prompt, image=init_image, guidance_scale=5.0, pag_scale=0.7).images[0]
```

#### encode_prompt[[diffusers.StableDiffusion3PAGImg2ImgPipeline.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/pag/pipeline_pag_sd_3_img2img.py#L351)

**매개변수:**

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 스케일입니다.

## PixArtSigmaPAGPipeline[[diffusers.PixArtSigmaPAGPipeline]]

#### diffusers.PixArtSigmaPAGPipeline[[diffusers.PixArtSigmaPAGPipeline]]

```python
diffusers.PixArtSigmaPAGPipeline(tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, vae: AutoencoderKL, transformer: PixArtTransformer2DModel, scheduler: KarrasDiffusionSchedulers, pag_applied_layers: str | list[str] = 'blocks.1')
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py#L144)

PixArt-Sigma를 사용한 텍스트-이미지 생성을 위한 [PAG pipeline](https://huggingface.co/docs/diffusers/main/en/using-diffusers/pag).

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 20, timesteps: list = None, sigmas: list = None, guidance_scale: float = 4.5, num_images_per_prompt: int | None = 1, height: int | None = None, width: int | None = None, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, clean_caption: bool = True, use_resolution_binning: bool = True, max_sequence_length: int = 300, pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py#L574)

**매개변수:**

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

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

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

timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.

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

guidance_scale (`float`, *선택 사항*, 기본값 4.5) : [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` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.

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

height (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size) : 생성된 이미지의 픽셀 단위 높이.

width (`int`, *선택 사항*, 기본값은 self.unet.config.sample_size) : 생성된 이미지의 픽셀 단위 너비.

eta (`float`, *선택 사항*, 기본값 0.0) : DDIM 논문(https://huggingface.co/papers/2010.02502)의 파라미터 eta (η)에 해당합니다. [schedulers.DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

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

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

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

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.

negative_prompt_embeds (`torch.Tensor`, *선택*) : 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 부정 텍스트 임베딩에 사용할 사전 생성된 어텐션 마스크입니다.

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

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

callback (`Callable`, *선택 사항*) : 추론 중 `callback_steps` 스텝마다 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback(step: int, timestep: int, latents: torch.Tensor)`.

callback_steps (`int`, *선택 사항*, 기본값 1) : `callback` 함수가 호출되는 주기입니다. 지정하지 않으면 모든 단계에서 callback이 호출됩니다.

clean_caption (`bool`, *선택 사항*, 기본값 `True`) : 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다. `beautifulsoup4`와 `ftfy`가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.

use_resolution_binning (`bool` 기본값은 `True`) : `True`로 설정하면, 요청된 높이와 너비가 `ASPECT_RATIO_1024_BIN`을 사용하여 가장 가까운 해상도로 먼저 매핑됩니다. 생성된 latents가 이미지로 디코딩된 후, 요청된 해상도로 다시 리사이즈됩니다. 정사각형이 아닌 이미지를 생성하는 데 유용합니다.

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

pag_scale (`float`, *선택 사항*, 기본값 3.0) : 교란된 어텐션 가이던스의 스케일 팩터입니다. 0.0으로 설정하면 교란된 어텐션 가이던스가 사용되지 않습니다.

pag_adaptive_scale (`float`, *선택 사항*, 기본값 0.0) : 교란된 어텐션 가이던스에 사용되는 적응 스케일 팩터입니다. 0.0으로 설정된 경우 `pag_scale`이 사용됩니다.

**반환값:** [ImagePipelineOutput](/docs/diffusers/main/ko/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) 또는 `tuple`

`return_dict`가 `True`인 경우 [ImagePipelineOutput](/docs/diffusers/main/ko/api/pipelines/consistency_models#diffusers.ImagePipelineOutput)가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록인 `tuple`이 반환됩니다.

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

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

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.14"],
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "A small cactus with a happy face in the Sahara desert"
>>> image = pipe(prompt, pag_scale=4.0, guidance_scale=1.0).images[0]
```

#### encode_prompt[[diffusers.PixArtSigmaPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 300, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py#L190)

**매개변수:**

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

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

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

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

device : (`torch.device`, *선택 사항*): 생성된 임베딩을 배치할 torch device

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

negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩. PixArt-Alpha의 경우, "" 문자열의 임베딩이어야 합니다.

clean_caption (`bool`, 기본값은 `False`) : `True`인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.

max_sequence_length (`int`, 기본값 300) : 프롬프트에 사용할 최대 시퀀스 길이입니다.

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

