#
# Apache License, Version 2.0("라이선스")에 따라 라이선스가 부여됩니다.
# 이 파일은 라이선스에 따라만 사용할 수 있습니다.
# 라이선스 사본은 다음에서 가져올 수 있습니다
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 적용 가능한 법률에 의해 요구되거나 서면으로 합의되지 않는 한, 소프트웨어
# 라이선스에 따라 배포되는 본 소프트웨어는 "있는 그대로"
# 명시적이든 묵시적이든 어떠한 종류의 보증이나 조건도 없이 제공됩니다.
# 권한을 관리하는 특정 언어에 대한 라이선스를 참조하세요
# 라이선스 하의 제한 사항. -->

# SanaPipeline

  
  

NVIDIA와 MIT HAN Lab의 Enze Xie, Junsong Chen, Junyu Chen, Han Cai, Haotian Tang, Yujun Lin, Zhekai Zhang, Muyang Li, Ligeng Zhu, Yao Lu, Song Han이 발표한 [SANA: Efficient High-Resolution Image Synthesis with Linear Diffusion Transformers](https://huggingface.co/papers/2410.10629)

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

*Sana를 소개합니다. Sana는 최대 4096×4096 해상도의 이미지를 효율적으로 생성할 수 있는 텍스트-이미지 프레임워크입니다. Sana는 놀라울 정도로 빠른 속도로 텍스트-이미지 정렬이 뛰어난 고해상도, 고품질 이미지를 합성할 수 있으며 노트북 GPU에 배포할 수 있습니다. 핵심 설계는 다음과 같습니다. (1) 딥 압축 오토인코더: 이미지를 8배만 압축하는 기존 AE와 달리, 우리는 잠재 토큰 수를 효과적으로 줄일 수 있는 32배 압축이 가능한 AE를 학습했습니다. (2) Linear DiT: DiT의 모든 일반 어텐션을 선형 어텐션으로 대체했습니다. 이는 품질 저하 없이 고해상도에서 더 효율적입니다. (3) 디코더 전용 텍스트 인코더: T5를 현대적인 디코더 전용 소형 LLM로 대체하여 텍스트 인코더로 사용했으며, 컨텍스트 내 학습을 통한 복잡한 인간 지시를 설계하여 이미지-텍스트 정렬을 강화했습니다. (4) 효율적인 학습 및 샘플링: 효율적인 캡션 라벨링 및 선택을 통해 수렴을 가속화하고, 샘플링 단계를 줄이기 위해 Flow-DPM-Solver를 제안했습니다. 그 결과, Sana-0.6B는 현대적인 거대 확산 모델(예: Flux-12B)과 매우 경쟁력이 있으며, 크기는 20배 작고 측정된 처리량은 100배 이상 빠릅니다. 또한, Sana-0.6B는 16GB 노트북 GPU에 배포할 수 있으며, 1024×1024 해상도의 이미지를 생성하는 데 1초 미만으로 소요됩니다. Sana는 저비용 콘텐츠 생성을 가능하게 합니다. 코드와 모델은 공개될 예정입니다.*

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

이 파이프라인은 [lawrence-cj](https://github.com/lawrence-cj)와 [chenjy2003](https://github.com/chenjy2003)가 기여했습니다. 원본 코드베이스는 [여기](https://github.com/NVlabs/Sana)에서 찾을 수 있습니다. 원본 가중치는 [hf.co/Efficient-Large-Model](https://huggingface.co/Efficient-Large-Model)에서 찾을 수 있습니다.

사용 가능한 모델:

| 모델 | 권장 dtype |
|:-----:|:-----------------:|
| [`Efficient-Large-Model/Sana_1600M_1024px_BF16_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_1600M_1024px_BF16_diffusers) | `torch.bfloat16` |
| [`Efficient-Large-Model/Sana_1600M_1024px_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_1600M_1024px_diffusers) | `torch.float16` |
| [`Efficient-Large-Model/Sana_1600M_1024px_MultiLing_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_1600M_1024px_MultiLing_diffusers) | `torch.float16` |
| [`Efficient-Large-Model/Sana_1600M_512px_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_1600M_512px_diffusers) | `torch.float16` |
| [`Efficient-Large-Model/Sana_1600M_512px_MultiLing_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_1600M_512px_MultiLing_diffusers) | `torch.float16` |
| [`Efficient-Large-Model/Sana_600M_1024px_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_600M_1024px_diffusers) | `torch.float16` |
| [`Efficient-Large-Model/Sana_600M_512px_diffusers`](https://huggingface.co/Efficient-Large-Model/Sana_600M_512px_diffusers) | `torch.float16` |

자세한 내용은 [이](https://huggingface.co/collections/Efficient-Large-Model/sana-673efba2a57ed99843f11f9e) 컬렉션을 참조하세요.

Note: 언급된 권장 dtype는 transformer 가중치에 대한 것입니다. 모델이 올바르게 작동하려면 텍스트 인코더와 VAE 가중치는 `torch.bfloat16` 또는 `torch.float32`로 유지해야 합니다. 권장 dtype로 모델을 로드하는 방법은 아래 추론 예시를 참고하세요.

> [!TIP]
> 다운로드한 체크포인트에 `variant` 인수를 전달하여 디스크 공간을 절약하세요. 권장 dtype가 `torch.float16`인 모델에는 `"fp16"`을, 권장 dtype가 `torch.bfloat16`인 모델에는 `"bf16"`으로 설정합니다. 기본적으로 `torch.float32` 가중치가 다운로드되며, 이는 두 배의 디스크 저장 공간을 사용합니다. 또한 `dtype` 인수를 지정하여 `torch.float32` 가중치를 실시간으로 다운캐스트할 수 있습니다. 자세한 내용은 [문서](https://huggingface.co/docs/diffusers/v0.31.0/en/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained)를 참고하세요.

## 양자화

Quantization은 모델 가중치를 더 낮은 정밀도의 데이터 타입으로 저장하여 매우 큰 모델의 메모리 요구 사항을 줄이는 데 도움이 됩니다. 그러나 quantization은 비디오 모델에 따라 비디오 품질에 다양한 영향을 미칠 수 있습니다.

지원되는 양자화 백엔드와 사용 사례에 맞는 양자화 백엔드 선택에 대해 자세히 알아보려면 [Quantization](../../quantization/overview) 개요를 참조하세요. 아래 예제는 bitsandbytes를 사용하여 추론을 위해 양자화된 [SanaPipeline](/docs/diffusers/main/ko/api/pipelines/sana#diffusers.SanaPipeline)을 로드하는 방법을 보여줍니다.

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SanaTransformer2DModel, SanaPipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, AutoModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = AutoModel.from_pretrained(
    "Efficient-Large-Model/Sana_1600M_1024px_diffusers",
    subfolder="text_encoder",
    quantization_config=quant_config,
    dtype=torch.float16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = SanaTransformer2DModel.from_pretrained(
    "Efficient-Large-Model/Sana_1600M_1024px_diffusers",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.float16,
)

pipeline = SanaPipeline.from_pretrained(
    "Efficient-Large-Model/Sana_1600M_1024px_diffusers",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    dtype=torch.float16,
    device_map="balanced",
)

prompt = "a tiny astronaut hatching from an egg on the moon"
image = pipeline(prompt).images[0]
image.save("sana.png")
```

## SanaPipeline[[diffusers.SanaPipeline]]

#### diffusers.SanaPipeline[[diffusers.SanaPipeline]]

```python
diffusers.SanaPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: AutoencoderDC, transformer: SanaTransformer2DModel, scheduler: DPMSolverMultistepScheduler)
```

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

[Sana](https://huggingface.co/papers/2410.10629)를 사용한 텍스트-이미지 생성 파이프라인.

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 20, timesteps: list = None, sigmas: list = None, guidance_scale: float = 4.5, num_images_per_prompt: int | None = 1, height: int = 1024, width: int = 1024, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, clean_caption: bool = False, use_resolution_binning: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 300, complex_human_instruction: list = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '])
```

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

**매개변수:**

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

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

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

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

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

guidance_scale (`float`, *선택 사항*, 기본값 4.5) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)에서 정의한 가이던스 스케일입니다. `guidance_scale`은 [Imagen Paper](https://huggingface.co/papers/2205.11487)의 2번 식의 `w`로 정의됩니다. `guidance_scale > 1`을 설정하여 가이던스 스케일을 활성화합니다. 가이던스 스케일이 높을수록 `prompt` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.

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

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

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

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

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

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

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

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.

negative_prompt_embeds (`torch.Tensor`, *선택*) : 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 부정 텍스트 임베딩에 사용할 사전 생성된 어텐션 마스크입니다.

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

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

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

clean_caption (`bool`, *선택 사항*, 기본값 `True`) : 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다. `beautifulsoup4`와 `ftfy`가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.

use_resolution_binning (`bool` 기본값은 `True`) : `True`로 설정하면, 요청된 높이와 너비가 `ASPECT_RATIO_1024_BIN`을 사용하여 가장 가까운 해상도로 먼저 매핑됩니다. 생성된 latents가 이미지로 디코딩된 후, 요청된 해상도로 다시 리사이즈됩니다. 정사각형이 아닌 이미지를 생성하는 데 유용합니다.

callback_on_step_end (`Callable`, *선택 사항*) : 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs`에는 `callback_on_step_end_tensor_inputs`로 지정된 모든 텐서 목록이 포함됩니다.

callback_on_step_end_tensor_inputs (`list`, *선택 사항*) : `callback_on_step_end` 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 `callback_kwargs` 인수로 전달됩니다. 파이프라인 클래스의 `._callback_tensor_inputs` 속성에 나열된 변수만 포함할 수 있습니다.

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

complex_human_instruction (`list[str]`, *선택 사항*) : 복잡한 인간 주의에 대한 지침: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.

**반환값:** [SanaPipelineOutput](/docs/diffusers/main/ko/api/pipelines/sana_sprint#diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput) 또는 `tuple`

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

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

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

>>> pipe = SanaPipeline.from_pretrained(
...     "Efficient-Large-Model/Sana_1600M_1024px_BF16_diffusers", torch_dtype=torch.float32
... )
>>> pipe.to("cuda")
>>> pipe.text_encoder.to(torch.bfloat16)
>>> pipe.transformer = pipe.transformer.to(torch.bfloat16)

>>> image = pipe(prompt='a cyberpunk cat with a neon sign that says "Sana"')[0]
>>> image[0].save("output.png")
```

#### encode_prompt[[diffusers.SanaPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 300, complex_human_instruction: list[str] | None = None, lora_scale: float | None = None)
```

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

**매개변수:**

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

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

do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부

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

device : (`torch.device`, *선택 사항*): 생성된 임베딩을 배치할 torch device

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

negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩. Sana의 경우, "" 문자열의 임베딩이어야 합니다.

clean_caption (`bool`, 기본값은 `False`) : `True`인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.

max_sequence_length (`int`, 기본값 300) : 프롬프트에 사용할 최대 시퀀스 길이입니다.

complex_human_instruction (`list[str]`, 기본값은 `complex_human_instruction`) : `complex_human_instruction`이 비어 있지 않으면, 이 함수는 프롬프트에 복잡한 Human 지시를 사용합니다.

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

## SanaPAGPipeline[[diffusers.SanaPAGPipeline]]

#### diffusers.SanaPAGPipeline[[diffusers.SanaPAGPipeline]]

```python
diffusers.SanaPAGPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: AutoencoderDC, transformer: SanaTransformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler, pag_applied_layers: str | list[str] = 'transformer_blocks.0')
```

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

[Sana](https://huggingface.co/papers/2410.10629)를 사용한 텍스트-이미지 생성을 위한 Pipeline입니다. 이 Pipeline은 [Perturbed Attention Guidance (PAG)](https://huggingface.co/docs/diffusers/main/en/using-diffusers/pag) 사용을 지원합니다.

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 20, timesteps: list = None, sigmas: list = None, guidance_scale: float = 4.5, num_images_per_prompt: int | None = 1, height: int = 1024, width: int = 1024, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, clean_caption: bool = False, use_resolution_binning: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 300, complex_human_instruction: list = ["Given a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.', '- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.', 'Here are examples of how to transform or refine prompts:', '- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.', 'Please generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:', 'User Prompt: '], pag_scale: float = 3.0, pag_adaptive_scale: float = 0.0)
```

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

**매개변수:**

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

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

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

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

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

guidance_scale (`float`, *선택 사항*, 기본값 4.5) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)에서 정의한 가이던스 스케일입니다. `guidance_scale`은 [Imagen Paper](https://huggingface.co/papers/2205.11487)의 2번 식의 `w`로 정의됩니다. `guidance_scale > 1`을 설정하여 가이던스 스케일을 활성화합니다. 가이던스 스케일이 높을수록 `prompt` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.

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

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

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

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

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

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

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

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.

negative_prompt_embeds (`torch.Tensor`, *선택*) : 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 부정 텍스트 임베딩에 사용할 사전 생성된 어텐션 마스크입니다.

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

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

clean_caption (`bool`, *선택 사항*, 기본값 `True`) : 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다. `beautifulsoup4`와 `ftfy`가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.

use_resolution_binning (`bool` 기본값은 `True`) : `True`로 설정하면, 요청된 높이와 너비가 `ASPECT_RATIO_1024_BIN`을 사용하여 가장 가까운 해상도로 먼저 매핑됩니다. 생성된 latents가 이미지로 디코딩된 후, 요청된 해상도로 다시 리사이즈됩니다. 정사각형이 아닌 이미지를 생성하는 데 유용합니다.

callback_on_step_end (`Callable`, *선택 사항*) : 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs`에는 `callback_on_step_end_tensor_inputs`로 지정된 모든 텐서 목록이 포함됩니다.

callback_on_step_end_tensor_inputs (`list`, *선택 사항*) : `callback_on_step_end` 함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는 `callback_kwargs` 인수로 전달됩니다. 파이프라인 클래스의 `._callback_tensor_inputs` 속성에 나열된 변수만 포함할 수 있습니다.

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

complex_human_instruction (`list[str]`, *선택 사항*) : 복잡한 인간 주의에 대한 지침: https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.

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

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

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

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

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

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

>>> pipe = SanaPAGPipeline.from_pretrained(
...     "Efficient-Large-Model/Sana_1600M_1024px_BF16_diffusers",
...     pag_applied_layers=["transformer_blocks.8"],
...     torch_dtype=torch.float32,
... )
>>> pipe.to("cuda")
>>> pipe.text_encoder.to(torch.bfloat16)
>>> pipe.transformer = pipe.transformer.to(torch.bfloat16)

>>> image = pipe(prompt='a cyberpunk cat with a neon sign that says "Sana"')[0]
>>> image[0].save("output.png")
```

#### encode_prompt[[diffusers.SanaPAGPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, clean_caption: bool = False, max_sequence_length: int = 300, complex_human_instruction: list[str] | None = None)
```

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

**매개변수:**

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

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

do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부

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

device : (`torch.device`, *선택 사항*): 생성된 임베딩을 배치할 torch device

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

negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩. Sana의 경우, "" 문자열의 임베딩이어야 합니다.

clean_caption (`bool`, 기본값은 `False`) : `True`인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.

max_sequence_length (`int`, 기본값 300) : 프롬프트에 사용할 최대 시퀀스 길이입니다.

complex_human_instruction (`list[str]`, 기본값은 `complex_human_instruction`) : `complex_human_instruction`이 비어 있지 않으면, 이 함수는 프롬프트에 복잡한 Human 지시를 사용합니다.

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

## SanaPipelineOutput[[diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput]]

#### diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput[[diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput]]

```python
diffusers.pipelines.sana.pipeline_output.SanaPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

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

**매개변수:**

images (`list[PIL.Image.Image]` 또는 `np.ndarray`) : 길이가 `batch_size`인 노이즈 제거된 PIL 이미지 목록 또는 `(batch_size, height, width, num_channels)` 모양의 numpy 배열. PIL 이미지 또는 numpy 배열은 diffusion 파이프라인의 노이즈 제거된 이미지를 나타냅니다.

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

