Buckets:

mishig's picture
|
download
raw
110 kB

Apache License, Version 2.0(「ライセンス」)の下でライセンスされています。

このファイルは、ライセンスに準拠した場合にのみ使用できます。

ライセンスのコピーは以下から入手できます

http://www.apache.org/licenses/LICENSE-2.0

適用される法律で要求される場合、または書面による合意がある場合を除き、ソフトウェア

ライセンスに基づき配布される本ソフトウェアは、「現状のまま」

明示的または黙示的を問わず、いかなる種類の保証や条件も付随しません。

権限を管理する特定の言語については、ライセンスを参照してください。

ライセンスの下での制限。-->

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モデルをクリックすると、動画生成のより多くの例を確認できます。

テキストから動画の生成

以下の例では、メモリまたは推論速度に最適化されたテキストから動画の生成方法を示しています。

メモリ使用量の削減に関する詳細については、メモリ使用量の削減ガイドを参照してください。

以下の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つの動作モードをサポートしています:

  1. アニメーションモード(デフォルト): 参照動画の動きと表情に基づいて、キャラクターの画像をアニメーション化します
  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[[diffusers.WanPipeline]]

diffusers.WanPipeline[[diffusers.WanPipeline]]

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)

ソース

パラメータ:

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[[diffusers.WanPipeline.call]]

__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[str] = ['latents'], max_sequence_length: int = 512)

ソース

パラメータ:

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, 任意) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、ラテンツのテンソルが生成されます。

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[[diffusers.WanPipeline.encode_prompt]]

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)

ソース

パラメータ:

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、optional、デフォルトは 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[[diffusers.WanImageToVideoPipeline]]

diffusers.WanImageToVideoPipeline[[diffusers.WanImageToVideoPipeline]]

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)

ソース

パラメータ:

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[[diffusers.WanImageToVideoPipeline.call]]

__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[str] = ['latents'], max_sequence_length: int = 512)

ソース

パラメータ:

image (PipelineImageInput) : 生成を条件づけるための入力画像。画像、画像のリスト、またはtorch.Tensorである必要があります。

last_image (torch.Tensor, optional) : 生成される動画の条件として指定する、任意の最後のフレームです。指定された場合、モデルは 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, 任意) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、ラテンツのテンソルが生成されます。

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[[diffusers.WanImageToVideoPipeline.encode_prompt]]

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)

ソース

パラメータ:

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、optional、デフォルトは 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[[diffusers.WanVACEPipeline]]

diffusers.WanVACEPipeline[[diffusers.WanVACEPipeline]]

diffusers.WanVACEPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: FlowMatchEulerDiscreteScheduler, transformer: WanVACETransformer3DModel = None, transformer_2: WanVACETransformer3DModel = None, boundary_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[[diffusers.WanVACEPipeline.call]]

__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[str] = ['latents'], max_sequence_length: int = 512)

ソース

パラメータ:

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 layer で、denoising latent stream に control conditioning latent stream を加算する際に適用される条件付けのスケールです。float が指定された場合、すべてのレイヤーに均一に適用されます。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で定義されるガイダンススケール。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, 任意) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、ラテンツのテンソルが生成されます。

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[[diffusers.WanVACEPipeline.encode_prompt]]

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)

ソース

パラメータ:

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、optional、デフォルトは 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[[diffusers.WanVideoToVideoPipeline]]

diffusers.WanVideoToVideoPipeline[[diffusers.WanVideoToVideoPipeline]]

diffusers.WanVideoToVideoPipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, transformer: WanTransformer3DModel, vae: AutoencoderKLWan, scheduler: 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[[diffusers.WanVideoToVideoPipeline.call]]

__call__(video: list[PIL.Image.Image] = 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[str] = ['latents'], max_sequence_length: int = 512)

ソース

パラメータ:

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]、任意) : set_timesteps メソッドで 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, 任意) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、ラテンツのテンソルが生成されます。

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[[diffusers.WanVideoToVideoPipeline.encode_prompt]]

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)

ソース

パラメータ:

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、optional、デフォルトは 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[[diffusers.WanAnimatePipeline]]

diffusers.WanAnimatePipeline[[diffusers.WanAnimatePipeline]]

diffusers.WanAnimatePipeline(tokenizer: AutoTokenizer, text_encoder: UMT5EncoderModel, vae: AutoencoderKLWan, scheduler: UniPCMultistepScheduler, image_processor: CLIPImageProcessorPil, image_encoder: CLIPVisionModel, transformer: 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つのモードで動画を生成します。

  1. アニメーションモード: モデルは、入力されたポーズ動画と顔動画に含まれる人間の動きを模倣するように、キャラクター画像の動画を生成します。提供されたモーションコントロールに基づいてキャラクターがアニメーション化され、キャラクターの新しいアニメーション動画が作成されます。

  2. 置換モード: モデルは、ポーズ動画と顔動画を用いてモーションを制御し、背景動画内のキャラクターを指定されたキャラクター画像に置き換えます。このモードでは、追加の background_video と mask_video 入力が必要です。マスク動画では、元のコンテンツを保持する領域を黒、新しいキャラクターを生成する領域を白としてください。

このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに実装されている汎用的なメソッド(ダウンロード、保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。

パイプラインは、以下の読み込みメソッドも継承します:

call[[diffusers.WanAnimatePipeline.call]]

__call__(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 = 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[str] = ['latents'], max_sequence_length: int = 512)

ソース

パラメータ:

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, optional) : モーションエンコーダーによる顔動画のバッチエンコーディングにおけるバッチサイズです。バッチサイズを小さくすることで、推論速度とメモリ使用量のトレードオフを行うことができます。設定されない場合、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, 任意) : 画像生成の入力として使用される、ガウス分布からサンプリングされた事前生成されたノイジー・ラテンツ。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダムgeneratorを使用してサンプリングを行い、ラテンツのテンソルが生成されます。

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[[diffusers.WanAnimatePipeline.encode_prompt]]

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)

ソース

パラメータ:

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、optional、デフォルトは 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

プロンプトをテキストエンコーダーの隠れ状態にエンコードします。

pad_video_frames[[diffusers.WanAnimatePipeline.pad_video_frames]]

pad_video_frames(frames: list[typing.Any], num_target_frames: int)

ソース

配列のような動画の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[[diffusers.pipelines.wan.pipeline_output.WanPipelineOutput]]

diffusers.pipelines.wan.pipeline_output.WanPipelineOutput[[diffusers.pipelines.wan.pipeline_output.WanPipelineOutput]]

diffusers.pipelines.wan.pipeline_output.WanPipelineOutput(frames: Tensor)

ソース

パラメータ:

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:
110 kB
·
Xet hash:
a6191efb6af960ba4b41ff50ad8478802a41cabe69c9773c7b438f1a9f18c3ff

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