Diffusers documentation
HunyuanVideo
HunyuanVideo
HunyuanVideo는 폐쇄형 비디오 파운데이션 모델과 경쟁할 수 있도록 설계된 13B 파라미터의 diffusion transformer 모델로, 더 넓은 커뮤니티의 접근을 가능하게 합니다. 이 모델은 “dual-stream to single-stream” 아키텍처를 사용하여 비디오와 텍스트 토큰을 먼저 별도로 처리한 후, 이를 연결하여 transformer에 입력함으로써 멀티모달 정보를 융합합니다. 이미지-텍스트 정렬이 우수하고, 이미지 세부 묘사 및 추론 능력이 뛰어나며, 사용자 프롬프트에 시스템 지시문을 추가하면 zero-shot learner로 사용할 수 있기 때문에 사전 학습된 멀티모달 대규모 언어 모델(MLLM)을 인코더로 사용합니다. 마지막으로, HunyuanVideo는 3D causal variational autoencoder를 사용하여 원래 해상도와 프레임 레이트의 비디오 데이터를 보다 효율적으로 처리합니다.
원본 HunyuanVideo 체크포인트는 모두 Tencent 조직에서 찾을 수 있습니다.
HunyuanVideo 모델에 대한 추가적인 비디오 생성 작업 예시를 보려면 오른쪽 사이드바의 해당 모델을 클릭하세요.
아래 예시에서는 가중치가 Diffusers와 호환되는 레이아웃으로 저장되어 있으므로 hunyuanvideo-community의 체크포인트를 사용합니다.
…
다양한 메모리 절약 기법에 대한 자세한 내용은 메모리 사용량 줄이기 가이드를 참조하세요.
아래의 양자화된 HunyuanVideo 모델은 약 14GB의 VRAM이 필요합니다.
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은 첫 번째 호출 시 느리지만, 이후 pipeline 호출은 더 빠릅니다.
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()를 통해 LoRA를 지원합니다.
예제 코드 보기
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.float16transformer dtype torch.bfloat16VAE dtype torch.float16num_frames (k)4 * k+ 1낮은 해상도의 비디오에는 더 낮은
shift값(2.0에서5.0), 높은 해상도의 이미지에는 더 높은shift값(7.0에서12.0)을 사용해 보세요.
HunyuanVideoPipeline
클래스 diffusers.HunyuanVideoPipeline
< source >( text_encoder: LlamaModeltokenizer: LlamaTokenizertransformer: HunyuanVideoTransformer3DModelvae: AutoencoderKLHunyuanVideoscheduler: FlowMatchEulerDiscreteSchedulertext_encoder_2: CLIPTextModeltokenizer_2: CLIPTokenizer )
매개변수
- text_encoder (
LlamaModel) — Llava Llama3-8B. - tokenizer (
LlamaTokenizer) — Llava Llama3-8B의 토크나이저. - transformer (HunyuanVideoTransformer3DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer입니다.
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러. - vae (AutoencoderKLHunyuanVideo) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- text_encoder_2 (
CLIPTextModel) — 구체적으로 clip-vit-large-patch14 변형을 사용하는 CLIP입니다. - tokenizer_2 (
CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저.
HunyuanVideo를 사용한 텍스트-비디오 생성을 위한 Pipeline
이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( prompt: str | list[str] = Noneprompt_2: str | list[str] = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] = Noneheight: int = 720width: int = 1280num_frames: int = 129num_inference_steps: int = 50sigmas: list = Nonetrue_cfg_scale: float = 1.0guidance_scale: float = 6.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_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 ) → ~HunyuanVideoPipelineOutput or tuple
매개변수
- 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-distilled 모델은
guidance_scale> 1인 경우 true classifer-free guidance를 근사합니다. 자세한 내용은 논문을 참고하세요. - num_videos_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한torch.Generator. - latents (
torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서를 생성합니다. - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면prompt입력 인자에서 텍스트 임베딩이 생성됩니다. - pooled_prompt_embeds (
torch.FloatTensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.FloatTensor, optional) — 미리 생성된 부정 텍스트 임베딩입니다. 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. e.g. 제공되지 않으면negative_prompt입력 인수에서 negative_prompt_embeds가 생성됩니다. - negative_pooled_prompt_embeds (
torch.FloatTensor, 선택) — 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 pooled negative_prompt_embeds가 생성됩니다. - prompt_attention_mask (
torch.Tensor, 선택 사항) —prompt_embeds에 대한 어텐션 마스크입니다.prompt_embeds를 직접 전달할 때 필수입니다. - negative_prompt_attention_mask (
torch.Tensor, 선택 사항) —negative_prompt_embeds에 대한 어텐션 마스크입니다.negative_prompt_embeds를 직접 전달할 때 필수입니다. - output_type (
str, 선택 사항, 기본값"pil") — 생성된 이미지의 출력 형식입니다.PIL.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신HunyuanVideoPipelineOutput를 반환할지 여부. - attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - prompt_template (
dict, 선택 사항) — 인코딩 전에 프롬프트를 포맷팅하는 데 사용되는 템플릿입니다. 기본값은 모델의 기본 템플릿입니다. - max_sequence_length (
int, 선택 사항, 기본값 256) — 프롬프트 인코더에 사용할 최대 시퀀스 길이입니다. - callback_on_step_end (
Callable,PipelineCallback,MultiPipelineCallbacks, 선택 사항) — 추론 중 각 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가 반환되고, 그렇지 않으면 tuple이 반환됩니다. 이 튜플의 첫 번째 요소는 생성된 이미지 목록이고, 두 번째 요소는 각 생성된 이미지에 “not-safe-for-work”(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 bool 목록입니다.
생성을 위한 pipeline의 호출 함수.
예:
>>> 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
< source >( frames: Tensor )
HunyuanVideo 파이프라인의 출력 클래스입니다.