Diffusers documentation

Mochi 1 Bản xem trước

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Mochi 1 Bản xem trước

LoRA

Hiện tại chỉ có bản xem trước nghiên cứu của trọng số mô hình.

Mochi 1 là mô hình tạo video của Genmo, tập trung mạnh vào việc tuân thủ prompt và chất lượng chuyển động. Mô hình sử dụng kiến trúc Asmmetric Diffusion Transformer (AsymmDiT) với 10B tham số, và dùng các lớp chiếu QKV và đầu ra không vuông để giảm yêu cầu bộ nhớ suy luận. Một mô hình T5-XXL duy nhất được dùng để mã hóa prompt.

Mochi 1 preview là một mô hình tạo video mã nguồn mở đạt trạng thái tiên tiến, với chuyển động độ trung thực cao và khả năng tuân thủ prompt mạnh mẽ trong đánh giá sơ bộ. Mô hình này thu hẹp đáng kể khoảng cách giữa các hệ thống tạo video đóng và mở. Mô hình được phát hành theo giấy phép Apache 2.0 thoáng mở.

Hãy chắc chắn xem qua hướng dẫn về Schedulers để tìm hiểu cách khám phá sự đánh đổi giữa tốc độ và chất lượng của scheduler, và xem phần tái sử dụng các thành phần giữa các pipeline để tìm hiểu cách nạp các thành phần giống nhau vào nhiều pipeline một cách hiệu quả.

Lượng tử hóa

Quantization giúp giảm yêu cầu về bộ nhớ của các mô hình rất lớn bằng cách lưu trữ trọng số mô hình trong kiểu dữ liệu có độ chính xác thấp hơn. Tuy nhiên, lượng tử hóa có thể ảnh hưởng khác nhau đến chất lượng video tùy thuộc vào mô hình video.

Tham khảo phần tổng quan Lượng tử hóa để tìm hiểu thêm về các backend lượng tử hóa được hỗ trợ và cách chọn một backend lượng tử hóa phù hợp với trường hợp sử dụng của bạn. Ví dụ bên dưới minh họa cách tải một MochiPipeline đã được lượng tử hóa để suy luận bằng 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,
    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")

Tạo video với Mochi-1 Preview

Ví dụ sau sẽ tải trọng số độ chính xác đầy đủ của mochi-1-preview và tạo ra kết quả có chất lượng cao nhất, nhưng sẽ yêu cầu ít nhất 42GB VRAM để chạy.

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)

Sử dụng biến thể có độ chính xác thấp hơn để tiết kiệm bộ nhớ

Ví dụ sau sẽ sử dụng biến thể bfloat16 của mô hình và cần 22GB VRAM để chạy. Kết quả là chất lượng video được tạo ra sẽ giảm đi một chút.

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)

Tái tạo kết quả từ kho Genmo Mochi

Genmo Mochi implementation sử dụng các giá trị độ chính xác khác nhau cho từng giai đoạn trong quá trình suy luận. Bộ mã hóa văn bản và VAE sử dụng torch.float32, trong khi DiT sử dụng torch.bfloat16 với attention kernel được đặt thành EFFICIENT_ATTENTION. Các pipeline của Diffusers hiện tại không hỗ trợ việc đặt các dtypes khác nhau cho các giai đoạn khác nhau của pipeline. Để chạy suy luận theo cách tương tự như bản triển khai gốc, vui lòng tham khảo ví dụ sau.

Cài đặt Mochi gốc sẽ đặt các prompt rỗng về số 0. Tuy nhiên, việc bật tùy chọn này và đặt toàn bộ pipeline dưới autocast có thể dẫn đến tràn số với bộ mã hóa văn bản T5.

Khi bật force_zeros_for_empty_prompt, khuyến nghị thực hiện bước mã hóa văn bản bên ngoài ngữ cảnh autocast ở độ chính xác đầy đủ.

Việc giải mã các biến tiềm ẩn (latents) ở độ chính xác đầy đủ tiêu tốn rất nhiều bộ nhớ. Bạn sẽ cần ít nhất 70GB VRAM để tạo ra 163 khung hình trong ví dụ này. Để giảm bộ nhớ, hãy giảm số lượng khung hình hoặc chạy bước giải mã ở 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)

Chạy suy luận với nhiều GPU

Bạn có thể chia nhỏ transformer Mochi lớn trên nhiều GPU bằng cách sử dụng các tùy chọn device_map và max_memory trong from_pretrained. Trong ví dụ sau, chúng ta chia mô hình trên hai GPU, mỗi GPU có 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.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)

Sử dụng tải tệp đơn với Mochi Transformer

Bạn có thể sử dụng from_single_file để nạp transformer Mochi ở định dạng gốc.

Diffusers hiện chưa hỗ trợ việc sử dụng các phiên bản FP8 đã được scale của các checkpoint tệp đơn của 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, 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

lớp diffusers.MochiPipeline

< >

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

Tham số

  • transformer (MochiTransformer3DModel) — Kiến trúc Transformer có điều kiện để khử nhiễu các latents video đã mã hóa.
  • scheduler (FlowMatchEulerDiscreteScheduler) — Một scheduler được sử dụng kết hợp với transformer để khử nhiễu các latents ảnh đã được mã hóa.
  • vae (AutoencoderKLMochi) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
  • text_encoder (T5EncoderModel) — T5, cụ thể là biến thể google/t5-v1_1-xxl.
  • tokenizer (CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer.
  • tokenizer (T5TokenizerFast) — Tokenizer thứ hai thuộc lớp T5TokenizerFast.

Pipeline mochi cho việc tạo video từ văn bản.

Tham khảo: 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

Tham số

  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền prompt_embeds thay thế.
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1).
  • height (int, tùy chọn, mặc định là self.default_height) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Mặc định được đặt là 480 để đạt kết quả tốt nhất.
  • width (int, tùy chọn, mặc định là self.default_width) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. Mặc định được đặt là 848 để đạt kết quả tốt nhất.
  • num_frames (int, mặc định là 19) — Số lượng khung hình video cần tạo
  • num_inference_steps (int, tùy chọn, mặc định là 50) — Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn với chi phí là suy luận chậm hơn.
  • timesteps (list[int], tùy chọn) — Các bước thời gian tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ đối số timesteps trong phương thức set_timesteps của chúng. Nếu không được định nghĩa, hành vi mặc định khi num_inference_steps được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.
  • guidance_scale (float, mặc định là 4.5) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance. guidance_scale được định nghĩa là w của phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặt guidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ với prompt văn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn.
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt.
  • generator (torch.Generator hoặc list[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất định.
  • latents (torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp.
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • prompt_attention_mask (torch.Tensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản.
  • negative_prompt_embeds (torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Đối với PixArt-Sigma, prompt âm này nên là "". Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • negative_prompt_attention_mask (torch.FloatTensor, tùy chọn) — Mặt nạ chú ý (attention mask) được tạo trước cho các vector nhúng văn bản âm (negative text embeddings).
  • output_type (str, tùy chọn, mặc định là "pil") — Định dạng đầu ra của hình ảnh được tạo. Chọn giữa PIL: PIL.Image.Image hoặc np.array.
  • return_dict (bool, tùy chọn, mặc định là True) — Có nên trả về một ~pipelines.mochi.MochiPipelineOutput thay vì một tuple thông thường hay không.
  • attention_kwargs (dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa dưới self.processor trong diffusers.models.attention_processor.
  • callback_on_step_end (Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs sẽ bao gồm danh sách tất cả các tensor như được chỉ định bởi callback_on_step_end_tensor_inputs.
  • callback_on_step_end_tensor_inputs (list, optional) — Danh sách các tensor đầu vào cho hàm callback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số callback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính ._callback_tensor_inputs của lớp pipeline của bạn.
  • max_sequence_length (int mặc định là 256) — Chiều dài tối đa của chuỗi để sử dụng với prompt.

Trả về

~pipelines.mochi.MochiPipelineOutput hoặc tuple

Nếu return_dict là True, ~pipelines.mochi.MochiPipelineOutput sẽ được trả về, ngược lại một tuple sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:

>>> 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 )

Tham số

  • prompt (str hoặc list[str], tùy chọn) — prompt cần được mã hóa
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • do_classifier_free_guidance (bool, tùy chọn, mặc định là True) — Có sử dụng classifier free guidance hay không.
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • negative_prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • device — (torch.device, tùy chọn): thiết bị torch
  • dtype — (torch.dtype, tùy chọn): torch dtype

Mã hóa prompt thành các trạng thái ẩn của text encoder.

MochiPipelineOutput

lớp diffusers.pipelines.mochi.pipeline_output.MochiPipelineOutput

< >

( frames: Tensor )

Tham số

  • frames (torch.Tensor, np.ndarray, hoặc list[list[PIL.Image.Image]]) — danh sách các đầu ra video - Có thể là một danh sách lồng nhau có độ dài batch_size, trong đó mỗi danh sách con chứa các chuỗi hình ảnh PIL đã khử nhiễu có độ dài num_frames. Nó cũng có thể là một mảng NumPy hoặc tensor Torch có hình dạng (batch_size, num_frames, channels, height, width).

Lớp đầu ra cho các pipeline Mochi.

Update on GitHub