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