# InstructPix2Pix

  

Tim Brooks, Aleksander Holynski, Alexei A. Efros의 [InstructPix2Pix: Learning to Follow Image Editing Instructions](https://huggingface.co/papers/2211.09800)입니다.

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

*인간 지시에 따라 이미지를 편집하는 방법을 제안합니다. 입력 이미지와 모델이 수행할 작업을 알려주는 텍스트 지시가 주어지면, 우리의 모델은 이러한 지시를 따르며 이미지를 편집합니다. 이 문제를 위한 학습 데이터를 얻기 위해, 두 개의 대규모 사전 학습 모델, 즉 언어 모델(GPT-3)과 텍스트-이미지 모델(Stable Diffusion)의 지식을 결합하여 이미지 편집 예시의 대규모 데이터셋을 생성했습니다. 우리의 조건부 확산 모델인 InstructPix2Pix는 생성된 데이터로 학습되며, 추론 시 실제 이미지와 사용자가 작성한 지시로 일반화됩니다. 이 모델은 순방향 패스에서 편집을 수행하며 예시별 미세 조정이나 역전이 필요하지 않으므로, 몇 초 만에 이미지를 빠르게 편집합니다. 다양한 입력 이미지와 텍스트 지시 모음에 대해 설득력 있는 편집 결과를 보여줍니다.*

InstructPix2Pix에 대한 추가 정보는 [논문](https://huggingface.co/papers/2211.09800), [원본 코드베이스](https://github.com/timothybrooks/instruct-pix2pix)에서 확인하고, [데모](https://huggingface.co/spaces/timbrooks/instruct-pix2pix)에서 직접 사용해 볼 수 있습니다.

> [!TIP]
> Scheduler의 [가이드](../../using-diffusers/schedulers)를 확인하여 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법을 배우고, [파이프라인 간 구성 요소 재사용](../../using-diffusers/loading#reusing-models-in-multiple-pipelines) 섹션을 확인하여 동일한 구성 요소를 여러 파이프라인에 효율적으로 로드하는 방법을 배워보세요.

## StableDiffusionInstructPix2PixPipeline[[diffusers.StableDiffusionInstructPix2PixPipeline]]

#### diffusers.StableDiffusionInstructPix2PixPipeline[[diffusers.StableDiffusionInstructPix2PixPipeline]]

```python
diffusers.StableDiffusionInstructPix2PixPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None, requires_safety_checker: bool = True)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py#L83)

**매개변수:**

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 기반 텍스트 지시사항을 따르는 픽셀 수준 이미지 편집을 위한 파이프라인

이 모델은 [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.StableDiffusionInstructPix2PixPipeline.__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, num_inference_steps: int = 100, guidance_scale: float = 7.5, image_guidance_scale: float = 1.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, 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'], cross_attention_kwargs: dict[str, typing.Any] | None = None, **kwargs)
```

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

**매개변수:**

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

image (`torch.Tensor` `np.ndarray`, `PIL.Image.Image`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : `prompt`에 따라 다시 페인트칠할 이미지 배치의 `Image` 또는 텐서를 나타냅니다. `image`로 이미지 레이턴트를 직접 전달할 수도 있으며, 이 경우 다시 인코딩되지 않습니다.

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

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

image_guidance_scale (`float`, *선택 사항*, 기본값 1.5) : 생성된 이미지를 초기 `image`로 유도합니다. `image_guidance_scale > 1`로 설정하면 이미지 가이던스 스케일이 활성화됩니다. 이미지 가이던스 스케일이 높을수록 소스 `image`와 밀접하게 연결된 이미지가 생성되도록 장려되며, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. 이 파이프라인은 최소 `1` 이상의 값을 요구합니다.

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`, *선택 사항*) : 생성을 결정적으로 만들기 위한 [`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)을 반환할지 여부.

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

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

**반환값:** [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 PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionInstructPix2PixPipeline

>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")

>>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"

>>> image = download_image(img_url).resize((512, 512))

>>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
...     "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "make the mountains snowy"
>>> image = pipe(prompt=prompt, image=image).images[0]
```

#### load_textual_inversion[[diffusers.StableDiffusionInstructPix2PixPipeline.load_textual_inversion]]

```python
load_textual_inversion(pretrained_model_name_or_path: str | list[str] | dict[str, torch.Tensor] | list[dict[str, torch.Tensor]], token: str | list[str] | None = None, tokenizer: 'PreTrainedTokenizer' | None = None, text_encoder: 'PreTrainedModel' | None = None, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L271)

**매개변수:**

pretrained_model_name_or_path (`str` 또는 `os.PathLike` 또는 `list[str or os.PathLike]` 또는 `Dict` 또는 `list[Dict]`) : 다음 중 하나이거나, 이들의 리스트일 수 있습니다:  - Hub에 호스팅된 사전 학습 모델의 *model id* 문자열 (예: `sd-concepts-library/low-poly-hd-logos-icons`). - 텍스트 인버전 가중치를 포함하는 *디렉터리* 경로 (예: `./my_text_inversion_directory/`). - 텍스트 인버전 가중치를 포함하는 *파일* 경로 (예: `./my_text_inversions.pt`). - [torch state dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

token (`str` 또는 `list[str]`, *선택 사항*) : 텍스트 인버전 가중치에 사용할 토큰을 재정의합니다. `pretrained_model_name_or_path`가 리스트인 경우, `token`도 동일한 길이의 리스트여야 합니다.

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)). 지정되지 않으면 함수가 self.tokenizer를 사용합니다.

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer), *선택 사항*) : 텍스트를 토큰화할 `CLIPTokenizer`입니다. 지정하지 않으면 함수가 self.tokenizer를 사용합니다.

weight_name (`str`, *선택 사항*) : 커스텀 가중치 파일의 이름. 다음 경우에 사용해야 합니다:  - 저장된 텍스트 인버전 파일이 🤗 Diffusers 형식이지만 `text_inv.bin`과 같은 특정 가중치 이름으로 저장된 경우. - 저장된 텍스트 인버전 파일이 Automatic1111 형식인 경우.

cache_dir (`str | os.PathLike`, *선택 사항*) : 표준 캐시를 사용하지 않을 경우, 다운로드된 사전 학습 모델 구성이 캐시되는 디렉터리의 경로입니다.

force_download (`bool`, *선택 사항*, 기본값 `False`) : 캐시된 버전이 존재하더라도 모델 가중치 및 구성 파일의 (재)다운로드를 강제할지 여부.

proxies (`dict[str, str]`, *선택 사항*) : 프로토콜 또는 엔드포인트별로 사용할 프록시 서버의 사전입니다. 예를 들어, `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`와 같습니다. 각 요청에 프록시가 사용됩니다.

local_files_only (`bool`, *선택 사항*, 기본값 `False`) : 로컬 모델 가중치와 구성 파일만 로드할지 여부를 지정합니다. `True`로 설정하면 Hub에서 모델을 다운로드하지 않습니다.

hf_token (`str` 또는 *bool*, *선택 사항*) : 원격 파일에 대한 HTTP bearer 인증으로 사용할 토큰입니다. `True`인 경우, `diffusers-cli login`에서 생성된 토큰(`~/.huggingface`에 저장됨)이 사용됩니다.

revision (`str`, *선택 사항*, 기본값 `"main"`) : 사용할 특정 모델 버전입니다. Git에서 허용하는 브랜치 이름, 태그 이름, 커밋 ID 또는 기타 식별자일 수 있습니다.

subfolder (`str`, *선택 사항*, 기본값 `""`) : Hub 또는 로컬의 더 큰 모델 저장소 내에서 모델 파일의 서브폴더 위치입니다.

mirror (`str`, *선택 사항*) : 중국에서 모델을 다운로드할 때 접근성 문제를 해결하기 위한 미러 소스입니다. 해당 소스의 적시성이나 안전성을 보장하지 않으며, 자세한 내용은 미러 사이트를 참고하세요.

[StableDiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline)의 텍스트 인코더에 Textual Inversion 임베딩을 로드합니다(🤗 Diffusers와 Automatic1111 형식 모두 지원).

예:

🤗 Diffusers 형식으로 Textual Inversion 임베딩 벡터를 로드하려면:

```py
from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")
```

Automatic1111 형식의 Textual Inversion 임베딩 벡터를 로드하려면 먼저 벡터를 다운로드(예: [civitAI](https://civitai.com/models/3036?modelVersionId=9857)에서)한 다음 벡터를 로드해야 합니다.

로컬에서:

```py
from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")
```

#### load_lora_weights[[diffusers.StableDiffusionInstructPix2PixPipeline.load_lora_weights]]

```python
load_lora_weights(pretrained_model_name_or_path_or_dict: str | dict[str, torch.Tensor], adapter_name: str | None = None, hotswap: bool = False, **kwargs)
```

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

**매개변수:**

pretrained_model_name_or_path_or_dict (`str` 또는 `os.PathLike` 또는 `dict`) : [lora_state_dict()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)을(를) 참조하세요.

adapter_name (`str`, *선택 사항*) : 로드된 어댑터 모델을 참조할 때 사용할 어댑터 이름. 지정하지 않으면 로드 중인 어댑터의 총 개수를 i라고 할 때 `default_{i}`가 사용됩니다.

low_cpu_mem_usage (`bool`, *선택 사항*) : 무작위 가중치를 초기화하지 않고 사전 학습된 LoRA 가중치만 로드하여 모델 로딩 속도를 높입니다.

hotswap (`bool`, *선택 사항*) : 기본값은 `False`입니다. 기존 (LoRA) 어댑터를 새로 로드한 어댑터로 제자리에서 교체할지 여부입니다. 즉, 추가 어댑터를 로드하는 대신 기존 어댑터의 가중치를 새 어댑터의 가중치로 대체합니다. 이는 더 빠르고 메모리 효율적일 수 있습니다. 그러나 핫스왑의 주요 이점은 모델이 torch.compile로 컴파일된 경우, 새 어댑터를 로드할 때 모델의 재컴파일이 필요하지 않다는 점입니다. 핫스왑을 사용할 때 전달하는 `adapter_name`은 이미 로드된 어댑터의 이름이어야 합니다. 새 어댑터와 기존 어댑터의 랭크와/또는 LoRA 알파(즉, 스케일링)가 다른 경우, 어댑터를 로드하기 전에 추가 메서드를 호출해야 합니다: ```py pipeline = ...  # load diffusers pipeline max_rank = ...  # the highest rank among all LoRAs that you want to load # call *before* compiling and loading the LoRA adapter pipeline.enable_lora_hotswap(target_rank=max_rank) pipeline.load_lora_weights(file_name) # optionally compile the model now ``` 텍스트 인코더의 어댑터 핫스왑은 아직 지원되지 않습니다. 이 기법에는 몇 가지 추가 제한 사항이 있으며, 여기에서 문서화되어 있습니다: https://huggingface.co/docs/peft/main/en/package_reference/hotswap

kwargs (`dict`, *선택 사항*) : [lora_state_dict()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)를 참조하세요.

`pretrained_model_name_or_path_or_dict`에 지정된 LoRA 가중치를 `self.unet`와 `self.text_encoder`에 로드합니다.

모든 kwargs는 `self.lora_state_dict`로 전달됩니다.

state dict가 로드되는 방법에 대한 자세한 내용은 [lora_state_dict()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)을 참조하세요.

See [load_lora_into_unet()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_into_unet) for more details on how the state dict is loaded into `self.unet`.

`self.text_encoder`에 state dict가 로드되는 방법에 대한 자세한 내용은 [load_lora_into_text_encoder()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder)를 참조하세요.

#### save_lora_weights[[diffusers.StableDiffusionInstructPix2PixPipeline.save_lora_weights]]

```python
save_lora_weights(save_directory: str | os.PathLike, unet_lora_layers: dict = None, text_encoder_lora_layers: dict = None, is_main_process: bool = True, weight_name: str = None, save_function: typing.Callable = None, safe_serialization: bool = True, unet_lora_adapter_metadata = None, text_encoder_lora_adapter_metadata = None)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/lora_pipeline.py#L466)

**매개변수:**

save_directory (`str` 또는 `os.PathLike`) : LoRA 파라미터를 저장할 디렉터리입니다. 존재하지 않으면 생성됩니다.

unet_lora_layers (`dict[str, torch.nn.Module]` 또는 `dict[str, torch.Tensor]`) : `unet`에 해당하는 LoRA 레이어의 state dict입니다.

text_encoder_lora_layers (`dict[str, torch.nn.Module]` 또는 `dict[str, torch.Tensor]`) : `text_encoder`에 해당하는 LoRA 레이어의 state dict입니다. 🤗 Transformers에서 가져오므로 text encoder LoRA state dict를 명시적으로 전달해야 합니다.

is_main_process (`bool`, *선택 사항*, 기본값 `True`) : 이 함수를 호출하는 프로세스가 메인 프로세스인지 여부입니다. 분산 학습 중에 모든 프로세스에서 이 함수를 호출해야 하는 경우 유용합니다. 이 경우 레이스 조건을 방지하기 위해 메인 프로세스에서만 `is_main_process=True`로 설정하세요.

save_function (`Callable`) : 상태 사전(state dictionary)을 저장하는 데 사용할 함수입니다. 분산 학습 중에 `torch.save`를 다른 방법으로 대체해야 하는 경우 유용합니다. 환경 변수 `DIFFUSERS_SAVE_MODE`로 설정할 수 있습니다.

safe_serialization (`bool`, *선택 사항*, 기본값 `True`) : `safetensors` 또는 `pickle`를 사용한 전통적인 PyTorch 방식으로 모델을 저장할지 여부.

unet_lora_adapter_metadata : state dict와 함께 직렬화될 unet에 연결된 LoRA 어댑터 메타데이터.

text_encoder_lora_adapter_metadata : state dict와 함께 직렬화될 텍스트 인코더와 관련된 LoRA 어댑터 메타데이터.

UNet과 텍스트 인코더에 해당하는 LoRA 매개변수를 저장합니다.

## StableDiffusionXLInstructPix2PixPipeline[[diffusers.StableDiffusionXLInstructPix2PixPipeline]]

#### diffusers.StableDiffusionXLInstructPix2PixPipeline[[diffusers.StableDiffusionXLInstructPix2PixPipeline]]

```python
diffusers.StableDiffusionXLInstructPix2PixPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, force_zeros_for_empty_prompt: bool = True, add_watermarker: bool | None = None, is_cosxl_edit: bool | None = False)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py#L113)

**매개변수:**

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가 적용되고, 그렇지 않으면 워터마커가 사용되지 않습니다.

is_cosxl_edit (`bool`, *선택 사항*) : 설정 시 이미지 잠재 변수가 스케일링됩니다.

텍스트 지시를 따르는 픽셀 수준 이미지 편집을 위한 Pipeline. Stable Diffusion XL 기반입니다.

이 모델은 [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)

#### __호출__[[diffusers.StableDiffusionXLInstructPix2PixPipeline.__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 = 100, denoising_end: float | None = None, guidance_scale: float = 5.0, image_guidance_scale: float = 1.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, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, 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)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py#L595)

**매개변수:**

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]`) : 파이프라인으로 수정할 이미지(들).

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) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.

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` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.

image_guidance_scale (`float`, *선택 사항*, 기본값 1.5) : 이미지 가이던스 스케일은 생성된 이미지를 초기 이미지 `image` 방향으로 유도하는 값입니다. `image_guidance_scale > 1`로 설정하면 이미지 가이던스 스케일이 활성화됩니다. 이미지 가이던스 스케일이 높을수록 소스 이미지 `image`와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. 이 파이프라인은 최소 `1` 이상의 값을 요구합니다.

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

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

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

callback (`Callable`, *선택 사항*) : 추론 중 `callback_steps` 스텝마다 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback(step: int, timestep: int, latents: torch.Tensor)`.

callback_steps (`int`, *선택 사항*, 기본값 1) : `callback` 함수가 호출되는 주기입니다. 지정하지 않으면 모든 단계에서 callback이 호출됩니다.

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)의 일부입니다.

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

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

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

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

>>> resolution = 768
>>> image = load_image(
...     "https://hf.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
... ).resize((resolution, resolution))
>>> edit_instruction = "Turn sky into a cloudy one"

>>> pipe = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
...     "diffusers/sdxl-instructpix2pix-768", torch_dtype=torch.float16
... ).to("cuda")

>>> edited_image = pipe(
...     prompt=edit_instruction,
...     image=image,
...     height=resolution,
...     width=resolution,
...     guidance_scale=3.0,
...     image_guidance_scale=1.5,
...     num_inference_steps=30,
... ).images[0]
>>> edited_image
```

#### encode_prompt[[diffusers.StableDiffusionXLInstructPix2PixPipeline.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)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py#L213)

**매개변수:**

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 스케일입니다.

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

