Diffusers 文档
Mochi 1 预览版
并获得增强的文档体验
开始使用
Mochi 1 预览版
目前只提供模型权重的研究预览版。
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
。为了以与原始实现相同的方式运行推理,请参考以下示例。
当启用 force_zeros_for_empty_prompt
时,建议在自动混合精度上下文之外以全精度运行文本编码步骤。
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 变换器拆分到多个 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 变换器。
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 )
参数
- 变换器 (MochiTransformer3DModel) — 用于对编码后的视频潜变量进行去噪的条件变换器架构。
- 调度器 (FlowMatchEulerDiscreteScheduler) — 与
transformer
结合使用,用于对编码图像潜在进行去噪的调度器。 - vae (AutoencoderKLMochi) — 用于将视频编码和解码为潜在表示的变分自编码器 (VAE) 模型。
- text_encoder (
T5EncoderModel
) — T5,特别是 google/t5-v1_1-xxl 变体。 - 分词器 (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - 分词器 (
T5TokenizerFast
) — 第二个 T5TokenizerFast 类的分词器。
用于文本到视频生成的 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.MochiPipelineOutput
或 tuple
参数
- 提示 (
str
或List[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.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。 - 潜在向量 (
torch.Tensor
, 可选) — 预生成的噪声潜在向量,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示词调整相同的生成。如果未提供,将使用提供的随机generator
采样生成一个潜在张量。 - 提示嵌入 (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,文本嵌入将从prompt
输入参数生成。 - 提示注意力掩码 (
torch.Tensor
, 可选) — 预生成的文本嵌入注意力掩码。 - 反向提示嵌入 (
torch.FloatTensor
, 可选) — 预生成的负文本嵌入。对于 PixArt-Sigma,此负提示应为空字符串。如果未提供,负提示嵌入将从negative_prompt
输入参数生成。 - 反向提示注意力掩码 (
torch.FloatTensor
, 可选) — 预生成的负文本嵌入注意力掩码。 - 输出类型 (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。可选择 PIL:PIL.Image.Image
或np.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.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
< 源 >( 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]
, 可选) — 待编码的提示词 - negative_prompt (
str
或List[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 )
Mochi 管道的输出类。