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

  
    
      
    
  

# HunyuanVideo

[HunyuanVideo](https://huggingface.co/papers/2412.03603)는 폐쇄형 비디오 파운데이션 모델과 경쟁할 수 있도록 설계된 13B 파라미터의 diffusion transformer 모델로, 더 넓은 커뮤니티의 접근을 가능하게 합니다. 이 모델은 "dual-stream to single-stream" 아키텍처를 사용하여 비디오와 텍스트 토큰을 먼저 별도로 처리한 후, 이를 연결하여 transformer에 입력함으로써 멀티모달 정보를 융합합니다. 이미지-텍스트 정렬이 우수하고, 이미지 세부 묘사 및 추론 능력이 뛰어나며, 사용자 프롬프트에 시스템 지시문을 추가하면 zero-shot learner로 사용할 수 있기 때문에 사전 학습된 멀티모달 대규모 언어 모델(MLLM)을 인코더로 사용합니다. 마지막으로, HunyuanVideo는 3D causal variational autoencoder를 사용하여 원래 해상도와 프레임 레이트의 비디오 데이터를 보다 효율적으로 처리합니다.

원본 HunyuanVideo 체크포인트는 모두 [Tencent](https://huggingface.co/tencent) 조직에서 찾을 수 있습니다.

> [!TIP]
> HunyuanVideo 모델에 대한 추가적인 비디오 생성 작업 예시를 보려면 오른쪽 사이드바의 해당 모델을 클릭하세요.
>
> 아래 예시에서는 가중치가 Diffusers와 호환되는 레이아웃으로 저장되어 있으므로 [hunyuanvideo-community](https://huggingface.co/hunyuanvideo-community)의 체크포인트를 사용합니다.

…

다양한 메모리 절약 기법에 대한 자세한 내용은 [메모리 사용량 줄이기](../../optimization/memory) 가이드를 참조하세요.

아래의 양자화된 HunyuanVideo 모델은 약 14GB의 VRAM이 필요합니다.

```py
import torch
from diffusers import AutoModel, HunyuanVideoPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.utils import export_to_video

# quantize weights to int4 with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
    quant_backend="bitsandbytes_4bit",
    quant_kwargs={
      "load_in_4bit": True,
      "bnb_4bit_quant_type": "nf4",
      "bnb_4bit_compute_dtype": torch.bfloat16
      },
    components_to_quantize="transformer"
)

pipeline = HunyuanVideoPipeline.from_pretrained(
    "hunyuanvideo-community/HunyuanVideo",
    quantization_config=pipeline_quant_config,
    dtype=torch.bfloat16,
)

# model-offloading and tiling
pipeline.enable_model_cpu_offload()
pipeline.vae.enable_tiling()

prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys."
video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
export_to_video(video, "output.mp4", fps=15)
```

[Compilation](../../optimization/fp16#torchcompile)은 첫 번째 호출 시 느리지만, 이후 pipeline 호출은 더 빠릅니다.

```py
import torch
from diffusers import AutoModel, HunyuanVideoPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.utils import export_to_video

# quantize weights to int4 with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
    quant_backend="bitsandbytes_4bit",
    quant_kwargs={
      "load_in_4bit": True,
      "bnb_4bit_quant_type": "nf4",
      "bnb_4bit_compute_dtype": torch.bfloat16
      },
    components_to_quantize="transformer"
)

pipeline = HunyuanVideoPipeline.from_pretrained(
    "hunyuanvideo-community/HunyuanVideo",
    quantization_config=pipeline_quant_config,
    dtype=torch.bfloat16,
)

# model-offloading and tiling
pipeline.enable_model_cpu_offload()
pipeline.vae.enable_tiling()

# torch.compile
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.transformer = torch.compile(
    pipeline.transformer, mode="max-autotune", fullgraph=True
)

prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys."
video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
export_to_video(video, "output.mp4", fps=15)
```

## The input is a single word "Notes".

참고

- HunyuanVideo는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.HunyuanVideoLoraLoaderMixin.load_lora_weights)를 통해 LoRA를 지원합니다.

  
  예제 코드 보기

  ```py
  import torch
  from diffusers import AutoModel, HunyuanVideoPipeline
  from diffusers.quantizers import PipelineQuantizationConfig
  from diffusers.utils import export_to_video

  # quantize weights to int4 with bitsandbytes
  pipeline_quant_config = PipelineQuantizationConfig(
      quant_backend="bitsandbytes_4bit",
      quant_kwargs={
        "load_in_4bit": True,
        "bnb_4bit_quant_type": "nf4",
        "bnb_4bit_compute_dtype": torch.bfloat16
        },
      components_to_quantize="transformer"
  )

  pipeline = HunyuanVideoPipeline.from_pretrained(
      "hunyuanvideo-community/HunyuanVideo",
      quantization_config=pipeline_quant_config,
      dtype=torch.bfloat16,
  )

  # load LoRA weights
  pipeline.load_lora_weights("https://huggingface.co/lucataco/hunyuan-steamboat-willie-10", adapter_name="steamboat-willie")
  pipeline.set_adapters("steamboat-willie", 0.9)

  # model-offloading and tiling
  pipeline.enable_model_cpu_offload()
  pipeline.vae.enable_tiling()

  # use "In the style of SWR" to trigger the LoRA
  prompt = """
  In the style of SWR. A black and white animated scene featuring a fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys.
  """
  video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
  export_to_video(video, "output.mp4", fps=15)
  ```

  

- 권장 추론 값은 아래 표를 참조하세요.

  | parameter | 권장 값 |
  |---|---|
  | 텍스트 인코더 dtype | `torch.float16` |
  | transformer dtype | `torch.bfloat16` |
  | VAE dtype | `torch.float16` |
  | `num_frames (k)` | 4 * `k` + 1 |

- 낮은 해상도의 비디오에는 더 낮은 `shift` 값(`2.0`에서 `5.0`), 높은 해상도의 이미지에는 더 높은 `shift` 값(`7.0`에서 `12.0`)을 사용해 보세요.

## HunyuanVideoPipeline[[diffusers.HunyuanVideoPipeline]]

#### diffusers.HunyuanVideoPipeline[[diffusers.HunyuanVideoPipeline]]

```python
diffusers.HunyuanVideoPipeline(text_encoder: LlamaModel, tokenizer: LlamaTokenizer, transformer: HunyuanVideoTransformer3DModel, vae: AutoencoderKLHunyuanVideo, scheduler: FlowMatchEulerDiscreteScheduler, text_encoder_2: CLIPTextModel, tokenizer_2: CLIPTokenizer)
```

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

**매개변수:**

text_encoder (`LlamaModel`) : [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).

tokenizer (`LlamaTokenizer`) : [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers)의 Tokenizer.

transformer ([HunyuanVideoTransformer3DModel](/docs/diffusers/main/ko/api/models/hunyuan_video_transformer_3d#diffusers.HunyuanVideoTransformer3DModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer입니다.

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

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/main/ko/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo)) : 비디오를 잠재 표현으로 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.

text_encoder_2 (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), 구체적으로 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 변형입니다.

tokenizer_2 (`CLIPTokenizer`) : [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) 클래스의 토크나이저.

HunyuanVideo를 사용한 텍스트-비디오 생성을 위한 Pipeline

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

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] = None, height: int = 720, width: int = 1280, num_frames: int = 129, num_inference_steps: int = 50, sigmas: list = None, true_cfg_scale: float = 1.0, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_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, attention_kwargs: dict[str, typing.Any] | None = 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'], prompt_template: dict = {'template': '<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: 1. The main content and theme of the video.2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.4. background environment, light, style and atmosphere.5. camera angles, movements, and transitions used in the video:<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 95}, max_sequence_length: int = 256)
```

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

**매개변수:**

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

prompt_2 (`str` 또는 `list[str]`, *선택 사항*) : `tokenizer_2`와 `text_encoder_2`에 전송할 프롬프트입니다. 정의되지 않은 경우 `prompt`가 대신 사용됩니다.

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

negative_prompt_2 (`str` 또는 `list[str]`, *선택*) : `tokenizer_2`와 `text_encoder_2`에 전송할 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우, 모든 text-encoder에서 `negative_prompt`가 사용됩니다.

height (`int`, 기본값 `720`) : 생성된 이미지의 픽셀 단위 높이입니다.

width (`int`, 기본값 `1280`) : 생성된 이미지의 픽셀 단위 너비입니다.

num_frames (`int`, 기본값 `129`) : 생성된 비디오의 프레임 수입니다.

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

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

true_cfg_scale (`float`, *선택 사항*, 기본값 1.0) : `true_cfg_scale` > 1이고 `negative_prompt`가 제공되면 True classifier-free guidance(guidance scale)가 활성화됩니다.

guidance_scale (`float`, 기본값 `6.0`) : `guidance_scale` > 1로 설정하면 임베디드 가이던스 스케일이 활성화됩니다. `guidance_scale` 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 `prompt`와 더 정렬된 이미지를 생성하도록 유도됩니다. 가이던스 디스틸레이션 모델은 `guidance_scale` > 1인 경우 진정한 클래스퍼-프리 가이던스를 근사합니다. 자세한 내용은 [논문](https://huggingface.co/papers/2210.03142)을 참고하세요.

num_videos_per_prompt (`int`, *선택 사항*, 기본값 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` 입력 인자에서 텍스트 임베딩이 생성됩니다.

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

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

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

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : `prompt_embeds`에 대한 Attention mask입니다. `prompt_embeds`를 직접 전달하는 경우 필수입니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택*) : `negative_prompt_embeds`에 대한 Attention mask입니다. `negative_prompt_embeds`가 직접 전달될 때 필수입니다.

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

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

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

prompt_template (`dict`, *선택 사항*) : 인코딩 전에 프롬프트를 포맷팅하는 데 사용되는 템플릿입니다. 기본값은 모델의 기본 템플릿입니다.

max_sequence_length (`int`, *선택 사항*, 기본값 256) : 프롬프트 인코더에 사용할 최대 시퀀스 길이입니다.

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

**반환값:** `~HunyuanVideoPipelineOutput` 또는 `tuple`

`return_dict`가 `True`인 경우 `HunyuanVideoPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 `bool` 목록인 `tuple`이 반환됩니다.

생성을 위한 pipeline의 호출 함수.

예:
```python
>>> import torch
>>> from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
>>> from diffusers.utils import export_to_video

>>> model_id = "hunyuanvideo-community/HunyuanVideo"
>>> transformer = HunyuanVideoTransformer3DModel.from_pretrained(
...     model_id, subfolder="transformer", torch_dtype=torch.bfloat16
... )
>>> pipe = HunyuanVideoPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.float16)
>>> pipe.vae.enable_tiling()
>>> pipe.to("cuda")

>>> output = pipe(
...     prompt="A cat walks on the grass, realistic",
...     height=320,
...     width=512,
...     num_frames=61,
...     num_inference_steps=30,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=15)
```

## HunyuanVideoPipelineOutput[[diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput]]

#### diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput[[diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput]]

```python
diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput(frames: Tensor)
```

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

**매개변수:**

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

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

