# 인페인팅

  

Stable Diffusion 모델은 Stable Diffusion을 사용하여 마스크와 텍스트 프롬프트를 제공함으로써 이미지의 특정 부분을 편집할 수 있는 inpainting에도 적용할 수 있습니다.

## 팁

인페인팅을 위해 특별히 파인튜닝된 체크포인트, 예를 들어 [stable-diffusion-v1-5/stable-diffusion-inpainting](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting)와 같은 체크포인트를 이 파이프라인과 함께 사용하는 것이 권장됩니다. [stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)와 같은 기본 텍스트-이미지 Stable Diffusion 체크포인트도 호환되지만 성능이 낮을 수 있습니다.

> [!TIP]
> 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법과 파이프라인 구성 요소를 효율적으로 재사용하는 방법을 배우려면 Stable Diffusion [Tips](overview#tips) 섹션을 꼭 확인하세요!
>
> 특정 작업에 공식 체크포인트 중 하나를 사용하려는 경우, [CompVis](https://huggingface.co/CompVis) 및 [Stability AI](https://huggingface.co/stabilityai) Hub 조직을 탐색해 보세요!

## StableDiffusionInpaintPipeline[[diffusers.StableDiffusionInpaintPipeline]]

#### diffusers.StableDiffusionInpaintPipeline[[diffusers.StableDiffusionInpaintPipeline]]

```python
diffusers.StableDiffusionInpaintPipeline(vae: diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL | diffusers.models.autoencoders.autoencoder_asym_kl.AsymmetricAutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True)
```

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

**매개변수:**

vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 Variational Auto-Encoder (VAE) 모델.

text_encoder (`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)
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)

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

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: Tensor = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 1.0, num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], **kwargs)
```

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

**매개변수:**

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

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : `Image`, numpy 배열 또는 텐서로 표현된 inpaint 대상 이미지 배치입니다(이미지의 어떤 부분을 `mask_image`로 마스킹하여 `prompt`에 따라 다시 채울지 지정). numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는 `[0, 1]`입니다. 텐서 또는 텐서 목록인 경우 예상 shape은 `(B, C, H, W)` 또는 `(C, H, W)`여야 합니다. numpy 배열 또는 배열 목록인 경우 예상 shape은 `(B, H, W, C)` 또는 `(H, W, C)`여야 합니다. `image`로 이미지 latents도 받을 수 있지만, latents를 직접 전달하는 경우 다시 인코딩되지 않습니다.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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`

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 StableDiffusionInpaintPipeline

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

>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = download_image(img_url).resize((512, 512))
>>> mask_image = download_image(mask_url).resize((512, 512))

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

>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
```

#### enable_attention_slicing[[diffusers.StableDiffusionInpaintPipeline.enable_attention_slicing]]

```python
enable_attention_slicing(slice_size: str | int = 'auto')
```

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

**매개변수:**

slice_size (`str` 또는 `int`, *선택 사항*, 기본값 `"auto"`) : `"auto"`인 경우 attention heads에 전달되는 입력을 절반으로 줄여 attention을 두 단계로 계산합니다. `"max"`인 경우 한 번에 하나의 슬라이스만 실행하여 최대의 메모리를 절약합니다. 숫자가 제공되면 `attention_head_dim // slice_size`만큼의 슬라이스를 사용합니다. 이 경우 `attention_head_dim`은 `slice_size`의 배수여야 합니다.

슬라이스된 어텐션 계산을 활성화합니다. 이 옵션이 활성화되면 어텐션 모듈은 입력 텐서를 슬라이스로 분할하여 여러 단계에 걸쳐 어텐션을 계산합니다. 어텐션 헤드 하나가 넘는 경우, 각 헤드를 순차적으로 계산합니다. 이는 속도가 약간 감소하는 대신 메모리를 절약하는 데 유용합니다.

> [!WARNING] > ⚠️ 이미 `scaled_dot_product_attention`(SDPA)를 사용 중이라면 attention slicing을 활성화하지 마세요
from PyTorch > 2.0 or xFormers. 이러한 attention 계산은 이미 메모리 효율성이 매우 높아 이 기능을 활성화할 필요가 없습니다. SDPA 또는 xFormers와 함께 attention slicing을 활성화하면 심각한 성능 저하가 발생할 수 있습니다!

예:

```py
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     dtype=torch.float16,
...     use_safetensors=True,
... )

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

#### disable_attention_slicing[[diffusers.StableDiffusionInpaintPipeline.disable_attention_slicing]]

```python
disable_attention_slicing()
```

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

슬라이스된 어텐션 계산 기능을 비활성화합니다. `enable_attention_slicing`가 이전에 호출된 경우, 어텐션은 한 번에 계산됩니다.

#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionInpaintPipeline.enable_xformers_memory_efficient_attention]]

```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```

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

**매개변수:**

attention_op (`Callable`, *선택 사항*) : xFormers의 [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 함수에 `op` 인수로 사용될 때 기본 `None` 연산자를 재정의합니다.

[xFormers](https://facebookresearch.github.io/xformers/)에서 메모리 효율적인 어텐션을 활성화합니다. 이 옵션을 활성화하면 추론 시 GPU 메모리 사용량이 감소하고 속도가 향상될 수 있습니다. 학습 시 속도 향상은 보장되지 않습니다.

> [!WARNING] > ⚠️ memory efficient attention과 sliced attention이 모두 활성화된 경우, memory efficient
attention은 > 우선순위를 가집니다.

예:

```py
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionInpaintPipeline.disable_xformers_memory_efficient_attention]]

```python
disable_xformers_memory_efficient_attention()
```

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

[xFormers](https://facebookresearch.github.io/xformers/)에서 메모리 효율적 어텐션을 비활성화합니다.

#### load_textual_inversion[[diffusers.StableDiffusionInpaintPipeline.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.StableDiffusionInpaintPipeline.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)을 참조하세요.

`self.unet`에 상태 사전이 로드되는 방법에 대한 자세한 내용은 [load_lora_into_unet()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_into_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.StableDiffusionInpaintPipeline.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 매개변수를 저장합니다.

#### encode_prompt[[diffusers.StableDiffusionInpaintPipeline.encode_prompt]]

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

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

**매개변수:**

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

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

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

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

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

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

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

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

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

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

#### get_guidance_scale_embedding[[diffusers.StableDiffusionInpaintPipeline.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/stable_diffusion/pipeline_stable_diffusion_inpaint.py#L823)

**매개변수:**

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

## StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

#### diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

```python
diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_content_detected: list[bool] | None)
```

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

**매개변수:**

images (`list[PIL.Image.Image]` 또는 `np.ndarray`) : `batch_size` 길이의 노이즈 제거된 PIL 이미지 목록 또는 `(batch_size, height, width, num_channels)` 모양의 NumPy 배열.

nsfw_content_detected (`list[bool]`) : 해당 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 리스트. 안전 검사를 수행할 수 없는 경우 `None`.

Stable Diffusion 파이프라인의 출력 클래스입니다.

