Diffusers 文档
Mochi 1 Preview
并获取增强的文档体验
开始使用
Mochi 1 Preview
Mochi 1 preview 是一个开放的先进视频生成模型,在初步评估中具有高保真运动和强大的 prompt 遵循能力。该模型显著缩小了封闭式和开放式视频生成系统之间的差距。该模型根据宽松的 Apache 2.0 许可证发布。
请务必查看调度器指南,了解如何探索调度器速度和质量之间的权衡,并查看跨 pipelines 重用组件部分,了解如何有效地将相同的组件加载到多个 pipelines 中。
使用 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.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 VRAM 才能运行。 生成视频的质量会因此略有下降。
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 repo 中的结果
Genmo Mochi 实现 在推理过程的每个阶段使用不同的精度值。文本编码器和 VAE 使用 torch.float32
,而 DiT 使用 torch.bfloat16
,并将 attention kernel 设置为 EFFICIENT_ATTENTION
。Diffusers pipelines 目前不支持为 pipeline 的不同阶段设置不同的 dtypes
。为了以与原始实现相同的方式运行推理,请参考以下示例。
当启用 force_zeros_for_empty_prompt
时,建议在全精度下在 autocast 上下文之外运行文本编码步骤。
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_map
和 max_memory
选项将大型 Mochi transformer 拆分到多个 GPU 上。在以下示例中,我们将模型拆分到两个 GPU 上,每个 GPU 具有 24GB 的 VRAM。
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 Transformer 结合使用
您可以使用 from_single_file
以原始格式加载 Mochi transformer。
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
class diffusers.MochiPipeline
< source >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: T5EncoderModel tokenizer: T5TokenizerFast transformer: MochiTransformer3DModel force_zeros_for_empty_prompt: bool = False )
参数
- transformer (MochiTransformer3DModel) — 条件 Transformer 架构,用于对编码后的视频 latent 进行去噪。
- scheduler (FlowMatchEulerDiscreteScheduler) — 与
transformer
结合使用的 scheduler,用于对编码后的图像 latent 进行去噪。 - vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为 latent 表示形式和从 latent 表示形式解码图像。
- text_encoder (
T5EncoderModel
) — T5,特别是 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - tokenizer (
T5TokenizerFast
) — T5TokenizerFast 类的第二个分词器。
用于文本到视频生成的 mochi pipeline。
参考:https://github.com/genmoai/models
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_frames: int = 19 num_inference_steps: int = 64 timesteps: typing.List[int] = None guidance_scale: float = 4.5 num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.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: typing.Optional[str] = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 256 ) → ~pipelines.mochi.MochiPipelineOutput
或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的 prompt。如果未定义,则必须改为传递prompt_embeds
。 - 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
参数的 scheduler 的去噪过程的自定义 timesteps。如果未定义,将使用传递num_inference_steps
时的默认行为。 必须按降序排列。 - guidance_scale (
float
, 默认为4.5
) — Classifier-Free Diffusion Guidance 中定义的 Guidance scale。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。通过设置guidance_scale > 1
启用 Guidance scale。较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,但通常以较低的图像质量为代价。 - num_videos_per_prompt (
int
, optional, defaults to 1) — 每个提示生成的视频数量。 - generator (
torch.Generator
或List[torch.Generator]
, optional) — 一个或一组 torch 生成器,用于使生成具有确定性。 - latents (
torch.Tensor
, optional) — 预生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,则将使用提供的随机generator
采样生成潜在张量。 - prompt_embeds (
torch.Tensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - prompt_attention_mask (
torch.Tensor
, optional) — 文本嵌入的预生成注意力掩码。 - negative_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的负面文本嵌入。对于 PixArt-Sigma,此负面提示应为 ""。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - negative_prompt_attention_mask (
torch.FloatTensor
, optional) — 负面文本嵌入的预生成注意力掩码。 - output_type (
str
, optional, defaults to"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回~pipelines.mochi.MochiPipelineOutput
而不是普通元组。 - attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则传递给 diffusers.models.attention_processor 中self.processor
下定义的AttentionProcessor
。 - callback_on_step_end (
Callable
, optional) — 一个在推理期间的每个去噪步骤结束时调用的函数。该函数使用以下参数调用: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
, optional) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您将只能包含在管道类的._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
defaults to256
) — 与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.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")
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将恢复为一步计算解码。
禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling
,此方法将恢复为一步计算解码。
启用切片 VAE 解码。启用此选项后,VAE 将把输入张量拆分为切片,以分步计算解码。这有助于节省一些内存并允许更大的批量大小。
启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成平铺块,以分步计算解码和编码。这对于节省大量内存并允许处理更大的图像非常有用。
encode_prompt
< source >( 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 (
str
或List[str]
, optional) — 要编码的提示 - negative_prompt (
str
或List[str]
, optional) — 不引导图像生成的提示或提示列表。如果未定义,则必须传递negative_prompt_embeds
来代替。当不使用引导时忽略(即,如果guidance_scale
小于1
则忽略)。 - do_classifier_free_guidance (
bool
, optional, defaults toTrue
) — 是否使用无分类器引导。 - num_videos_per_prompt (
int
, optional, defaults to 1) — 每个提示应生成的视频数量。用于放置结果嵌入的 torch 设备 - prompt_embeds (
torch.Tensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - device — (
torch.device
, optional): torch 设备 - dtype — (
torch.dtype
, 可选): torch dtype
将 prompt 编码为文本编码器隐藏状态。
MochiPipelineOutput
类 diffusers.pipelines.mochi.pipeline_output.MochiPipelineOutput
< 源码 >( frames: Tensor )
Mochi pipeline 的输出类。