Diffusers 文件

Mochi 1 預覽版

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Mochi 1 預覽版

LoRA

目前只提供模型權重的研究預覽版。

Mochi 1 是 Genmo 開發的影片生成模型,其強大之處在於對提示詞的遵循度和運動質量。該模型採用 100 億引數的 Asymmetric Diffusion Transformer (AsymmDiT) 架構,並使用非方陣的 QKV 和輸出投影層以減少推理記憶體需求。使用單個 T5-XXL 模型對提示詞進行編碼。

Mochi 1 預覽版是一個開放的最先進影片生成模型,在初步評估中具有高保真運動和強大的提示詞遵循度。該模型顯著縮小了封閉式和開放式影片生成系統之間的差距。該模型以寬鬆的 Apache 2.0 許可證釋出。

請務必檢視排程器指南,瞭解如何探索排程器速度和質量之間的權衡,並檢視跨管道重用元件部分,瞭解如何有效地將相同元件載入到多個管道中。

量化

量化有助於透過以較低精度資料型別儲存模型權重來減少大型模型的記憶體需求。但是,量化對影片質量的影響可能因影片模型而異。

請參閱量化概述,瞭解更多支援的量化後端以及如何選擇支援您用例的量化後端。下面的示例演示如何載入量化的 MochiPipeline 進行 bitsandbytes 推理。

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,
    torch_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,
    torch_dtype=torch.float16,
)

pipeline = MochiPipeline.from_pretrained(
    "genmo/mochi-1-preview",
    text_encoder=text_encoder_8bit,
    transformer=transformer_8bit,
    torch_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 預覽版生成影片

以下示例將下載完整精度的 mochi-1-preview 權重並生成最高質量的結果,但至少需要 42GB 視訊記憶體才能執行。

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.enable_vae_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 視訊記憶體才能執行。因此,生成的影片質量會略有下降。

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

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

# Enable memory savings
pipe.enable_model_cpu_offload()
pipe.enable_vae_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,並將注意力核設定為 EFFICIENT_ATTENTION。Diffusers 管道目前不支援為管道的不同階段設定不同的 dtypes。為了以與原始實現相同的方式執行推理,請參考以下示例。

原始的 Mochi 實現將空提示詞歸零。然而,啟用此選項並將整個管道置於自動混合精度 (autocast) 下可能會導致 T5 文字編碼器出現數值溢位。

當啟用 force_zeros_for_empty_prompt 時,建議在自動混合精度上下文之外以全精度執行文字編碼步驟。

以全精度解碼潛變數會消耗大量記憶體。在本示例中,您至少需要 70GB 視訊記憶體才能生成 163 幀。為了減少記憶體,可以減少幀數或以 `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.enable_vae_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_mapmax_memory 選項將大型 Mochi 變換器拆分到多個 GPU 上。在以下示例中,我們將模型拆分到兩個 GPU 上,每個 GPU 都有 24GB 視訊記憶體。

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.enable_vae_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),
        max_sequence_length=256,
        output_type="pil",
    ).frames[0]

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

使用單檔案載入 Mochi 變換器

您可以使用 from_single_file 以其原始格式載入 Mochi 變換器。

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, torch_dtype=torch.bfloat16)

pipe = MochiPipeline.from_pretrained(model_id,  transformer=transformer)
pipe.enable_model_cpu_offload()
pipe.enable_vae_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),
        max_sequence_length=256,
        output_type="pil",
    ).frames[0]

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

MochiPipeline

diffusers.MochiPipeline

< >

( 排程器: FlowMatchEulerDiscreteScheduler vae: AutoencoderKLMochi 文字編碼器: T5EncoderModel 分詞器: T5TokenizerFast 變換器: MochiTransformer3DModel force_zeros_for_empty_prompt: bool = False )

引數

用於文字到影片生成的 Mochi 管道。

參考資料:https://github.com/genmoai/models

__call__

< >

( 提示: typing.Union[str, typing.List[str]] = None 反向提示: typing.Union[str, typing.List[str], NoneType] = None 高度: typing.Optional[int] = None 寬度: typing.Optional[int] = None 幀數: int = 19 推理步數: int = 64 時間步長: typing.List[int] = None 引導比例: float = 4.5 每個提示詞的影片數量: typing.Optional[int] = 1 生成器: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None 潛在向量: typing.Optional[torch.Tensor] = None 提示嵌入: typing.Optional[torch.Tensor] = None 提示注意力掩碼: typing.Optional[torch.Tensor] = None 反向提示嵌入: typing.Optional[torch.Tensor] = None 反向提示注意力掩碼: typing.Optional[torch.Tensor] = None 輸出型別: typing.Optional[str] = 'pil' 返回字典: bool = True 注意力引數: typing.Optional[typing.Dict[str, typing.Any]] = None 步進結束回撥: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None 步進結束回撥張量輸入: typing.List[str] = ['latents'] 最大序列長度: int = 256 ) ~pipelines.mochi.MochiPipelineOutputtuple

引數

  • 提示 (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳遞 prompt_embeds
  • 高度 (int, 可選, 預設為 self.default_height) — 生成影像的高度(畫素)。為了獲得最佳結果,預設設定為 480。
  • 寬度 (int, 可選, 預設為 self.default_width) — 生成影像的寬度(畫素)。為了獲得最佳結果,預設設定為 848。
  • 幀數 (int, 預設為 19) — 要生成的影片幀數
  • 推理步數 (int, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高的影像質量,但推理速度會變慢。
  • 時間步長 (List[int], 可選) — 用於去噪過程的自定義時間步長,適用於支援在 set_timesteps 方法中帶有 timesteps 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • 引導比例 (float, 預設為 4.5) — 無分類器擴散引導中定義的引導比例。guidance_scale 定義為 Imagen 論文中公式 2 的 w。透過設定 guidance_scale > 1 啟用引導比例。更高的引導比例會鼓勵生成與文字 prompt 緊密相關的影像,通常會犧牲影像質量。
  • 每個提示詞的影片數量 (int, 可選, 預設為 1) — 每個提示詞生成的影片數量。
  • 生成器 (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。
  • 潛在向量 (torch.Tensor, 可選) — 預生成的噪聲潛在向量,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同提示詞調整相同的生成。如果未提供,將使用提供的隨機 generator 取樣生成一個潛在張量。
  • 提示嵌入 (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • 提示注意力掩碼 (torch.Tensor, 可選) — 預生成的文字嵌入注意力掩碼。
  • 反向提示嵌入 (torch.FloatTensor, 可選) — 預生成的負文字嵌入。對於 PixArt-Sigma,此負提示應為空字串。如果未提供,負提示嵌入將從 negative_prompt 輸入引數生成。
  • 反向提示注意力掩碼 (torch.FloatTensor, 可選) — 預生成的負文字嵌入注意力掩碼。
  • 輸出型別 (str, 可選, 預設為 "pil") — 生成影像的輸出格式。可選擇 PIL: PIL.Image.Imagenp.array
  • 返回字典 (bool, 可選, 預設為 True) — 是否返回 ~pipelines.mochi.MochiPipelineOutput 而不是普通元組。
  • 注意力引數 (dict, 可選) — 一個 kwargs 字典,如果指定,將作為 self.processor 中定義的 AttentionProcessor 的引數傳遞給 diffusers.models.attention_processor
  • 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.MochiPipelineOutputtuple

如果return_dictTrue,則返回~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.enable_vae_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")

disable_vae_slicing

< >

( )

停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing,此方法將返回一步計算解碼。

disable_vae_tiling

< >

( )

停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling,此方法將恢復一步計算解碼。

enable_vae_slicing

< >

( )

啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。

enable_vae_tiling

< >

( )

啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = 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 (strList[str], 可選) — 待編碼的提示詞
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞negative_prompt_embeds。當不使用引導時(即,如果guidance_scale小於1時,則忽略)。
  • do_classifier_free_guidance (bool, 可選, 預設為True) — 是否使用無分類器引導。
  • num_videos_per_prompt (int, 可選, 預設為1) — 每個提示詞應生成的影片數量。用於放置結果嵌入的torch裝置
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將根據prompt輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,負面提示詞嵌入將根據negative_prompt輸入引數生成。
  • device — (torch.device, 可選): torch 裝置
  • dtype — (torch.dtype, 可選): torch 資料型別

將提示編碼為文字編碼器隱藏狀態。

MochiPipelineOutput

class 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 管道的輸出類。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.