Diffusers documentation

Mochi 1 プレビュー

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Mochi 1 プレビュー

LoRA

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

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

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLMochitext_encoder: T5EncoderModeltokenizer: T5Tokenizertransformer: MochiTransformer3DModelforce_zeros_for_empty_prompt: bool = False )

パラメータ

  • transformer (MochiTransformer3DModel) — エンコードされた動画の潜在変数をノイズ除去するための条件付き Transformer アーキテクチャ。
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer と組み合わせて、エンコードされた画像の潜在変数からノイズを除去するために使用するスケジューラ。
  • vae (AutoencoderKLMochi) — 動画を潜在表現にエンコードし、潜在表現からデコードするための Variational Auto-Encoder (VAE) モデル。
  • text_encoder (T5EncoderModel) — 具体的には、T5 の google/t5-v1_1-xxl バリアントです。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer クラスのトークナイザー。
  • tokenizer (T5TokenizerFast) — クラス T5TokenizerFast の 2 つ目の Tokenizer。

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

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

__call__

< >

( prompt: str | list[str] = Nonenegative_prompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_frames: int = 19num_inference_steps: int = 64timesteps: list[int] = Noneguidance_scale: float = 4.5num_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] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 256 ) → ~pipelines.mochi.MochiPipelineOutput or tuple

パラメータ

  • 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], 任意) — timesteps 引数をサポートするスケジューラーの set_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、任意、デフォルト値は 1) — 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

< >

( 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] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 256device: 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

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

MochiPipelineOutput

クラス diffusers.pipelines.mochi.pipeline_output.MochiPipelineOutput

< >

( frames: Tensor )

パラメータ

  • frames (torch.Tensor, np.ndarray, or list[list[PIL.Image.Image]]) — 動画出力のリストです。batch_size, 長のネストされたリストであり、各サブリストが num_frames. 長のノイズ除去済み PIL 画像シーケンスを含む形式をとることもできます。また、(batch_size, num_frames, channels, height, width) の形状を持つ NumPy 配列や Torch テンソルとしても指定できます。

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

Update on GitHub