# Latent 업스케일러

Stable Diffusion latent upscaler 모델은 [Katherine Crowson](https://github.com/crowsonkb/k-diffusion)이 [Stability AI](https://stability.ai/)와 협력하여 만들었습니다. 이 모델은 출력 이미지의 해상도를 2배로 향상시키는 데 사용되며(원래 구현의 데모는 이 [notebook](https://colab.research.google.com/drive/1o1qYJcFeywzCIdkfKJy7cTpgZTCM2EI4)을 참고하세요).

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

## StableDiffusionLatentUpscalePipeline[[diffusers.StableDiffusionLatentUpscalePipeline]]

#### diffusers.StableDiffusionLatentUpscalePipeline[[diffusers.StableDiffusionLatentUpscalePipeline]]

```python
diffusers.StableDiffusionLatentUpscalePipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: EulerDiscreteScheduler)
```

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

**매개변수:**

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의 노이즈를 제거하는 [EulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/euler#diffusers.EulerDiscreteScheduler).

Stable Diffusion 출력 이미지의 해상도를 2배로 상향 조정하는 Pipeline입니다.

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

파이프라인은 다음 로딩 메서드도 상속합니다:
- `.ckpt` 파일을 로드하기 위한 [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)

#### __호출__[[diffusers.StableDiffusionLatentUpscalePipeline.__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 = 75, guidance_scale: float = 9.0, negative_prompt: str | list[str] | None = None, 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)
```

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

**매개변수:**

prompt (`str` 또는 `list[str]`) : 이미지 업스케일링을 안내할 프롬프트 또는 프롬프트 목록.

image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, 또는 `list[np.ndarray]`) : 업스케일링할 이미지 배치의 `Image` 또는 텐서를 나타냅니다. 텐서인 경우, Stable Diffusion 모델의 latent 출력이거나 `[-1, 1]` 범위의 이미지 텐서일 수 있습니다. `image.shape[1]`이 `4`인 경우 `latent`로 간주하고, 그렇지 않으면 이미지 표현으로 간주하여 이 파이프라인의 `vae` 인코더를 사용하여 인코딩합니다.

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

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

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

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

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 (`Callable`, *선택 사항*) : 추론 중 `callback_steps` 단계마다 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback(step: int, timestep: int, latents: torch.Tensor)`.

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

**반환값:** [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
>>> from diffusers import StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline
>>> import torch

>>> pipeline = StableDiffusionPipeline.from_pretrained(
...     "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
... )
>>> pipeline.to("cuda")

>>> model_id = "stabilityai/sd-x2-latent-upscaler"
>>> upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
>>> upscaler.to("cuda")

>>> prompt = "a photo of an astronaut high resolution, unreal engine, ultra realistic"
>>> generator = torch.manual_seed(33)

>>> low_res_latents = pipeline(prompt, generator=generator, output_type="latent").images

>>> with torch.no_grad():
...     image = pipeline.decode_latents(low_res_latents)
>>> image = pipeline.numpy_to_pil(image)[0]

>>> image.save("../images/a1.png")

>>> upscaled_image = upscaler(
...     prompt=prompt,
...     image=low_res_latents,
...     num_inference_steps=20,
...     guidance_scale=0,
...     generator=generator,
... ).images[0]

>>> upscaled_image.save("../images/a2.png")
```

#### enable_sequential_cpu_offload[[diffusers.StableDiffusionLatentUpscalePipeline.enable_sequential_cpu_offload]]

```python
enable_sequential_cpu_offload(gpu_id: int | None = None, device: typing.Union[torch.device, str] = None)
```

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

**매개변수:**

gpu_id (`int`, *선택 사항*) : 추론에 사용할 accelerator의 ID입니다. 지정하지 않으면 기본값으로 0이 사용됩니다.

device (`torch.Device` 또는 `str`, *선택 사항*, 기본값 None) : 추론에 사용할 가속기의 PyTorch 장치 유형입니다. 지정하지 않으면 사용 가능한 가속기를 자동으로 감지하여 사용합니다.

🤗 Accelerate를 사용하여 모든 모델을 CPU로 오프로드하여 메모리 사용량을 크게 줄입니다. 호출 시 `self._exclude_from_cpu_offload`에 포함된 것을 제외한 모든 `torch.nn.Module` 구성 요소의 상태 딕트가 CPU에 저장된 후 `torch.device('meta')`로 이동되며, 해당 서브모듈의 `forward` 메서드가 호출될 때에만 가속기로 로드됩니다. 오프로딩은 서브모듈 단위로 수행됩니다. `enable_model_cpu_offload`를 사용할 때보다 메모리 절감 효과가 크지만 성능은 낮습니다.

#### enable_attention_slicing[[diffusers.StableDiffusionLatentUpscalePipeline.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.StableDiffusionLatentUpscalePipeline.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.StableDiffusionLatentUpscalePipeline.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.StableDiffusionLatentUpscalePipeline.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/)에서 메모리 효율적 어텐션을 비활성화합니다.

#### encode_prompt[[diffusers.StableDiffusionLatentUpscalePipeline.encode_prompt]]

```python
encode_prompt(prompt, device, do_classifier_free_guidance, negative_prompt = 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)
```

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

**매개변수:**

prompt (`str` 또는 `list(int)`) : 인코딩할 프롬프트

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

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

negative_prompt (`str` 또는 `list[str]`) : 이미지 생성을 유도하지 않을 프롬프트입니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).

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

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

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

## 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 파이프라인의 출력 클래스입니다.

