# ControlNetUnion

  

ControlNetUnionModel은 Stable Diffusion XL용 ControlNet의 구현입니다.

ControlNet 모델은 xinsir6에 의해 [ControlNetPlus](https://github.com/xinsir6/ControlNetPlus)에서 소개되었습니다. 계산량을 증가시키지 않고 여러 조건 입력을 지원합니다.

*조건부 텍스트-이미지 생성에서 10개 이상의 제어 유형을 지원하고, Midjourney와 시각적으로 비교할 수 있는 고해상도 이미지를 생성할 수 있는 새로운 아키텍처를 설계했습니다. 이 네트워크는 원래의 ControlNet 아키텍처를 기반으로 하며, 두 가지 새로운 모듈을 제안합니다. 1. 동일한 네트워크 파라미터를 사용하여 다양한 이미지 조건을 지원하도록 원래의 ControlNet을 확장합니다. 2. 계산 오프로드를 증가시키지 않고도 여러 조건 입력을 지원합니다. 이는 이미지를 세밀하게 편집하려는 디자이너에게 특히 중요하며, 서로 다른 조건은 동일한 조건 인코더를 사용하여 추가적인 계산이나 파라미터를 추가하지 않습니다.*

## StableDiffusionXLControlNetUnionPipeline[[diffusers.StableDiffusionXLControlNetUnionPipeline]]

#### diffusers.StableDiffusionXLControlNetUnionPipeline[[diffusers.StableDiffusionXLControlNetUnionPipeline]]

```python
diffusers.StableDiffusionXLControlNetUnionPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet_union.ControlNetUnionModel | list[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | tuple[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | diffusers.models.controlnets.multicontrolnet_union.MultiControlNetUnionModel, scheduler: KarrasDiffusionSchedulers, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py#L175)

**매개변수:**

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 ([ControlNetUnionModel](/docs/diffusers/main/ko/api/models/controlnet_union#diffusers.ControlNetUnionModel)`) : Provides additional conditioning to the `unet` during the denoising process.

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.StableDiffusionXLControlNetUnionPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[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, guess_mode: bool = False, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, control_mode: int | list[int] | list[list[int]] | None = None, 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'])
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py#L976)

**매개변수:**

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

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

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

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이 지정된 경우, 해당 스케일을 리스트로 설정할 수 있습니다.

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이 적용을 중단하는 전체 스텝의 비율입니다.

control_mode (`int` or `list[int]` or `list[list[int]], *optional*) : The control condition types for the ControlNet. See the ControlNet's model card forinformation on the available control modes. If multiple ControlNets are specified in `init`, control_mode should be a list where each ControlNet should have its corresponding control mode list. Should reflect the order of conditions in control_image.

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

**반환값:** [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 controlnet_aux
>>> from controlnet_aux import LineartAnimeDetector
>>> from diffusers import StableDiffusionXLControlNetUnionPipeline, ControlNetUnionModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import torch

>>> prompt = "A cat"
>>> # download an image
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> # initialize the models and pipeline
>>> controlnet = ControlNetUnionModel.from_pretrained(
...     "xinsir/controlnet-union-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetUnionPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     torch_dtype=torch.float16,
...     variant="fp16",
... )
>>> pipe.enable_model_cpu_offload()
>>> # prepare image
>>> processor = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators")
>>> controlnet_img = processor(image, output_type="pil")
>>> # generate image
>>> image = pipe(prompt, control_image=[controlnet_img], control_mode=[3], height=1024, width=1024).images[0]
```

#### encode_prompt[[diffusers.StableDiffusionXLControlNetUnionPipeline.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/controlnet/pipeline_controlnet_union_sd_xl.py#L291)

**매개변수:**

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.StableDiffusionXLControlNetUnionPipeline.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/controlnet/pipeline_controlnet_union_sd_xl.py#L915)

**매개변수:**

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 를 참조하세요.

## StableDiffusionXLControlNetUnionImg2ImgPipeline[[diffusers.StableDiffusionXLControlNetUnionImg2ImgPipeline]]

#### diffusers.StableDiffusionXLControlNetUnionImg2ImgPipeline[[diffusers.StableDiffusionXLControlNetUnionImg2ImgPipeline]]

```python
diffusers.StableDiffusionXLControlNetUnionImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet_union.ControlNetUnionModel | list[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | tuple[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | diffusers.models.controlnets.multicontrolnet_union.MultiControlNetUnionModel, 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)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py#L188)

**매개변수:**

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 ([ControlNetUnionModel](/docs/diffusers/main/ko/api/models/controlnet_union#diffusers.ControlNetUnionModel)) : 노이즈 제거 과정에서 unet에 추가 조건을 제공합니다.

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.StableDiffusionXLControlNetUnionImg2ImgPipeline.__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], list[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, control_mode: int | list[int] | list[list[int]] | None = None, 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'], **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py#L1068)

**매개변수:**

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 (`PipelineImageInput` 또는 `list[PipelineImageInput]`, *선택*) : 생성 시 `unet`에 가이드를 제공하기 위한 ControlNet 입력 조건입니다. 타입이 `torch.Tensor`로 지정된 경우, ControlNet에 그대로 전달됩니다. `PIL.Image.Image`도 이미지로 허용됩니다. 출력 이미지의 차원은 기본적으로 `image`의 차원을 따릅니다. height와/또는 width가 전달되면, `image`는 그에 맞게 리사이즈됩니다. `init`에서 여러 ControlNet이 지정된 경우, 각 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`의 잔차에 더해지기 전에 `controlnet_conditioning_scale`과 곱해집니다. `init`에 여러 ControlNet이 지정된 경우, 해당 스케일을 리스트로 설정할 수 있습니다.

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이 적용을 중단하는 전체 스텝의 비율입니다.

control_mode (`int` or `list[int]` or `list[list[int]], *optional*) : The control condition types for the ControlNet. See the ControlNet's model card forinformation on the available control modes. If multiple ControlNets are specified in `init`, control_mode should be a list where each ControlNet should have its corresponding control mode list. Should reflect the order of conditions in control_image

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

**반환값:** [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`

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

예:
```py
# !pip install controlnet_aux
from diffusers import (
    StableDiffusionXLControlNetUnionImg2ImgPipeline,
    ControlNetUnionModel,
    AutoencoderKL,
)
from diffusers.utils import load_image
import torch
from PIL import Image
import numpy as np

prompt = "A cat"
# download an image
image = load_image(
    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky/cat.png"
)
# initialize the models and pipeline
controlnet = ControlNetUnionModel.from_pretrained(
    "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
)
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe = StableDiffusionXLControlNetUnionImg2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet=controlnet,
    vae=vae,
    torch_dtype=torch.float16,
    variant="fp16",
).to("cuda")
# `enable_model_cpu_offload` is not recommended due to multiple generations
height = image.height
width = image.width
ratio = np.sqrt(1024.0 * 1024.0 / (width * height))
# 3 * 3 upscale correspond to 16 * 3 multiply, 2 * 2 correspond to 16 * 2 multiply and so on.
scale_image_factor = 3
base_factor = 16
factor = scale_image_factor * base_factor
W, H = int(width * ratio) // factor * factor, int(height * ratio) // factor * factor
image = image.resize((W, H))
target_width = W // scale_image_factor
target_height = H // scale_image_factor
images = []
crops_coords_list = [
    (0, 0),
    (0, width // 2),
    (height // 2, 0),
    (width // 2, height // 2),
    0,
    0,
    0,
    0,
    0,
]
for i in range(scale_image_factor):
    for j in range(scale_image_factor):
        left = j * target_width
        top = i * target_height
        right = left + target_width
        bottom = top + target_height
        cropped_image = image.crop((left, top, right, bottom))
        cropped_image = cropped_image.resize((W, H))
        images.append(cropped_image)
# set ControlNetUnion input
result_images = []
for sub_img, crops_coords in zip(images, crops_coords_list):
    new_width, new_height = W, H
    out = pipe(
        prompt=[prompt] * 1,
        image=sub_img,
        control_image=[sub_img],
        control_mode=[6],
        width=new_width,
        height=new_height,
        num_inference_steps=30,
        crops_coords_top_left=(W, H),
        target_size=(W, H),
        original_size=(W * 2, H * 2),
    )
    result_images.append(out.images[0])
new_im = Image.new("RGB", (new_width * scale_image_factor, new_height * scale_image_factor))
new_im.paste(result_images[0], (0, 0))
new_im.paste(result_images[1], (new_width, 0))
new_im.paste(result_images[2], (new_width * 2, 0))
new_im.paste(result_images[3], (0, new_height))
new_im.paste(result_images[4], (new_width, new_height))
new_im.paste(result_images[5], (new_width * 2, new_height))
new_im.paste(result_images[6], (0, new_height * 2))
new_im.paste(result_images[7], (new_width, new_height * 2))
new_im.paste(result_images[8], (new_width * 2, new_height * 2))
```

#### encode_prompt[[diffusers.StableDiffusionXLControlNetUnionImg2ImgPipeline.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/controlnet/pipeline_controlnet_union_sd_xl_img2img.py#L310)

**매개변수:**

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이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다.

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

## StableDiffusionXLControlNetUnionInpaintPipeline[[diffusers.StableDiffusionXLControlNetUnionInpaintPipeline]]

#### diffusers.StableDiffusionXLControlNetUnionInpaintPipeline[[diffusers.StableDiffusionXLControlNetUnionInpaintPipeline]]

```python
diffusers.StableDiffusionXLControlNetUnionInpaintPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, controlnet: diffusers.models.controlnets.controlnet_union.ControlNetUnionModel | list[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | tuple[diffusers.models.controlnets.controlnet_union.ControlNetUnionModel] | diffusers.models.controlnets.multicontrolnet_union.MultiControlNetUnionModel, scheduler: KarrasDiffusionSchedulers, requires_aesthetics_score: bool = False, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = None, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py#L160)

**매개변수:**

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) 중 하나일 수 있습니다.

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.StableDiffusionXLControlNetUnionInpaintPipeline.__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, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], list[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 = 0.9999, num_inference_steps: int = 50, 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, 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, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = 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, guess_mode: bool = False, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, control_mode: int | list[int] | list[list[int]] | None = None, guidance_rescale: float = 0.0, original_size: tuple = None, crops_coords_top_left: tuple = (0, 0), target_size: tuple = 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'], **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py#L1146)

**매개변수:**

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)`입니다.

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

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`의 마스킹된 부분을 무시하는 것과 같습니다. `denoising_start`가 정수로 선언된 경우, `strength`의 값은 무시됩니다.

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

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가 생성됩니다.

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` 입력 인자로부터 임베딩이 계산됩니다.

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

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

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 사전입니다.

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

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이 적용을 중단하는 전체 스텝의 비율입니다.

control_mode (`int` or `list[int]` or `list[list[int]], *optional*) : The control condition types for the ControlNet. See the ControlNet's model card forinformation on the available control modes. If multiple ControlNets are specified in `init`, control_mode should be a list where each ControlNet should have its corresponding control mode list. Should reflect the order of conditions in control_image.

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

original_size (`tuple[int]`, *선택 사항*, 기본값 (1024, 1024)) : `original_size`가 `target_size`와 같지 않으면 이미지가 다운샘플링 또는 업샘플링된 것처럼 보입니다. `original_size`는 지정되지 않은 경우 기본값으로 `(width, height)`를 사용합니다. [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`는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정되지 않으면 기본값으로 `(width, height)`가 사용됩니다. [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952)의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다.

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

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

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

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

예:
```py
from diffusers import StableDiffusionXLControlNetUnionInpaintPipeline, ControlNetUnionModel, AutoencoderKL
from diffusers.utils import load_image
import torch
import numpy as np
from PIL import Image

prompt = "A cat"
# download an image
image = load_image(
    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo.png"
).resize((1024, 1024))
mask = load_image(
    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/in_paint/overture-creations-5sI6fQgYIuo_mask.png"
).resize((1024, 1024))
# initialize the models and pipeline
controlnet = ControlNetUnionModel.from_pretrained(
    "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
)
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe = StableDiffusionXLControlNetUnionInpaintPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    controlnet=controlnet,
    vae=vae,
    torch_dtype=torch.float16,
    variant="fp16",
)
pipe.enable_model_cpu_offload()
controlnet_img = image.copy()
controlnet_img_np = np.array(controlnet_img)
mask_np = np.array(mask)
controlnet_img_np[mask_np > 0] = 0
controlnet_img = Image.fromarray(controlnet_img_np)
# generate image
image = pipe(prompt, image=image, mask_image=mask, control_image=[controlnet_img], control_mode=[7]).images[0]
image.save("inpaint.png")
```

#### encode_prompt[[diffusers.StableDiffusionXLControlNetUnionInpaintPipeline.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/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py#L280)

**매개변수:**

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이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다.

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

