Buckets:

mishig's picture
|
download
raw
25.7 kB

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

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

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

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

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

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

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

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

ライセンスの下での制限事項。

-->

Mochi 1 プレビュー

現時点では、モデルの重みの研究プレビューのみが利用可能です。

Mochi 1 は Genmo による動画生成モデルで、プロンプトの忠実性とモーションの品質に重点を置いています。このモデルは 10B パラメータの Asmmetric Diffusion Transformer (AsymmDiT) アーキテクチャを採用しており、非正方形の QKV および出力投影層を使用することで推論時のメモリ要件を削減しています。プロンプトのエンコードには単一の T5-XXL モデルが使用されます。

Mochi 1 preview は、高忠実度のモーションと、予備評価におけるプロンプトへの高い忠実性を備えた、オープンな最先端の動画生成モデルです。このモデルは、クローズドな動画生成システムとオープンな動画生成システムとの間のギャップを大幅に縮小します。このモデルは、寛容な Apache 2.0 ライセンスの下で公開されています。

スケジューラーのトレードオフ、すなわち速度と品質のバランスをどのように探求するかを学ぶには、ガイドを必ずご確認ください。また、同じコンポーネントを複数のパイプラインに効率的に読み込む方法については、パイプライン間でコンポーネントを再利用するセクションを参照してください。

量子化

Quantizationは、モデルの重みを低精度のデータ型で保存することで、非常に大規模なモデルのメモリ要件を軽減するのに役立ちます。ただし、動画モデルによって、Quantizationが動画の品質に与える影響は異なります。

サポートされている量子化バックエンドと、ユースケースに対応する量子化バックエンドの選択について詳しくは、Quantizationの概要を参照してください。以下の例では、bitsandbytesを使用して量子化されたMochiPipelineを読み込んで推論を実行する方法を示しています。

import torch
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, MochiTransformer3DModel, MochiPipeline
from diffusers.utils import export_to_video
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel

quant_config = BitsAndBytesConfig(load_in_8bit=True)
text_encoder_8bit = T5EncoderModel.from_pretrained(
    "genmo/mochi-1-preview",
    subfolder="text_encoder",
    quantization_config=quant_config,
    dtype=torch.float16,
)

quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
transformer_8bit = MochiTransformer3DModel.from_pretrained(
    "genmo/mochi-1-preview",
    subfolder="transformer",
    quantization_config=quant_config,
    dtype=torch.float16,
)

pipeline = MochiPipeline.from_pretrained(
    "genmo/mochi-1-preview",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    dtype=torch.float16,
    device_map="balanced",
)

video = pipeline(
  "Close-up of a cats eye, with the galaxy reflected in the cats eye. Ultra high resolution 4k.",
  num_inference_steps=28,
  guidance_scale=3.5
).frames[0]
export_to_video(video, "cat.mp4")

Mochi-1 Previewで動画を生成する

次の例では、フルプレシションのmochi-1-preview重みをダウンロードし、最高品質の結果を生成しますが、実行には少なくとも42GBのVRAMが必要です。

import torch
from diffusers import MochiPipeline
from diffusers.utils import export_to_video

pipe = MochiPipeline.from_pretrained("genmo/mochi-1-preview")

# Enable memory savings
pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()

prompt = "Close-up of a chameleon's eye, with its scaly skin changing color. Ultra high resolution 4k."

with torch.autocast("cuda", torch.bfloat16, cache_enabled=False):
      frames = pipe(prompt, num_frames=85).frames[0]

export_to_video(frames, "mochi.mp4", fps=30)

メモリを節約するために低精度のバリアントを使用する

次の例では、モデルのbfloat16バリアントを使用し、実行には22GBのVRAMが必要です。その結果、生成される動画の品質がわずかに低下します。

import torch
from diffusers import MochiPipeline
from diffusers.utils import export_to_video

pipe = MochiPipeline.from_pretrained("genmo/mochi-1-preview", variant="bf16", dtype=torch.bfloat16)

# Enable memory savings
pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()

prompt = "Close-up of a chameleon's eye, with its scaly skin changing color. Ultra high resolution 4k."
frames = pipe(prompt, num_frames=85).frames[0]

export_to_video(frames, "mochi.mp4", fps=30)

Genmo Mochi リポジトリの結果を再現する

Genmo Mochiの実装では、推論プロセスの各ステージで異なる精度値が使用されています。テキストエンコーダーとVAEはtorch.float32を使用し、DiTはtorch.bfloat16を使用するとともに、attentionカーネルがEFFICIENT_ATTENTIONに設定されています。Diffusersのパイプラインは、パイプラインの異なるステージに対して異なるdtypesを設定することを現在サポートしていません。元の実装と同様の方法で推論を実行するには、以下の例を参照してください。

元の Mochi 実装では、空のプロンプトをゼロにします。ただし、このオプションを有効にして、パイプライン全体を autocast の下で実行すると、T5 テキストエンコーダーで数値オーバーフローが発生する可能性があります。

force_zeros_for_empty_promptを有効にする場合、テキストエンコーディングのステップは、フル精度でautocastコンテキストの外で実行することをお勧めします。

フル精度で潜在変数(latents)をデコードするのは、メモリ消費量が非常に大きくなります。この例で163フレームを生成するには、少なくとも70GBのVRAMが必要です。メモリを削減するには、フレーム数を減らすか、デコード処理をtorch.bfloat16で実行してください。

import torch
from torch.nn.attention import SDPBackend, sdpa_kernel

from diffusers import MochiPipeline
from diffusers.utils import export_to_video
from diffusers.video_processor import VideoProcessor

pipe = MochiPipeline.from_pretrained("genmo/mochi-1-preview", force_zeros_for_empty_prompt=True)
pipe.vae.enable_tiling()
pipe.enable_model_cpu_offload()

prompt =  "An aerial shot of a parade of elephants walking across the African savannah. The camera showcases the herd and the surrounding landscape."

with torch.no_grad():
    prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask = (
        pipe.encode_prompt(prompt=prompt)
    )

with torch.autocast("cuda", torch.bfloat16):
    with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
        frames = pipe(
            prompt_embeds=prompt_embeds,
            prompt_attention_mask=prompt_attention_mask,
            negative_prompt_embeds=negative_prompt_embeds,
            negative_prompt_attention_mask=negative_prompt_attention_mask,
            guidance_scale=4.5,
            num_inference_steps=64,
            height=480,
            width=848,
            num_frames=163,
            generator=torch.Generator("cuda").manual_seed(0),
            output_type="latent",
            return_dict=False,
        )[0]

video_processor = VideoProcessor(vae_scale_factor=8)
has_latents_mean = hasattr(pipe.vae.config, "latents_mean") and pipe.vae.config.latents_mean is not None
has_latents_std = hasattr(pipe.vae.config, "latents_std") and pipe.vae.config.latents_std is not None
if has_latents_mean and has_latents_std:
    latents_mean = (
        torch.tensor(pipe.vae.config.latents_mean).view(1, 12, 1, 1, 1).to(frames.device, frames.dtype)
    )
    latents_std = (
        torch.tensor(pipe.vae.config.latents_std).view(1, 12, 1, 1, 1).to(frames.device, frames.dtype)
    )
    frames = frames * latents_std / pipe.vae.config.scaling_factor + latents_mean
else:
    frames = frames / pipe.vae.config.scaling_factor

with torch.no_grad():
    video = pipe.vae.decode(frames.to(pipe.vae.dtype), return_dict=False)[0]

video = video_processor.postprocess_video(video)[0]
export_to_video(video, "mochi.mp4", fps=30)

複数GPUでの推論の実行

from_pretrained の device_map と max_memory オプションを使用して、大規模な Mochi transformer を複数の GPU に分割して配置できます。次の例では、VRAM 24GB を搭載した 2 つの GPU にモデルを分割しています。

import torch
from diffusers import MochiPipeline, MochiTransformer3DModel
from diffusers.utils import export_to_video

model_id = "genmo/mochi-1-preview"
transformer = MochiTransformer3DModel.from_pretrained(
    model_id,
    subfolder="transformer",
    device_map="auto",
    max_memory={0: "24GB", 1: "24GB"}
)

pipe = MochiPipeline.from_pretrained(model_id,  transformer=transformer)
pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()

with torch.autocast(device_type="cuda", dtype=torch.bfloat16, cache_enabled=False):
    frames = pipe(
        prompt="Close-up of a chameleon's eye, with its scaly skin changing color. Ultra high resolution 4k.",
        negative_prompt="",
        height=480,
        width=848,
        num_frames=85,
        num_inference_steps=50,
        guidance_scale=4.5,
        num_videos_per_prompt=1,
        generator=torch.Generator(device="cuda").manual_seed(0),  # or "mps", "xpu", "cpu"
        max_sequence_length=256,
        output_type="pil",
    ).frames[0]

export_to_video(frames, "output.mp4", fps=30)

Mochi Transformer を用いた単一ファイル読み込み

from_single_file を使用して、Mochi transformer を元の形式で読み込むことができます。

Diffusers は現在、Mochi の単一ファイル形式のチェックポイントの FP8 スケール版の使用をサポートしていません。

import torch
from diffusers import MochiPipeline, MochiTransformer3DModel
from diffusers.utils import export_to_video

model_id = "genmo/mochi-1-preview"

ckpt_path = "https://huggingface.co/Comfy-Org/mochi_preview_repackaged/blob/main/split_files/diffusion_models/mochi_preview_bf16.safetensors"

transformer = MochiTransformer3DModel.from_pretrained(ckpt_path, dtype=torch.bfloat16)

pipe = MochiPipeline.from_pretrained(model_id,  transformer=transformer)
pipe.enable_model_cpu_offload()
pipe.vae.enable_tiling()

with torch.autocast(device_type="cuda", dtype=torch.bfloat16, cache_enabled=False):
    frames = pipe(
        prompt="Close-up of a chameleon's eye, with its scaly skin changing color. Ultra high resolution 4k.",
        negative_prompt="",
        height=480,
        width=848,
        num_frames=85,
        num_inference_steps=50,
        guidance_scale=4.5,
        num_videos_per_prompt=1,
        generator=torch.Generator(device="cuda").manual_seed(0),  # or "mps", "xpu", "cpu"
        max_sequence_length=256,
        output_type="pil",
    ).frames[0]

export_to_video(frames, "output.mp4", fps=30)

MochiPipeline[[diffusers.MochiPipeline]]

diffusers.MochiPipeline[[diffusers.MochiPipeline]]

diffusers.MochiPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLMochi, text_encoder: T5EncoderModel, tokenizer: T5Tokenizer, transformer: MochiTransformer3DModel, force_zeros_for_empty_prompt: bool = False)

ソース

パラメータ:

transformer (MochiTransformer3DModel) : エンコードされた動画の潜在変数をノイズ除去するための条件付き Transformer アーキテクチャ。

scheduler (FlowMatchEulerDiscreteScheduler) : transformer と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。

vae (AutoencoderKLMochi) : 動画を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。

text_encoder (T5EncoderModel) : T5、具体的には google/t5-v1_1-xxl バリアントです。

tokenizer (CLIPTokenizer) : クラス CLIPTokenizer の Tokenizer。

tokenizer (T5TokenizerFast) : クラス T5TokenizerFast の2番目の Tokenizer。

テキストから動画を生成するためのmochiパイプライン。

参考: https://github.com/genmoai/models

call[[diffusers.MochiPipeline.call]]

__call__(prompt: str | list[str] = None, negative_prompt: str | list[str] | None = None, height: int | None = None, width: int | None = None, num_frames: int = 19, num_inference_steps: int = 64, timesteps: list[int] = None, guidance_scale: float = 4.5, 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, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 256)

ソース

パラメータ:

prompt (str または list[str]、省略可) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに prompt_embeds を渡す必要があります。

negative_prompt (str または list[str]、任意) : 画像生成をガイドしないプロンプトです。定義されていない場合、代わりに negative_prompt_embeds を渡す必要があります。guidance を使用していない場合(guidance_scale < 1)は無視されます。

height (int、任意、デフォルトは self.default_height) : 生成される画像のピクセル単位の縦幅です。最適な結果を得るため、デフォルトでは 480 に設定されています。

width (int、任意、デフォルトは self.default_width) : 生成される画像の幅(ピクセル単位)です。最適な結果を得るため、デフォルトでは 848 に設定されています。

num_frames (int、デフォルトは19) : 生成する動画のフレーム数

num_inference_steps (int、任意、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。

timesteps (list[int]、任意) : set_timesteps メソッドで timesteps 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムタイムステップ。num_inference_steps が渡された場合のデフォルトの動作が使用されます。降順で指定する必要があります。

guidance_scale (float、デフォルトは4.5) : Classifier-Free Diffusion Guidanceで定義されているガイダンススケールです。guidance_scaleは、Imagen Paperの式2のwとして定義されています。guidance_scale > 1を設定することで、ガイダンススケールが有効になります。ガイダンススケールを高くすると、promptのテキストと密接に関連した画像の生成が促されますが、通常は画像の品質が低下する傾向があります。

num_videos_per_prompt (int、optional、デフォルトは 1) : プロンプトごとに生成する動画の数を指定します。

generator (torch.Generator または list[torch.Generator]、任意) : 生成を決定論的にするための torch ジェネレーター 1 つまたはそのリスト。

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

prompt_embeds (torch.Tensor, 任意) : 事前生成されたテキスト埋め込み。テキスト入力の調整、例えばプロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、prompt 入力引数からテキスト埋め込みが生成されます。

prompt_attention_mask (torch.Tensor, 任意) : テキスト埋め込み用の事前生成されたアテンションマスク。

negative_prompt_embeds (torch.FloatTensor, 任意) : 事前に生成されたネガティブテキスト埋め込み。PixArt-Sigma の場合、このネガティブプロンプトは "" である必要があります。指定されない場合、negative_prompt 入力引数から negative_prompt_embeds が生成されます。

negative_prompt_attention_mask (torch.FloatTensor、任意) : 負のテキスト埋め込み用の事前生成済みアテンションマスク。

output_type (str、任意、デフォルトは "pil") : 生成画像の出力形式。PIL(PIL.Image.Image)または np.array から選択します。

return_dict (bool、任意、デフォルトは True) : プレーンなタプルではなく ~pipelines.mochi.MochiPipelineOutput を返すかどうか。

attention_kwargs (dict, 任意) : 指定された場合、diffusers.models.attention_processor の self.processor で定義されている AttentionProcessor に渡される kwargs の辞書です。

callback_on_step_end (Callable、任意) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: 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、デフォルトは256) : promptに使用する最大シーケンス長。

戻り値: ~pipelines.mochi.MochiPipelineOutput または tuple

return_dict が True の場合、~pipelines.mochi.MochiPipelineOutput が返され、それ以外の場合は、最初の要素が生成された画像のリストである tuple が返されます。

生成用のパイプラインを呼び出したときに実行される関数。

例:

>>> import torch
>>> from diffusers import MochiPipeline
>>> from diffusers.utils import export_to_video

>>> pipe = MochiPipeline.from_pretrained("genmo/mochi-1-preview", torch_dtype=torch.bfloat16)
>>> pipe.enable_model_cpu_offload()
>>> pipe.vae.enable_tiling()
>>> prompt = "Close-up of a chameleon's eye, with its scaly skin changing color. Ultra high resolution 4k."
>>> frames = pipe(prompt, num_inference_steps=28, guidance_scale=3.5).frames[0]
>>> export_to_video(frames, "mochi.mp4")

encode_prompt[[diffusers.MochiPipeline.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, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 256, 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

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

MochiPipelineOutput[[diffusers.pipelines.mochi.pipeline_output.MochiPipelineOutput]]

diffusers.pipelines.mochi.pipeline_output.MochiPipelineOutput[[diffusers.pipelines.mochi.pipeline_output.MochiPipelineOutput]]

diffusers.pipelines.mochi.pipeline_output.MochiPipelineOutput(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 テンソルである場合もあります。

Mochi パイプライン用の出力クラスです。

Xet Storage Details

Size:
25.7 kB
·
Xet hash:
b02ed2de308a252d02fba36cda2c77798882aca6402c2a95ac84a9c3f73f1cf1

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