Buckets:

mishig's picture
|
download
raw
104 kB
#
# Apache License, Version 2.0("라이선스")에 따라 라이선스가 부여됩니다.
# 이 파일은 라이선스에 따라만 사용할 수 있습니다.
# 라이선스 사본은 다음에서 가져올 수 있습니다
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 적용 가능한 법률에 의해 요구되거나 서면으로 합의되지 않는 한, 소프트웨어
# 라이선스에 따라 배포되는 본 소프트웨어는 "있는 그대로"
# 명시적이든 묵시적이든 어떠한 종류의 보증이나 조건도 없이 제공됩니다.
# 권한을 관리하는 특정 언어에 대한 라이선스를 참조하세요
# 라이선스 하의 제한 사항. -->
# Wan
Wan 팀의 [Wan-2.1](https://huggingface.co/papers/2503.20314).
*이 보고서는 비디오 생성의 한계를 확장하기 위해 설계된 포괄적이고 오픈된 비디오 파운데이션 모델 스위트인 Wan을 소개합니다. 주류 diffusion transformer 패러다임 위에 구축된 Wan은 새로운 VAE, 확장 가능한 사전 학습 전략, 대규모 데이터 큐레이션, 자동화 평가 지표 등 일련의 혁신을 통해 생성 기능에서 상당한 진전을 이루었습니다. 이러한 기여들은 모델의 성능과 다용도성을 종합적으로 향상시킵니다. 구체적으로 Wan은 네 가지 주요 특징을 지닙니다. 선도적 성능: 수십억 개의 이미지와 비디오로 구성된 방대한 데이터셋에서 학습된 Wan의 14B 모델은 데이터와 모델 크기에 대한 비디오 생성의 스케일링 법칙을 입증합니다. 이는 여러 내부 및 외부 벤치마크에서 기존 오픈소스 모델은 물론 최첨단 상용 솔루션을 일관되게 능가하며, 명확하고 상당한 성능 우위를 보여줍니다. 포괄성: Wan은 효율성과 효과성을 각각 위해 1.3B와 14B 파라미터의 두 가지 유능한 모델을 제공합니다. 또한 이미지-투-비디오, 지시어 기반 비디오 편집, 개인 비디오 생성을 포함한 최대 8가지 작업을 아우르는 여러 다운스트림 애플리케이션을 지원합니다. 소비자 등급 효율성: 1.3B 모델은 8.19 GB의 VRAM만 필요로 하는 뛰어난 자원 효율성을 보여주며, 다양한 소비자 등급 GPU와 호환됩니다. 개방성: 비디오 생성 커뮤니티의 성장을 촉진하기 위해 Wan의 전체 시리즈, 즉 소스 코드와 모든 모델을 오픈소스로 공개합니다. 이러한 개방성은 산업계의 비디오 제작 창의적 가능성을 크게 확장하고, 학계에 고품질 비디오 파운데이션 모델을 제공하고자 합니다. 모든 코드와 모델은 [이 https URL](https://github.com/Wan-Video/Wan2.1)에서 사용할 수 있습니다.*
모든 원본 Wan2.1 체크포인트는 [Wan-AI](https://huggingface.co/Wan-AI) 조직에서 찾을 수 있습니다.
다음 Wan 모델들이 Diffusers에서 지원됩니다:
- [Wan 2.1 T2V 1.3B](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B-Diffusers)
- [Wan 2.1 T2V 14B](https://huggingface.co/Wan-AI/Wan2.1-T2V-14B-Diffusers)
- [Wan 2.1 I2V 14B - 480P](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-480P-Diffusers)
- [Wan 2.1 I2V 14B - 720P](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-720P-Diffusers)
- [Wan 2.1 FLF2V 14B - 720P](https://huggingface.co/Wan-AI/Wan2.1-FLF2V-14B-720P-diffusers)
- [Wan 2.1 VACE 1.3B](https://huggingface.co/Wan-AI/Wan2.1-VACE-1.3B-diffusers)
- [Wan 2.1 VACE 14B](https://huggingface.co/Wan-AI/Wan2.1-VACE-14B-diffusers)
- [Wan 2.2 T2V 14B](https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B-Diffusers)
- [Wan 2.2 I2V 14B](https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B-Diffusers)
- [Wan 2.2 TI2V 5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B-Diffusers)
- [Wan 2.2 Animate 14B](https://huggingface.co/Wan-AI/Wan2.2-Animate-14B-Diffusers)
> [!TIP]
> Wan 모델에 대한 추가 비디오 생성 예제는 오른쪽 사이드바에서 확인하세요.
### 텍스트-투-비디오 생성
…
다양한 메모리 절약 기법에 대한 자세한 내용은 [메모리 사용량 줄이기](../../optimization/memory) 가이드를 참조하세요.
아래의 Wan2.1 텍스트-비디오 모델은 약 13GB의 VRAM이 필요합니다.
```py
# pip install ftfy
import torch
import numpy as np
from diffusers import AutoModel, WanPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.hooks.group_offloading import apply_group_offloading
from diffusers.utils import export_to_video, load_image
from transformers import UMT5EncoderModel
text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", dtype=torch.bfloat16)
vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32)
transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", dtype=torch.bfloat16)
# group-offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
apply_group_offloading(text_encoder,
onload_device=onload_device,
offload_device=offload_device,
offload_type="block_level",
num_blocks_per_group=4
)
transformer.enable_group_offload(
onload_device=onload_device,
offload_device=offload_device,
offload_type="leaf_level",
use_stream=True
)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers",
vae=vae,
transformer=transformer,
text_encoder=text_encoder,
dtype=torch.bfloat16
)
pipeline.to("cuda") # or "mps", "xpu", "cpu"
prompt = """
The camera rushes from far to near in a low-angle shot,
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""
output = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
num_frames=81,
guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
[Compilation](../../optimization/fp16#torchcompile)은 첫 번째 호출 시 느리지만, 이후 [Caching](../../optimization/cache)은 중간 결과를 저장하고 재사용하여 추론 속도를 높이는 데 도움이 될 수 있습니다.
```py
# pip install ftfy
import torch
import numpy as np
from diffusers import AutoModel, WanPipeline
from diffusers.hooks.group_offloading import apply_group_offloading
from diffusers.utils import export_to_video, load_image
from transformers import UMT5EncoderModel
text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", dtype=torch.bfloat16)
vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32)
transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", dtype=torch.bfloat16)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-14B-Diffusers",
vae=vae,
transformer=transformer,
text_encoder=text_encoder,
dtype=torch.bfloat16
)
pipeline.to("cuda") # or "mps", "xpu", "cpu"
# torch.compile
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.transformer = torch.compile(
pipeline.transformer, mode="max-autotune", fullgraph=True
)
prompt = """
The camera rushes from far to near in a low-angle shot,
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""
output = pipeline(
prompt=prompt,
negative_prompt=negative_prompt,
num_frames=81,
guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
### 첫 번째-마지막 프레임-투-비디오 생성
…
```python
import numpy as np
import torch
import torchvision.transforms.functional as TF
from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
from diffusers.utils import export_to_video, load_image
from transformers import CLIPVisionModel
model_id = "Wan-AI/Wan2.1-FLF2V-14B-720P-diffusers"
image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", dtype=torch.float32)
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanImageToVideoPipeline.from_pretrained(
model_id, vae=vae, image_encoder=image_encoder, dtype=torch.bfloat16
)
pipe.to("cuda") # or "mps", "xpu", "cpu"
first_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png")
last_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png")
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
def center_crop_resize(image, height, width):
# Calculate resize ratio to match first frame dimensions
resize_ratio = max(width / image.width, height / image.height)
# Resize the image
width = round(image.width * resize_ratio)
height = round(image.height * resize_ratio)
size = [width, height]
image = TF.center_crop(image, size)
return image, height, width
first_frame, height, width = aspect_ratio_resize(first_frame, pipe)
if last_frame.size != first_frame.size:
last_frame, _, _ = center_crop_resize(last_frame, height, width)
prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
output = pipe(
image=first_frame, last_image=last_frame, prompt=prompt, height=height, width=width, guidance_scale=5.5
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
### Any-to-Video 제어 가능한 생성
Wan VACE는 제어 가능한 비디오 생성을 달성하는 다양한 생성 기법을 지원합니다. 일부 기능은 다음과 같습니다:
- Control to Video (Depth, Pose, Sketch, Flow, Grayscale, Scribble, Layout, Boundary Box 등). 컨트롤 비디오를 얻기 위해 비디오를 전처리하는 데 권장되는 라이브러리: [huggingface/controlnet_aux]()
- 이미지/비디오에서 비디오로 (첫 프레임, 마지막 프레임, 시작 클립, 종료 클립, 랜덤 클립)
- Inpainting과 Outpainting
- Subject to Video (얼굴, 객체, 캐릭터 등)
- Composition to Video (참조, 애니메이션, 교체, 확장, 이동 등)
이 [pull request](https://github.com/huggingface/diffusers/pull/11582)에 포함된 코드 스니펫은 controllability 신호를 사용하여 비디오를 생성하는 몇 가지 예를 보여줍니다.
VACE 파이프라인의 입력을 준비할 때 기억해야 할 일반적인 원칙은, 조건부 생성에 사용할 입력 이미지나 비디오 프레임에는 검은색으로 된 대응하는 마스크가 있어야 한다는 것입니다. 검은색 마스크는 해당 영역에 새로운 콘텐츠를 생성하지 않고, 생성 과정의 조건으로만 해당 부분을 사용한다는 것을 의미합니다. 모델이 생성해야 하는 부분/프레임의 경우, 마스크는 흰색이어야 합니다.
### Wan-Animate: 통합 캐릭터 애니메이션 및 교체와 전방위 복제
Wan 팀의 [Wan-Animate](https://huggingface.co/papers/2509.14055).
*Wan-Animate는 캐릭터 애니메이션 및 교체에 대한 통합 프레임워크입니다. 캐릭터 이미지와 참조 비디오가 주어지면, Wan-Animate는 비디오 속 캐릭터의 표정과 움직임을 정밀하게 복제하여 캐릭터를 애니메이션화하고, 고품질 캐릭터 비디오를 생성할 수 있습니다. 또는, 애니메이션화된 캐릭터를 참조 비디오에 통합하여 원래 캐릭터를 교체할 수 있으며, 장면의 조명과 색조를 복제하여 매끄러운 환경 통합을 달성합니다. Wan-Animate는 Wan 모델 위에 구축되었습니다. 캐릭터 애니메이션 작업에 적용하기 위해, 참조 조건과 생성 영역을 구별하기 위한 수정된 입력 패러다임을 사용합니다. 이 설계는 여러 작업을 공통된 기호 표현으로 통합합니다. 공간적으로 정렬된 스켈레톤 신호를 사용하여 신체 움직임을 복제하고, 소스 이미지에서 추출한 암시적 얼굴 특징을 사용하여 표정을 재연함으로써, 높은 제어성과 표현력을 갖춘 캐릭터 비디오 생성을 가능하게 합니다. 또한, 캐릭터 교체 시 환경 통합을 강화하기 위해 보조 Relighting LoRA를 개발했습니다. 이 모듈은 캐릭터의 외형 일관성을 유지하면서 적절한 환경 조명과 색조를 적용합니다. 실험 결과는 Wan-Animate가 최첨단 성능을 달성함을 보여줍니다. 모델 가중치와 소스 코드를 오픈소스로 공개하는 것을 약속드립니다.*
프로젝트 페이지: https://humanaigc.github.io/wan-animate
이 모델은 주로 [M. Tolga Cangöz](https://github.com/tolgacangoz)에 의해 기여되었습니다.
#### 사용
Wan-Animate 파이프라인은 두 가지 운영 모드를 지원합니다:
1. **애니메이션 모드**(기본값): 참조 비디오의 움직임과 표정을 기반으로 캐릭터 이미지를 애니메이션화합니다
2. **교체 모드**: 배경 영상의 캐릭터를 새로운 캐릭터로 교체하되, 장면을 유지합니다
##### 필수 조건
pipeline를 사용하기 전에 참조 비디오를 전처리하여 다음을 추출해야 합니다:
- **포즈 비디오**: 신체 동작을 나타내는 골격 키포인트를 포함
- **얼굴 비디오**: 표정 제어를 위한 얼굴 특징 표현을 포함
교체 모드에는 추가로 다음이 필요합니다:
- **배경 비디오**: 해당 장면을 포함하는 원본 비디오
- **마스크 비디오**: 콘텐츠 생성 영역(흰색)과 원본 유지 영역(검은색)을 나타내는 마스크
> [!NOTE]
> `pose_video`와 같은 입력에는 원본 비디오를 사용해서는 안 됩니다. 파이프라인은 이러한 입력이 적절한 정보를 추출하도록 사전 처리되어 있을 것을 기대합니다. 이러한 입력을 준비하기 위한 사전 처리 스크립트는 [원본 Wan-Animate 저장소](https://github.com/Wan-Video/Wan2.2?tab=readme-ov-file#1-preprocessing)에서 사용할 수 있습니다. 이러한 사전 처리 단계의 Diffusers 통합은 향후 릴리스에서 계획되어 있습니다.
아래 예제는 Wan-Animate 파이프라인을 사용하는 방법을 보여줍니다:
```python
import numpy as np
import torch
from diffusers import AutoencoderKLWan, WanAnimatePipeline
from diffusers.utils import export_to_video, load_image, load_video
model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanAnimatePipeline.from_pretrained(model_id, vae=vae, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
# Load character image and preprocessed videos
image = load_image("path/to/character.jpg")
pose_video = load_video("path/to/pose_video.mp4") # Preprocessed skeletal keypoints
face_video = load_video("path/to/face_video.mp4") # Preprocessed facial features
# Resize image to match VAE constraints
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
image, height, width = aspect_ratio_resize(image, pipe)
prompt = "A person dancing energetically in a studio with dynamic lighting and professional camera work"
negative_prompt = "blurry, low quality, distorted, deformed, static, poorly drawn"
# Generate animated video
output = pipe(
image=image,
pose_video=pose_video,
face_video=face_video,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
segment_frame_length=77,
guidance_scale=1.0,
mode="animate", # Animation mode (default)
).frames[0]
export_to_video(output, "animated_character.mp4", fps=30)
```
```python
import numpy as np
import torch
from diffusers import AutoencoderKLWan, WanAnimatePipeline
from diffusers.utils import export_to_video, load_image, load_video
model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanAnimatePipeline.from_pretrained(model_id, vae=vae, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
# Load all required inputs for replacement mode
image = load_image("path/to/new_character.jpg")
pose_video = load_video("path/to/pose_video.mp4") # Preprocessed skeletal keypoints
face_video = load_video("path/to/face_video.mp4") # Preprocessed facial features
background_video = load_video("path/to/background_video.mp4") # Original scene
mask_video = load_video("path/to/mask_video.mp4") # Black: preserve, White: generate
# Resize image to match video dimensions
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
image, height, width = aspect_ratio_resize(image, pipe)
prompt = "A person seamlessly integrated into the scene with consistent lighting and environment"
negative_prompt = "blurry, low quality, inconsistent lighting, floating, disconnected from scene"
# Replace character in background video
output = pipe(
image=image,
pose_video=pose_video,
face_video=face_video,
background_video=background_video,
mask_video=mask_video,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
segment_frame_lengths=77,
guidance_scale=1.0,
mode="replace", # Replacement mode
).frames[0]
export_to_video(output, "character_replaced.mp4", fps=30)
```
```python
import numpy as np
import torch
from diffusers import AutoencoderKLWan, WanAnimatePipeline
from diffusers.utils import export_to_video, load_image, load_video
model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanAnimatePipeline.from_pretrained(model_id, vae=vae, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = load_image("path/to/character.jpg")
pose_video = load_video("path/to/pose_video.mp4")
face_video = load_video("path/to/face_video.mp4")
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
image, height, width = aspect_ratio_resize(image, pipe)
prompt = "A person dancing energetically in a studio"
negative_prompt = "blurry, low quality"
# Advanced: Use temporal guidance and custom callback
def callback_fn(pipe, step_index, timestep, callback_kwargs):
# You can modify latents or other tensors here
print(f"Step {step_index}, Timestep {timestep}")
return callback_kwargs
output = pipe(
image=image,
pose_video=pose_video,
face_video=face_video,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
segment_frame_length=77,
num_inference_steps=50,
guidance_scale=5.0,
prev_segment_conditioning_frames=5, # Use 5 frames for temporal guidance (1 or 5 recommended)
callback_on_step_end=callback_fn,
callback_on_step_end_tensor_inputs=["latents"],
).frames[0]
export_to_video(output, "animated_advanced.mp4", fps=30)
```
#### 주요 매개변수
- **mode**: `"animate"`(기본값) 또는 `"replace"` 중 선택
- **prev_segment_conditioning_frames**: 시간적 안내를 위한 프레임 수 (1 또는 5 권장). 5를 사용하면 시간적 일관성이 더 좋지만 더 많은 메모리가 필요합니다
- **guidance_scale**: 텍스트 프롬프트를 출력 결과가 얼마나 밀접하게 따르는지 제어합니다. 값이 높을수록(5-7) 프롬프트와 더 일치하는 결과가 생성됩니다. Wan-Animate의 경우 기본적으로 CFG가 비활성화되어 있지만(`guidance_scale=1.0`) 활성화하면 네거티브 프롬프트를 지원하고 표정 표현에 대한 더 정밀한 제어가 가능합니다. (CFG는 텍스트 프롬프트와 얼굴 조건부 입력에만 적용됩니다.)
## The input is a single word "Notes".
참고
- Wan2.1은 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.WanLoraLoaderMixin.load_lora_weights)를 통해 LoRA를 지원합니다.
예제 코드 보기
```py
# pip install ftfy
import torch
from diffusers import AutoModel, WanPipeline
from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
from diffusers.utils import export_to_video
vae = AutoModel.from_pretrained(
"Wan-AI/Wan2.1-T2V-1.3B-Diffusers", subfolder="vae", dtype=torch.float32
)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-1.3B-Diffusers", vae=vae, dtype=torch.bfloat16
)
pipeline.scheduler = UniPCMultistepScheduler.from_config(
pipeline.scheduler.config, flow_shift=5.0
)
pipeline.to("cuda") # or "mps", "xpu", "cpu"
pipeline.load_lora_weights("benjamin-paine/steamboat-willie-1.3b", adapter_name="steamboat-willie")
pipeline.set_adapters("steamboat-willie")
pipeline.enable_model_cpu_offload()
# use "steamboat willie style" to trigger the LoRA
prompt = """
steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot,
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
output = pipeline(
prompt=prompt,
num_frames=81,
guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)
```
- [WanTransformer3DModel](/docs/diffusers/main/ko/api/models/wan_transformer_3d#diffusers.WanTransformer3DModel) and [AutoencoderKLWan](/docs/diffusers/main/ko/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan) supports loading from single files with [from_single_file()](/docs/diffusers/main/ko/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file).
예제 코드 보기
```py
# pip install ftfy
import torch
from diffusers import WanPipeline, WanTransformer3DModel, AutoencoderKLWan
vae = AutoencoderKLWan.from_single_file(
"https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/vae/wan_2.1_vae.safetensors"
)
transformer = WanTransformer3DModel.from_single_file(
"https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/diffusion_models/wan2.1_t2v_1.3B_bf16.safetensors",
dtype=torch.bfloat16
)
pipeline = WanPipeline.from_pretrained(
"Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
vae=vae,
transformer=transformer,
dtype=torch.bfloat16
)
```
- 더 나은 디코딩 품질을 위해 [AutoencoderKLWan](/docs/diffusers/main/ko/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)의 dtype를 `torch.float32`로 설정하세요.
- 초당 프레임 수(fps) 또는 `k`는 `4 * k + 1`로 계산해야 합니다.
- 낮은 해상도의 비디오에는 더 낮은 `shift` 값(`2.0`에서 `5.0`), 높은 해상도의 이미지에는 더 높은 `shift` 값(`7.0`에서 `12.0`)을 사용해 보세요.
- Wan 2.1과 2.2는 [LightX2V LoRAs](https://huggingface.co/Kijai/WanVideo_comfy/tree/main/Lightx2v)를 사용하여 추론 속도를 높이는 것을 지원합니다. Wan 2.2에서 이를 사용하는 과정은 약간 더 복잡합니다. 자세한 내용은 [이 코드 스니펫](https://github.com/huggingface/diffusers/pull/12040#issuecomment-3144185272)을 참고하세요.
- Wan 2.2에는 두 개의 denoiser가 있습니다. 기본적으로 LoRA는 첫 번째 denoiser에만 로드됩니다. `load_into_transformer_2=True`를 설정하면 LoRA를 두 번째 denoiser에도 로드할 수 있습니다. 자세한 내용은 [이](https://github.com/huggingface/diffusers/pull/12074#issue-3292620048) 및 [이](https://github.com/huggingface/diffusers/pull/12074#issuecomment-3155896144) 예시를 참고하세요.
## WanPipeline[[diffusers.WanPipeline]]
#### diffusers.WanPipeline[[diffusers.WanPipeline]]
```python
diffusers.WanPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: FlowMatchEulerDiscreteScheduler, transformer: diffusers.models.transformers.transformer_wan.WanTransformer3DModel | None = None, transformer_2: diffusers.models.transformers.transformer_wan.WanTransformer3DModel | None = None, boundary_ratio: float | None = None, expand_timesteps: bool = False)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py#L96)
**매개변수:**
tokenizer (`T5Tokenizer`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer)의 토크나이저로, 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
transformer ([WanTransformer3DModel](/docs/diffusers/main/ko/api/models/wan_transformer_3d#diffusers.WanTransformer3DModel)) : 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer
scheduler ([UniPCMultistepScheduler](/docs/diffusers/main/ko/api/schedulers/unipc#diffusers.UniPCMultistepScheduler)) : `transformer`와 함께 사용되어 인코딩된 이미지 잠재를 디노이즈하는 스케줄러입니다.
vae ([AutoencoderKLWan](/docs/diffusers/main/ko/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)) : 비디오를 잠재 표현으로 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
transformer_2 ([WanTransformer3DModel](/docs/diffusers/main/ko/api/models/wan_transformer_3d#diffusers.WanTransformer3DModel), *선택 사항*) : 저노이즈 단계에서 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer입니다. 제공되면 `transformer`가 고노이즈 단계를, `transformer_2`가 저노이즈 단계를 처리하는 2단계 노이즈 제거가 활성화됩니다. 제공되지 않으면 `transformer`만 사용됩니다.
boundary_ratio (`float`, *선택 사항*, 기본값 `None`) : 2단계 디노이징에서 트랜스포머 전환 경계로 사용할 전체 타임스텝 비율입니다. 실제 경계 타임스텝은 `boundary_ratio * num_train_timesteps`으로 계산됩니다. 값이 제공되면 `transformer`는 boundary_timestep 이상의 타임스텝을, `transformer_2`는 boundary_timestep 미만의 타임스텝을 처리합니다. `None`인 경우, 디노이징 전체 과정에서 `transformer`만 사용됩니다.
Wan을 사용한 텍스트-비디오 생성을 위한 Pipeline
이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
#### __호출__[[diffusers.WanPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 480, width: int = 832, num_frames: int = 81, num_inference_steps: int = 50, guidance_scale: float = 5.0, guidance_scale_2: float | None = None, 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, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', 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'], max_sequence_length: int = 512)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py#L382)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 대신 `prompt_embeds`를 전달하세요.
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성 과정에서 피해야 할 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달하세요. guidance를 사용하지 않을 때(`guidance_scale` < `1`)에는 무시됩니다.
height (`int`, 기본값 `480`) : 생성된 이미지의 픽셀 단위 높이입니다.
width (`int`, 기본값 `832`) : 생성된 이미지의 픽셀 단위 너비.
num_frames (`int`, 기본값 `81`) : 생성된 비디오의 프레임 수입니다.
num_inference_steps (`int`, 기본값 `50`) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.
guidance_scale (`float`, 기본값 `5.0`) : [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` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
guidance_scale_2 (`float`, *선택 사항*, 기본값 `None`) : 저노이즈 단계 트랜스포머(`transformer_2`)의 가이던스 스케일입니다. `None`이고 파이프라인의 `boundary_ratio`가 None이 아닌 경우, `guidance_scale`과 동일한 값을 사용합니다. `transformer_2`와 파이프라인의 `boundary_ratio`가 모두 None이 아닐 때만 사용됩니다.
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` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 `negative_prompt_embeds`가 생성됩니다.
output_type (`str`, *선택 사항*, 기본값 `"np"`) : 생성된 이미지의 출력 형식입니다. `PIL.Image` 또는 `np.array` 중 하나를 선택합니다.
return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `WanPipelineOutput`을 반환할지 여부.
attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.
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` 속성에 나열된 변수만 포함할 수 있습니다.
max_sequence_length (`int`, 기본값 `512`) : 텍스트 인코더의 최대 시퀀스 길이입니다. 프롬프트가 이 길이보다 길면 잘리고, 짧으면 이 길이까지 패딩됩니다.
**반환값:** `~WanPipelineOutput` 또는 `tuple`
`return_dict`가 `True`인 경우 `WanPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 `bool` 목록인 `tuple`이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
```python
>>> import torch
>>> from diffusers.utils import export_to_video
>>> from diffusers import AutoencoderKLWan, WanPipeline
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
>>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
>>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> flow_shift = 5.0 # 5.0 for 720P, 3.0 for 480P
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe.to("cuda")
>>> 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 = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
>>> output = pipe(
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=720,
... width=1280,
... num_frames=81,
... guidance_scale=5.0,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)
```
#### encode_prompt[[diffusers.WanPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py#L200)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch 장치
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.
device : (`torch.device`, *선택 사항*): torch device
dtype : (`torch.dtype`, *선택 사항*): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
## WanImageToVideoPipeline[[diffusers.WanImageToVideoPipeline]]
#### diffusers.WanImageToVideoPipeline[[diffusers.WanImageToVideoPipeline]]
```python
diffusers.WanImageToVideoPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: FlowMatchEulerDiscreteScheduler, image_processor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModel = None, transformer: WanTransformer3DModel = None, transformer_2: WanTransformer3DModel = None, boundary_ratio: float | None = None, expand_timesteps: bool = False)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_i2v.py#L127)
**매개변수:**
tokenizer (`T5Tokenizer`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer)의 토크나이저로, 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
image_encoder (`CLIPVisionModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), 구체적으로 [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large) 변형입니다.
transformer ([WanTransformer3DModel](/docs/diffusers/main/ko/api/models/wan_transformer_3d#diffusers.WanTransformer3DModel)) : 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer
scheduler ([UniPCMultistepScheduler](/docs/diffusers/main/ko/api/schedulers/unipc#diffusers.UniPCMultistepScheduler)) : `transformer`와 함께 사용되어 인코딩된 이미지 잠재를 디노이즈하는 스케줄러입니다.
vae ([AutoencoderKLWan](/docs/diffusers/main/ko/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)) : 비디오를 잠재 표현으로 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
transformer_2 ([WanTransformer3DModel](/docs/diffusers/main/ko/api/models/wan_transformer_3d#diffusers.WanTransformer3DModel), *선택 사항*) : 저노이즈 단계에서 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer입니다. 2단계 노이즈 제거에서 `transformer`는 고노이즈 단계를, `transformer_2`는 저노이즈 단계를 처리합니다. 제공되지 않으면 `transformer`만 사용됩니다.
boundary_ratio (`float`, *선택 사항*, 기본값 `None`) : 2단계 디노이징에서 트랜스포머 전환 경계로 사용할 전체 타임스텝 비율입니다. 실제 경계 타임스텝은 `boundary_ratio * num_train_timesteps`으로 계산됩니다. 값이 제공되면 `transformer`는 boundary_timestep 이상의 타임스텝을, `transformer_2`는 boundary_timestep 미만의 타임스텝을 처리합니다. `None`인 경우, 디노이징 전체 과정에서 `transformer`만 사용됩니다.
Wan을 사용하여 이미지에서 비디오로 생성하는 Pipeline
이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
#### __호출__[[diffusers.WanImageToVideoPipeline.__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 | list[str] = None, height: int = 480, width: int = 832, num_frames: int = 81, num_inference_steps: int = 50, guidance_scale: float = 5.0, guidance_scale_2: float | None = None, 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, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, image_embeds: typing.Optional[torch.Tensor] = None, last_image: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', 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'], max_sequence_length: int = 512)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_i2v.py#L510)
**매개변수:**
image (`PipelineImageInput`) : 생성을 조건화할 입력 이미지. 이미지, 이미지 목록 또는 `torch.Tensor`여야 합니다.
last_image (`torch.Tensor`, *선택 사항*) : 생성된 비디오를 조건부로 설정하기 위한 선택적 마지막 프레임입니다. 제공되면 모델은 `image`(첫 번째 프레임)와 `last_image`(마지막 프레임) 사이에 보간을 수행합니다.
prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 대신 전달해야 합니다.
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
height (`int`, 기본값 `480`) : 생성된 비디오의 높이입니다.
width (`int`, 기본값 `832`) : 생성된 비디오의 너비입니다.
num_frames (`int`, 기본값 `81`) : 생성된 비디오의 프레임 수입니다.
num_inference_steps (`int`, 기본값 `50`) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.
guidance_scale (`float`, 기본값 `5.0`) : [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` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
guidance_scale_2 (`float`, *선택 사항*, 기본값 `None`) : 저노이즈 단계 트랜스포머(`transformer_2`)의 가이던스 스케일입니다. `None`이고 파이프라인의 `boundary_ratio`가 None이 아닌 경우, `guidance_scale`과 동일한 값을 사용합니다. `transformer_2`와 파이프라인의 `boundary_ratio`가 모두 None이 아닐 때만 사용됩니다.
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` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
image_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 이미지 임베딩입니다. 이미지 입력(가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `image` 입력 인자에서 이미지 임베딩이 생성됩니다.
output_type (`str`, *선택 사항*, 기본값 `"np"`) : 생성된 이미지의 출력 형식입니다. `PIL.Image` 또는 `np.array` 중 하나를 선택합니다.
return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `WanPipelineOutput`을 반환할지 여부.
attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.
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` 속성에 나열된 변수만 포함할 수 있습니다.
max_sequence_length (`int`, 기본값 `512`) : 텍스트 인코더의 최대 시퀀스 길이입니다. 프롬프트가 이 길이보다 길면 잘리고, 짧으면 이 길이까지 패딩됩니다.
**반환값:** `~WanPipelineOutput` 또는 `tuple`
`return_dict`가 `True`인 경우 `WanPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 `bool` 목록인 `tuple`이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
```python
>>> import torch
>>> import numpy as np
>>> from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
>>> from diffusers.utils import export_to_video, load_image
>>> from transformers import CLIPVisionModel
>>> # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
>>> model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
>>> image_encoder = CLIPVisionModel.from_pretrained(
... model_id, subfolder="image_encoder", torch_dtype=torch.float32
... )
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanImageToVideoPipeline.from_pretrained(
... model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
... )
>>> max_area = 480 * 832
>>> aspect_ratio = image.height / image.width
>>> mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
>>> height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
>>> width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
>>> image = image.resize((width, height))
>>> prompt = (
... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
... )
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
>>> output = pipe(
... image=image,
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=height,
... width=width,
... num_frames=81,
... guidance_scale=5.0,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)
```
#### encode_prompt[[diffusers.WanImageToVideoPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_i2v.py#L254)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch 장치
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.
device : (`torch.device`, *선택 사항*): torch device
dtype : (`torch.dtype`, *선택 사항*): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
## WanVACEPipeline[[diffusers.WanVACEPipeline]]
#### diffusers.WanVACEPipeline[[diffusers.WanVACEPipeline]]
```python
diffusers.WanVACEPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: FlowMatchEulerDiscreteScheduler, transformer: WanVACETransformer3DModel = None, transformer_2: WanVACETransformer3DModel = None, boundary_ratio: float | None = None)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_vace.py#L141)
**매개변수:**
tokenizer (`T5Tokenizer`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer)의 토크나이저로, 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
vae ([AutoencoderKLWan](/docs/diffusers/main/ko/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)) : 비디오를 잠재 표현으로 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
scheduler ([UniPCMultistepScheduler](/docs/diffusers/main/ko/api/schedulers/unipc#diffusers.UniPCMultistepScheduler)) : `transformer`와 함께 사용되어 인코딩된 이미지 잠재를 디노이즈하는 스케줄러입니다.
transformer (`WanVACETransformer3DModel`, *선택 사항*) : 고잡음 단계에서 입력 latents의 잡음을 제거하기 위한 조건부 Transformer입니다. 2단계 denoising에서는 `transformer`가 고잡음 단계를, `transformer_2`가 저잡음 단계를 처리합니다. `transformer` 또는 `transformer_2` 중 적어도 하나는 제공되어야 합니다.
transformer_2 (`WanVACETransformer3DModel`, *선택 사항*) : 저노이즈 단계에서 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer입니다. 2단계 denoising에서는 `transformer`가 고노이즈 단계를, `transformer_2`가 저노이즈 단계를 처리합니다. `transformer` 또는 `transformer_2` 중 적어도 하나는 제공되어야 합니다.
boundary_ratio (`float`, *선택 사항*, 기본값 `None`) : 2단계 디노이징에서 트랜스포머 전환 경계로 사용할 전체 타임스텝 비율입니다. 실제 경계 타임스텝은 `boundary_ratio * num_train_timesteps`으로 계산됩니다. 값이 제공되면 `transformer`는 boundary_timestep 이상의 타임스텝을, `transformer_2`는 boundary_timestep 미만의 타임스텝을 처리합니다. `None`인 경우, 사용 가능한 트랜스포머 하나만 전체 디노이징 과정에 사용됩니다.
Wan을 사용하여 제어 가능한 생성을 수행하는 Pipeline
이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
#### __호출__[[diffusers.WanVACEPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] = None, video: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = None, mask: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = None, reference_images: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = None, conditioning_scale: typing.Union[float, list[float], torch.Tensor] = 1.0, height: int = 480, width: int = 832, num_frames: int = 81, num_inference_steps: int = 50, guidance_scale: float = 5.0, guidance_scale_2: float | None = None, 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, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', 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'], max_sequence_length: int = 512)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_vace.py#L690)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 대신 전달해야 합니다.
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
video (`list[PIL.Image.Image]`, *선택 사항*) : 생성의 시작점으로 사용할 입력 비디오 또는 비디오들입니다. 비디오는 PIL 이미지 목록, numpy 배열, 또는 torch 텐서여야 합니다. 현재 파이프라인은 한 번에 하나의 비디오만 생성하는 것을 지원합니다.
mask (`list[PIL.Image.Image]`, *선택 사항*) : 입력 마스크는 비디오의 어떤 영역을 조건으로 사용할지, 어떤 영역을 생성할지를 정의합니다. 마스크의 검은색 영역은 조건부 영역을, 흰색 영역은 생성 영역을 나타냅니다. 마스크는 PIL 이미지 목록, numpy 배열 또는 torch 텐서여야 합니다. 현재 한 번에 하나의 비디오만 생성하는 것을 지원합니다.
reference_images (`list[PIL.Image.Image]`, *선택 사항*) : 생성을 위한 추가 조건으로 사용할 하나 이상의 참조 이미지 목록입니다. 예를 들어, 캐릭터를 변경하기 위해 비디오 인페인팅을 수행하는 경우, 새로운 캐릭터의 참조 이미지를 여기에 전달할 수 있습니다. 지원되는 작업 및 사용 사례의 전체 목록은 Diffusers [예제](https://github.com/huggingface/diffusers/pull/11582) 및 원본 [사용자 가이드](https://github.com/ali-vilab/VACE/blob/0897c6d055d7d9ea9e191dce763006664d9780f8/UserGuide.md)를 참조하세요.
conditioning_scale (`float`, `list[float]`, `torch.Tensor`, 기본값 `1.0`) : 모델의 각 control layer에서 denoising latent stream에 control conditioning latent stream을 추가할 때 적용되는 conditioning scale입니다. float가 제공되면 모든 layer에 균일하게 적용됩니다. list 또는 tensor가 제공되면 모델의 control layer 수(`len(transformer.config.vace_layers)`)와 동일한 길이를 가져야 합니다.
height (`int`, 기본값 `480`) : 생성된 이미지의 픽셀 단위 높이입니다.
width (`int`, 기본값 `832`) : 생성된 이미지의 픽셀 단위 너비.
num_frames (`int`, 기본값 `81`) : 생성된 비디오의 프레임 수입니다.
num_inference_steps (`int`, 기본값 `50`) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.
guidance_scale (`float`, 기본값 `5.0`) : [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` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
guidance_scale_2 (`float`, *선택 사항*, 기본값 `None`) : 저노이즈 단계 트랜스포머(`transformer_2`)의 가이던스 스케일입니다. `None`이고 파이프라인의 `boundary_ratio`가 None이 아닌 경우, `guidance_scale`과 동일한 값을 사용합니다. `transformer_2`와 파이프라인의 `boundary_ratio`가 모두 None이 아닐 때만 사용됩니다.
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` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 `negative_prompt_embeds`가 생성됩니다.
output_type (`str`, *선택 사항*, 기본값 `"np"`) : 생성된 이미지의 출력 형식입니다. `PIL.Image` 또는 `np.array` 중 하나를 선택합니다.
return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `WanPipelineOutput`을 반환할지 여부.
attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.
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` 속성에 나열된 변수만 포함할 수 있습니다.
max_sequence_length (`int`, 기본값 `512`) : 텍스트 인코더의 최대 시퀀스 길이입니다. 프롬프트가 이 길이보다 길면 잘리고, 짧으면 이 길이까지 패딩됩니다.
**반환값:** `~WanPipelineOutput` 또는 `tuple`
`return_dict`가 `True`인 경우 `WanPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 `bool` 목록인 `tuple`이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
```python
>>> import torch
>>> import PIL.Image
>>> from diffusers import AutoencoderKLWan, WanVACEPipeline
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
>>> from diffusers.utils import export_to_video, load_image
def prepare_video_and_mask(first_img: PIL.Image.Image, last_img: PIL.Image.Image, height: int, width: int, num_frames: int):
first_img = first_img.resize((width, height))
last_img = last_img.resize((width, height))
frames = []
frames.append(first_img)
# Ideally, this should be 127.5 to match original code, but they perform computation on numpy arrays
# whereas we are passing PIL images. If you choose to pass numpy arrays, you can set it to 127.5 to
# match the original code.
frames.extend([PIL.Image.new("RGB", (width, height), (128, 128, 128))] * (num_frames - 2))
frames.append(last_img)
mask_black = PIL.Image.new("L", (width, height), 0)
mask_white = PIL.Image.new("L", (width, height), 255)
mask = [mask_black, *[mask_white] * (num_frames - 2), mask_black]
return frames, mask
>>> # Available checkpoints: Wan-AI/Wan2.1-VACE-1.3B-diffusers, Wan-AI/Wan2.1-VACE-14B-diffusers
>>> model_id = "Wan-AI/Wan2.1-VACE-1.3B-diffusers"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanVACEPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe.to("cuda")
>>> prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
>>> first_frame = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
... )
>>> last_frame = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png>>> "
... )
>>> height = 512
>>> width = 512
>>> num_frames = 81
>>> video, mask = prepare_video_and_mask(first_frame, last_frame, height, width, num_frames)
>>> output = pipe(
... video=video,
... mask=mask,
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=height,
... width=width,
... num_frames=num_frames,
... num_inference_steps=30,
... guidance_scale=5.0,
... generator=torch.Generator().manual_seed(42),
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)
```
#### encode_prompt[[diffusers.WanVACEPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_vace.py#L247)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch 장치
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.
device : (`torch.device`, *선택 사항*): torch device
dtype : (`torch.dtype`, *선택 사항*): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
## WanVideoToVideoPipeline[[diffusers.WanVideoToVideoPipeline]]
#### diffusers.WanVideoToVideoPipeline[[diffusers.WanVideoToVideoPipeline]]
```python
diffusers.WanVideoToVideoPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, transformer: WanTransformer3DModel, vae: AutoencoderKLWan, scheduler: FlowMatchEulerDiscreteScheduler)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_video2video.py#L174)
**매개변수:**
tokenizer (`T5Tokenizer`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer)의 토크나이저로, 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
transformer ([WanTransformer3DModel](/docs/diffusers/main/ko/api/models/wan_transformer_3d#diffusers.WanTransformer3DModel)) : 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer
scheduler ([UniPCMultistepScheduler](/docs/diffusers/main/ko/api/schedulers/unipc#diffusers.UniPCMultistepScheduler)) : `transformer`와 함께 사용되어 인코딩된 이미지 잠재를 디노이즈하는 스케줄러입니다.
vae ([AutoencoderKLWan](/docs/diffusers/main/ko/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)) : 비디오를 잠재 표현으로 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
Wan을 사용한 비디오-대-비디오 생성을 위한 Pipeline
이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
#### __호출__[[diffusers.WanVideoToVideoPipeline.__call__]]
```python
__call__(video: list = None, prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 480, width: int = 832, num_inference_steps: int = 50, timesteps: list[int] | None = None, guidance_scale: float = 5.0, strength: float = 0.8, 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, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', 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'], max_sequence_length: int = 512)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_video2video.py#L481)
**매개변수:**
video (`list[PIL.Image.Image]`) : 비디오-대-비디오 생성의 시작점으로 사용되는 입력 비디오입니다. 비디오는 PIL 이미지 목록, numpy 배열 또는 torch 텐서로 제공해야 합니다.
prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 대신 전달해야 합니다.
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
height (`int`, 기본값 `480`) : 생성된 이미지의 픽셀 단위 높이입니다.
width (`int`, 기본값 `832`) : 생성된 이미지의 픽셀 단위 너비.
num_inference_steps (`int`, 기본값 `50`) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.
timesteps (`list[int]`, *선택 사항*) : `set_timesteps` 메서드에 `timesteps` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 타임스텝입니다. 정의되지 않은 경우, `num_inference_steps`가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.
guidance_scale (`float`, 기본값 `5.0`) : [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` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
strength (`float`, 기본값 `0.8`) : 강도가 높을수록 원본 이미지와 생성된 비디오 간의 차이가 커집니다.
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` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 `negative_prompt_embeds`가 생성됩니다.
output_type (`str`, *선택 사항*, 기본값 `"np"`) : 생성된 이미지의 출력 형식입니다. `PIL.Image` 또는 `np.array` 중 하나를 선택합니다.
return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `WanPipelineOutput`을 반환할지 여부.
attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.
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` 속성에 나열된 변수만 포함할 수 있습니다.
max_sequence_length (`int`, 기본값 `512`) : 텍스트 인코더의 최대 시퀀스 길이입니다. 프롬프트가 이 길이보다 길면 잘리고, 짧으면 이 길이까지 패딩됩니다.
**반환값:** `~WanPipelineOutput` 또는 `tuple`
`return_dict`가 `True`인 경우 `WanPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 `bool` 목록인 `tuple`이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
```python
>>> import torch
>>> from diffusers.utils import export_to_video, load_video
>>> from diffusers import AutoencoderKLWan, WanVideoToVideoPipeline
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
>>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
>>> model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanVideoToVideoPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe.to("cuda")
>>> prompt = "A robot standing on a mountain top. The sun is setting in the background"
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
>>> video = load_video(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
... )
>>> output = pipe(
... video=video,
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=480,
... width=720,
... guidance_scale=5.0,
... strength=0.7,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)
```
#### encode_prompt[[diffusers.WanVideoToVideoPipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_video2video.py#L265)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch 장치
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.
device : (`torch.device`, *선택 사항*): torch device
dtype : (`torch.dtype`, *선택 사항*): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
## WanAnimatePipeline[[diffusers.WanAnimatePipeline]]
#### diffusers.WanAnimatePipeline[[diffusers.WanAnimatePipeline]]
```python
diffusers.WanAnimatePipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler, image_processor: CLIPImageProcessorPil, image_encoder: CLIPVisionModel, transformer: WanAnimateTransformer3DModel)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_animate.py#L150)
**매개변수:**
tokenizer (`T5Tokenizer`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer)의 토크나이저로, 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
text_encoder (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), 구체적으로 [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) 변형입니다.
image_encoder (`CLIPVisionModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), 구체적으로 [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large) 변형입니다.
transformer ([WanAnimateTransformer3DModel](/docs/diffusers/main/ko/api/models/wan_animate_transformer_3d#diffusers.WanAnimateTransformer3DModel)) : 입력 latents의 노이즈를 제거하기 위한 조건부 Transformer입니다.
scheduler ([UniPCMultistepScheduler](/docs/diffusers/main/ko/api/schedulers/unipc#diffusers.UniPCMultistepScheduler)) : `transformer`와 함께 사용되어 인코딩된 이미지 잠재를 디노이즈하는 스케줄러입니다.
vae ([AutoencoderKLWan](/docs/diffusers/main/ko/api/models/autoencoder_kl_wan#diffusers.AutoencoderKLWan)) : 비디오를 잠재 표현으로 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
image_processor (`CLIPImageProcessor`) : 인코딩 전에 이미지를 전처리하는 이미지 프로세서입니다.
Wan-Animate를 활용한 통합 캐릭터 애니메이션 및 교체 파이프라인
WanAnimatePipeline은 캐릭터 이미지, 포즈 비디오, 얼굴 비디오를 입력으로 받아 두 가지 모드로 비디오를 생성합니다:
1. **애니메이션 모드**: 모델은 입력된 포즈 및 얼굴 비디오의 인간 동작을 모방하는 캐릭터 이미지의 비디오를 생성합니다. 제공된 모션 컨트롤을 기반으로 캐릭터가 애니메이션 처리되어 캐릭터의 새로운 애니메이션 비디오가 생성됩니다.
2. **교체 모드**: 포즈 및 얼굴 비디오를 모션 제어에 사용하여 배경 비디오의 캐릭터를 제공된 캐릭터 이미지로 교체합니다. 이 모드에는 `background_video`와 `mask_video` 입력이 추가로 필요합니다. 마스크 비디오에서는 원래 콘텐츠를 유지해야 하는 영역은 검은색, 새로운 캐릭터가 생성되어야 하는 영역은 흰색으로 설정해야 합니다.
이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
파이프라인은 다음 로딩 메서드도 상속합니다:
- LoRA 가중치를 로드하는 [load_lora_weights()](/docs/diffusers/main/ko/api/loaders/lora#diffusers.loaders.WanLoraLoaderMixin.load_lora_weights)
#### __호출__[[diffusers.WanAnimatePipeline.__call__]]
```python
__call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], pose_video: list, face_video: list, background_video: list[PIL.Image.Image] | None = None, mask_video: list[PIL.Image.Image] | None = None, prompt: str | list[str] = None, negative_prompt: str | list[str] = None, height: int = 720, width: int = 1280, segment_frame_length: int = 77, num_inference_steps: int = 20, mode: str = 'animate', prev_segment_conditioning_frames: int = 1, motion_encode_batch_size: int | None = None, guidance_scale: float = 1.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, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, image_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'np', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int, NoneType], diffusers.callbacks.PipelineCallback | diffusers.callbacks.MultiPipelineCallbacks]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], max_sequence_length: int = 512)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_animate.py#L763)
**매개변수:**
image (`PipelineImageInput`) : 생성을 조건화할 입력 문자 이미지. 이미지, 이미지 목록 또는 `torch.Tensor`여야 합니다.
pose_video (`list[PIL.Image.Image]`) : 생성을 조건으로 사용할 입력 포즈 비디오. PIL 이미지 목록이어야 합니다.
face_video (`list[PIL.Image.Image]`) : 생성을 조건으로 사용할 입력 얼굴 비디오. PIL 이미지 목록이어야 합니다.
background_video (`list[PIL.Image.Image]`, *선택 사항*) : mode가 `"replace"`인 경우, 생성을 조건화하기 위한 입력 배경 비디오입니다. PIL 이미지 목록이어야 합니다.
mask_video (`list[PIL.Image.Image]`, *선택 사항*) : mode가 `"replace"`인 경우, 생성을 조건화하기 위한 입력 마스크 비디오입니다. PIL 이미지 목록이어야 합니다.
prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 대신 전달해야 합니다.
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
mode (`str`, 기본값 `"animation"`) : 생성 모드입니다. `"animate"`와 `"replace"` 중 하나를 선택합니다.
prev_segment_conditioning_frames (`int`, 기본값 `1`) : 시간적 안내(temporal guidance)에 사용할 이전 비디오 세그먼트의 프레임 수입니다. 1 또는 5를 권장합니다. 일반적으로 N이 음이 아닌 정수일 때 4N + 1이어야 합니다.
motion_encode_batch_size (`int`, *optional*) : motion encoder를 통해 얼굴 비디오를 배치 인코딩할 때 사용할 배치 크기입니다. 더 작은 배치 크기를 설정하여 추론 속도와 낮은 메모리 사용량 사이의 트레이드오프를 조정할 수 있습니다. 설정하지 않으면 기본적으로 `self.transformer.config.motion_encoder_batch_size`가 사용됩니다.
height (`int`, 기본값 `720`) : 생성된 비디오의 높이입니다.
width (`int`, 기본값 `1280`) : 생성된 비디오의 너비입니다.
segment_frame_length (`int`, 기본값 `77`) : 생성된 각 비디오 세그먼트의 프레임 수입니다. 생성되는 비디오의 총 프레임 수는 `pose_video`의 프레임 수와 같으며, 이 길이에 도달할 때까지 비디오를 세그먼트 단위로 생성합니다. 일반적으로 N이 음이 아닌 정수일 때 4N + 1이어야 합니다.
num_inference_steps (`int`, 기본값 `20`) : 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다.
guidance_scale (`float`, 기본값 `1.0`) : [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` 텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. 기본적으로 Wan Animate 추론에서는 CFG를 사용하지 않습니다.
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` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
image_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 이미지 임베딩입니다. 이미지 입력(가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `image` 입력 인자에서 이미지 임베딩이 생성됩니다.
output_type (`str`, *선택 사항*, 기본값 `"np"`) : 생성된 이미지의 출력 형식입니다. `PIL.Image` 또는 `np.array` 중 하나를 선택합니다.
return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 `WanPipelineOutput`을 반환할지 여부.
attention_kwargs (`dict`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.
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` 속성에 나열된 변수만 포함할 수 있습니다.
max_sequence_length (`int`, 기본값 `512`) : 텍스트 인코더의 최대 시퀀스 길이입니다. 프롬프트가 이 길이보다 길면 잘리고, 짧으면 이 길이까지 패딩됩니다.
**반환값:** `~WanPipelineOutput` 또는 `tuple`
`return_dict`가 `True`인 경우 `WanPipelineOutput`가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록이고 두 번째 요소가 각 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 `bool` 목록인 `tuple`이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
```python
>>> import torch
>>> import numpy as np
>>> from diffusers import WanAnimatePipeline
>>> from diffusers.utils import export_to_video, load_image, load_video
>>> model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
>>> pipe = WanAnimatePipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> # Optionally upcast the Wan VAE to FP32
>>> pipe.vae.to(torch.float32)
>>> pipe.to("cuda")
>>> # Load the reference character image
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
... )
>>> # Load pose and face videos (preprocessed from reference video)
>>> # Note: Videos should be preprocessed to extract pose keypoints and face features
>>> # Refer to the Wan-Animate preprocessing documentation for details
>>> pose_video = load_video("path/to/pose_video.mp4")
>>> face_video = load_video("path/to/face_video.mp4")
>>> # CFG is generally not used for Wan Animate
>>> prompt = (
... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
... )
>>> # Animation mode: Animate the character with the motion from pose/face videos
>>> output = pipe(
... image=image,
... pose_video=pose_video,
... face_video=face_video,
... prompt=prompt,
... height=height,
... width=width,
... segment_frame_length=77, # Frame length of each inference segment
... guidance_scale=1.0,
... num_inference_steps=20,
... mode="animate",
... ).frames[0]
>>> export_to_video(output, "output_animation.mp4", fps=30)
>>> # Replacement mode: Replace a character in the background video
>>> # Requires additional background_video and mask_video inputs
>>> background_video = load_video("path/to/background_video.mp4")
>>> mask_video = load_video("path/to/mask_video.mp4") # Black areas preserved, white areas generated
>>> output = pipe(
... image=image,
... pose_video=pose_video,
... face_video=face_video,
... background_video=background_video,
... mask_video=mask_video,
... prompt=prompt,
... height=height,
... width=width,
... segment_frame_length=77, # Frame length of each inference segment
... guidance_scale=1.0,
... num_inference_steps=20,
... mode="replace",
... ).frames[0]
>>> export_to_video(output, "output_replacement.mp4", fps=30)
```
#### encode_prompt[[diffusers.WanAnimatePipeline.encode_prompt]]
```python
encode_prompt(prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 226, device: typing.Optional[torch.device] = None, dtype: typing.Optional[torch.dtype] = None)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_animate.py#L291)
**매개변수:**
prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트
negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).
do_classifier_free_guidance (`bool`, *선택 사항*, 기본값 `True`) : classifier free guidance를 사용할지 여부.
num_videos_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch 장치
prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. *예를 들어* 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.
negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 negative_prompt_embeds가 생성됩니다.
device : (`torch.device`, *선택 사항*): torch device
dtype : (`torch.dtype`, *선택 사항*): torch dtype
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
#### pad_video_frames[[diffusers.WanAnimatePipeline.pad_video_frames]]
```python
pad_video_frames(frames: list, num_target_frames: int)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan_animate.py#L718)
배열과 유사한 비디오 `frames`를 "reflect"와 유사한 전략을 사용하여 `num_target_frames`까지 패딩합니다. 프레임 차원은 첫 번째 차원으로 가정됩니다. 1D의 경우, 이 전략을 다음과 같이 시각화할 수 있습니다:
pad_video_frames([1, 2, 3, 4, 5], 10) -> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2]
## WanPipelineOutput[[diffusers.pipelines.wan.pipeline_output.WanPipelineOutput]]
#### diffusers.pipelines.wan.pipeline_output.WanPipelineOutput[[diffusers.pipelines.wan.pipeline_output.WanPipelineOutput]]
```python
diffusers.pipelines.wan.pipeline_output.WanPipelineOutput(frames: Tensor)
```
[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/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 텐서일 수도 있습니다.
Wan 파이프라인의 출력 클래스입니다.

Xet Storage Details

Size:
104 kB
·
Xet hash:
f363993fa0b58e861934283673823e8ef179b91b7ff2b4b08db6802e065208e0

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.