From 9ecd90b037361b994550db65b48690fbd9204fc6 Mon Sep 17 00:00:00 2001 From: Your Name Date: Wed, 29 Oct 2025 12:17:07 +0000 Subject: [PATCH] VideoAsPrompt CogVideoX --- __init__.py | 3 + attention_processor_mot.py | 117 +++ cogvideox_transformer_3d_mot.py | 1108 ++++++++++++++++++++++++ embeddings_mot.py | 148 ++++ nodes.py | 136 +++ pipeline_cogvideox_image2video_mot.py | 1129 +++++++++++++++++++++++++ rh_config.json | 1 + 7 files changed, 2642 insertions(+) create mode 100644 __init__.py create mode 100644 attention_processor_mot.py create mode 100644 cogvideox_transformer_3d_mot.py create mode 100644 embeddings_mot.py create mode 100644 nodes.py create mode 100644 pipeline_cogvideox_image2video_mot.py create mode 100644 rh_config.json diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..76028e6 --- /dev/null +++ b/__init__.py @@ -0,0 +1,3 @@ +from .nodes import NODE_CLASS_MAPPINGS +NODE_DISPLAY_NAME_MAPPINGS = {k:k for k,v in NODE_CLASS_MAPPINGS.items()} +__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] diff --git a/attention_processor_mot.py b/attention_processor_mot.py new file mode 100644 index 0000000..7340e99 --- /dev/null +++ b/attention_processor_mot.py @@ -0,0 +1,117 @@ +# Copyright (c) 2025 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team. +# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates +# SPDX-License-Identifier: Apache-2.0 +# +# MOT (Motion Transfer) attention processor for Video-As-Prompt +# Extracted from Video-As-Prompt modified diffusers + +from typing import Optional + +import torch +import torch.nn.functional as F + + +class CogVideoXAttnMOTProcessor2_0: + r""" + Processor for implementing scaled dot-product attention for the CogVideoX model with MOT support. + It applies a rotary embedding on query and key vectors, but does not include spatial normalization. + + This processor handles motion transfer by processing reference video attention separately. + """ + + def __init__(self): + if not hasattr(F, "scaled_dot_product_attention"): + raise ImportError("CogVideoXAttnMOTProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") + + def __call__( + self, + attn, # Attention module from diffusers.models.attention + hidden_states: torch.Tensor, + encoder_hidden_states: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + image_rotary_emb: Optional[torch.Tensor] = None, + # MOT specific parameters + is_before_attn: bool = False, + is_ref_video: Optional[bool] = False, + text_seq_length: Optional[int] = None, + ) -> torch.Tensor: + """ + Apply attention with MOT support. + + Args: + attn: The Attention module + hidden_states: Input hidden states + encoder_hidden_states: Encoder hidden states (text embeddings) + attention_mask: Attention mask + image_rotary_emb: Rotary position embeddings for images + is_before_attn: If True, only compute Q, K, V projections (before attention) + is_ref_video: Whether this is processing reference video + text_seq_length: Length of text sequence for splitting + + Returns: + If is_before_attn=True: (query, key, value, attention_mask) + If is_before_attn=False: (hidden_states, encoder_hidden_states) + """ + if is_before_attn: + # Phase 1: Compute Q, K, V projections + text_seq_length = encoder_hidden_states.size(1) + + # Concatenate text and video sequences + hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1) + + batch_size, sequence_length, _ = hidden_states.shape + + if attention_mask is not None: + attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) + attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) + + # Linear projections + query = attn.to_q(hidden_states) + key = attn.to_k(hidden_states) + value = attn.to_v(hidden_states) + + inner_dim = key.shape[-1] + head_dim = inner_dim // attn.heads + + # Reshape for multi-head attention + query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) + + # Apply normalization if available + if attn.norm_q is not None: + query = attn.norm_q(query) + if attn.norm_k is not None: + key = attn.norm_k(key) + + # Apply RoPE (Rotary Position Embedding) if needed + if image_rotary_emb is not None: + # Import here to avoid circular dependency + from diffusers.models.embeddings import apply_rotary_emb + + # Apply RoPE only to video tokens (skip text tokens) + query[:, :, text_seq_length:] = apply_rotary_emb(query[:, :, text_seq_length:], image_rotary_emb) + if not attn.is_cross_attention: + key[:, :, text_seq_length:] = apply_rotary_emb(key[:, :, text_seq_length:], image_rotary_emb) + + return query, key, value, attention_mask + + else: + # Phase 2: Post-attention processing + batch_size, _, sequence_length, head_dim = hidden_states.shape + + # Reshape back from multi-head format + hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, sequence_length, attn.heads * head_dim) + + # Linear projection + hidden_states = attn.to_out[0](hidden_states) + # Dropout + hidden_states = attn.to_out[1](hidden_states) + + # Split back into text and video sequences + encoder_hidden_states, hidden_states = hidden_states.split( + [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1 + ) + + return hidden_states, encoder_hidden_states + diff --git a/cogvideox_transformer_3d_mot.py b/cogvideox_transformer_3d_mot.py new file mode 100644 index 0000000..89b04db --- /dev/null +++ b/cogvideox_transformer_3d_mot.py @@ -0,0 +1,1108 @@ +# Copyright (c) 2025 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team. +# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates +# SPDX-License-Identifier: Apache-2.0 +# +# This file has been modified by Bytedance Ltd. and/or its affiliates on September 15, 2025. +# +# Original file was released under Apache License 2.0, with the full license text +# available at https://github.com/huggingface/finetrainers/blob/main/LICENSE. +# +# This modified file is released under the same license. + + +from typing import Any, Dict, Optional, Tuple, Union, List + +import torch +from torch import nn +import torch.nn.functional as F + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.loaders import PeftAdapterMixin +from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers +from diffusers.utils.torch_utils import maybe_allow_in_graph +from diffusers.models.attention import Attention, FeedForward +from diffusers.models.attention_processor import AttentionProcessor, CogVideoXAttnProcessor2_0, FusedCogVideoXAttnProcessor2_0 +from diffusers.models.cache_utils import CacheMixin +from diffusers.models.embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps +from diffusers.models.modeling_outputs import Transformer2DModelOutput +from diffusers.models.modeling_utils import ModelMixin +from diffusers.models.normalization import AdaLayerNorm, CogVideoXLayerNormZero + +from .attention_processor_mot import CogVideoXAttnMOTProcessor2_0 + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +@maybe_allow_in_graph +class CogVideoXBlock(nn.Module): + r""" + Transformer block used in [CogVideoX](https://github.com/THUDM/CogVideo) model. + + Parameters: + dim (`int`): + The number of channels in the input and output. + num_attention_heads (`int`): + The number of heads to use for multi-head attention. + attention_head_dim (`int`): + The number of channels in each head. + time_embed_dim (`int`): + The number of channels in timestep embedding. + dropout (`float`, defaults to `0.0`): + The dropout probability to use. + activation_fn (`str`, defaults to `"gelu-approximate"`): + Activation function to be used in feed-forward. + attention_bias (`bool`, defaults to `False`): + Whether or not to use bias in attention projection layers. + qk_norm (`bool`, defaults to `True`): + Whether or not to use normalization after query and key projections in Attention. + norm_elementwise_affine (`bool`, defaults to `True`): + Whether to use learnable elementwise affine parameters for normalization. + norm_eps (`float`, defaults to `1e-5`): + Epsilon value for normalization layers. + final_dropout (`bool` defaults to `False`): + Whether to apply a final dropout after the last feed-forward layer. + ff_inner_dim (`int`, *optional*, defaults to `None`): + Custom hidden dimension of Feed-forward layer. If not provided, `4 * dim` is used. + ff_bias (`bool`, defaults to `True`): + Whether or not to use bias in Feed-forward layer. + attention_out_bias (`bool`, defaults to `True`): + Whether or not to use bias in Attention output projection layer. + """ + + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + time_embed_dim: int, + dropout: float = 0.0, + activation_fn: str = "gelu-approximate", + attention_bias: bool = False, + qk_norm: bool = True, + norm_elementwise_affine: bool = True, + norm_eps: float = 1e-5, + final_dropout: bool = True, + ff_inner_dim: Optional[int] = None, + ff_bias: bool = True, + attention_out_bias: bool = True, + # mot + with_mot_ref: bool = False, + _block_idx: int = 0, + dim_mot_ref: Optional[int] = None, + # ablation + ablation_single_encoder: bool = False, + ablation_residual_addition: bool = False, + ): + super().__init__() + self.with_mot_ref = with_mot_ref + self._block_idx = _block_idx + self.dim_mot_ref = dim_mot_ref + + self.ablation_single_encoder = ablation_single_encoder + self.ablation_residual_addition = ablation_residual_addition + + # 1. Self Attention + self.norm1 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True) + + self.attn1 = Attention( + query_dim=dim, + dim_head=attention_head_dim, + heads=num_attention_heads, + qk_norm="layer_norm" if qk_norm else None, + eps=1e-6, + bias=attention_bias, + out_bias=attention_out_bias, + processor=CogVideoXAttnProcessor2_0() if (not self.with_mot_ref or self.ablation_single_encoder or self.ablation_residual_addition) else CogVideoXAttnMOTProcessor2_0(), + ) + + # 2. Feed Forward + self.norm2 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True) + + self.ff = FeedForward( + dim, + dropout=dropout, + activation_fn=activation_fn, + final_dropout=final_dropout, + inner_dim=ff_inner_dim, + bias=ff_bias, + ) + + if self.with_mot_ref: + # 1. Self Attention + self.norm1_mot_ref = CogVideoXLayerNormZero(time_embed_dim, dim if dim_mot_ref is None else dim_mot_ref, norm_elementwise_affine, norm_eps, bias=True) + + self.attn1_mot_ref = Attention( + query_dim=dim if dim_mot_ref is None else dim_mot_ref, + dim_head=attention_head_dim, + heads=num_attention_heads, + qk_norm="layer_norm" if qk_norm else None, + eps=1e-6, + bias=attention_bias, + out_bias=attention_out_bias, + processor=CogVideoXAttnMOTProcessor2_0() if (not self.ablation_single_encoder and not self.ablation_residual_addition) else CogVideoXAttnProcessor2_0(), + ) + + # 2. Feed Forward + self.norm2_mot_ref = CogVideoXLayerNormZero(time_embed_dim, dim if dim_mot_ref is None else dim_mot_ref, norm_elementwise_affine, norm_eps, bias=True) + + self.ff_mot_ref = FeedForward( + dim if dim_mot_ref is None else dim_mot_ref, + dropout=dropout, + activation_fn=activation_fn, + final_dropout=final_dropout, + inner_dim=ff_inner_dim, + bias=ff_bias, + ) + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor, + temb: torch.Tensor, + image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + attention_kwargs: Optional[Dict[str, Any]] = None, + # mot + hidden_states_mot_ref: Optional[torch.Tensor] = None, + encoder_hidden_states_mot_ref: Optional[torch.Tensor] = None, + temb_mot_ref: Optional[torch.Tensor] = None, + temb_list_mot_ref: Optional[List[torch.Tensor]] = None, + image_rotary_emb_mot_ref: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + ) -> torch.Tensor: + + if not self.with_mot_ref: + text_seq_length = encoder_hidden_states.size(1) + attention_kwargs = attention_kwargs or {} + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1( + hidden_states, encoder_hidden_states, temb + ) + + # attention + attn_hidden_states, attn_encoder_hidden_states = self.attn1( + hidden_states=norm_hidden_states, + encoder_hidden_states=norm_encoder_hidden_states, + image_rotary_emb=image_rotary_emb, + **attention_kwargs, + ) + + hidden_states = hidden_states + gate_msa * attn_hidden_states + encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2( + hidden_states, encoder_hidden_states, temb + ) + + # feed-forward + norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1) + ff_output = self.ff(norm_hidden_states) + + hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:] + encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length] + + return hidden_states, encoder_hidden_states, hidden_states_mot_ref, encoder_hidden_states_mot_ref + + elif self.ablation_single_encoder and not self.ablation_residual_addition and self.with_mot_ref: + text_seq_length = encoder_hidden_states.size(1) + video_seq_length = hidden_states.size(1) + attention_kwargs = attention_kwargs or {} + + ################################ + # reference encoder begin + ################################ + + # norm & modulate + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_msa_mot_ref, enc_gate_msa_mot_ref = self.norm1_mot_ref( + hidden_states_mot_ref, encoder_hidden_states_mot_ref, temb_mot_ref + ) + + # attention + attn_hidden_states_mot_ref, attn_encoder_hidden_states_mot_ref = self.attn1_mot_ref( + hidden_states=norm_hidden_states_mot_ref, + encoder_hidden_states=norm_encoder_hidden_states_mot_ref, + image_rotary_emb=image_rotary_emb, + **attention_kwargs, + ) + + hidden_states_mot_ref = hidden_states_mot_ref + gate_msa_mot_ref * attn_hidden_states_mot_ref + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref + enc_gate_msa_mot_ref * attn_encoder_hidden_states_mot_ref + + # norm & modulate + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_ff_mot_ref, enc_gate_ff_mot_ref = self.norm2_mot_ref( + hidden_states_mot_ref, encoder_hidden_states_mot_ref, temb_mot_ref + ) + + # feed-forward + norm_hidden_states_mot_ref = torch.cat([norm_encoder_hidden_states_mot_ref, norm_hidden_states_mot_ref], dim=1) + ff_output_mot_ref = self.ff_mot_ref(norm_hidden_states_mot_ref) + + hidden_states_mot_ref = hidden_states_mot_ref + gate_ff_mot_ref * ff_output_mot_ref[:, text_seq_length:] + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref + enc_gate_ff_mot_ref * ff_output_mot_ref[:, :text_seq_length] + + + ################################ + # reference encoder end + ################################ + + + hidden_states = torch.cat([hidden_states, hidden_states_mot_ref], dim=1) + encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states_mot_ref], dim=1) + + tmp_image_rotary_emb = ( + torch.cat([image_rotary_emb[0], image_rotary_emb_mot_ref[0]], dim=0), + torch.cat([image_rotary_emb[1], image_rotary_emb_mot_ref[1]], dim=0) + ) + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1( + hidden_states, encoder_hidden_states, temb + ) + + # attention + attn_hidden_states, attn_encoder_hidden_states = self.attn1( + hidden_states=norm_hidden_states, + encoder_hidden_states=norm_encoder_hidden_states, + image_rotary_emb=tmp_image_rotary_emb, + **attention_kwargs, + ) + + + attn_hidden_states = attn_hidden_states[:, :video_seq_length] + attn_encoder_hidden_states = attn_encoder_hidden_states[:, :text_seq_length] + hidden_states = hidden_states[:, :video_seq_length] + encoder_hidden_states = encoder_hidden_states[:, :text_seq_length] + + + hidden_states = hidden_states + gate_msa * attn_hidden_states + encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2( + hidden_states, encoder_hidden_states, temb + ) + + # feed-forward + norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1) + ff_output = self.ff(norm_hidden_states) + + hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:] + encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length] + + return hidden_states, encoder_hidden_states, hidden_states_mot_ref, encoder_hidden_states_mot_ref + + elif self.ablation_residual_addition and not self.ablation_single_encoder and self.with_mot_ref: + text_seq_length = encoder_hidden_states.size(1) + video_seq_length = hidden_states.size(1) + attention_kwargs = attention_kwargs or {} + + ################################ + # reference encoder begin + ################################ + + # norm & modulate + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_msa_mot_ref, enc_gate_msa_mot_ref = self.norm1_mot_ref( + hidden_states_mot_ref, encoder_hidden_states_mot_ref, temb_mot_ref + ) + + # attention + attn_hidden_states_mot_ref, attn_encoder_hidden_states_mot_ref = self.attn1_mot_ref( + hidden_states=norm_hidden_states_mot_ref, + encoder_hidden_states=norm_encoder_hidden_states_mot_ref, + image_rotary_emb=image_rotary_emb, + **attention_kwargs, + ) + + hidden_states_mot_ref = hidden_states_mot_ref + gate_msa_mot_ref * attn_hidden_states_mot_ref + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref + enc_gate_msa_mot_ref * attn_encoder_hidden_states_mot_ref + + # norm & modulate + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_ff_mot_ref, enc_gate_ff_mot_ref = self.norm2_mot_ref( + hidden_states_mot_ref, encoder_hidden_states_mot_ref, temb_mot_ref + ) + + # feed-forward + norm_hidden_states_mot_ref = torch.cat([norm_encoder_hidden_states_mot_ref, norm_hidden_states_mot_ref], dim=1) + ff_output_mot_ref = self.ff_mot_ref(norm_hidden_states_mot_ref) + + hidden_states_mot_ref = hidden_states_mot_ref + gate_ff_mot_ref * ff_output_mot_ref[:, text_seq_length:] + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref + enc_gate_ff_mot_ref * ff_output_mot_ref[:, :text_seq_length] + + + ################################ + # reference encoder end + ################################ + + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1( + hidden_states, encoder_hidden_states, temb + ) + + # attention + attn_hidden_states, attn_encoder_hidden_states = self.attn1( + hidden_states=norm_hidden_states, + encoder_hidden_states=norm_encoder_hidden_states, + image_rotary_emb=image_rotary_emb, + **attention_kwargs, + ) + + hidden_states = hidden_states + gate_msa * attn_hidden_states + encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2( + hidden_states, encoder_hidden_states, temb + ) + + # feed-forward + norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1) + ff_output = self.ff(norm_hidden_states) + + hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:] + encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length] + + ################################ + # residual add + ################################ + hidden_states = hidden_states + hidden_states_mot_ref + encoder_hidden_states = encoder_hidden_states + encoder_hidden_states_mot_ref + ################################ + # residual end + ################################ + + return hidden_states, encoder_hidden_states, hidden_states_mot_ref, encoder_hidden_states_mot_ref + + elif not self.ablation_single_encoder and not self.ablation_residual_addition and self.with_mot_ref: + batch_size, hidden_dim = hidden_states.size(0), hidden_states.size(-1) + video_seq_length = hidden_states.size(-2) + video_seq_length_mot_ref = hidden_states_mot_ref.size(-2) + text_seq_length = encoder_hidden_states.size(-2) + text_seq_length_mot_ref = encoder_hidden_states_mot_ref.size(-2) + num_mot_ref = int(video_seq_length_mot_ref // video_seq_length) + attention_kwargs = attention_kwargs or {} + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1( + hidden_states, encoder_hidden_states, temb + ) + + if temb_list_mot_ref is None and temb_mot_ref is not None: + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_msa_mot_ref, enc_gate_msa_mot_ref = self.norm1_mot_ref( + hidden_states_mot_ref, encoder_hidden_states_mot_ref, temb_mot_ref + ) + elif temb_list_mot_ref is not None and temb_mot_ref is None: + + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_msa_mot_ref, enc_gate_msa_mot_ref = self.norm1_mot_ref( + hidden_states_mot_ref.reshape(batch_size * num_mot_ref, video_seq_length, hidden_dim), + encoder_hidden_states_mot_ref.reshape(batch_size * num_mot_ref, text_seq_length, hidden_dim), + torch.cat(temb_list_mot_ref, dim=0) + ) + norm_hidden_states_mot_ref = norm_hidden_states_mot_ref.reshape(batch_size, num_mot_ref * video_seq_length, hidden_dim) + norm_encoder_hidden_states_mot_ref = norm_encoder_hidden_states_mot_ref.reshape(batch_size, num_mot_ref * text_seq_length, hidden_dim) + else: + raise NotImplementedError("Not supprted for temb_list_mot_ref is not None and temb_mot_ref is not None or both are None") + + # attention + + query, key, value, attention_mask = self.attn1( + hidden_states=norm_hidden_states, + encoder_hidden_states=norm_encoder_hidden_states, + image_rotary_emb=image_rotary_emb, + is_before_attn=True, + is_ref_video=False, + **attention_kwargs, + ) + query_mot_ref, key_mot_ref, value_mot_ref, attention_mask_mot_ref = self.attn1_mot_ref( + hidden_states=norm_hidden_states_mot_ref, + encoder_hidden_states=norm_encoder_hidden_states_mot_ref, + image_rotary_emb=image_rotary_emb_mot_ref, + is_before_attn=True, + is_ref_video=True, + **attention_kwargs, + ) + + tmp_hidden_states = F.scaled_dot_product_attention( + torch.cat([query, query_mot_ref], dim=-2), + torch.cat([key, key_mot_ref], dim=-2), + torch.cat([value, value_mot_ref], dim=-2), + attn_mask=None, + dropout_p=0.0, + is_causal=False + ) + + attn_hidden_states, attn_encoder_hidden_states = self.attn1( + hidden_states=tmp_hidden_states[..., :video_seq_length + text_seq_length, :], + is_before_attn=False, + text_seq_length=text_seq_length, + ) + attn_hidden_states_mot_ref, attn_encoder_hidden_states_mot_ref = self.attn1_mot_ref( + hidden_states=tmp_hidden_states[..., video_seq_length + text_seq_length:, :], + is_before_attn=False, + text_seq_length=text_seq_length_mot_ref, + ) + + + hidden_states = hidden_states + gate_msa * attn_hidden_states + encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states + + # norm & modulate + norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2( + hidden_states, encoder_hidden_states, temb + ) + + # feed-forward + norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1) + ff_output = self.ff(norm_hidden_states) + + hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:] + encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length] + + # mot + + # norm & modulate + + if temb_list_mot_ref is None and temb_mot_ref is not None: + hidden_states_mot_ref = hidden_states_mot_ref + gate_msa_mot_ref * attn_hidden_states_mot_ref + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref + enc_gate_msa_mot_ref * attn_encoder_hidden_states_mot_ref + + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_ff_mot_ref, enc_gate_ff_mot_ref = self.norm2_mot_ref( + hidden_states_mot_ref, encoder_hidden_states_mot_ref, temb_mot_ref + ) + elif temb_list_mot_ref is not None and temb_mot_ref is None: + hidden_states_mot_ref = hidden_states_mot_ref.reshape(batch_size, num_mot_ref, video_seq_length, hidden_dim) + \ + gate_msa_mot_ref.reshape(batch_size, num_mot_ref, 1, hidden_dim) * \ + attn_hidden_states_mot_ref.reshape(batch_size, num_mot_ref, video_seq_length, hidden_dim) + hidden_states_mot_ref = hidden_states_mot_ref.reshape(batch_size, -1, hidden_dim) + + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref.reshape(batch_size, num_mot_ref, text_seq_length, hidden_dim) + \ + enc_gate_msa_mot_ref.reshape(batch_size, num_mot_ref, 1, hidden_dim) * \ + attn_encoder_hidden_states_mot_ref.reshape(batch_size, num_mot_ref, text_seq_length, hidden_dim) + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref.reshape(batch_size, -1, hidden_dim) + + norm_hidden_states_mot_ref, norm_encoder_hidden_states_mot_ref, gate_ff_mot_ref, enc_gate_ff_mot_ref = self.norm2_mot_ref( + hidden_states_mot_ref.reshape(batch_size * num_mot_ref, video_seq_length, hidden_dim), + encoder_hidden_states_mot_ref.reshape(batch_size * num_mot_ref, text_seq_length, hidden_dim), + torch.cat(temb_list_mot_ref, dim=0) + ) + norm_hidden_states_mot_ref = norm_hidden_states_mot_ref.reshape(batch_size, num_mot_ref * video_seq_length, hidden_dim) + norm_encoder_hidden_states_mot_ref = norm_encoder_hidden_states_mot_ref.reshape(batch_size, num_mot_ref * text_seq_length, hidden_dim) + + else: + raise NotImplementedError("Not supprted for temb_list_mot_ref is not None and temb_mot_ref is not None or both are None") + + # feed-forward + norm_hidden_states_mot_ref = torch.cat([norm_encoder_hidden_states_mot_ref, norm_hidden_states_mot_ref], dim=1) + ff_output_mot_ref = self.ff_mot_ref(norm_hidden_states_mot_ref) + + + if temb_list_mot_ref is None and temb_mot_ref is not None: + hidden_states_mot_ref = hidden_states_mot_ref + gate_ff_mot_ref * ff_output_mot_ref[:, text_seq_length_mot_ref:] + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref + enc_gate_ff_mot_ref * ff_output_mot_ref[:, :text_seq_length_mot_ref] + elif temb_list_mot_ref is not None and temb_mot_ref is None: + + hidden_states_mot_ref = hidden_states_mot_ref.reshape(batch_size, num_mot_ref, video_seq_length, hidden_dim) + \ + gate_ff_mot_ref.reshape(batch_size, num_mot_ref, 1, hidden_dim) * \ + ff_output_mot_ref[:, text_seq_length_mot_ref:].reshape(batch_size, num_mot_ref, video_seq_length, hidden_dim) + hidden_states_mot_ref = hidden_states_mot_ref.reshape(batch_size, -1, hidden_dim) + + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref.reshape(batch_size, num_mot_ref, text_seq_length, hidden_dim) + \ + enc_gate_ff_mot_ref.reshape(batch_size, num_mot_ref, 1, hidden_dim) * \ + ff_output_mot_ref[:, :text_seq_length_mot_ref].reshape(batch_size, num_mot_ref, text_seq_length, hidden_dim) + encoder_hidden_states_mot_ref = encoder_hidden_states_mot_ref.reshape(batch_size, -1, hidden_dim) + + return hidden_states, encoder_hidden_states, hidden_states_mot_ref, encoder_hidden_states_mot_ref + else: + raise ValueError(f"ablation_single_encoder: {self.ablation_single_encoder}, ablation_residual_addition: {self.ablation_residual_addition}, self.with_mot_ref: {self.with_mot_ref}") + +class CogVideoXTransformer3DMOTModel(ModelMixin, ConfigMixin, PeftAdapterMixin, CacheMixin): + """ + A Transformer model for video-like data in [CogVideoX](https://github.com/THUDM/CogVideo). + + Parameters: + num_attention_heads (`int`, defaults to `30`): + The number of heads to use for multi-head attention. + attention_head_dim (`int`, defaults to `64`): + The number of channels in each head. + in_channels (`int`, defaults to `16`): + The number of channels in the input. + out_channels (`int`, *optional*, defaults to `16`): + The number of channels in the output. + flip_sin_to_cos (`bool`, defaults to `True`): + Whether to flip the sin to cos in the time embedding. + time_embed_dim (`int`, defaults to `512`): + Output dimension of timestep embeddings. + ofs_embed_dim (`int`, defaults to `512`): + Output dimension of "ofs" embeddings used in CogVideoX-5b-I2B in version 1.5 + text_embed_dim (`int`, defaults to `4096`): + Input dimension of text embeddings from the text encoder. + num_layers (`int`, defaults to `30`): + The number of layers of Transformer blocks to use. + dropout (`float`, defaults to `0.0`): + The dropout probability to use. + attention_bias (`bool`, defaults to `True`): + Whether to use bias in the attention projection layers. + sample_width (`int`, defaults to `90`): + The width of the input latents. + sample_height (`int`, defaults to `60`): + The height of the input latents. + sample_frames (`int`, defaults to `49`): + The number of frames in the input latents. Note that this parameter was incorrectly initialized to 49 + instead of 13 because CogVideoX processed 13 latent frames at once in its default and recommended settings, + but cannot be changed to the correct value to ensure backwards compatibility. To create a transformer with + K latent frames, the correct value to pass here would be: ((K - 1) * temporal_compression_ratio + 1). + patch_size (`int`, defaults to `2`): + The size of the patches to use in the patch embedding layer. + temporal_compression_ratio (`int`, defaults to `4`): + The compression ratio across the temporal dimension. See documentation for `sample_frames`. + max_text_seq_length (`int`, defaults to `226`): + The maximum sequence length of the input text embeddings. + activation_fn (`str`, defaults to `"gelu-approximate"`): + Activation function to use in feed-forward. + timestep_activation_fn (`str`, defaults to `"silu"`): + Activation function to use when generating the timestep embeddings. + norm_elementwise_affine (`bool`, defaults to `True`): + Whether to use elementwise affine in normalization layers. + norm_eps (`float`, defaults to `1e-5`): + The epsilon value to use in normalization layers. + spatial_interpolation_scale (`float`, defaults to `1.875`): + Scaling factor to apply in 3D positional embeddings across spatial dimensions. + temporal_interpolation_scale (`float`, defaults to `1.0`): + Scaling factor to apply in 3D positional embeddings across temporal dimensions. + """ + + _skip_layerwise_casting_patterns = ["patch_embed", "norm"] + _supports_gradient_checkpointing = True + _no_split_modules = ["CogVideoXBlock", "CogVideoXPatchEmbed"] + + @register_to_config + def __init__( + self, + num_attention_heads: int = 30, + attention_head_dim: int = 64, + in_channels: int = 16, + out_channels: Optional[int] = 16, + flip_sin_to_cos: bool = True, + freq_shift: int = 0, + time_embed_dim: int = 512, + ofs_embed_dim: Optional[int] = None, + text_embed_dim: int = 4096, + num_layers: int = 30, + dropout: float = 0.0, + attention_bias: bool = True, + sample_width: int = 90, + sample_height: int = 60, + sample_frames: int = 49, + patch_size: int = 2, + patch_size_t: Optional[int] = None, + temporal_compression_ratio: int = 4, + max_text_seq_length: int = 226, + activation_fn: str = "gelu-approximate", + timestep_activation_fn: str = "silu", + norm_elementwise_affine: bool = True, + norm_eps: float = 1e-5, + spatial_interpolation_scale: float = 1.875, + temporal_interpolation_scale: float = 1.0, + use_rotary_positional_embeddings: bool = False, + use_learned_positional_embeddings: bool = False, + patch_bias: bool = True, + # mot + block_idx_with_mot_ref: List[int] = [0, 10, 20], + attention_head_dim_mot_ref: Optional[int] = None, + supported_effect_types: Optional[List[str]] = None, + num_ref_embeddings: Optional[int] = None, + reference_train_mode: Optional[str] = None, + # ablation + ablation_single_encoder: bool = False, + ablation_residual_addition: bool = False, + ): + super().__init__() + inner_dim = num_attention_heads * attention_head_dim + + if attention_head_dim_mot_ref is not None: + inner_dim_mot_ref = num_attention_heads * attention_head_dim_mot_ref + else: + inner_dim_mot_ref = None + + if not use_rotary_positional_embeddings and use_learned_positional_embeddings: + raise ValueError( + "There are no CogVideoX checkpoints available with disable rotary embeddings and learned positional " + "embeddings. If you're using a custom model and/or believe this should be supported, please open an " + "issue at https://github.com/huggingface/diffusers/issues." + ) + + # 1. Patch embedding + self.patch_embed = CogVideoXPatchEmbed( + patch_size=patch_size, + patch_size_t=patch_size_t, + in_channels=in_channels, + embed_dim=inner_dim, + text_embed_dim=text_embed_dim, + bias=patch_bias, + sample_width=sample_width, + sample_height=sample_height, + sample_frames=sample_frames, + temporal_compression_ratio=temporal_compression_ratio, + max_text_seq_length=max_text_seq_length, + spatial_interpolation_scale=spatial_interpolation_scale, + temporal_interpolation_scale=temporal_interpolation_scale, + use_positional_embeddings=not use_rotary_positional_embeddings, + use_learned_positional_embeddings=use_learned_positional_embeddings, + ) + self.embedding_dropout = nn.Dropout(dropout) + + # mot + self.patch_embed_mot_ref = CogVideoXPatchEmbed( + patch_size=patch_size, + patch_size_t=patch_size_t, + in_channels=in_channels, + embed_dim=inner_dim if inner_dim_mot_ref is None else inner_dim_mot_ref, + text_embed_dim=text_embed_dim, + bias=patch_bias, + sample_width=sample_width, + sample_height=sample_height, + sample_frames=sample_frames, + temporal_compression_ratio=temporal_compression_ratio, + max_text_seq_length=max_text_seq_length, + spatial_interpolation_scale=spatial_interpolation_scale, + temporal_interpolation_scale=temporal_interpolation_scale, + use_positional_embeddings=not use_rotary_positional_embeddings, + use_learned_positional_embeddings=use_learned_positional_embeddings, + ) + self.embedding_dropout_mot_ref = nn.Dropout(dropout) + + # 2. Time embeddings and ofs embedding(Only CogVideoX1.5-5B I2V have) + + self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift) + self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn) + + # mot + self.time_proj_mot_ref = Timesteps(inner_dim if inner_dim_mot_ref is None else inner_dim_mot_ref, flip_sin_to_cos, freq_shift) + self.time_embedding_mot_ref = TimestepEmbedding(inner_dim if inner_dim_mot_ref is None else inner_dim_mot_ref, time_embed_dim, timestep_activation_fn) + + + + self.ofs_proj = None + self.ofs_embedding = None + if ofs_embed_dim: + self.ofs_proj = Timesteps(ofs_embed_dim, flip_sin_to_cos, freq_shift) + self.ofs_embedding = TimestepEmbedding( + ofs_embed_dim, ofs_embed_dim, timestep_activation_fn + ) # same as time embeddings, for ofs + + + # 3. Define spatio-temporal transformers blocks + print(f"block_idx_with_mot_ref: {block_idx_with_mot_ref}") + self.transformer_blocks = nn.ModuleList( + [ + CogVideoXBlock( + dim=inner_dim, + num_attention_heads=num_attention_heads, + attention_head_dim=attention_head_dim, + time_embed_dim=time_embed_dim, + dropout=dropout, + activation_fn=activation_fn, + attention_bias=attention_bias, + norm_elementwise_affine=norm_elementwise_affine, + norm_eps=norm_eps, + # mot + with_mot_ref=i in block_idx_with_mot_ref, + _block_idx=i, + dim_mot_ref=inner_dim_mot_ref, + # ablation + ablation_single_encoder=ablation_single_encoder, + ablation_residual_addition=ablation_residual_addition, + ) + for i in range(num_layers) + ] + ) + self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine) + + + # 4. Output blocks + self.norm_out = AdaLayerNorm( + embedding_dim=time_embed_dim, + output_dim=2 * inner_dim, + norm_elementwise_affine=norm_elementwise_affine, + norm_eps=norm_eps, + chunk_dim=1, + ) + + if patch_size_t is None: + # For CogVideox 1.0 + output_dim = patch_size * patch_size * out_channels + else: + # For CogVideoX 1.5 + output_dim = patch_size * patch_size * patch_size_t * out_channels + + self.proj_out = nn.Linear(inner_dim, output_dim) + + # mot + self.reference_train_mode = reference_train_mode + if self.reference_train_mode in ["reference_independent"]: + + self.norm_final_mot_ref = nn.LayerNorm(inner_dim if inner_dim_mot_ref is None else inner_dim_mot_ref, norm_eps, norm_elementwise_affine) + + self.norm_out_mot_ref = AdaLayerNorm( + embedding_dim=time_embed_dim, + output_dim=2 * inner_dim if inner_dim_mot_ref is None else 2 * inner_dim_mot_ref, + norm_elementwise_affine=norm_elementwise_affine, + norm_eps=norm_eps, + chunk_dim=1, + ) + + self.proj_out_mot_ref = nn.Linear(inner_dim if inner_dim_mot_ref is None else inner_dim_mot_ref, output_dim) + + + self.supported_effect_types = supported_effect_types or [] + self.effect_embed_dim = inner_dim_mot_ref or inner_dim + + if self.supported_effect_types: + # print(f"supported_effect_types: {supported_effect_types}") + self.effect_embeddings = nn.ParameterDict({ + effect_type: nn.Parameter(torch.randn(1, 1, self.effect_embed_dim)) + for effect_type in self.supported_effect_types + }) + for effect_embed in self.effect_embeddings.values(): + nn.init.normal_(effect_embed, std=0.02) + else: + self.effect_embeddings = None + + self.num_ref_embeddings = num_ref_embeddings + self.ref_embed_dim = inner_dim_mot_ref or inner_dim + + if self.num_ref_embeddings: + # print(f"num_ref_embeddings: {num_ref_embeddings}") + self.ref_embeddings = nn.ParameterDict({ + f"ref_{ref_idx}": nn.Parameter(torch.randn(1, 1, self.ref_embed_dim)) + for ref_idx in range(self.num_ref_embeddings) + }) + for ref_embed in self.ref_embeddings.values(): + nn.init.normal_(ref_embed, std=0.02) + else: + self.ref_embeddings = None + + self.gradient_checkpointing = False + + @property + # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors + def attn_processors(self) -> Dict[str, AttentionProcessor]: + r""" + Returns: + `dict` of attention processors: A dictionary containing all attention processors used in the model with + indexed by its weight name. + """ + # set recursively + processors = {} + + def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): + if hasattr(module, "get_processor"): + processors[f"{name}.processor"] = module.get_processor() + + for sub_name, child in module.named_children(): + fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) + + return processors + + for name, module in self.named_children(): + fn_recursive_add_processors(name, module, processors) + + return processors + + # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor + def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): + r""" + Sets the attention processor to use to compute attention. + + Parameters: + processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): + The instantiated processor class or a dictionary of processor classes that will be set as the processor + for **all** `Attention` layers. + + If `processor` is a dict, the key needs to define the path to the corresponding cross attention + processor. This is strongly recommended when setting trainable attention processors. + + """ + count = len(self.attn_processors.keys()) + + if isinstance(processor, dict) and len(processor) != count: + raise ValueError( + f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" + f" number of attention layers: {count}. Please make sure to pass {count} processor classes." + ) + + def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): + if hasattr(module, "set_processor"): + if not isinstance(processor, dict): + module.set_processor(processor) + else: + module.set_processor(processor.pop(f"{name}.processor")) + + for sub_name, child in module.named_children(): + fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) + + for name, module in self.named_children(): + fn_recursive_attn_processor(name, module, processor) + + # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedCogVideoXAttnProcessor2_0 + def fuse_qkv_projections(self): + """ + Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value) + are fused. For cross-attention modules, key and value projection matrices are fused. + + + + This API is 🧪 experimental. + + + """ + self.original_attn_processors = None + + for _, attn_processor in self.attn_processors.items(): + if "Added" in str(attn_processor.__class__.__name__): + raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.") + + self.original_attn_processors = self.attn_processors + + for module in self.modules(): + if isinstance(module, Attention): + module.fuse_projections(fuse=True) + + self.set_attn_processor(FusedCogVideoXAttnProcessor2_0()) + + # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections + def unfuse_qkv_projections(self): + """Disables the fused QKV projection if enabled. + + + + This API is 🧪 experimental. + + + + """ + if self.original_attn_processors is not None: + self.set_attn_processor(self.original_attn_processors) + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor, + timestep: Union[int, float, torch.LongTensor], + timestep_cond: Optional[torch.Tensor] = None, + ofs: Optional[Union[int, float, torch.LongTensor]] = None, + image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + attention_kwargs: Optional[Dict[str, Any]] = None, + return_dict: bool = True, + # mot + num_mot_ref: int = 1, + hidden_states_mot_ref: Optional[torch.Tensor] = None, + encoder_hidden_states_mot_ref: Optional[torch.Tensor] = None, + image_rotary_emb_mot_ref: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, + effect_types: Optional[List[str]] = None, + reference_train_mode: Optional[str] = None, + timestep_list_mot_ref: Union[List[int], List[float], List[torch.LongTensor]] = None, + ): + if attention_kwargs is not None: + attention_kwargs = attention_kwargs.copy() + lora_scale = attention_kwargs.pop("scale", 1.0) + else: + lora_scale = 1.0 + + if USE_PEFT_BACKEND: + # weight the lora layers by setting `lora_scale` for each PEFT layer + scale_lora_layers(self, lora_scale) + else: + if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None: + logger.warning( + "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective." + ) + + batch_size, num_frames, channels, height, width = hidden_states.shape + num_text_tokens = encoder_hidden_states.shape[-2] + + # 1. Time embedding + timesteps = timestep + t_emb = self.time_proj(timesteps) + + # timesteps does not contain any weights and will always return f32 tensors + # but time_embedding might actually be running in fp16. so we need to cast here. + # there might be better ways to encapsulate this. + t_emb = t_emb.to(dtype=hidden_states.dtype) + emb = self.time_embedding(t_emb, timestep_cond) + + # mot + if timestep_list_mot_ref is not None: + emb_list_mot_ref = [] + for timestep_mot_ref in timestep_list_mot_ref: + timesteps_mot_ref = timestep_mot_ref + t_emb_mot_ref = self.time_proj_mot_ref(timesteps_mot_ref) + t_emb_mot_ref = t_emb_mot_ref.to(dtype=hidden_states.dtype) + emb_mot_ref = self.time_embedding_mot_ref(t_emb_mot_ref, timestep_cond) + emb_list_mot_ref.append(emb_mot_ref) + emb_mot_ref = None + # print(f"emb_list_mot_ref: {len(emb_list_mot_ref)}-{emb_list_mot_ref[0].shape}, timestep_list_mot_ref: {timestep_list_mot_ref}") + else: + timesteps_mot_ref = timestep + t_emb_mot_ref = self.time_proj_mot_ref(timesteps_mot_ref) + t_emb_mot_ref = t_emb_mot_ref.to(dtype=hidden_states.dtype) + emb_mot_ref = self.time_embedding_mot_ref(t_emb_mot_ref, timestep_cond) + emb_list_mot_ref = None + # print(f"emb_mot_ref: {emb_mot_ref.shape}, timestep: {timestep}") + + if self.ofs_embedding is not None: + ofs_emb = self.ofs_proj(ofs) + ofs_emb = ofs_emb.to(dtype=hidden_states.dtype) + ofs_emb = self.ofs_embedding(ofs_emb) + emb = emb + ofs_emb + # mot + if emb_list_mot_ref is None: + emb_mot_ref = emb_mot_ref + ofs_emb + else: + emb_list_mot_ref = [emb_list_mot_ref_item + ofs_emb for emb_list_mot_ref_item in emb_list_mot_ref] + + + + assert hidden_states_mot_ref.shape[1] // hidden_states.shape[1] == num_mot_ref, f"hidden_states_mot_ref.shape[1]: {hidden_states_mot_ref.shape}, hidden_states.shape[1]: {hidden_states.shape}" + # 2. Patch embedding + hidden_states = self.patch_embed(encoder_hidden_states, hidden_states) + hidden_states = self.embedding_dropout(hidden_states) + + text_seq_length = encoder_hidden_states.shape[1] + encoder_hidden_states = hidden_states[:, :text_seq_length] + hidden_states = hidden_states[:, text_seq_length:] + + # mot + hidden_states_mot_ref_list = [] + encoder_hidden_states_mot_ref_list = [] + for i in range(num_mot_ref): + hidden_states_mot_ref_i = self.patch_embed_mot_ref(encoder_hidden_states_mot_ref[:, i*num_text_tokens:(i+1)*num_text_tokens], hidden_states_mot_ref[:, i*num_frames:(i+1)*num_frames]) + hidden_states_mot_ref_i = self.embedding_dropout_mot_ref(hidden_states_mot_ref_i) + + if self.ref_embeddings is not None: + ref_embed = self.ref_embeddings[f"ref_{int(num_mot_ref - i - 1)}"] # [1, 1, D] + ref_embed = ref_embed.expand( + hidden_states_mot_ref_i.shape[0], + hidden_states_mot_ref_i.shape[1], + self.ref_embed_dim + ) + hidden_states_mot_ref_i = hidden_states_mot_ref_i + ref_embed + + if self.effect_embeddings is not None and effect_types is not None and i < len(effect_types): + effect_type = effect_types[i] + if effect_type in self.effect_embeddings: + effect_embed = self.effect_embeddings[effect_type] # [1, 1, D] + effect_embed = effect_embed.expand( + hidden_states_mot_ref_i.shape[0], + hidden_states_mot_ref_i.shape[1], + self.effect_embed_dim + ) + hidden_states_mot_ref_i = hidden_states_mot_ref_i + effect_embed + else: + raise ValueError(f"{effect_type} is not supported in {self.effect_embeddings.keys()}") + + encoder_hidden_states_mot_ref_list.append(hidden_states_mot_ref_i[:, :text_seq_length]) + hidden_states_mot_ref_list.append(hidden_states_mot_ref_i[:, text_seq_length:]) + hidden_states_mot_ref = torch.cat(hidden_states_mot_ref_list, dim=1) + encoder_hidden_states_mot_ref = torch.cat(encoder_hidden_states_mot_ref_list, dim=1) + + # HACK: DPO + if hidden_states.shape[0] == 2 and emb.shape[0] == 1 and emb_mot_ref is not None and emb_mot_ref.shape[0] == 1: + emb = emb.unsqueeze(1).expand(-1, 2, -1).reshape(2, -1) + emb_mot_ref = emb_mot_ref.unsqueeze(1).expand(-1, 2, -1).reshape(2, -1) + + # 3. Transformer blocks + for i, block in enumerate(self.transformer_blocks): + if torch.is_grad_enabled() and self.gradient_checkpointing: + hidden_states, encoder_hidden_states, hidden_states_mot_ref, encoder_hidden_states_mot_ref = self._gradient_checkpointing_func( + block, + hidden_states, + encoder_hidden_states, + emb, + image_rotary_emb, + attention_kwargs, + # mot + hidden_states_mot_ref=hidden_states_mot_ref, + encoder_hidden_states_mot_ref=encoder_hidden_states_mot_ref, + temb_mot_ref=emb_mot_ref, + temb_list_mot_ref=emb_list_mot_ref, + image_rotary_emb_mot_ref=image_rotary_emb_mot_ref, + ) + else: + hidden_states, encoder_hidden_states, hidden_states_mot_ref, encoder_hidden_states_mot_ref = block( + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + temb=emb, + image_rotary_emb=image_rotary_emb, + attention_kwargs=attention_kwargs, + # mot + hidden_states_mot_ref=hidden_states_mot_ref, + encoder_hidden_states_mot_ref=encoder_hidden_states_mot_ref, + temb_mot_ref=emb_mot_ref, + temb_list_mot_ref=emb_list_mot_ref, + image_rotary_emb_mot_ref=image_rotary_emb_mot_ref, + ) + + hidden_states = self.norm_final(hidden_states) + + # 4. Final block + hidden_states = self.norm_out(hidden_states, temb=emb) + hidden_states = self.proj_out(hidden_states) + + # 5. Unpatchify + p = self.config.patch_size + p_t = self.config.patch_size_t + + if p_t is None: + output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p) + output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4) + else: + output = hidden_states.reshape( + batch_size, (num_frames + p_t - 1) // p_t, height // p, width // p, -1, p_t, p, p + ) + output = output.permute(0, 1, 5, 4, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(1, 2) + + + if self.reference_train_mode in ["reference_independent"]: + hidden_states_mot_ref = self.norm_final_mot_ref(hidden_states_mot_ref) + + # 4. Final block + if emb_mot_ref is not None and emb_list_mot_ref is None: + hidden_states_mot_ref = self.norm_out_mot_ref(hidden_states_mot_ref, temb=emb_mot_ref) + elif emb_mot_ref is None and emb_list_mot_ref is not None: + hidden_states_mot_ref = self.norm_out_mot_ref( + hidden_states_mot_ref.reshape(batch_size*num_mot_ref, hidden_states.shape[-2], hidden_states_mot_ref.shape[-1]), + temb=torch.cat(emb_list_mot_ref, dim=0) + ) + else: + raise ValueError("emb_mot_ref and emb_list_mot_ref cannot be both None or both Non-None") + hidden_states_mot_ref = self.proj_out_mot_ref(hidden_states_mot_ref) + + # 5. Unpatchify + p = self.config.patch_size + p_t = self.config.patch_size_t + + if p_t is None: + output_mot_ref = hidden_states_mot_ref.reshape(batch_size, num_frames * num_mot_ref, height // p, width // p, -1, p, p) + output_mot_ref = output_mot_ref.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4) + else: + output_mot_ref = hidden_states_mot_ref.reshape( + batch_size, (num_frames * num_mot_ref + p_t - 1) // p_t, height // p, width // p, -1, p_t, p, p + ) + output_mot_ref = output_mot_ref.permute(0, 1, 5, 4, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(1, 2) + else: + output_mot_ref = None + + if USE_PEFT_BACKEND: + # remove `lora_scale` from each PEFT layer + unscale_lora_layers(self, lora_scale) + + if not return_dict and output_mot_ref is None: + return (output,) + elif not return_dict and output_mot_ref is not None: + return (output, output_mot_ref) + elif return_dict and output_mot_ref is None: + return Transformer2DModelOutput(sample=output) + elif return_dict and output_mot_ref is not None: + return Transformer2DModelOutput(sample=output, sample_mot_ref=output_mot_ref) + diff --git a/embeddings_mot.py b/embeddings_mot.py new file mode 100644 index 0000000..8859991 --- /dev/null +++ b/embeddings_mot.py @@ -0,0 +1,148 @@ +# Copyright (c) 2025 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team. +# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates +# SPDX-License-Identifier: Apache-2.0 +# +# MOT-specific embedding functions for Video-As-Prompt +# Extracted from Video-As-Prompt modified diffusers + +from typing import Optional, Tuple, Union + +import torch + +# Import get_1d_rotary_pos_embed from official diffusers +from diffusers.models.embeddings import get_1d_rotary_pos_embed + + +def get_3d_rotary_pos_embed( + embed_dim, + crops_coords, + grid_size, + temporal_size, + theta: int = 10000, + use_real: bool = True, + grid_type: str = "linspace", + max_size: Optional[Tuple[int, int]] = None, + device: Optional[torch.device] = None, + mot_num: int = 0, # MOT-specific parameter + ref_type: str = "continous_negative", # MOT-specific parameter + start_point: int = 50, + gap: int = 30, +) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + RoPE for video tokens with 3D structure, with MOT support. + + This is the MOT-modified version that supports motion transfer by handling + reference video position embeddings differently. + + Args: + embed_dim: (`int`): + The embedding dimension size, corresponding to hidden_size_head. + crops_coords (`Tuple[int]`): + The top-left and bottom-right coordinates of the crop. + grid_size (`Tuple[int]`): + The grid size of the spatial positional embedding (height, width). + temporal_size (`int`): + The size of the temporal dimension. + theta (`float`): + Scaling factor for frequency computation. + grid_type (`str`): + Whether to use "linspace" or "slice" to compute grids. + mot_num (`int`): + Number of motion reference videos (MOT-specific). + ref_type (`str`): + Type of reference video position encoding (MOT-specific). + + Returns: + `Tuple[torch.Tensor, torch.Tensor]`: cos and sin positional embeddings. + """ + if use_real is not True: + raise ValueError("`use_real = False` is not currently supported for get_3d_rotary_pos_embed") + + if grid_type == "linspace": + start, stop = crops_coords + grid_size_h, grid_size_w = grid_size + grid_h = torch.linspace( + start[0], stop[0] * (grid_size_h - 1) / grid_size_h, grid_size_h, device=device, dtype=torch.float32 + ) + grid_w = torch.linspace( + start[1], stop[1] * (grid_size_w - 1) / grid_size_w, grid_size_w, device=device, dtype=torch.float32 + ) + grid_t = torch.arange(temporal_size, device=device, dtype=torch.float32) + grid_t = torch.linspace( + 0, temporal_size * (temporal_size - 1) / temporal_size, temporal_size, device=device, dtype=torch.float32 + ) + + # MOT-specific: Handle reference video position embeddings + if mot_num > 0: + if ref_type == "continous_negative": + orig_t_start = 0 + orig_t_stop = temporal_size * (temporal_size - 1) / temporal_size + + t_range = orig_t_stop - orig_t_start + 1 + + temporal_size = temporal_size * mot_num + grid_t = torch.linspace(-mot_num * t_range, -1, temporal_size, device=device, dtype=torch.float32) + + elif ref_type == "discrete_long_reference": + start_offsets = start_point + torch.arange(mot_num, device=device, dtype=torch.float32) * gap + base_range = torch.arange(temporal_size, device=device, dtype=torch.float32) + grid_t = start_offsets.unsqueeze(1) + base_range + grid_t = grid_t.flatten().to(device=device, dtype=torch.float32) + else: + raise ValueError(f"Invalid {ref_type} passed for `ref_type`.") + + elif grid_type == "slice": + max_h, max_w = max_size + grid_size_h, grid_size_w = grid_size + grid_h = torch.arange(max_h, device=device, dtype=torch.float32) + grid_w = torch.arange(max_w, device=device, dtype=torch.float32) + grid_t = torch.arange(temporal_size, device=device, dtype=torch.float32) + if mot_num > 0: + grid_t = torch.arange(-mot_num * temporal_size, 0, device=device, dtype=torch.float32) + else: + raise ValueError("Invalid value passed for `grid_type`.") + + # Compute dimensions for each axis + dim_t = embed_dim // 4 + dim_h = embed_dim // 8 * 3 + dim_w = embed_dim // 8 * 3 + + # Temporal frequencies + freqs_t = get_1d_rotary_pos_embed(dim_t, grid_t, theta=theta, use_real=True) + # Spatial frequencies for height and width + freqs_h = get_1d_rotary_pos_embed(dim_h, grid_h, theta=theta, use_real=True) + freqs_w = get_1d_rotary_pos_embed(dim_w, grid_w, theta=theta, use_real=True) + + # BroadCast and concatenate temporal and spatial frequencies (height and width) into a 3d tensor + def combine_time_height_width(freqs_t, freqs_h, freqs_w): + freqs_t = freqs_t[:, None, None, :].expand( + -1, grid_size_h, grid_size_w, -1 + ) # temporal_size, grid_size_h, grid_size_w, dim_t + freqs_h = freqs_h[None, :, None, :].expand( + temporal_size, -1, grid_size_w, -1 + ) # temporal_size, grid_size_h, grid_size_2, dim_h + freqs_w = freqs_w[None, None, :, :].expand( + temporal_size, grid_size_h, -1, -1 + ) # temporal_size, grid_size_h, grid_size_2, dim_w + + freqs = torch.cat( + [freqs_t, freqs_h, freqs_w], dim=-1 + ) # temporal_size, grid_size_h, grid_size_w, (dim_t + dim_h + dim_w) + freqs = freqs.view( + temporal_size * grid_size_h * grid_size_w, -1 + ) # (temporal_size * grid_size_h * grid_size_w), (dim_t + dim_h + dim_w) + return freqs + + t_cos, t_sin = freqs_t # both t_cos and t_sin has shape: temporal_size, dim_t + h_cos, h_sin = freqs_h # both h_cos and h_sin has shape: grid_size_h, dim_h + w_cos, w_sin = freqs_w # both w_cos and w_sin has shape: grid_size_w, dim_w + + if grid_type == "slice": + t_cos, t_sin = t_cos[:temporal_size], t_sin[:temporal_size] + h_cos, h_sin = h_cos[:grid_size_h], h_sin[:grid_size_h] + w_cos, w_sin = w_cos[:grid_size_w], w_sin[:grid_size_w] + + cos = combine_time_height_width(t_cos, h_cos, w_cos) + sin = combine_time_height_width(t_sin, h_sin, w_sin) + return cos, sin + diff --git a/nodes.py b/nodes.py new file mode 100644 index 0000000..2ab29c4 --- /dev/null +++ b/nodes.py @@ -0,0 +1,136 @@ +from weakref import ref +import torch +import os +from diffusers import ( + AutoencoderKLCogVideoX, + # CogVideoXImageToVideoMOTPipeline, + # CogVideoXTransformer3DMOTModel, +) +from diffusers.utils import export_to_video, load_video +from .pipeline_cogvideox_image2video_mot import CogVideoXImageToVideoMOTPipeline +from PIL import Image +from optimum.quanto import freeze, qint8, quantize + +import folder_paths + +from .cogvideox_transformer_3d_mot import CogVideoXTransformer3DMOTModel +import numpy as np +import comfy.utils + +def pil_2_tensor(pil_image): + image = np.array(pil_image).astype(np.float32) / 255.0 + image = torch.from_numpy(image) + return image + +def tensor_2_pil(img_tensor): + i = 255. * img_tensor.squeeze().cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + return img + +class RunningHub_VideoAsPrompt_Loader: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "type": (["CogVideoX"], ), + } + } + + RETURN_TYPES = ('RH_VideoAsPrompt_Pipeline', ) + FUNCTION = "load" + + CATEGORY = "RunningHub/VideoAsPrompt" + + def load(self, type): + if type == "CogVideoX": + return (self.load_cogvideox(), ) + return (None, ) + + def load_cogvideox(self): + model_base = os.path.join(folder_paths.models_dir, "Video-As-Prompt", "CogVideoX-5B") + vae = AutoencoderKLCogVideoX.from_pretrained(model_base, subfolder="vae", torch_dtype=torch.bfloat16) + transformer = CogVideoXTransformer3DMOTModel.from_pretrained(model_base, subfolder="transformer", torch_dtype=torch.bfloat16) + pipe = CogVideoXImageToVideoMOTPipeline.from_pretrained( + model_base, vae=vae, transformer=transformer, torch_dtype=torch.bfloat16, + ) + if hasattr(pipe.vae, 'enable_slicing'): + pipe.vae.enable_slicing() + if hasattr(pipe.vae, 'enable_tiling'): + pipe.vae.enable_tiling() + + quantize(pipe.transformer, qint8) + freeze(pipe.transformer) + + pipe.enable_model_cpu_offload() + return pipe + +class RunningHub_VideoAsPrompt_Sampler_CogVideoX: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "pipeline": ("RH_VideoAsPrompt_Pipeline", ), + "image": ("IMAGE", ), + "ref_video": ("IMAGE", ), + "prompt": ("STRING", {"default": "", "multiline": True}), + "prompt_mot_ref": ("STRING", {"default": "", "multiline": True}), + "height": ("INT", {"default": 480, "min": 16, "max": 1024}), + "width": ("INT", {"default": 720, "min": 16, "max": 1024}), + "num_frames": ("INT", {"default": 49, "min": 1, "max": 1024}), + # "frames_selection": ("STRING", {"default": "evenly", "choices": ["first", "evenly", "random"]}), + # "use_dynamic_cfg": ("BOOLEAN", {"default": False}), + "num_inference_steps": ("INT", {"default": 50, "min": 1, "max": 1000}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, + "tooltip": "The random seed used for creating the noise."}), + } + } + + RETURN_TYPES = ('IMAGE', ) + FUNCTION = "sample" + TITLE = 'RunningHub VideoAsPrompt Sampler(CogVideoX)' + + CATEGORY = "RunningHub/VideoAsPrompt" + + def sample(self, **kwargs): + pipeline = kwargs["pipeline"] + image = kwargs["image"] + ref_video = kwargs["ref_video"] + prompt = kwargs["prompt"] + prompt_mot_ref = kwargs["prompt_mot_ref"] + height = kwargs["height"] + width = kwargs["width"] + num_frames = kwargs["num_frames"] + num_inference_steps = kwargs["num_inference_steps"] + self.pbar = comfy.utils.ProgressBar(num_inference_steps + 2) + # seed = kwargs["seed"] + + ref_video = [tensor_2_pil(ref_frame) for ref_frame in ref_video] + image = tensor_2_pil(image) + idx = torch.linspace(0, len(ref_video) - 1, num_frames).long().tolist() + ref_frames = [ref_video[i] for i in idx] + + output_frames = pipeline( + image=image, + ref_videos=[ref_frames], + prompt=prompt, + prompt_mot_ref=[prompt_mot_ref], + height=height, + width=width, + num_frames=num_frames, + frames_selection="evenly", + use_dynamic_cfg=True, + num_inference_steps = num_inference_steps, + update_func=self.update, + ).frames[0] + export_to_video(output_frames, "output.mp4") + output_frames = [pil_2_tensor(output_frame) for output_frame in output_frames] + return (output_frames, ) + + def update(self): + self.pbar.update(1) + +NODE_CLASS_MAPPINGS = { + "RunningHub VideoAsPrompt Sampler(CogVideoX)": RunningHub_VideoAsPrompt_Sampler_CogVideoX, + "RunningHub VideoAsPrompt Loader": RunningHub_VideoAsPrompt_Loader, +} \ No newline at end of file diff --git a/pipeline_cogvideox_image2video_mot.py b/pipeline_cogvideox_image2video_mot.py new file mode 100644 index 0000000..612f8c3 --- /dev/null +++ b/pipeline_cogvideox_image2video_mot.py @@ -0,0 +1,1129 @@ +# Copyright (c) 2025 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team. +# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates +# SPDX-License-Identifier: Apache-2.0 +# +# This file has been modified by Bytedance Ltd. and/or its affiliates on September 15, 2025. +# +# Original file was released under Apache License 2.0, with the full license text +# available at https://github.com/huggingface/finetrainers/blob/main/LICENSE. +# +# This modified file is released under the same license. + + +import inspect +import math +import random +from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Literal + +import PIL +import torch +from transformers import T5EncoderModel, T5Tokenizer + +from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback +from diffusers.image_processor import PipelineImageInput +from diffusers.loaders import CogVideoXLoraLoaderMixin +from diffusers.models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel +# from diffusers.models.embeddings import get_3d_rotary_pos_embed # Use MOT version instead +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler +from diffusers.utils import ( + is_torch_xla_available, + logging, + replace_example_docstring, +) +from diffusers.utils.torch_utils import randn_tensor +from diffusers.video_processor import VideoProcessor +from diffusers.pipelines.cogvideo.pipeline_output import CogVideoXPipelineOutput + +from .cogvideox_transformer_3d_mot import CogVideoXTransformer3DMOTModel +from .embeddings_mot import get_3d_rotary_pos_embed + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + XLA_AVAILABLE = True +else: + XLA_AVAILABLE = False + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + +def soft_empty_cache(force=False): + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> import torch + >>> from diffusers import CogVideoXImageToVideoPipeline + >>> from diffusers.utils import export_to_video, load_image + + >>> pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V", torch_dtype=torch.bfloat16) + >>> pipe.to("cuda") + + >>> prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot." + >>> image = load_image( + ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg" + ... ) + >>> video = pipe(image, prompt, use_dynamic_cfg=True) + >>> export_to_video(video.frames[0], "output.mp4", fps=8) + ``` +""" + + +# Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid +def get_resize_crop_region_for_grid(src, tgt_width, tgt_height): + tw = tgt_width + th = tgt_height + h, w = src + r = h / w + if r > (th / tw): + resize_height = th + resize_width = int(round(th / h * w)) + else: + resize_width = tw + resize_height = int(round(tw / w * h)) + + crop_top = int(round((th - resize_height) / 2.0)) + crop_left = int(round((tw - resize_width) / 2.0)) + + return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width) + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps +def retrieve_timesteps( + scheduler, + num_inference_steps: Optional[int] = None, + device: Optional[Union[str, torch.device]] = None, + timesteps: Optional[List[int]] = None, + sigmas: Optional[List[float]] = None, + **kwargs, +): + r""" + Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles + custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`. + + Args: + scheduler (`SchedulerMixin`): + The scheduler to get timesteps from. + num_inference_steps (`int`): + The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps` + must be `None`. + device (`str` or `torch.device`, *optional*): + The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. + timesteps (`List[int]`, *optional*): + Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed, + `num_inference_steps` and `sigmas` must be `None`. + sigmas (`List[float]`, *optional*): + Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed, + `num_inference_steps` and `timesteps` must be `None`. + + Returns: + `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the + second element is the number of inference steps. + """ + if timesteps is not None and sigmas is not None: + raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values") + if timesteps is not None: + accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) + if not accepts_timesteps: + raise ValueError( + f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" + f" timestep schedules. Please check whether you are using the correct scheduler." + ) + scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs) + timesteps = scheduler.timesteps + num_inference_steps = len(timesteps) + elif sigmas is not None: + accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) + if not accept_sigmas: + raise ValueError( + f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" + f" sigmas schedules. Please check whether you are using the correct scheduler." + ) + scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs) + timesteps = scheduler.timesteps + num_inference_steps = len(timesteps) + else: + scheduler.set_timesteps(num_inference_steps, device=device, **kwargs) + timesteps = scheduler.timesteps + return timesteps, num_inference_steps + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents +def retrieve_latents( + encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample" +): + if hasattr(encoder_output, "latent_dist") and sample_mode == "sample": + return encoder_output.latent_dist.sample(generator) + elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax": + return encoder_output.latent_dist.mode() + elif hasattr(encoder_output, "latents"): + return encoder_output.latents + else: + raise AttributeError("Could not access latents of provided encoder_output") + + +class CogVideoXImageToVideoMOTPipeline(DiffusionPipeline, CogVideoXLoraLoaderMixin): + r""" + Pipeline for image-to-video generation using CogVideoX. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the + library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) + + Args: + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations. + text_encoder ([`T5EncoderModel`]): + Frozen text-encoder. CogVideoX uses + [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the + [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant. + tokenizer (`T5Tokenizer`): + Tokenizer of class + [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer). + transformer ([`CogVideoXTransformer3DModel`]): + A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `transformer` to denoise the encoded video latents. + """ + + _optional_components = [] + model_cpu_offload_seq = "text_encoder->transformer->vae" + + _callback_tensor_inputs = [ + "latents", + "prompt_embeds", + "negative_prompt_embeds", + ] + + def __init__( + self, + tokenizer: T5Tokenizer, + text_encoder: T5EncoderModel, + vae: AutoencoderKLCogVideoX, + transformer: CogVideoXTransformer3DMOTModel, + scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler], + ): + super().__init__() + + self.register_modules( + tokenizer=tokenizer, + text_encoder=text_encoder, + vae=vae, + transformer=transformer, + scheduler=scheduler, + ) + self.vae_scale_factor_spatial = ( + 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8 + ) + self.vae_scale_factor_temporal = ( + self.vae.config.temporal_compression_ratio if getattr(self, "vae", None) else 4 + ) + self.vae_scaling_factor_image = self.vae.config.scaling_factor if getattr(self, "vae", None) else 0.7 + + self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial) + + # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._get_t5_prompt_embeds + def _get_t5_prompt_embeds( + self, + prompt: Union[str, List[str]] = None, + num_videos_per_prompt: int = 1, + max_sequence_length: int = 226, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ): + device = device or self._execution_device + dtype = dtype or self.text_encoder.dtype + + prompt = [prompt] if isinstance(prompt, str) else prompt + batch_size = len(prompt) + + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=max_sequence_length, + truncation=True, + add_special_tokens=True, + return_tensors="pt", + ) + text_input_ids = text_inputs.input_ids + untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids + + if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): + removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1]) + logger.warning( + "The following part of your input was truncated because `max_sequence_length` is set to " + f" {max_sequence_length} tokens: {removed_text}" + ) + + prompt_embeds = self.text_encoder(text_input_ids.to(device))[0] + prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) + + # duplicate text embeddings for each generation per prompt, using mps friendly method + _, seq_len, _ = prompt_embeds.shape + prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) + prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) + + return prompt_embeds + + # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.encode_prompt + def encode_prompt( + self, + prompt: Union[str, List[str]], + negative_prompt: Optional[Union[str, List[str]]] = None, + do_classifier_free_guidance: bool = True, + num_videos_per_prompt: int = 1, + prompt_embeds: Optional[torch.Tensor] = None, + negative_prompt_embeds: Optional[torch.Tensor] = None, + max_sequence_length: int = 226, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + do_classifier_free_guidance (`bool`, *optional*, defaults to `True`): + Whether to use classifier free guidance or not. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + Number of videos that should be generated per prompt. torch device to place the resulting embeddings on + prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.Tensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + device: (`torch.device`, *optional*): + torch device + dtype: (`torch.dtype`, *optional*): + torch dtype + """ + device = device or self._execution_device + + prompt = [prompt] if isinstance(prompt, str) else prompt + if prompt is not None: + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + prompt_embeds = self._get_t5_prompt_embeds( + prompt=prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + if do_classifier_free_guidance and negative_prompt_embeds is None: + negative_prompt = negative_prompt or "" + negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt + + if prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + + negative_prompt_embeds = self._get_t5_prompt_embeds( + prompt=negative_prompt, + num_videos_per_prompt=num_videos_per_prompt, + max_sequence_length=max_sequence_length, + device=device, + dtype=dtype, + ) + + return prompt_embeds, negative_prompt_embeds + + def prepare_latents( + self, + image: torch.Tensor, + batch_size: int = 1, + num_channels_latents: int = 16, + num_frames: int = 13, + height: int = 60, + width: int = 90, + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + generator: Optional[torch.Generator] = None, + latents: Optional[torch.Tensor] = None, + ref_videos: Optional[List[torch.Tensor]] = None, + ref_video_first_frames: Optional[torch.Tensor] = None, + ): + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1 + shape = ( + batch_size, + num_frames, + num_channels_latents, + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + ) + + # For CogVideoX1.5, the latent should add 1 for padding (Not use) + if self.transformer.config.patch_size_t is not None: + shape = shape[:1] + (shape[1] + shape[1] % self.transformer.config.patch_size_t,) + shape[2:] + + image = image.unsqueeze(2) # [B, C, F, H, W] + + if isinstance(generator, list): + image_latents = [ + retrieve_latents(self.vae.encode(image[i].unsqueeze(0)), generator[i]) for i in range(batch_size) + ] + else: + image_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator) for img in image] + + image_latents = torch.cat(image_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W] + + if not self.vae.config.invert_scale_latents: + image_latents = self.vae_scaling_factor_image * image_latents + else: + # This is awkward but required because the CogVideoX team forgot to multiply the + # scaling factor during training :) + # image_latents = 1 / self.vae_scaling_factor_image * image_latents + image_latents = 1.0 * image_latents + + padding_shape = ( + batch_size, + num_frames - 1, + num_channels_latents, + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + ) + + latent_padding = torch.zeros(padding_shape, device=device, dtype=dtype) + image_latents = torch.cat([image_latents, latent_padding], dim=1) + + # Select the first frame along the second dimension + if self.transformer.config.patch_size_t is not None: + first_frame = image_latents[:, : image_latents.size(1) % self.transformer.config.patch_size_t, ...] + image_latents = torch.cat([first_frame, image_latents], dim=1) + + if latents is None: + latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + else: + latents = latents.to(device) + + # scale the initial noise by the standard deviation required by the scheduler + latents = latents * self.scheduler.init_noise_sigma + + + ref_video_latents_list = [] + for ref_video in ref_videos: + if isinstance(generator, list): + init_latents = [ + retrieve_latents(self.vae.encode(ref_video[i].unsqueeze(0)), generator[i]) for i in range(batch_size) + ] + else: + init_latents = [retrieve_latents(self.vae.encode(vid.unsqueeze(0)), generator) for vid in ref_video] + + init_latents = torch.cat(init_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W] + ref_video_latents = self.vae_scaling_factor_image * init_latents + + if self.transformer.config.patch_size_t is not None: + additional_frames = self.transformer.config.patch_size_t - (ref_video_latents.size(1) % self.transformer.config.patch_size_t) + if additional_frames > 0: + last_frame = ref_video_latents[:, -1:] + padding_frames = last_frame.expand(-1, additional_frames, -1, -1, -1) + ref_video_latents = torch.cat([ref_video_latents, padding_frames], dim=1) + ref_video_latents_list.append(ref_video_latents) + + ref_video_first_frame_latents_list = [] + for ref_video_first_frame in ref_video_first_frames: + + ref_video_first_frame = ref_video_first_frame.unsqueeze(2) # [B, C, F, H, W] + + if isinstance(generator, list): + ref_video_first_frame_latents = [ + retrieve_latents(self.vae.encode(ref_video_first_frame[i].unsqueeze(0)), generator[i]) for i in range(batch_size) + ] + else: + ref_video_first_frame_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator) for img in ref_video_first_frame] + + ref_video_first_frame_latents = torch.cat(ref_video_first_frame_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W] + + if not self.vae.config.invert_scale_latents: + ref_video_first_frame_latents = self.vae_scaling_factor_image * ref_video_first_frame_latents + else: + # # This is awkward but required because the CogVideoX team forgot to multiply the + # # scaling factor during training :) + # ref_video_first_frame_latents = 1 / self.vae_scaling_factor_image * ref_video_first_frame_latents + ref_video_first_frame_latents = 1.0 * ref_video_first_frame_latents + + padding_shape = ( + batch_size, + num_frames - 1, + num_channels_latents, + height // self.vae_scale_factor_spatial, + width // self.vae_scale_factor_spatial, + ) + + latent_padding = torch.zeros(padding_shape, device=device, dtype=dtype) + ref_video_first_frame_latents = torch.cat([ref_video_first_frame_latents, latent_padding], dim=1) + + # Select the first frame along the second dimension + if self.transformer.config.patch_size_t is not None: + first_frame = ref_video_first_frame_latents[:, : ref_video_first_frame_latents.size(1) % self.transformer.config.patch_size_t, ...] + ref_video_first_frame_latents = torch.cat([first_frame, ref_video_first_frame_latents], dim=1) + + ref_video_first_frame_latents_list.append(ref_video_first_frame_latents) + + + ref_video_latents = torch.cat(ref_video_latents_list, dim=1) + ref_video_image_latents = torch.cat(ref_video_first_frame_latents_list, dim=1) + + return latents, image_latents, ref_video_latents, ref_video_image_latents + + # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.decode_latents + def decode_latents(self, latents: torch.Tensor) -> torch.Tensor: + latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width] + latents = 1 / self.vae_scaling_factor_image * latents + + frames = self.vae.decode(latents).sample + return frames + + # Copied from diffusers.pipelines.animatediff.pipeline_animatediff_video2video.AnimateDiffVideoToVideoPipeline.get_timesteps + def get_timesteps(self, num_inference_steps, timesteps, strength, device): + # get the original timestep using init_timestep + init_timestep = min(int(num_inference_steps * strength), num_inference_steps) + + t_start = max(num_inference_steps - init_timestep, 0) + timesteps = timesteps[t_start * self.scheduler.order :] + + return timesteps, num_inference_steps - t_start + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) + if accepts_generator: + extra_step_kwargs["generator"] = generator + return extra_step_kwargs + + def check_inputs( + self, + image, + prompt, + height, + width, + negative_prompt, + callback_on_step_end_tensor_inputs, + latents=None, + prompt_embeds=None, + negative_prompt_embeds=None, + ): + if ( + not isinstance(image, torch.Tensor) + and not isinstance(image, PIL.Image.Image) + and not isinstance(image, list) + ): + raise ValueError( + "`image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is" + f" {type(image)}" + ) + + if height % 8 != 0 or width % 8 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") + + if callback_on_step_end_tensor_inputs is not None and not all( + k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs + ): + raise ValueError( + f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" + ) + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + + # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.fuse_qkv_projections + def fuse_qkv_projections(self) -> None: + r"""Enables fused QKV projections.""" + self.fusing_transformer = True + self.transformer.fuse_qkv_projections() + + # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.unfuse_qkv_projections + def unfuse_qkv_projections(self) -> None: + r"""Disable QKV projection fusion if enabled.""" + if not self.fusing_transformer: + logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.") + else: + self.transformer.unfuse_qkv_projections() + self.fusing_transformer = False + + # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._prepare_rotary_positional_embeddings + def _prepare_rotary_positional_embeddings( + self, + height: int, + width: int, + num_frames: int, + device: torch.device, + mot_num: int = 0, + ref_type: str = "continous_negative", + ) -> Tuple[torch.Tensor, torch.Tensor]: + grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size) + grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size) + + p = self.transformer.config.patch_size + p_t = self.transformer.config.patch_size_t + + base_size_width = self.transformer.config.sample_width // p + base_size_height = self.transformer.config.sample_height // p + + if p_t is None: + # CogVideoX 1.0 + grid_crops_coords = get_resize_crop_region_for_grid( + (grid_height, grid_width), base_size_width, base_size_height + ) + freqs_cos, freqs_sin = get_3d_rotary_pos_embed( + embed_dim=self.transformer.config.attention_head_dim, + crops_coords=grid_crops_coords, + grid_size=(grid_height, grid_width), + temporal_size=num_frames, + device=device, + mot_num=mot_num, + ref_type=ref_type, + ) + else: + # CogVideoX 1.5 + base_num_frames = (num_frames + p_t - 1) // p_t + + freqs_cos, freqs_sin = get_3d_rotary_pos_embed( + embed_dim=self.transformer.config.attention_head_dim, + crops_coords=None, + grid_size=(grid_height, grid_width), + temporal_size=base_num_frames, + grid_type="slice", + max_size=(base_size_height, base_size_width), + device=device, + mot_num=mot_num, + ) + + return freqs_cos, freqs_sin + + @property + def guidance_scale(self): + return self._guidance_scale + + @property + def num_timesteps(self): + return self._num_timesteps + + @property + def attention_kwargs(self): + return self._attention_kwargs + + @property + def current_timestep(self): + return self._current_timestep + + @property + def interrupt(self): + return self._interrupt + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + image: PipelineImageInput, + prompt: Optional[Union[str, List[str]]] = None, + negative_prompt: Optional[Union[str, List[str]]] = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards", + height: Optional[int] = None, + width: Optional[int] = None, + num_frames: int = 49, + num_inference_steps: int = 50, + timesteps: Optional[List[int]] = None, + guidance_scale: float = 6, + use_dynamic_cfg: bool = False, + num_videos_per_prompt: int = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: str = "pil", + return_dict: bool = True, + attention_kwargs: Optional[Dict[str, Any]] = None, + callback_on_step_end: Optional[ + Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks] + ] = None, + callback_on_step_end_tensor_inputs: List[str] = ["latents"], + max_sequence_length: int = 226, + # mot + ref_videos: Optional[List[List[PIL.Image.Image]]] = None, + prompt_mot_ref: Optional[Union[str, List[str]]] = None, + negative_prompt_mot_ref: Optional[Union[str, List[str]]] = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards", + empty_caption_mot_ref: Optional[str] = None, + caption_guidance_scale: float = 0, + effect_types: Optional[List[str]] = None, + reference_train_mode: Optional[str] = None, + random_refer_noise: Optional[bool] = False, + frames_selection: Literal["first", "evenly", "random"] = "evenly", + ref_type: Optional[str] = "continous_negative", + # ablation + ablation_single_branch: bool = False, + # baseline + baseline_single_condition: Optional[str] = None, + **kwargs, + ) -> Union[CogVideoXPipelineOutput, Tuple]: + """ + Function invoked when calling the pipeline for generation. + + Args: + image (`PipelineImageInput`): + The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`. + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. + instead. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial): + The height in pixels of the generated image. This is set to 480 by default for the best results. + width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial): + The width in pixels of the generated image. This is set to 720 by default for the best results. + num_frames (`int`, defaults to `48`): + Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will + contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where + num_seconds is 6 and fps is 8. However, since videos can be saved at any fps, the only condition that + needs to be satisfied is that of divisibility mentioned above. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + timesteps (`List[int]`, *optional*): + Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument + in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is + passed will be used. Must be in descending order. + guidance_scale (`float`, *optional*, defaults to 7.0): + Guidance scale as defined in [Classifier-Free Diffusion + Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2. + of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting + `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to + the text `prompt`, usually at the expense of lower image quality. + num_videos_per_prompt (`int`, *optional*, defaults to 1): + The number of videos to generate per prompt. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead + of a plain tuple. + attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + callback_on_step_end (`Callable`, *optional*): + A function that calls at the end of each denoising steps during the inference. The function is called + with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, + callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by + `callback_on_step_end_tensor_inputs`. + callback_on_step_end_tensor_inputs (`List`, *optional*): + The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list + will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the + `._callback_tensor_inputs` attribute of your pipeline class. + max_sequence_length (`int`, defaults to `226`): + Maximum sequence length in encoded prompt. Must be consistent with + `self.transformer.config.max_text_seq_length` otherwise may lead to poor results. + + Examples: + + Returns: + [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] or `tuple`: + [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a + `tuple`. When returning a tuple, the first element is a list with the generated images. + """ + + if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): + callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs + + height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial + width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial + num_frames = num_frames or self.transformer.config.sample_frames + + num_videos_per_prompt = 1 + + #kiki + update = kwargs.get('update_func', lambda *args, **kwargs: None) + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + image=image, + prompt=prompt, + height=height, + width=width, + negative_prompt=negative_prompt, + callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, + latents=latents, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + ) + self._guidance_scale = guidance_scale + self._current_timestep = None + self._attention_kwargs = attention_kwargs + self._interrupt = False + + # 2. Default call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # kiki + # device = "cuda" + + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + + # kiki + # self.text_encoder.to(device) + # 3. Encode input prompt + prompt_embeds, negative_prompt_embeds = self.encode_prompt( + prompt=prompt, + negative_prompt=negative_prompt, + do_classifier_free_guidance=do_classifier_free_guidance, + num_videos_per_prompt=num_videos_per_prompt, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + max_sequence_length=max_sequence_length, + device=device, + ) + if do_classifier_free_guidance: + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) + + prompt_embeds_mot_ref_list = [] + negative_prompt_embeds_mot_ref_list = [] + for prompt_mot_ref_item in prompt_mot_ref: + prompt_embeds_mot_ref, negative_prompt_embeds_mot_ref = self.encode_prompt( + prompt=prompt_mot_ref_item, + negative_prompt=negative_prompt_mot_ref, + do_classifier_free_guidance=do_classifier_free_guidance, + num_videos_per_prompt=num_videos_per_prompt, + prompt_embeds=None, + negative_prompt_embeds=None, + max_sequence_length=max_sequence_length, + device=device, + ) + prompt_embeds_mot_ref_list.append(prompt_embeds_mot_ref) + negative_prompt_embeds_mot_ref_list.append(negative_prompt_embeds_mot_ref) + prompt_embeds_mot_ref = torch.cat(prompt_embeds_mot_ref_list, dim=1) + negative_prompt_embeds_mot_ref = torch.cat(negative_prompt_embeds_mot_ref_list, dim=1) + if do_classifier_free_guidance: + prompt_embeds_mot_ref = torch.cat([negative_prompt_embeds_mot_ref, prompt_embeds_mot_ref], dim=0) + + update() + # kiki + # print('----> step 3 done') + # self.text_encoder.to("cpu") + # kiki_debug_gpu('step 3') + # 4. Prepare timesteps + timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps) + self._num_timesteps = len(timesteps) + + # 5. Prepare latents + latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1 + + # For CogVideoX 1.5, the latent frames should be padded to make it divisible by patch_size_t + ori_num_frames = num_frames + patch_size_t = self.transformer.config.patch_size_t + additional_frames = 0 + if patch_size_t is not None and latent_frames % patch_size_t != 0: + additional_frames = patch_size_t - latent_frames % patch_size_t + num_frames += additional_frames * self.vae_scale_factor_temporal + + image = self.video_processor.preprocess(image, height=height, width=width).to( + device, dtype=prompt_embeds.dtype + ) + + if frames_selection == "first": + ref_videos = [ref_video[:num_frames] for ref_video in ref_videos] + elif frames_selection == "evenly": + indices = torch.linspace(0, len(ref_videos[0]) - 1, num_frames).long().tolist() + for ref_idx, ref_video in enumerate(ref_videos): + ref_videos[ref_idx] = [ref_videos[ref_idx][i] for i in indices] + elif frames_selection == "random": + for ref_idx, ref_video in enumerate(ref_videos): + start_index = random.randint(0, len(ref_videos[ref_idx]) - num_frames) + indices = torch.arange(start_index, start_index + num_frames).long().tolist() + ref_videos[ref_idx] = [ref_videos[ref_idx][i] for i in indices] + else: + raise ValueError(f"Invalid frames_selection: {frames_selection}. Choose from 'first' or 'evenly' or 'random'.") + + tmp_ref_videos = ref_videos + + ref_video_first_frames = [ref_video[0] for ref_video in ref_videos] + ref_video_first_frames = [self.video_processor.preprocess(ref_video_first_frame, height=height, width=width) for ref_video_first_frame in ref_video_first_frames] + ref_video_first_frames = [ref_video_first_frame.to(device=device, dtype=prompt_embeds.dtype) for ref_video_first_frame in ref_video_first_frames] + + ref_videos = [self.video_processor.preprocess_video(ref_video, height=height, width=width).to(device=device, dtype=prompt_embeds.dtype) for ref_video in ref_videos] + + # kiki + # self.vae.to(device) + latent_channels = self.transformer.config.in_channels // 2 + latents, image_latents, ref_video_latents, ref_video_image_latents = self.prepare_latents( + image, + batch_size * num_videos_per_prompt, + latent_channels, + num_frames, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + ref_videos=ref_videos, + ref_video_first_frames=ref_video_first_frames, + ) + + mot_num = int(ref_video_latents.shape[1] // latents.shape[1]) + + # kiki + update() + # print('----> step 5 done') + # self.vae.to("cpu") + # kiki_debug_gpu('step 5') + # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 7. Create rotary embeds if required + image_rotary_emb = ( + self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device) + if self.transformer.config.use_rotary_positional_embeddings + else None + ) + + image_rotary_emb_mot_ref = ( + self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device, mot_num=mot_num, ref_type=ref_type) + if self.transformer.config.use_rotary_positional_embeddings + else None + ) + + # 8. Create ofs embeds if required + ofs_emb = None if self.transformer.config.ofs_embed_dim is None else latents.new_full((1,), fill_value=2.0) + + # 8. Denoising loop + num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0) + + + if ablation_single_branch and not baseline_single_condition: + image_rotary_emb = ( + torch.cat([image_rotary_emb[0], image_rotary_emb_mot_ref[0]], dim=0), + torch.cat([image_rotary_emb[1], image_rotary_emb_mot_ref[1]], dim=0) + ) + + # kiki + # self.transformer.to(device) + + with self.progress_bar(total=num_inference_steps) as progress_bar: + # for DPM-solver++ + old_pred_original_sample = None + for i, t in enumerate(timesteps): + if self.interrupt: + continue + + self._current_timestep = t + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) + + latent_image_input = torch.cat([image_latents] * 2) if do_classifier_free_guidance else image_latents + latent_model_input = torch.cat([latent_model_input, latent_image_input], dim=2) + + latent_model_input_mot_ref = torch.cat([ref_video_latents] * 2) if do_classifier_free_guidance else ref_video_latents + latent_image_input_mot_ref = torch.cat([ref_video_image_latents] * 2) if do_classifier_free_guidance else ref_video_image_latents + latent_model_input_mot_ref = torch.cat([latent_model_input_mot_ref, latent_image_input_mot_ref], dim=2) + + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timestep = t.expand(latent_model_input.shape[0]) + if not ablation_single_branch: + # predict noise model_output + noise_pred = self.transformer( + hidden_states=latent_model_input, + encoder_hidden_states=prompt_embeds, + timestep=timestep, + ofs=ofs_emb, + image_rotary_emb=image_rotary_emb, + attention_kwargs=attention_kwargs, + return_dict=False, + # mot + num_mot_ref=mot_num, + hidden_states_mot_ref=latent_model_input_mot_ref, + encoder_hidden_states_mot_ref=prompt_embeds_mot_ref, + image_rotary_emb_mot_ref=image_rotary_emb_mot_ref, + effect_types=effect_types, + timestep_list_mot_ref=clean_ref_video_latent_timesteps_list if random_refer_noise else None, + )[0] + else: + if not baseline_single_condition: + latent_model_input = torch.cat([latent_model_input, latent_model_input_mot_ref], dim=1) + + noise_pred = self.transformer( + hidden_states=latent_model_input, + encoder_hidden_states=prompt_embeds, + timestep=timestep, + ofs=ofs_emb, + image_rotary_emb=image_rotary_emb, + attention_kwargs=attention_kwargs, + return_dict=False, + # ablation + ablation_single_branch=ablation_single_branch, + )[0] + + noise_pred = noise_pred[:, :latents.shape[1], ...] + else: + + noise_pred = self.transformer( + hidden_states=latent_model_input, + encoder_hidden_states=prompt_embeds, + timestep=timestep, + ofs=ofs_emb, + image_rotary_emb=image_rotary_emb, + attention_kwargs=attention_kwargs, + return_dict=False, + # ablation + ablation_single_branch=False, + )[0] + + noise_pred = noise_pred.float() + + # perform guidance + if use_dynamic_cfg: + self._guidance_scale = 1 + guidance_scale * ( + (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2 + ) + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond) + + # compute the previous noisy sample x_t -> x_t-1 + if not isinstance(self.scheduler, CogVideoXDPMScheduler): + latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] + else: + latents, old_pred_original_sample = self.scheduler.step( + noise_pred, + old_pred_original_sample, + t, + timesteps[i - 1] if i > 0 else None, + latents, + **extra_step_kwargs, + return_dict=False, + ) + latents = latents.to(prompt_embeds.dtype) + + #kiki + update() + + # call the callback, if provided + if callback_on_step_end is not None: + callback_kwargs = {} + for k in callback_on_step_end_tensor_inputs: + callback_kwargs[k] = locals()[k] + callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) + + latents = callback_outputs.pop("latents", latents) + prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) + negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) + + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + + if XLA_AVAILABLE: + xm.mark_step() + + self._current_timestep = None + + # kiki + # self.transformer.to("cpu") + # kiki_debug_gpu('step 8') + # self.vae.to(device) + # kiki_debug_gpu('vae reload') + + if not output_type == "latent": + # Discard any padding frames that were added for CogVideoX 1.5 + latents = latents[:, additional_frames:] + video = self.decode_latents(latents) + video = self.video_processor.postprocess_video(video=video, output_type=output_type) + else: + video = latents + + # Offload all models + self.maybe_free_model_hooks() + + if not return_dict: + return (video,) + + return CogVideoXPipelineOutput(frames=video) diff --git a/rh_config.json b/rh_config.json new file mode 100644 index 0000000..6e0b528 --- /dev/null +++ b/rh_config.json @@ -0,0 +1 @@ +{"enable": true, "untracked_paths": []}