Diffusers documentation
Wan
Wan
Wan Team による Wan-2.1。
本レポートでは、動画生成の限界を押し広げることを目的に設計された、包括的でオープンな動画基盤モデルのスーイである Wan を紹介します。Wan は、主流の拡散トランスフォーマーのパラダイムを基盤として構築されており、独自の VAE、スケーラブルな事前学習戦略、大規模なデータキュレーション、自動評価指標といった一連の革新を通じて、生成能力において大幅な進歩を達成しています。これらの貢献により、モデルのパフォーマンスと多用途性が総合的に高まっています。具体的には、Wan は以下の 4 つの主要な特徴を備えています。優れたパフォーマンス: 数十億枚の画像と動画からなる膨大なデータセットで学習された Wan の 14B モデルは、データ量とモデルサイズに対する動画生成のスケーリング則を示しています。複数の社内および社外のベンチマークにおいて、既存のオープンソースモデルや最先端の商用ソリューションを一貫して上回り、明確かつ顕著なパフォーマンスの優位性を示しています。包括性: Wan は、効率性と効果性それぞれに対応する 1.3B パラメータと 14B パラメータの 2 つの高性能モデルを提供しています。また、画像から動画への生成、指示に基づく動画編集、パーソナル動画生成など、最大 8 つのタスクを含む複数の下流アプリケーションをカバーしています。コンシューマーグレードの効率性: 1.3B モデルは、VRAM 8.19 GB しか必要としないという優れたリソース効率を示しており、幅広いコンシューマーグレードの GPU と互換性があります。オープン性: 動画生成コミュニティの成長を促進することを目的に、ソースコードとすべてのモデルを含む Wan のシリーズ全体をオープンソース化しています。このオープン化により、業界における動画制作の創造的な可能性を大幅に拡大し、学術界に高品質な動画基盤モデルを提供することを目指しています。すべてのコードとモデルは この https URL で利用可能です。
すべての元のWan2.1チェックポイントは、Wan-AI組織の下で確認できます。
Diffusersでは、以下のWanモデルがサポートされています:
- Wan 2.1 T2V 1.3B
- Wan 2.1 T2V 14B
- Wan 2.1 I2V 14B - 480P
- Wan 2.1 I2V 14B - 720P
- Wan 2.1 FLF2V 14B - 720P
- Wan 2.1 VACE 1.3B
- Wan 2.1 VACE 14B
- Wan 2.2 T2V 14B
- Wan 2.2 I2V 14B
- Wan 2.2 TI2V 5B
- Wan 2.2 Animate 14B
右側のサイドバーにあるWanモデルをクリックすると、動画生成のより多くの例を確認できます。
テキストから動画の生成
以下の例では、メモリまたは推論速度に最適化されたテキストから動画の生成方法を示しています。
メモリ使用量の削減に関する詳細については、メモリ使用量の削減ガイドを参照してください。
以下のWan2.1テキストtoビデオモデルには、約13GBのVRAMが必要です。
# 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は初回に時間がかかりますが、以降のpipeline呼び出しは高速になります。Cachingにより、中間出力を保存して再利用することで、推論の高速化も期待できます。
# 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)First-Last-Frame-to-Video 生成
以下の例では、テキストの説明、開始フレーム、および終了フレームを使用して、image-to-video パイプラインで動画を生成する方法を示しています。
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 など)。Control video を取得するために動画を前処理するのにおすすめのライブラリ: huggingface/controlnet_aux
- 画像/動画から動画へ(最初のフレーム、最後のフレーム、開始クリップ、終了クリップ、ランダムクリップ)
- インペインティングとアウトペインティング
- 対象となる動画(顔、オブジェクト、キャラクターなど)
- コンポジションから動画へ(任意のものを参照、任意のものをアニメーション化、任意のものをスワップ、任意のものを拡張、任意のものを移動、など)
このプルリクエストのこちらにあるコードスニペットは、制御可能性シグナルを用いた動画生成のいくつかの例を示しています。
VACE パイプラインの入力を準備する際に念頭に置いておくべき一般的なルールは、条件付けに使用する入力画像や動画のフレームには、黒色の対応するマスクが必要であるということです。黒いマスクは、その領域に対してモデルが新しいコンテンツを生成せず、生成プロセスの条件付けにのみ使用することを示します。モデルによって生成されるべき部分やフレームについては、マスクは白色である必要があります。
Wan-Animate: 包括的な複製による統合的なキャラクターアニメーションと置換
Wan Team による Wan-Animate。
Wan-Animate は、キャラクターアニメーションと置換のための統一フレームワークです。キャラクター画像と参照動画が与えられると、Wan-Animate は動画内のキャラクターの表情や動きを正確に再現することでキャラクターをアニメーション化し、高忠実度のキャラクター動画を生成できます。あるいは、アニメーション化されたキャラクターを参照動画に統合して元のキャラクターを置換し、シーンのライティングや色調を再現することで、シームレスな環境統合を実現します。Wan-Animate は Wan モデルを基盤として構築されています。キャラクターアニメーションタスクへの適応のため、参照条件と生成領域を区別するよう修正された入力パラダイムを採用しています。この設計により、複数のタスクが共通の記号表現に統合されます。空間的にアラインされたスケルトンシグナルを用いて体の動きを再現し、ソース画像から抽出された暗黙の顔の特徴を用いて表情を再演することで、高い制御性と表現力を持つキャラクター動画の生成を可能にしています。さらに、キャラクター置換時の環境統合を強化するため、補助的な Relighting LoRA を開発しました。このモジュールは、キャラクターの外観の一貫性を保ちながら、適切な環境ライティングと色調を適用します。実験結果により、Wan-Animate が最先端の性能を達成していることが示されています。モデルの重みとソースコードのオープンソース化に取り組んでいます。
プロジェクトページ: https://humanaigc.github.io/wan-animate
このモデルは主にM. Tolga Cangözによって貢献されました。
使用方法
Wan-Animate パイプラインは、2つの動作モードをサポートしています:
- アニメーションモード(デフォルト): 参照動画の動きと表情に基づいて、キャラクターの画像をアニメーション化します
- 置換モード: 背景の映像内のキャラクターを新しいキャラクターに置き換える。シーン自体は維持される
前提条件
パイプラインを使用する前に、参照動画の前処理を行い、以下を抽出する必要があります。
- ポーズ動画: 体の動きを表す骨格キーポイントを含む
- 顔の動画: 表情制御用の顔の特徴量表現が含まれています
置換モードを使用するには、さらに以下が必要です:
- 背景動画: シーンを含む元の動画
- マスク動画: コンテンツを生成する領域(白)と、元の画像を保持する領域(黒)を示すマスク
pose_videoなどの入力には、パイプラインが適切な情報を抽出するために事前処理済みであることを期待しているため、生の動画は使用しないでください。これらの入力を準備するための事前処理スクリプトは、元の Wan-Animate リポジトリ で利用できます。これらの事前処理ステップの Diffusers への統合は、将来のリリースで計画されています。
以下の例は、Wan-Animate パイプラインの使用方法を示しています。
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)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)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 はテキストプロンプトと顔の条件付けのみを対象とします。)
注記
Wan2.1は、load_lora_weights()によるLoRAをサポートしています。
サンプルコードを表示
# 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 and AutoencoderKLWan supports loading from single files with from_single_file().
サンプルコードを表示
# 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 の dtype を
torch.float32に設定します。1秒あたりのフレーム数(fps)または
kは、4 * k + 1で計算されるべきです。低解像度の動画には低い
shift値(2.0から5.0)を、高解像度の画像には高いshift値(7.0から12.0)を使用してください。Wan 2.1 と 2.2 は、LightX2V LoRA を使用して推論を高速化することをサポートしています。Wan 2.2 でこれらを使用するには、やや複雑な手順が必要です。詳細については、このコードスニペットを参照してください。
Wan 2.2には2つのデノイザーがあります。デフォルトでは、LoRAは最初のデノイザーにのみ読み込まれます。
load_into_transformer_2=Trueを設定することで、LoRAを2番目のデノイザーに読み込むことができます。詳細については、このおよびこの例を参照してください。
WanPipeline
class diffusers.WanPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulertransformer: diffusers.models.transformers.transformer_wan.WanTransformer3DModel | None = Nonetransformer_2: diffusers.models.transformers.transformer_wan.WanTransformer3DModel | None = Noneboundary_ratio: float | None = Noneexpand_timesteps: bool = False )
パラメータ
- tokenizer (
T5Tokenizer) — T5 の Tokenizer、具体的には google/umt5-xxl バリアントです。 - text_encoder (
T5EncoderModel) — T5、具体的には google/umt5-xxl バリアントです。 - transformer (WanTransformer3DModel) — 入力潜在変数をノイズ除去するための条件付き Transformer。
- scheduler (UniPCMultistepScheduler) —
transformerと組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。 - vae (AutoencoderKLWan) — 潜在表現へのエンコードとデコードを行う、動画用の変分オートエンコーダ (VAE) モデル。
- transformer_2 (WanTransformer3DModel、任意) —
低ノイズ段階で入力潜在変数をデノイズするための条件付き Transformer です。指定された場合、
transformerが高ノイズ段階を、transformer_2が低ノイズ段階を処理する 2 段階デノイジングが有効になります。指定されない場合、transformerのみ使用されます。 - boundary_ratio (
float、任意、デフォルトはNone) — 2段階のデノイジングにおいて、transformer の切り替え境界として使用する、総タイムステップ数に対する比率です。 実際の境界タイムステップはboundary_ratio * num_train_timestepsで計算されます。指定された場合、transformerはタイムステップ >= boundary_timestep を処理し、transformer_2はタイムステップ < boundary_timestep を処理します。Noneの場合、デノイジングの全プロセスでtransformerのみを使用します。
Wan を使用したテキストから動画への生成を行う Pipeline。
このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str | list[str] = Noneheight: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50guidance_scale: float = 5.0guidance_scale_2: float | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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[str] = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
パラメータ
- 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 で定義されているガイダンススケールです。guidance_scaleは、Imagen Paper の数式 2 のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 - guidance_scale_2 (
float、任意、デフォルトはNone) — 低ノイズ段階の transformer (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。 - latents (
torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き latents。画像生成のインプットとして使用します。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを用いてサンプリングを行い、latents テンソルが生成されます。 - prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたテキスト埋め込みです。テキスト入力(プロンプトの重み付けなど)を簡単に調整するために使用できます。指定されない場合、prompt入力引数からテキスト埋め込みが生成されます。 - negative_prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt_embedsはnegative_prompt入力引数から生成されます。 - output_type (
str、任意、デフォルトは"np") — 生成された画像の出力形式。PIL.Imageまたはnp.arrayから選択します。 - return_dict (
bool、省略可能、デフォルトはTrue) —WanPipelineOutputを返すか、プレーンなタプルを返すかを指定します。 - attention_kwargs (
dict, 省略可) — 指定された場合、diffusers.models.attention_processor で定義されているself.processor内のAttentionProcessorに渡される kwargs 辞書です。 - callback_on_step_end (
Callable、PipelineCallback、MultiPipelineCallbacks、省略可) — 推論中の各デノイジングステップの終了時に呼び出される関数、または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 が返され、それ以外の場合は tuple が返されます。この tuple の最初の要素は生成された画像のリストであり、2番目の要素は、対応する生成画像に「not-safe-for-work」(nsfw)コンテンツが含まれているかどうかを示す bool のリストです。
生成用の pipeline への呼び出し関数。
例:
>>> 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
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
パラメータ
- 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 デバイス - dtype — (
torch.dtype、省略可): torch の dtype
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
WanImageToVideoPipeline
class diffusers.WanImageToVideoPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulerimage_processor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModel = Nonetransformer: WanTransformer3DModel = Nonetransformer_2: WanTransformer3DModel = Noneboundary_ratio: float | None = Noneexpand_timesteps: bool = False )
パラメータ
- tokenizer (
T5Tokenizer) — T5 の Tokenizer、具体的には google/umt5-xxl バリアントです。 - text_encoder (
T5EncoderModel) — T5、具体的には google/umt5-xxl バリアントです。 - image_encoder (
CLIPVisionModel) — CLIP、具体的には clip-vit-huge-patch14 バリアントです。 - transformer (WanTransformer3DModel) — 入力潜在変数をノイズ除去するための条件付き Transformer。
- scheduler (UniPCMultistepScheduler) —
transformerと組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。 - vae (AutoencoderKLWan) — 潜在表現へのエンコードとデコードを行う、動画用の変分オートエンコーダ (VAE) モデル。
- transformer_2 (WanTransformer3DModel、任意) —
低ノイズ段階で入力潜在変数をデノイズするための条件付き Transformer。2段階デノイズでは、
transformerが高ノイズ段階を、transformer_2が低ノイズ段階を担当します。指定されない場合、transformerのみを使用します。 - boundary_ratio (
float、任意、デフォルトはNone) — 2段階のデノイジングにおいて、transformer の切り替え境界として使用する、総タイムステップ数に対する比率です。 実際の境界タイムステップはboundary_ratio * num_train_timestepsで計算されます。指定された場合、transformerはタイムステップ >= boundary_timestep を処理し、transformer_2はタイムステップ < boundary_timestep を処理します。Noneの場合、デノイジングの全プロセスでtransformerのみを使用します。
Wan を使用した画像から動画への生成を行う Pipeline です。
このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]prompt: str | list[str] = Nonenegative_prompt: str | list[str] = Noneheight: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50guidance_scale: float = 5.0guidance_scale_2: float | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneimage_embeds: typing.Optional[torch.Tensor] = Nonelast_image: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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[str] = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
パラメータ
- 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 で定義されているガイダンススケールです。guidance_scaleは、Imagen Paper の数式 2 のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 - guidance_scale_2 (
float、任意、デフォルトはNone) — 低ノイズ段階の transformer (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。 - 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 で定義されているself.processor内のAttentionProcessorに渡される kwargs 辞書です。 - callback_on_step_end (
Callable、PipelineCallback、MultiPipelineCallbacks、省略可) — 推論中の各デノイジングステップの終了時に呼び出される関数、または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 が返され、それ以外の場合は tuple が返されます。この tuple の最初の要素は生成された画像のリストであり、2番目の要素は、対応する生成画像に「not-safe-for-work」(nsfw)コンテンツが含まれているかどうかを示す bool のリストです。
生成用の pipeline への呼び出し関数。
例:
>>> 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
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
パラメータ
- 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 デバイス - dtype — (
torch.dtype、省略可): torch の dtype
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
WanVACEPipeline
class diffusers.WanVACEPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulertransformer: WanVACETransformer3DModel = Nonetransformer_2: WanVACETransformer3DModel = Noneboundary_ratio: float | None = None )
パラメータ
- tokenizer (
T5Tokenizer) — T5 の Tokenizer、具体的には google/umt5-xxl バリアントです。 - text_encoder (
T5EncoderModel) — T5、具体的には google/umt5-xxl バリアントです。 - vae (AutoencoderKLWan) — 潜在表現へのエンコードとデコードを行う、動画用の変分オートエンコーダ (VAE) モデル。
- scheduler (UniPCMultistepScheduler) —
transformerと組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。 - transformer (
WanVACETransformer3DModel、任意) — 高ノイズ段階で入力ラテンツをデノイズするための条件付き Transformer。2段階デノイズでは、transformerが高ノイズ段階を、transformer_2が低ノイズ段階を担当します。transformerとtransformer_2の少なくとも一方を指定する必要があります。 - transformer_2 (
WanVACETransformer3DModel、任意) — 低ノイズ段階で入力潜在変数をデノイズするための条件付き Transformer。2段階デノイズでは、transformerが高ノイズ段階を、transformer_2が低ノイズ段階を担当します。transformerとtransformer_2の少なくとも一方を指定する必要があります。 - boundary_ratio (
float、任意、デフォルトはNone) — 2段階のデノイジングにおいて、transformer の切り替え境界として使用する、総タイムステップに対する比率です。 実際の境界タイムステップはboundary_ratio * num_train_timestepsで計算されます。指定された場合、transformerは boundary_timestep 以上のタイムステップを、transformer_2は boundary_timestep 未満のタイムステップを処理します。Noneの場合、デノイジングの全過程で利用可能な transformer のみを使用します。
Wan を使用した制御可能な生成のための Pipeline。
このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。
__call__
< source >( prompt: str | list[str] = Nonenegative_prompt: str | list[str] = Nonevideo: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Nonemask: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Nonereference_images: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneconditioning_scale: typing.Union[float, list[float], torch.Tensor] = 1.0height: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50guidance_scale: float = 5.0guidance_scale_2: float | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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[str] = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
パラメータ
- prompt (
strまたはlist[str]、任意) — 画像生成をガイドするためのプロンプトです。定義されていない場合、代わりにprompt_embedsを渡す必要があります。 - negative_prompt (
strまたはlist[str]、省略可) — 画像生成をガイドしないプロンプトです。未定義の場合、代わりにnegative_prompt_embedsを渡す必要があります。ガイダンスを使用していない場合は無視されます(guidance_scaleが1未満の場合は無視されます)。 - video (
list[PIL.Image.Image], optional) — 生成の起点として使用する入力動画です。動画は、PIL イメージのリスト、NumPy 配列、または Torch テンソルの形式である必要があります。現在、このパイプラインは一度に 1 つの動画のみを生成できます。 - mask (
list[PIL.Image.Image], 任意) — 入力マスクは、条件付けを行う動画領域と生成を行う領域を定義します。マスク内の黒い領域は条件付けの対象領域を示し、白い領域は生成の対象領域を示します。マスクは、PIL画像のリスト、numpy配列、またはtorchテンソルである必要があります。現在、一度に1本の動画の生成のみをサポートしています。 - reference_images (
list[PIL.Image.Image]、任意) — 生成の追加条件として使用する、1枚以上の参照画像のリストです。例えば、キャラクターを変更するために動画をインペイントする場合、新しいキャラクターの参照画像をここで渡すことができます。サポートされているタスクとユースケースの完全なリストについては、Diffusers の examples および元の ユーザーガイド を参照してください。 - conditioning_scale (
float、list[float]、torch.Tensor、デフォルト値は1.0) — モデルの各 control レイヤーにおいて、denoising latent stream に control conditioning latent stream を加算する際に適用される conditioning scale です。float が指定された場合、すべてのレイヤーに均一に適用されます。list または tensor が指定された場合、その長さはモデルの control レイヤー数(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 で定義されているガイダンススケールです。guidance_scaleは、Imagen Paper の数式 2 のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 - guidance_scale_2 (
float、任意、デフォルトはNone) — 低ノイズ段階の transformer (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。 - latents (
torch.Tensor, 任意) — ガウス分布からサンプリングされた事前生成されたノイズ付き latents。画像生成のインプットとして使用します。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを用いてサンプリングを行い、latents テンソルが生成されます。 - prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたテキスト埋め込みです。テキスト入力(プロンプトの重み付けなど)を簡単に調整するために使用できます。指定されない場合、prompt入力引数からテキスト埋め込みが生成されます。 - negative_prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt_embedsはnegative_prompt入力引数から生成されます。 - output_type (
str、任意、デフォルトは"np") — 生成された画像の出力形式。PIL.Imageまたはnp.arrayから選択します。 - return_dict (
bool、省略可能、デフォルトはTrue) —WanPipelineOutputを返すか、プレーンなタプルを返すかを指定します。 - attention_kwargs (
dict, 省略可) — 指定された場合、diffusers.models.attention_processor で定義されているself.processor内のAttentionProcessorに渡される kwargs 辞書です。 - callback_on_step_end (
Callable、PipelineCallback、MultiPipelineCallbacks、省略可) — 推論中の各デノイジングステップの終了時に呼び出される関数、または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 が返され、それ以外の場合は tuple が返されます。この tuple の最初の要素は生成された画像のリストであり、2番目の要素は、対応する生成画像に「not-safe-for-work」(nsfw)コンテンツが含まれているかどうかを示す bool のリストです。
生成用の pipeline への呼び出し関数。
例:
>>> 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
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
パラメータ
- 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 デバイス - dtype — (
torch.dtype、省略可): torch の dtype
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
WanVideoToVideoPipeline
class diffusers.WanVideoToVideoPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModeltransformer: WanTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteScheduler )
パラメータ
- tokenizer (
T5Tokenizer) — T5 の Tokenizer、具体的には google/umt5-xxl バリアントです。 - text_encoder (
T5EncoderModel) — T5、具体的には google/umt5-xxl バリアントです。 - transformer (WanTransformer3DModel) — 入力潜在変数をノイズ除去するための条件付き Transformer。
- scheduler (UniPCMultistepScheduler) —
transformerと組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。 - vae (AutoencoderKLWan) — 潜在表現へのエンコードとデコードを行う、動画用の変分オートエンコーダ (VAE) モデル。
Wanを使用して、動画から動画への変換を行うためのPipelineです。
このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。
__call__
< source >( video: list[PIL.Image.Image] = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] = Noneheight: int = 480width: int = 832num_inference_steps: int = 50timesteps: list[int] | None = Noneguidance_scale: float = 5.0strength: float = 0.8num_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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[str] = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
パラメータ
- video (
list[PIL.Image.Image]) — The input video used as the starting point for video-to-video generation. The video should be provided as a list of PIL images, a numpy array, or a torch tensor. - 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], 任意) —timesteps引数をサポートするスケジューラーのset_timestepsメソッドで、デノイジングプロセスに使用するカスタムタイムステップ。未定義の場合、num_inference_stepsが渡された際のデフォルトの動作が使用されます。降順で指定する必要があります。 - guidance_scale (
float、デフォルト値は5.0) — Classifier-Free Diffusion Guidance で定義されているガイダンススケールです。guidance_scaleは、Imagen Paper の数式 2 のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 - strength (
float、デフォルト値は0.8) — 値を高くすると、元の画像と生成された動画の差が大きくなります。 - 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入力引数からテキスト埋め込みが生成されます。 - negative_prompt_embeds (
torch.Tensor, 任意) — 事前に生成されたネガティブなテキスト埋め込み。テキスト入力(プロンプトの重み付け)を簡単に調整するために使用できます。指定されない場合、negative_prompt_embedsはnegative_prompt入力引数から生成されます。 - output_type (
str、任意、デフォルトは"np") — 生成された画像の出力形式。PIL.Imageまたはnp.arrayから選択します。 - return_dict (
bool、省略可能、デフォルトはTrue) —WanPipelineOutputを返すか、プレーンなタプルを返すかを指定します。 - attention_kwargs (
dict, 省略可) — 指定された場合、diffusers.models.attention_processor で定義されているself.processor内のAttentionProcessorに渡される kwargs 辞書です。 - callback_on_step_end (
Callable、PipelineCallback、MultiPipelineCallbacks、省略可) — 推論中の各デノイジングステップの終了時に呼び出される関数、または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 が返され、それ以外の場合は tuple が返されます。この tuple の最初の要素は生成された画像のリストであり、2番目の要素は、対応する生成画像に「not-safe-for-work」(nsfw)コンテンツが含まれているかどうかを示す bool のリストです。
生成用の pipeline への呼び出し関数。
例:
>>> 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
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
パラメータ
- 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 デバイス - dtype — (
torch.dtype、省略可): torch の dtype
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
WanAnimatePipeline
class diffusers.WanAnimatePipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: UniPCMultistepSchedulerimage_processor: CLIPImageProcessorPilimage_encoder: CLIPVisionModeltransformer: WanAnimateTransformer3DModel )
パラメータ
- tokenizer (
T5Tokenizer) — T5 の Tokenizer、具体的には google/umt5-xxl バリアントです。 - text_encoder (
T5EncoderModel) — T5、具体的には google/umt5-xxl バリアントです。 - image_encoder (
CLIPVisionModel) — CLIP、具体的には clip-vit-huge-patch14 バリアントです。 - transformer (WanAnimateTransformer3DModel) — 入力潜在変数をデノイズするための条件付き Transformer。
- scheduler (UniPCMultistepScheduler) —
transformerと組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。 - vae (AutoencoderKLWan) — 潜在表現へのエンコードとデコードを行う、動画用の変分オートエンコーダ (VAE) モデル。
- image_processor (
CLIPImageProcessor) — エンコード前に画像を前処理するための画像プロセッサ。
Wan-Animate を用いた統一キャラクターアニメーションおよび置換の Pipeline です。
WanAnimatePipeline は、キャラクター画像、ポーズ動画、顔動画をインプットとして受け取り、2つのモードで動画を生成します。
アニメーションモード: モデルは、入力されたポーズ動画と顔動画に含まれる人間の動きを模倣して、キャラクター画像の動画を生成します。キャラクターは提供されたモーションコントロールに基づいてアニメーション化され、キャラクターの新しいアニメーション動画が作成されます。
置換モード: モデルは、ポーズ動画と顔動画を用いてモーションを制御し、背景動画内のキャラクターを指定されたキャラクター画像に置き換えます。このモードでは、追加の
background_videoとmask_video入力が必要です。マスク動画では、元のコンテンツを保持する領域を黒、新しいキャラクターを生成する領域を白としてください。
このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。
パイプラインは、以下の読み込みメソッドも継承します:
- LoRA重みの読み込みにload_lora_weights()
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]pose_video: list[PIL.Image.Image]face_video: list[PIL.Image.Image]background_video: list[PIL.Image.Image] | None = Nonemask_video: list[PIL.Image.Image] | None = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] = Noneheight: int = 720width: int = 1280segment_frame_length: int = 77num_inference_steps: int = 20mode: str = 'animate'prev_segment_conditioning_frames: int = 1motion_encode_batch_size: int | None = Noneguidance_scale: float = 1.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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneimage_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, NoneType], diffusers.callbacks.PipelineCallback | diffusers.callbacks.MultiPipelineCallbacks]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
パラメータ
- 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], optional) — 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) — 時間的なガイダンスに使用する、前の動画セグメントのフレーム数です。1または5を推奨します。一般的には、Nを非負整数として4N + 1であるべきです。 - motion_encode_batch_size (
int, 任意) — モーションエンコーダーによる顔動画のバッチ化エンコードにおけるバッチサイズです。バッチサイズを小さくすることで、推論速度とメモリ使用量のトレードオフを調整できます。設定されていない場合は、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 で定義されているガイダンススケールです。guidance_scaleは、Imagen Paper の数式 2 のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連する画像の生成が促されますが、通常は画像品質の低下を伴います。デフォルトでは、Wan Animate の推論では CFG は使用されません。 - 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入力引数からテキスト埋め込みが生成されます。 - 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 で定義されているself.processor内のAttentionProcessorに渡される kwargs 辞書です。 - callback_on_step_end (
Callable、PipelineCallback、MultiPipelineCallbacks、省略可) — 推論中の各デノイジングステップの終了時に呼び出される関数、または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 が返され、それ以外の場合は tuple が返されます。この tuple の最初の要素は生成された画像のリストであり、2番目の要素は、対応する生成画像に「not-safe-for-work」(nsfw)コンテンツが含まれているかどうかを示す bool のリストです。
生成用の pipeline への呼び出し関数。
例:
>>> 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
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
パラメータ
- 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 デバイス - dtype — (
torch.dtype、省略可): torch の dtype
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。
配列のような動画のframesを、“reflect”に似た戦略を用いてnum_target_framesにパディングします。フレーム次元は最初の次元であると仮定します。1次元の場合、この戦略は次のように視覚化できます。
pad_video_frames([1, 2, 3, 4, 5], 10) -> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2]
WanPipelineOutput
class diffusers.pipelines.wan.pipeline_output.WanPipelineOutput
< source >( frames: Tensor )
Wan パイプライン用の出力クラスです。