Diffusers documentation

Mochi 1 Preview

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

and get access to the augmented documentation experience

to get started

Mochi 1 Preview

LoRA

현재는 모델 가중치의 연구용 미리보기만 제공됩니다.

Mochi 1은 Genmo에서 개발한 비디오 생성 모델로, 프롬프트 준수와 모션 품질에 중점을 두고 있습니다. 이 모델은 10B 파라미터의 Asmmetric Diffusion Transformer(AsymmDiT) 아키텍처를 갖추고 있으며, 추론 시 메모리 요구량을 줄이기 위해 비정방형(non-square) QKV 및 출력 투영 레이어를 사용합니다. 프롬프트 인코딩에는 단일 T5-XXL 모델이 사용됩니다.

Mochi 1 preview는 예비 평가에서 높은 충실도의 움직임과 강력한 프롬프트 준수 능력을 갖춘 오픈 최첨단 비디오 생성 모델입니다. 이 모델은 폐쇄형과 오픈형 비디오 생성 시스템 간의 격차를 크게 줄였습니다. 이 모델은 관대한 Apache 2.0 라이선스로 공개되었습니다.

Scheduler의 가이드를 확인하여 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법을 배우고, 파이프라인 간 구성 요소 재사용 섹션을 확인하여 동일한 구성 요소를 여러 파이프라인에 효율적으로 로드하는 방법을 배워보세요.

양자화

Quantization은 모델 가중치를 더 낮은 정밀도의 데이터 타입으로 저장하여 매우 큰 모델의 메모리 요구 사항을 줄이는 데 도움이 됩니다. 그러나 quantization은 비디오 모델에 따라 비디오 품질에 다양한 영향을 미칠 수 있습니다.

지원되는 양자화 백엔드와 사용 사례에 맞는 양자화 백엔드 선택에 대해 자세히 알아보려면 Quantization 개요를 참조하세요. 아래 예제는 bitsandbytes를 사용하여 추론을 위해 양자화된 MochiPipeline을 로드하는 방법을 보여줍니다.

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

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

메모리를 절약하기 위해 낮은 정밀도 변형 사용

다음 예제는 모델의 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", 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)

Genmo Mochi 저장소의 결과를 재현하기

Genmo Mochi 구현은 추론 과정의 각 단계에 대해 다른 정밀도 값을 사용합니다. 텍스트 인코더와 VAE는 torch.float32를 사용하는 반면, DiT는 attention kernel을 EFFICIENT_ATTENTION으로 설정하고 torch.bfloat16를 사용합니다. Diffusers 파이프라인은 현재 파이프라인의 서로 다른 단계에 대해 서로 다른 dtypes를 설정하는 것을 지원하지 않습니다. 원래 구현과 동일한 방식으로 추론을 실행하려면 다음 예시를 참고하세요.

original Mochi implementation은 빈 프롬프트를 0으로 초기화합니다. 그러나 이 옵션을 활성화하고 파이프라인 전체를 autocast 아래에 두면 T5 텍스트 인코더에서 수치 오버플로가 발생할 수 있습니다.

force_zeros_for_empty_prompt를 활성화할 경우, 텍스트 인코딩 단계를 전체 정밀도로 autocast 컨텍스트 외부에서 실행하는 것이 권장됩니다.

전체 정밀도로 latents를 디코딩하는 것은 메모리 사용량이 매우 높습니다. 이 예시의 163프레임을 생성하려면 최소 70GB의 VRAM이 필요합니다. 메모리를 줄이려면 프레임 수를 줄이거나 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)

여러 GPU를 사용하여 추론 실행

from_pretrained의 device_map 및 max_memory 옵션을 사용하여 대형 Mochi transformer를 여러 GPU에 나눠 배치할 수 있습니다. 다음 예시에서는 VRAM이 24GB인 두 개의 GPU에 모델을 나눠 배치합니다.

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)

Mochi Transformer를 사용한 단일 파일 로딩

from_single_file를 사용하여 Mochi transformer를 원래 형식으로 로드할 수 있습니다.

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

클래스 diffusers.MochiPipeline

< >

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

매개변수

  • transformer (MochiTransformer3DModel) — 인코딩된 비디오 잠재 변수를 디노이즈하기 위한 조건부 Transformer 아키텍처.
  • scheduler (FlowMatchEulerDiscreteScheduler) — transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • vae (AutoencoderKLMochi) — 잠재 표현으로 비디오를 인코딩 및 디코딩하는 Variational Auto-Encoder (VAE) 모델.
  • text_encoder (T5EncoderModel) — 구체적으로 google/t5-v1_1-xxl 변형을 사용하는 T5입니다.
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저.
  • tokenizer (T5TokenizerFast) — T5TokenizerFast 클래스의 두 번째 토크나이저.

텍스트-투-비디오 생성을 위한 mochi 파이프라인.

참고: 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 = 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 = ['latents']max_sequence_length: int = 256 ) → ~pipelines.mochi.MochiPipelineOutput or tuple

매개변수

  • prompt (str 또는 list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 prompt_embeds를 대신 전달해야 합니다.
  • negative_prompt (str 또는 list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 negative_prompt_embeds를 전달해야 합니다. 가이던스를 사용하지 않을 때(guidance_scale < 1) 무시됩니다.
  • height (int, 선택 사항, 기본값 self.default_height) — 생성된 이미지의 픽셀 단위 높이입니다. 최적의 결과를 위해 기본값은 480으로 설정되어 있습니다.
  • width (int, 선택 사항, 기본값 self.default_width) — 생성된 이미지의 픽셀 단위 너비입니다. 최적의 결과를 위해 기본값은 848로 설정되어 있습니다.
  • num_frames (int, 기본값 19) — 생성할 비디오 프레임의 수
  • num_inference_steps (int, 선택 사항, 기본값 50) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다.
  • timesteps (list[int], 선택 사항) — timesteps 인수를 지원하는 스케줄러의 set_timesteps 메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우, num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다.
  • guidance_scale (float, 기본값 4.5) — Classifier-Free Diffusion Guidance에서 정의한 가이던스 스케일입니다. guidance_scale은 Imagen Paper의 방정식 2의 w로 정의됩니다. guidance_scale > 1로 설정하면 가이던스 스케일이 활성화됩니다. 가이던스 스케일이 높을수록 prompt 텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다.
  • num_videos_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 비디오의 수입니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록
  • latents (torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다.
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • prompt_attention_mask (torch.Tensor, 선택 사항) — 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • negative_prompt_embeds (torch.FloatTensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. PixArt-Sigma의 경우 이 negative prompt는 ""여야 합니다. 제공되지 않으면 negative_prompt 입력 인수에서 negative_prompt_embeds가 생성됩니다.
  • negative_prompt_attention_mask (torch.FloatTensor, 선택 사항) — 부정 텍스트 임베딩을 위한 사전 생성된 어텐션 마스크입니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 이미지 생성의 출력 형식입니다. PIL: PIL.Image.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — 일반 튜플 대신 ~pipelines.mochi.MochiPipelineOutput를 반환할지 여부.
  • attention_kwargs (dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의 self.processor에서 정의된 AttentionProcessor로 전달되는 kwargs 사전입니다.
  • 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.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 )

매개변수

  • prompt (str 또는 list[str], 선택 사항) — 인코딩할 프롬프트
  • negative_prompt (str 또는 list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때 무시됩니다(즉, guidance_scale이 1보다 작으면 무시됩니다).
  • do_classifier_free_guidance (bool, 선택 사항, 기본값 True) — classifier free guidance를 사용할지 여부.
  • num_videos_per_prompt (int, 선택 사항, 기본값 1) — 프롬프트당 생성할 비디오의 수. 결과 임베딩을 배치할 torch device
  • prompt_embeds (torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 prompt 입력 인자로부터 텍스트 임베딩이 생성됩니다.
  • negative_prompt_embeds (torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • device — (torch.device, 선택 사항): torch device
  • dtype — (torch.dtype, 선택 사항): torch dtype

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

MochiPipelineOutput

클래스 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 파이프라인의 출력 클래스입니다.

Update on GitHub