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

# Sana-Video

  
  

NVIDIA와 MIT HAN Lab의 Junsong Chen, Yuyang Zhao, Jincheng Yu, Ruihang Chu, Junyu Chen, Shuai Yang, Xianbang Wang, Yicheng Pan, Daquan Zhou, Huan Ling, Haozhe Liu, Hongwei Yi, Hao Zhang, Muyang Li, Yukang Chen, Han Cai, Sanja Fidler, Ping Luo, Song Han, Enze Xie가 발표한 [SANA-Video: Efficient Video Generation with Block Linear Diffusion Transformer](https://huggingface.co/papers/2509.24695)

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

*SANA-Video를 소개합니다. SANA-Video는 최대 720x1280 해상도와 분 단위 길이의 영상을 효율적으로 생성할 수 있는 소형 diffusion 모델입니다. SANA-Video는 놀라울 정도로 빠른 속도로 텍스트-영상 정합성이 강한 고해상도, 고품질, 장시간 영상을 합성하며, RTX 5090 GPU에 배포할 수 있습니다. 효율적이고 효과적이며 긴 영상 생성을 보장하는 두 가지 핵심 설계가 있습니다. (1) Linear DiT: 영상 생성에서 처리되는 토큰 수가 많기 때문에, 기존 attention보다 효율적인 linear attention을 핵심 연산으로 활용합니다. (2) Block Linear Attention을 위한 Constant-Memory KV cache: linear attention의 누적 특성에서 파생된 constant-memory state를 사용하여 장시간 영상 생성을 위한 block-wise autoregressive 접근법을 설계했습니다. 이 KV cache는 고정된 메모리 비용으로 Linear DiT에 전역 컨텍스트를 제공하여, 기존 KV cache의 필요성을 제거하고 효율적인 분 단위 영상 생성을 가능하게 합니다. 또한, 효과적인 데이터 필터와 모델 학습 전략을 탐구하여 64개의 H100 GPU에서 학습 비용을 12일로 줄였으며, 이는 MovieGen 비용의 1%에 불과합니다. 이러한 낮은 비용에도 불구하고, SANA-Video는 측정된 지연 시간에서 16배 더 빠르면서 최신 state-of-the-art 소형 diffusion 모델(예: Wan 2.1-1.3B 및 SkyReel-V2-1.3B)과 경쟁하는 성능을 달성합니다. 게다가, SANA-Video는 NVFP4 정밀도로 RTX 5090 GPU에 배포할 수 있으며, 5초 720p 영상 생성의 추론 속도를 71초에서 29초로 단축시켜 2.4배의 속도 향상을 이룹니다. 요약하자면, SANA-Video는 저비용 고품질 영상 생성을 가능하게 합니다. [this https URL](https://github.com/NVlabs/SANA).*

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

사용 가능한 모델:

| 모델 | 권장 dtype |
|:-----:|:-----------------:|
| [`Efficient-Large-Model/SANA-Video_2B_480p_diffusers`](https://huggingface.co/Efficient-Large-Model/ANA-Video_2B_480p_diffusers) | `torch.bfloat16` |

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

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

## 생성 파이프라인

`

…

```python
pipe = SanaVideoPipeline.from_pretrained(
    "Efficient-Large-Model/SANA-Video_2B_480p_diffusers", 
    dtype=torch.bfloat16,
)
pipe.text_encoder.to(torch.bfloat16)
pipe.vae.to(torch.float32)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
motion_scale = 30
motion_prompt = f" motion score: {motion_scale}."
prompt = prompt + motion_prompt

video = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    height=480,
    width=832,
    frames=81,
    guidance_scale=6,
    num_inference_steps=50,
    generator=torch.Generator(device="cuda").manual_seed(0),
).frames[0]

export_to_video(video, "sana_video.mp4", fps=16)
```

…

```python
pipe = SanaImageToVideoPipeline.from_pretrained(
    "Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
    dtype=torch.bfloat16,
)
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(pipe.scheduler.config, flow_shift=8.0)
pipe.vae.to(torch.float32)
pipe.text_encoder.to(torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = load_image("https://raw.githubusercontent.com/NVlabs/Sana/refs/heads/main/asset/samples/i2v-1.png")
prompt = "A woman stands against a stunning sunset backdrop, her long, wavy brown hair gently blowing in the breeze. She wears a sleeveless, light-colored blouse with a deep V-neckline, which accentuates her graceful posture. The warm hues of the setting sun cast a golden glow across her face and hair, creating a serene and ethereal atmosphere. The background features a blurred landscape with soft, rolling hills and scattered clouds, adding depth to the scene. The camera remains steady, capturing the tranquil moment from a medium close-up angle."
negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
motion_scale = 30
motion_prompt = f" motion score: {motion_scale}."
prompt = prompt + motion_prompt

motion_scale = 30.0

video = pipe(
    image=image,
    prompt=prompt,
    negative_prompt=negative_prompt,
    height=480,
    width=832,
    frames=81,
    guidance_scale=6,
    num_inference_steps=50,
    generator=torch.Generator(device="cuda").manual_seed(0),
).frames[0]

export_to_video(video, "sana-i2v.mp4", fps=16)
```

## 양자화

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

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

```py
import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, SanaVideoTransformer3DModel, SanaVideoPipeline
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, AutoModel

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

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

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

model_score = 30
prompt = "Evening, backlight, side lighting, soft light, high contrast, mid-shot, centered composition, clean solo shot, warm color. A young Caucasian man stands in a forest, golden light glimmers on his hair as sunlight filters through the leaves. He wears a light shirt, wind gently blowing his hair and collar, light dances across his face with his movements. The background is blurred, with dappled light and soft tree shadows in the distance. The camera focuses on his lifted gaze, clear and emotional."
negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
motion_prompt = f" motion score: {model_score}."
prompt = prompt + motion_prompt

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    height=480,
    width=832,
    num_frames=81,
    guidance_scale=6.0,
    num_inference_steps=50
).frames[0]
export_to_video(output, "sana-video-output.mp4", fps=16)
```

## SanaVideoPipeline[[diffusers.SanaVideoPipeline]]

#### diffusers.SanaVideoPipeline[[diffusers.SanaVideoPipeline]]

```python
diffusers.SanaVideoPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: diffusers.models.autoencoders.autoencoder_dc.AutoencoderDC | diffusers.models.autoencoders.autoencoder_kl_ltx2.AutoencoderKLLTX2Video | diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan, transformer: SanaVideoTransformer3DModel, scheduler: DPMSolverMultistepScheduler)
```

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

**매개변수:**

tokenizer (`GemmaTokenizer` 또는 `GemmaTokenizerFast`) : 프롬프트를 토큰화하는 데 사용되는 토크나이저.

text_encoder (`Gemma2PreTrainedModel`) : 입력 프롬프트를 인코딩하는 텍스트 인코더 모델입니다.

vae ([`AutoencoderKLWan`, `AutoencoderDC`, 또는 `AutoencoderKLLTX2Video`]) : 비디오를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.

transformer ([SanaVideoTransformer3DModel](/docs/diffusers/main/ko/api/models/sana_video_transformer3d#diffusers.SanaVideoTransformer3DModel)) : 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer입니다.

scheduler ([DPMSolverMultistepScheduler](/docs/diffusers/main/ko/api/schedulers/multistep_dpm_solver#diffusers.DPMSolverMultistepScheduler)) : `transformer`와 함께 사용하여 인코딩된 비디오 잠재를 디노이즈하는 데 사용되는 스케줄러입니다.

[Sana](https://huggingface.co/papers/2509.24695)를 사용한 텍스트-비디오 생성을 위한 Pipeline입니다. 이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 pipeline에 대해 구현된 일반적 방법(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, height: int = 480, width: int = 832, frames: int = 81, 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 video generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, motion, and temporal relationships to create vivid and dynamic 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 slowly settling into a curled position, peacefully falling asleep on a warm sunny windowsill, with gentle sunlight filtering through surrounding pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps gradually lighting up, a diverse crowd of people in colorful clothing walking past, and a double-decker bus smoothly 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_video/pipeline_sana_video.py#L712)

**매개변수:**

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

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

num_inference_steps (`int`, *선택 사항*, 기본값 50) : 디노이징 단계의 수입니다. 디노이징 단계를 늘리면 추론 속도가 느려지는 대신 일반적으로 더 높은 품질의 비디오를 얻을 수 있습니다.

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_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수입니다.

height (`int`, *선택 사항*, 기본값 480) : 생성된 비디오의 픽셀 단위 높이입니다.

width (`int`, *선택 사항*, 기본값 832) : 생성된 비디오의 픽셀 단위 너비입니다.

frames (`int`, *선택 사항*, 기본값 81) : 생성된 비디오의 프레임 수입니다.

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"`) : 생성된 비디오의 출력 형식입니다. mp4 또는 `np.array` 중 하나를 선택합니다.

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

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_480_BIN` 또는 `ASPECT_RATIO_720_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.

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

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

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

예:
```py
>>> import torch
>>> from diffusers import SanaVideoPipeline
>>> from diffusers.utils import export_to_video

>>> pipe = SanaVideoPipeline.from_pretrained("Efficient-Large-Model/SANA-Video_2B_480p_diffusers")
>>> pipe.transformer.to(torch.bfloat16)
>>> pipe.text_encoder.to(torch.bfloat16)
>>> pipe.vae.to(torch.float32)
>>> pipe.to("cuda")
>>> motion_score = 30

>>> prompt = "Evening, backlight, side lighting, soft light, high contrast, mid-shot, centered composition, clean solo shot, warm color. A young Caucasian man stands in a forest, golden light glimmers on his hair as sunlight filters through the leaves. He wears a light shirt, wind gently blowing his hair and collar, light dances across his face with his movements. The background is blurred, with dappled light and soft tree shadows in the distance. The camera focuses on his lifted gaze, clear and emotional."
>>> negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
>>> motion_prompt = f" motion score: {motion_score}."
>>> prompt = prompt + motion_prompt

>>> output = pipe(
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     height=480,
...     width=832,
...     frames=81,
...     guidance_scale=6,
...     num_inference_steps=50,
...     generator=torch.Generator(device="cuda").manual_seed(42),
... ).frames[0]

>>> export_to_video(output, "sana-video-output.mp4", fps=16)
```

#### encode_prompt[[diffusers.SanaVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_videos_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_video/pipeline_sana_video.py#L303)

**매개변수:**

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_videos_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 지시를 사용합니다.

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

## SanaImageToVideoPipeline[[diffusers.SanaImageToVideoPipeline]]

#### diffusers.SanaImageToVideoPipeline[[diffusers.SanaImageToVideoPipeline]]

```python
diffusers.SanaImageToVideoPipeline(tokenizer: GemmaTokenizer, text_encoder: Gemma2PreTrainedModel, vae: diffusers.models.autoencoders.autoencoder_dc.AutoencoderDC | diffusers.models.autoencoders.autoencoder_kl_ltx2.AutoencoderKLLTX2Video | diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan, transformer: SanaVideoTransformer3DModel, scheduler: FlowMatchEulerDiscreteScheduler)
```

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

**매개변수:**

tokenizer (`GemmaTokenizer` 또는 `GemmaTokenizerFast`) : 프롬프트를 토큰화하는 데 사용되는 토크나이저.

text_encoder (`Gemma2PreTrainedModel`) : 입력 프롬프트를 인코딩하는 텍스트 인코더 모델입니다.

vae ([`AutoencoderKLWan`, `AutoencoderDC`, 또는 `AutoencoderKLLTX2Video`]) : 비디오를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.

transformer ([SanaVideoTransformer3DModel](/docs/diffusers/main/ko/api/models/sana_video_transformer3d#diffusers.SanaVideoTransformer3DModel)) : 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer입니다.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`와 함께 사용하여 인코딩된 비디오 잠재를 디노이즈하는 데 사용되는 스케줄러입니다.

[Sana](https://huggingface.co/papers/2509.24695)를 사용한 이미지/텍스트-투-비디오 생성을 위한 Pipeline입니다. 이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 pipeline에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

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

```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], prompt: str | list[str] = None, negative_prompt: str = '', num_inference_steps: int = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, height: int = 480, width: int = 832, frames: int = 81, 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 video generation. Evaluate the level of detail in the user prompt:", '- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, motion, and temporal relationships to create vivid and dynamic 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 slowly settling into a curled position, peacefully falling asleep on a warm sunny windowsill, with gentle sunlight filtering through surrounding pots of blooming red flowers.', '- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps gradually lighting up, a diverse crowd of people in colorful clothing walking past, and a double-decker bus smoothly 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_video/pipeline_sana_video_i2v.py#L739)

**매개변수:**

image (`PipelineImageInput`) : 비디오 생성을 조건화할 입력 이미지입니다. 생성된 비디오의 첫 번째 프레임은 이 이미지에 조건화됩니다.

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

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

num_inference_steps (`int`, *선택 사항*, 기본값 50) : 디노이징 단계의 수입니다. 디노이징 단계를 늘리면 추론 속도가 느려지는 대신 일반적으로 더 높은 품질의 비디오를 얻을 수 있습니다.

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_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수입니다.

height (`int`, *선택 사항*, 기본값 480) : 생성된 비디오의 픽셀 단위 높이입니다.

width (`int`, *선택 사항*, 기본값 832) : 생성된 비디오의 픽셀 단위 너비입니다.

frames (`int`, *선택 사항*, 기본값 81) : 생성된 비디오의 프레임 수입니다.

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"`) : 생성된 비디오의 출력 형식입니다. mp4 또는 `np.array` 중 하나를 선택합니다.

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

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_480_BIN` 또는 `ASPECT_RATIO_720_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.

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

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

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

예:
```py
>>> import torch
>>> from diffusers import SanaImageToVideoPipeline
>>> from diffusers.utils import export_to_video, load_image

>>> pipe = SanaImageToVideoPipeline.from_pretrained("Efficient-Large-Model/SANA-Video_2B_480p_diffusers")
>>> pipe.transformer.to(torch.bfloat16)
>>> pipe.text_encoder.to(torch.bfloat16)
>>> pipe.vae.to(torch.float32)
>>> pipe.to("cuda")
>>> motion_score = 30

>>> prompt = "A woman stands against a stunning sunset backdrop, her long, wavy brown hair gently blowing in the breeze. She wears a sleeveless, light-colored blouse with a deep V-neckline, which accentuates her graceful posture. The warm hues of the setting sun cast a golden glow across her face and hair, creating a serene and ethereal atmosphere. The background features a blurred landscape with soft, rolling hills and scattered clouds, adding depth to the scene. The camera remains steady, capturing the tranquil moment from a medium close-up angle."
>>> negative_prompt = "A chaotic sequence with misshapen, deformed limbs in heavy motion blur, sudden disappearance, jump cuts, jerky movements, rapid shot changes, frames out of sync, inconsistent character shapes, temporal artifacts, jitter, and ghosting effects, creating a disorienting visual experience."
>>> motion_prompt = f" motion score: {motion_score}."
>>> prompt = prompt + motion_prompt
>>> image = load_image("https://raw.githubusercontent.com/NVlabs/Sana/refs/heads/main/asset/samples/i2v-1.png")

>>> output = pipe(
...     image=image,
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     height=480,
...     width=832,
...     frames=81,
...     guidance_scale=6,
...     num_inference_steps=50,
...     generator=torch.Generator(device="cuda").manual_seed(42),
... ).frames[0]

>>> export_to_video(output, "sana-ti2v-output.mp4", fps=16)
```

#### encode_prompt[[diffusers.SanaImageToVideoPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_videos_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_video/pipeline_sana_video_i2v.py#L301)

**매개변수:**

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_videos_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 지시를 사용합니다.

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

## SanaVideoPipelineOutput[[diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput]]

#### diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput[[diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput]]

```python
diffusers.pipelines.sana_video.pipeline_output.SanaVideoPipelineOutput(frames: Tensor)
```

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

**매개변수:**

frames (`torch.Tensor`, `np.ndarray`, 또는 list[list[PIL.Image.Image]]) : 비디오 출력 목록 - `batch_size,` 길이의 중첩 목록일 수 있으며, 각 하위 목록에는 `num_frames.` 길이의 노이즈 제거된 PIL 이미지 시퀀스가 포함됩니다. 또한 `(batch_size, num_frames, channels, height, width)` 형상의 NumPy 배열 또는 Torch 텐서일 수도 있습니다.

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

