Python
release longcat video avatar
gaofeng5104016aab1a
diff --git a/README.md b/README.mdindex 624b106..41300ab 100644--- a/README.md+++ b/README.md@@ -37,6 +37,12 @@ For more detail, please refer to the comprehensive [***LongCat-Video Technical R<video src="https://github.com/user-attachments/assets/00fa63f0-9c4e-461a-a79e-c662ad596d7d" width="2264" height="384"> </video></div>+## 🔥 Latest News!!+- Dec 16, 2025: 🚀 We are excited to announce the release of LongCat-Video-Avatar, a unified model that delivers expressive and highly dynamic audio-driven character animation, supporting native tasks including *Audio-Text-to-Video*, *Audio-Text-Image-to-Video*, and *Video Continuation* with seamless compatibility for both *single-stream* and *multi-stream* audio inputs. The release includes our [***Technical Report***](https://github.com/meituan-longcat/LongCat-Video), [***inference code***](https://github.com/meituan-longcat/LongCat-Video), 🤗 [***model weights***](https://huggingface.co/meituan-longcat/LongCat-Video-Avatar), and [***project page***](https://meigen-ai.github.io/LongCat-Video-Avatar/).+- Oct 25, 2025: 🚀 We've released LongCat-Video, a foundational video generation model. Tech report and models are available at [***LongCat-Video Technical Report***](https://arxiv.org/abs/2510.22200) and 🤗 [***Huggingface***](https://huggingface.co/meituan-longcat/LongCat-Video) !+++## Quick Start### Installation@@ -66,20 +72,29 @@ pip install flash_attn==2.7.4.post1# install other requirementspip install -r requirements.txt++# install longcat-video-avatar requirements+conda install -c conda-forge librosa+conda install -c conda-forge ffmpeg+pip install -r requirements_avatar.txt+```FlashAttention-2 is enabled in the model config by default; you can also change the model config ("./weights/LongCat-Video/dit/config.json") to use FlashAttention-3 or xformers once installed.### Model Download-| Models | Download Link |-| --- | --- |-| LongCat-Video | 🤗 [Huggingface](https://huggingface.co/meituan-longcat/LongCat-Video) |+| Models | Description | Download Link |+| --- | --- | --- |+| LongCat-Video | foundational video generation | 🤗 [Huggingface](https://huggingface.co/meituan-longcat/LongCat-Video) |+| LongCat-Video-Avatar-Single | single-character audio-driven video generation | 🤗 [Huggingface](https://huggingface.co/meituan-longcat/LongCat-Video-Avatar) |+| LongCat-Video-Avatar-Multi | multi-character audio-driven video generation | 🤗 [Huggingface](https://huggingface.co/meituan-longcat/LongCat-Video-Avatar) |Download models using huggingface-cli:```shellpip install "huggingface_hub[cli]"huggingface-cli download meituan-longcat/LongCat-Video --local-dir ./weights/LongCat-Video+huggingface-cli download meituan-longcat/LongCat-Video-Avatar --local-dir ./weights/LongCat-Video-Avatar```### Run Text-to-Video@@ -132,6 +147,38 @@ torchrun run_demo_interactive_video.py --checkpoint_dir=./weights/LongCat-Videotorchrun --nproc_per_node=2 run_demo_interactive_video.py --context_parallel_size=2 --checkpoint_dir=./weights/LongCat-Video --enable_compile```+### Run LongCat-Video-Avatar+💡 User tips+> - Lip synchronization accuracy: Audio CFG works optimally between 3–5. Increase the audio CFG value for better synchronization.+> - Prompt Enhancement: Include clear verbal-action cues (e.g., talking, speaking) in the prompt to achieve more natural lip movements.+> - Mitigate repeated actions: Setting the reference image index(--ref_img_index, default to 10) between 0 and 24 ensures better consistency, while selecting other ranges (e.g., -10 or 30) helps reduce repeated actions. Additionally, increasing the mask frame range (--mask_frame_range, default to 3) can further help mitigate repeated actions, but excessively large values may introduce artifacts.+> - Super resolution: Our model is compatible with both 480P and 720P, which can be controlled via --resolution.+> - Dual-Audio Modes: Merge mode (set audio_type to para) requires two audio clips of equal length, and the resulting audio is obtained by summing the two clips; Concatenation mode (set audio_type to add) does not require equal-length inputs, and the resulting audio is formed by sequentially concatenating the two clips with silence padding for any gaps, where by default person1 speaks first and person2 speaks afterward.++- Single-Audio-to-Video Generation+```shell+# Audio-Text-to-Video+torchrun --nproc_per_node=2 run_demo_avatar_single_audio_to_video.py --context_parallel_size=2 --checkpoint_dir=./weights/LongCat-Video-Avatar --stage_1=at2v --input_json=assets/avatar/single_example_1.json++# Audio-Image-to-Video+torchrun --nproc_per_node=2 run_demo_avatar_single_audio_to_video.py --context_parallel_size=2 --checkpoint_dir=./weights/LongCat-Video-Avatar --stage_1=ai2v --input_json=assets/avatar/single_example_1.json++# Audio-Text-to-Video and Video-Continuation+torchrun --nproc_per_node=2 run_demo_avatar_single_audio_to_video.py --context_parallel_size=2 --checkpoint_dir=./weights/LongCat-Video-Avatar --stage_1=at2v --input_json=assets/avatar/single_example_1.json --num_segments=5 --ref_img_index=10 --mask_frame_range=3++# Audio-Image-to-Video and Video-Continuation+torchrun --nproc_per_node=2 run_demo_avatar_single_audio_to_video.py --context_parallel_size=2 --checkpoint_dir=./weights/LongCat-Video-Avatar --stage_1=ai2v --input_json=assets/avatar/single_example_1.json --num_segments=5 --ref_img_index=10 --mask_frame_range=3+```++- Multi-Audio-to-Video Generation+```shell+# Audio-Image-to-Video+torchrun --nproc_per_node=2 run_demo_avatar_multi_audio_to_video.py --context_parallel_size=2 --checkpoint_dir=./weights/LongCat-Video-Avatar --input_json=assets/avatar/multi_example_1.json++# Audio-Image-to-Video and Video-Continuation+torchrun --nproc_per_node=2 run_demo_avatar_multi_audio_to_video.py --context_parallel_size=2 --checkpoint_dir=./weights/LongCat-Video-Avatar --input_json=assets/avatar/multi_example_1.json --num_segments=5 --ref_img_index=10 --mask_frame_range=3+```+### Run Streamlit```shell@@ -209,6 +256,15 @@ We kindly encourage citation of our work if you find it useful.primaryClass={cs.CV},url={https://arxiv.org/abs/2510.22200},}+@misc{meituanlongcatteam2025longcatvideoavatartechnicalreport,+ title={LongCat-Video-Avatar Technical Report},+ author={Meituan LongCat Team},+ year={2025},+ eprint={},+ archivePrefix={arXiv},+ primaryClass={cs.CV},+ url={},+}```## Acknowledgementsdiff --git a/assets/LongCat-Video-Avatar-Tech-Report.pdf b/assets/LongCat-Video-Avatar-Tech-Report.pdfnew file mode 100644index 0000000..1759fe7Binary files /dev/null and b/assets/LongCat-Video-Avatar-Tech-Report.pdf differdiff --git a/assets/avatar/multi/introduce.png b/assets/avatar/multi/introduce.pngnew file mode 100644index 0000000..bf8720dBinary files /dev/null and b/assets/avatar/multi/introduce.png differdiff --git a/assets/avatar/multi/introduce_man.mp3 b/assets/avatar/multi/introduce_man.mp3new file mode 100644index 0000000..d564129Binary files /dev/null and b/assets/avatar/multi/introduce_man.mp3 differdiff --git a/assets/avatar/multi/introduce_woman.mp3 b/assets/avatar/multi/introduce_woman.mp3new file mode 100644index 0000000..f55ff8bBinary files /dev/null and b/assets/avatar/multi/introduce_woman.mp3 differdiff --git a/assets/avatar/multi/sing.png b/assets/avatar/multi/sing.pngnew file mode 100644index 0000000..60471baBinary files /dev/null and b/assets/avatar/multi/sing.png differdiff --git a/assets/avatar/multi/sing_man.WAV b/assets/avatar/multi/sing_man.WAVnew file mode 100644index 0000000..0953348Binary files /dev/null and b/assets/avatar/multi/sing_man.WAV differdiff --git a/assets/avatar/multi/sing_woman.WAV b/assets/avatar/multi/sing_woman.WAVnew file mode 100644index 0000000..9302a1cBinary files /dev/null and b/assets/avatar/multi/sing_woman.WAV differdiff --git a/assets/avatar/multi_example_1.json b/assets/avatar/multi_example_1.jsonnew file mode 100644index 0000000..95cbdc4--- /dev/null+++ b/assets/avatar/multi_example_1.json@@ -0,0 +1,9 @@+{+ "prompt": "Static camera, In a professional recording studio, two people stand facing each other, both wearing large headphones. They are speaking clearly into a large condenser microphone suspended between them. They looked at each other affectionately and occasionally shook their heads according to the rhythm. The soundproofed walls and visible recording equipment create an atmosphere focused on capturing high-quality audio as they interact and communicate.",+ "cond_image": "assets/avatar/multi/sing.png",+ "cond_audio": {+ "person1": "assets/avatar/multi/sing_man.WAV",+ "person2": "assets/avatar/multi/sing_woman.WAV"+ },+ "audio_type": "para"+}\ No newline at end of filediff --git a/assets/avatar/multi_example_2.json b/assets/avatar/multi_example_2.jsonnew file mode 100644index 0000000..06c43ee--- /dev/null+++ b/assets/avatar/multi_example_2.json@@ -0,0 +1,13 @@+{+ "prompt": "Static camera, two people are speaking. Two people sit side by side in a warmly lit café, engaged in a lively conversation. The woman has vivid expressions as she speaks, while the man listens attentively. They occasionally look at each other and nod in affirmation. Their interaction suggests they are discussing something meaningful, sharing thoughts and exchanging ideas in a relaxed and friendly atmosphere.",+ "cond_image": "assets/avatar/multi/introduce.png",+ "cond_audio": {+ "person1": "assets/avatar/multi/introduce_woman.mp3",+ "person2": "assets/avatar/multi/introduce_man.mp3"+ },+ "audio_type": "add",+ "bbox": {+ "person1": [100, 80, 800, 640],+ "person2": [50, 720, 820, 1300]+ }+}\ No newline at end of filediff --git a/assets/avatar/single/man.mp3 b/assets/avatar/single/man.mp3new file mode 100644index 0000000..102e9deBinary files /dev/null and b/assets/avatar/single/man.mp3 differdiff --git a/assets/avatar/single/man.png b/assets/avatar/single/man.pngnew file mode 100644index 0000000..dbfc7c5Binary files /dev/null and b/assets/avatar/single/man.png differdiff --git a/assets/avatar/single_example_1.json b/assets/avatar/single_example_1.jsonnew file mode 100644index 0000000..e854538--- /dev/null+++ b/assets/avatar/single_example_1.json@@ -0,0 +1,7 @@+{+ "prompt": "A western man stands on stage under dramatic lighting, holding a microphone close to their mouth. Wearing a vibrant red jacket with gold embroidery, the singer is speaking while smoke swirls around them, creating a dynamic and atmospheric scene.",+ "cond_image": "assets/avatar/single/man.png",+ "cond_audio": {+ "person1": "assets/avatar/single/man.mp3"+ }+}\ No newline at end of filediff --git a/longcat_video/audio_process/torch_utils.py b/longcat_video/audio_process/torch_utils.pynew file mode 100644index 0000000..a72f368--- /dev/null+++ b/longcat_video/audio_process/torch_utils.py@@ -0,0 +1,246 @@+import os+import json+import librosa+import binascii+import imageio+import subprocess+import numpy as np+import os.path as osp+from tqdm import tqdm+import pyloudnorm as pyln+from einops import rearrange+import scipy.signal as ss++import torch+import torch.nn.functional as F+import torchvision++from ..context_parallel import context_parallel_util+++def torch_gc():+ torch.cuda.empty_cache()+ torch.cuda.ipc_collect()+++def linear_interpolation(features, seq_len):+ features = features.transpose(1, 2)+ output_features = F.interpolate(features, size=seq_len, align_corners=True, mode='linear')+ return output_features.transpose(1, 2)+++def calculate_x_ref_attn_map(noise_q, ref_k, ref_target_masks, attn_bias=None):++ # compute cross-reference attention maps between query features and reference key features.+ ref_k = ref_k.to(noise_q.dtype).to(noise_q.device)+ scale = 1.0 / noise_q.shape[-1] ** 0.5+ noise_q = noise_q * scale+ noise_q = noise_q.transpose(1, 2)+ ref_k = ref_k.transpose(1, 2)+ attn = noise_q @ ref_k.transpose(-2, -1)++ if attn_bias is not None:+ attn = attn + attn_bias++ x_ref_attn_map_source = attn.softmax(-1)++ x_ref_attn_maps = []+ ref_target_masks = ref_target_masks.to(noise_q.dtype)+ x_ref_attn_map_source = x_ref_attn_map_source.to(noise_q.dtype)++ for _, ref_target_mask in enumerate(ref_target_masks):+ torch_gc()+ ref_target_mask = ref_target_mask[None, None, None, ...]+ x_ref_attn_map = x_ref_attn_map_source.clone()+ x_ref_attn_map = x_ref_attn_map * ref_target_mask+ x_ref_attn_map = x_ref_attn_map.sum(-1) / ref_target_mask.sum()+ x_ref_attn_map = x_ref_attn_map.permute(0, 2, 1)+ x_ref_attn_map = x_ref_attn_map.mean(-1)++ x_ref_attn_maps.append(x_ref_attn_map)++ del attn+ del x_ref_attn_map_source+ torch_gc()++ return torch.concat(x_ref_attn_maps, dim=0)+++def get_attn_map_with_target(noise_q, key, shape, ref_target_masks=None, split_num=2, cp_split_hw=None):++ N_t, N_h, N_w = shape+ x_seqlens = N_h * N_w+ if cp_split_hw[0] * cp_split_hw[1] > 1:+ cp_size = context_parallel_util.get_cp_size()+ (split_h, split_w) = (cp_size, 1) if cp_split_hw is None else cp_split_hw++ assert N_h % split_h == 0, N_w % split_w == 0++ N_h_ = N_h // split_h+ N_w_ = N_w // split_w+ x_seqlens = N_h_ * N_w_++ ref_k = key[:, :x_seqlens] # reference image size after cp split+ noise_q = noise_q.contiguous()++ # gather reference image key features+ if cp_split_hw[0] * cp_split_hw[1] > 1:+ _, _, H, _ = ref_k.shape+ ref_k = ref_k.permute(0, 2, 1, 3)+ ref_k = rearrange(ref_k, "b h m k -> b (h m) k")+ ref_k = context_parallel_util.gather_cp_2d(ref_k, shape=(H, N_h, N_w), split_hw=cp_split_hw)+ ref_k = rearrange(ref_k, "b (h m) k -> b h m k", h=H)+ ref_k = ref_k.permute(0, 2, 1, 3)++ _, seq_lens, heads, _ = noise_q.shape+ class_num, _ = ref_target_masks.shape+ x_ref_attn_maps = torch.zeros(class_num, seq_lens).to(noise_q.device).to(noise_q.dtype)++ split_chunk = heads // split_num++ # calculate attn map within each group and take the mean+ for i in range(split_num):+ x_ref_attn_maps_perhead = calculate_x_ref_attn_map(noise_q[:, :, i*split_chunk:(i+1)*split_chunk, :], ref_k[:, :, i*split_chunk:(i+1)*split_chunk, :], ref_target_masks)+ x_ref_attn_maps += x_ref_attn_maps_perhead++ return x_ref_attn_maps / split_num+++def rand_name(length=8, suffix=''):+ name = binascii.b2a_hex(os.urandom(length)).decode('utf-8')+ if suffix:+ if not suffix.startswith('.'):+ suffix = '.' + suffix+ name += suffix+ return name++def cache_video(tensor,+ save_file=None,+ fps=30,+ suffix='.mp4',+ nrow=8,+ normalize=True,+ value_range=(-1, 1),+ retry=5):++ # cache file+ cache_file = osp.join('/tmp', rand_name(+ suffix=suffix)) if save_file is None else save_file++ # save to cache+ error = None+ for _ in range(retry):++ # preprocess+ tensor = tensor.clamp(min(value_range), max(value_range))+ tensor = torch.stack([+ torchvision.utils.make_grid(+ u, nrow=nrow, normalize=normalize, value_range=value_range)+ for u in tensor.unbind(2)+ ],+ dim=1).permute(1, 2, 3, 0)+ tensor = (tensor * 255).type(torch.uint8).cpu()++ # write video+ writer = imageio.get_writer(cache_file, fps=fps, codec='libx264', quality=10, ffmpeg_params=["-crf", "10"])+ for frame in tensor.numpy():+ writer.append_data(frame)+ writer.close()+ return cache_file++def get_audio_duration(audio_path):+ cmd = [+ "ffprobe",+ "-v", "quiet",+ "-print_format", "json",+ "-show_entries", "format=duration",+ audio_path,+ ]+ out = subprocess.check_output(cmd)+ info = json.loads(out)+ return float(info["format"]["duration"])+++def save_video_ffmpeg(gen_video_samples, save_path, audio_path, fps=25, quality=5, high_quality_save=False):++ def save_video(frames, save_path, fps, quality=9, ffmpeg_params=None):+ writer = imageio.get_writer(+ save_path, fps=fps, quality=quality, ffmpeg_params=ffmpeg_params+ )+ for frame in tqdm(frames, desc="Saving video"):+ frame = np.array(frame)+ writer.append_data(frame)+ writer.close()+ save_path_tmp = save_path + "-temp.mp4"++ os.makedirs(os.path.dirname(save_path_tmp), exist_ok=True)+ video_audio = gen_video_samples.cpu().numpy()+ video_audio = np.clip(video_audio, 0, 255).astype(np.uint8)+ save_video(video_audio, save_path_tmp, fps=fps, quality=quality)++ # crop audio according to video length+ T, _, _, _ = gen_video_samples.shape+ duration = T / fps+ save_path_crop_audio = save_path + "-cropaudio.wav"+ final_command = [+ "ffmpeg",+ "-y",+ "-i",+ audio_path,+ "-t",+ f'{duration}',+ save_path_crop_audio,+ ]+ subprocess.run(final_command, check=True)++ # crop video according to audio length+ crop_audio_duration = get_audio_duration(save_path_crop_audio)+ save_path_crop_tmp = save_path + "-cropvideo.mp4"+ cmd = [+ "ffmpeg",+ "-y",+ "-i", save_path_tmp,+ "-t", f"{crop_audio_duration}",+ "-c:v", "copy",+ "-c:a", "copy",+ save_path_crop_tmp,+ ]+ subprocess.run(cmd, check=True)++ # generate video with audio+ save_path = save_path + ".mp4"+ if high_quality_save:+ final_command = [+ "ffmpeg",+ "-y",+ "-i", save_path_crop_tmp,+ "-i", save_path_crop_audio,+ "-c:v", "libx264",+ "-crf", "0",+ "-preset", "veryslow",+ "-c:a", "aac",+ "-shortest",+ save_path,+ ]+ subprocess.run(final_command, check=True)+ else:+ final_command = [+ "ffmpeg",+ "-y",+ "-i",+ save_path_crop_tmp,+ "-i",+ save_path_crop_audio,+ "-c:v",+ "libx264",+ "-c:a",+ "aac",+ "-shortest",+ save_path,+ ]+ subprocess.run(final_command, check=True)++ os.remove(save_path_tmp)+ os.remove(save_path_crop_tmp)+ os.remove(save_path_crop_audio)\ No newline at end of filediff --git a/longcat_video/audio_process/wav2vec2.py b/longcat_video/audio_process/wav2vec2.pynew file mode 100644index 0000000..0aaf72d--- /dev/null+++ b/longcat_video/audio_process/wav2vec2.py@@ -0,0 +1,252 @@+import os+import copy+import logging++import torch+import torch.nn as nn+from transformers import Wav2Vec2Config+from transformers import Wav2Vec2Model as Wav2Vec2Model_base+from transformers.models.wav2vec2.modeling_wav2vec2 import Wav2Vec2SamePadLayer, Wav2Vec2PositionalConvEmbedding+from transformers.activations import ACT2FN+from transformers.modeling_outputs import BaseModelOutput++from .torch_utils import linear_interpolation+++def _Wav2Vec2PositionalConvEmbedding_init_hack_(self, config):+ super(Wav2Vec2PositionalConvEmbedding, self).__init__()+ self.conv = nn.Conv1d(+ config.hidden_size,+ config.hidden_size,+ kernel_size=config.num_conv_pos_embeddings,+ padding=config.num_conv_pos_embeddings // 2,+ groups=config.num_conv_pos_embedding_groups,+ )++ weight_norm = nn.utils.weight_norm+ if hasattr(nn.utils.parametrizations, "weight_norm"):+ weight_norm = nn.utils.parametrizations.weight_norm+ self.conv = weight_norm(self.conv, name="weight", dim=2)++ self.padding = Wav2Vec2SamePadLayer(config.num_conv_pos_embeddings)+ self.activation = ACT2FN[config.feat_extract_activation]++Wav2Vec2PositionalConvEmbedding.__init__ = _Wav2Vec2PositionalConvEmbedding_init_hack_+++class Wav2Vec2ModelWrapper(nn.Module):+ def __init__(self, config_path, device='cuda', prefix='wav2vec2.'):+ super(Wav2Vec2ModelWrapper, self).__init__()++ config, model_kwargs = Wav2Vec2Config.from_pretrained(+ config_path,+ return_unused_kwargs=True,+ force_download=False,+ local_files_only=True,+ )++ model_path = os.path.join(config_path, 'pytorch_model.bin')+ state_dict = torch.load(model_path, map_location=device)++ config.name_or_path = config_path+ config = copy.deepcopy(config) # We do not want to modify the config inplace in from_pretrained.+ config = Wav2Vec2Mode._autoset_attn_implementation(config, use_flash_attention_2=False)++ # init model+ with torch.device('meta'):+ model = Wav2Vec2Mode(config)++ # load checkpoint+ logging.info(f'loading {model_path}')+ if prefix is not None:+ state_dict = {i.replace(prefix, ''):state_dict[i] for i in state_dict}++ model.tie_weights()+ m, u = model.load_state_dict(state_dict, assign=True, strict=False)++ model.tie_weights()+ model.eval()++ self.model = model++ @property+ def feature_extractor(self):+ return self.model.feature_extractor++ def forward(+ self,+ input_values,+ seq_len,+ attention_mask=None,+ mask_time_indices=None,+ output_attentions=None,+ output_hidden_states=None,+ return_dict=None,+ ):+ return self.model(+ input_values,+ seq_len,+ attention_mask=attention_mask,+ mask_time_indices=mask_time_indices,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ )++ def feature_extract(+ self,+ input_values,+ seq_len,+ ):+ extract_features = self.feature_extractor(input_values)+ extract_features = extract_features.transpose(1, 2)+ extract_features = linear_interpolation(extract_features, seq_len=seq_len)++ return self.model.feature_extract(+ input_values,+ seq_len+ )++ def encode(+ self,+ extract_features,+ attention_mask=None,+ mask_time_indices=None,+ output_attentions=None,+ output_hidden_states=None,+ return_dict=None,+ ):++ return self.model.encode(+ extract_features,+ attention_mask=attention_mask,+ mask_time_indices=mask_time_indices,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ )+++# the implementation of Wav2Vec2Model is borrowed from+# https://github.com/huggingface/transformers/blob/HEAD/src/transformers/models/wav2vec2/modeling_wav2vec2.py+# initialize our encoder with the pre-trained wav2vec 2.0 weights.+class Wav2Vec2Mode(Wav2Vec2Model_base):+ def __init__(self, config: Wav2Vec2Config):+ config.attn_implementation = "eager"+ super().__init__(config)+++ def forward(+ self,+ input_values,+ seq_len,+ attention_mask=None,+ mask_time_indices=None,+ output_attentions=None,+ output_hidden_states=None,+ return_dict=None,+ ):+ self.config._attn_implementation = "eager"+ self.config.output_attentions = True++ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict++ extract_features = self.feature_extractor(input_values)+ extract_features = extract_features.transpose(1, 2)+ extract_features = linear_interpolation(extract_features, seq_len=seq_len)++ if attention_mask is not None:+ # compute reduced attention_mask corresponding to feature vectors+ attention_mask = self._get_feature_vector_attention_mask(+ extract_features.shape[1], attention_mask, add_adapter=False+ )++ hidden_states, extract_features = self.feature_projection(extract_features)+ hidden_states = self._mask_hidden_states(+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask+ )++ encoder_outputs = self.encoder(+ hidden_states,+ attention_mask=attention_mask,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ )++ hidden_states = encoder_outputs[0]++ if self.adapter is not None:+ hidden_states = self.adapter(hidden_states)++ if not return_dict:+ return (hidden_states, ) + encoder_outputs[1:]+ return BaseModelOutput(+ last_hidden_state=hidden_states,+ hidden_states=encoder_outputs.hidden_states,+ attentions=encoder_outputs.attentions,+ )+++ def feature_extract(+ self,+ input_values,+ seq_len,+ ):+ extract_features = self.feature_extractor(input_values)+ extract_features = extract_features.transpose(1, 2)+ extract_features = linear_interpolation(extract_features, seq_len=seq_len)++ return extract_features++ def encode(+ self,+ extract_features,+ attention_mask=None,+ mask_time_indices=None,+ output_attentions=None,+ output_hidden_states=None,+ return_dict=None,+ ):+ self.config.output_attentions = True++ output_hidden_states = (+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states+ )+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict++ if attention_mask is not None:+ # compute reduced attention_mask corresponding to feature vectors+ attention_mask = self._get_feature_vector_attention_mask(+ extract_features.shape[1], attention_mask, add_adapter=False+ )+++ hidden_states, extract_features = self.feature_projection(extract_features)+ hidden_states = self._mask_hidden_states(+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask+ )++ encoder_outputs = self.encoder(+ hidden_states,+ attention_mask=attention_mask,+ output_attentions=output_attentions,+ output_hidden_states=output_hidden_states,+ return_dict=return_dict,+ )++ hidden_states = encoder_outputs[0]++ if self.adapter is not None:+ hidden_states = self.adapter(hidden_states)++ if not return_dict:+ return (hidden_states, ) + encoder_outputs[1:]+ return BaseModelOutput(+ last_hidden_state=hidden_states,+ hidden_states=encoder_outputs.hidden_states,+ attentions=encoder_outputs.attentions,+ )diff --git a/longcat_video/context_parallel/context_parallel_util.py b/longcat_video/context_parallel/context_parallel_util.pyindex 1dc55e9..ddf10c6 100644--- a/longcat_video/context_parallel/context_parallel_util.py+++ b/longcat_video/context_parallel/context_parallel_util.py@@ -121,6 +121,24 @@ def split_tensor_in_cp_2d(input, dim_hw, split_hw):return split_tensor+class GatherFunction(torch.autograd.Function):++ @staticmethod+ def forward(ctx, input, process_group, seq_dim, frames):+ ctx.cp_group = process_group+ ctx.seq_dim = seq_dim+ ctx.frames = frames+ ctx.cp_size = get_cp_size()+ input = rearrange(input, "B (T S) C -> B T S C", T=frames)+ with torch.no_grad():+ input = input.contiguous()+ output_tensors = [torch.zeros_like(input) for _ in range(ctx.cp_size)]+ dist.all_gather(output_tensors, input, group=ctx.cp_group)+ output_tensor = torch.cat(output_tensors, dim=seq_dim)+ output_tensor = rearrange(output_tensor, "B T S C -> B (T S) C", T=frames)+ return output_tensor++class GatherFunction2D(torch.autograd.Function):@staticmethod@@ -197,6 +215,12 @@ class SplitFunction2D(torch.autograd.Function):return grad_input, None, None, None+def gather_cp(input, frames):+ cp_process_group = get_cp_group()+ output_tensor = GatherFunction.apply(input, cp_process_group, 2, frames)++ return output_tensor+def gather_cp_2d(input, shape, split_hw):cp_process_group = get_cp_group()output_tensor = GatherFunction2D.apply(input, cp_process_group, (2, 3), shape, split_hw)diff --git a/longcat_video/modules/avatar/attention.py b/longcat_video/modules/avatar/attention.pynew file mode 100644index 0000000..97ee132--- /dev/null+++ b/longcat_video/modules/avatar/attention.py@@ -0,0 +1,457 @@+from typing import List, Optional++import torch+import torch.nn as nn++from einops import rearrange++from .rope_3d import RotaryPositionalEmbedding+from ..blocks import RMSNorm_FP32+from ...block_sparse_attention.bsa_interface import flash_attn_bsa_3d+from ...context_parallel.ulysses_wrapper import ulysses_wrapper+from ...audio_process.torch_utils import get_attn_map_with_target+from .rope_3d import RotaryPositionalEmbedding1D+from ...context_parallel import context_parallel_util+++def normalize_and_scale(column, source_range, target_range, epsilon=1e-8):+ source_min, source_max = source_range+ new_min, new_max = target_range+ normalized = (column - source_min) / (source_max - source_min + epsilon)+ scaled = normalized * (new_max - new_min) + new_min+ return scaled+++class Attention(nn.Module):+ def __init__(+ self,+ dim: int,+ num_heads: int,+ enable_flashattn3: bool = False,+ enable_flashattn2: bool = False,+ enable_xformers: bool = False,+ enable_bsa: bool = False,+ bsa_params: dict = None,+ cp_split_hw: Optional[List[int]] = None+ ) -> None:+ super().__init__()+ assert dim % num_heads == 0, "dim should be divisible by num_heads"+ self.dim = dim+ self.num_heads = num_heads+ self.head_dim = dim // num_heads+ self.scale = self.head_dim**-0.5+ self.enable_flashattn3 = enable_flashattn3+ self.enable_flashattn2 = enable_flashattn2+ self.enable_xformers = enable_xformers+ self.enable_bsa = enable_bsa+ self.bsa_params = bsa_params+ self.cp_split_hw = cp_split_hw++ self.qkv = nn.Linear(dim, dim * 3, bias=True)+ self.q_norm = RMSNorm_FP32(self.head_dim, eps=1e-6)+ self.k_norm = RMSNorm_FP32(self.head_dim, eps=1e-6)+ self.proj = nn.Linear(dim, dim)++ self.rope_3d = RotaryPositionalEmbedding(+ self.head_dim,+ cp_split_hw=cp_split_hw+ )++ @ulysses_wrapper+ def _process_attn(self, q, k, v, shape):+ """+ function wrapper to do attention with q, k, v+ """++ B, H, SQ, D = q.shape+ _, _, SKV, _ = k.shape++ if self.enable_bsa and shape[0] > 1: # bsa will not be used in image training / sampling+ assert self.bsa_params is not None+ _, H, W = shape+ assert H % self.cp_split_hw[0] == 0, W % self.cp_split_hw[1] == 0+ H, W = H // self.cp_split_hw[0], W // self.cp_split_hw[1]+ Tq = SQ // (H * W)+ Tk = SKV // (H * W)+ latent_shape_q = (Tq, H, W)+ latent_shape_k = (Tk, H, W)+ x = flash_attn_bsa_3d(q, k, v, latent_shape_q, latent_shape_k, **self.bsa_params)+ elif self.enable_flashattn3:+ from flash_attn_interface import flash_attn_func+ q = rearrange(q, "B H S D -> B S H D").contiguous()+ k = rearrange(k, "B H S D -> B S H D").contiguous()+ v = rearrange(v, "B H S D -> B S H D").contiguous()+ x, *_ = flash_attn_func(+ q,+ k,+ v,+ softmax_scale=self.scale,+ )+ x = rearrange(x, "B S H D -> B H S D")+ elif self.enable_flashattn2:+ from flash_attn import flash_attn_func+ q = rearrange(q, "B H S D -> B S H D")+ k = rearrange(k, "B H S D -> B S H D")+ v = rearrange(v, "B H S D -> B S H D")+ x = flash_attn_func(+ q,+ k,+ v,+ dropout_p=0.0,+ softmax_scale=self.scale,+ )+ x = rearrange(x, "B S H D -> B H S D")+ elif self.enable_xformers:+ import xformers.ops+ # Input tensors must be in format ``[B, M, H, K]``, where B is the batch size, M \+ # the sequence length, H the number of heads, and K the embeding size per head+ q = rearrange(q, "B H M K -> B M H K")+ k = rearrange(k, "B H M K -> B M H K")+ v = rearrange(v, "B H M K -> B M H K")+ x = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=None,)+ x = rearrange(x, "B M H K -> B H M K")+ else:+ raise RuntimeError("Unsupported attention operations.")++ return x++ def forward(self, x: torch.Tensor, shape=None, num_cond_latents=None, return_kv=False, num_ref_latents=None, ref_img_index=None, mask_frame_range=None, ref_target_masks=None) -> torch.Tensor:+ """+ """+ B, N, C = x.shape+ qkv = self.qkv(x)++ qkv_shape = (B, N, 3, self.num_heads, self.head_dim)+ qkv = qkv.view(qkv_shape).permute((2, 0, 3, 1, 4))+ q, k, v = qkv.unbind(0)+ q, k = self.q_norm(q), self.k_norm(k)++ if return_kv:+ k_cache, v_cache = k.clone(), v.clone()++ q, k = self.rope_3d(q, k, shape, ref_img_index, num_ref_latents)++ N_t, N_h, N_w = shape+ # cond mode+ if num_cond_latents is not None and num_cond_latents == 1:+ # image to video+ num_cond_latents_thw = num_cond_latents * (N // N_t)+ # process the condition tokens+ q_cond = q[:, :, :num_cond_latents_thw].contiguous()+ k_cond = k[:, :, :num_cond_latents_thw].contiguous()+ v_cond = v[:, :, :num_cond_latents_thw].contiguous()+ x_cond = self._process_attn(q_cond, k_cond, v_cond, shape)+ # process the noise tokens+ q_noise = q[:, :, num_cond_latents_thw:].contiguous()+ x_noise = self._process_attn(q_noise, k, v, shape)+ # merge x_cond and x_noise+ x = torch.cat([x_cond, x_noise], dim=2).contiguous()+ elif num_cond_latents is not None and num_cond_latents > 1:+ # video continuation+ assert num_ref_latents is not None and ref_img_index is not None, f"No specified insertion position for reference frame"+ num_ref_latents_thw = (N // N_t)+ num_cond_latents_thw = num_cond_latents * (N // N_t)+ # process the condition tokens+ q_ref = q[:, :, :num_ref_latents_thw].contiguous()+ k_ref = k[:, :, :num_ref_latents_thw].contiguous()+ v_ref = v[:, :, :num_ref_latents_thw].contiguous()+ q_cond = q[:, :, num_ref_latents_thw:num_cond_latents_thw].contiguous()+ k_cond = k[:, :, num_ref_latents_thw:num_cond_latents_thw].contiguous()+ v_cond = v[:, :, num_ref_latents_thw:num_cond_latents_thw].contiguous()+ x_ref = self._process_attn(q_ref, k_ref, v_ref, shape)+ x_cond = self._process_attn(q_cond, k_cond, v_cond, shape)+ if num_cond_latents == N_t:+ x = torch.cat([x_ref, x_cond], dim=2).contiguous()+ else:+ # process the noise tokens+ q_noise = q[:, :, num_cond_latents_thw:].contiguous()++ start_noise, end_noise, num_noisy_frames = 0, 0, N_t - num_cond_latents+ if mask_frame_range is not None and mask_frame_range > 0:+ start_noise = ref_img_index - mask_frame_range - num_cond_latents + num_ref_latents+ end_noise = ref_img_index + mask_frame_range - num_cond_latents + num_ref_latents + 1++ if start_noise >= 0 and end_noise > start_noise and end_noise <= num_noisy_frames:+ # remove attention with the reference image in the target range, preventing repeated actions.+ _enable_bsa = self.enable_bsa+ self.enable_bsa = False # close bsa to prevent the temporal dimension from being divisible by bsa chunks++ start_pos = start_noise * (N // N_t)+ end_pos = end_noise * (N // N_t)+ q_noise_front = q_noise[:, :, :start_pos].contiguous()+ q_noise_maskref = q_noise[:, :, start_pos:end_pos].contiguous()+ q_noise_back = q_noise[:, :, end_pos:].contiguous()+ k_non_ref = k[:, :, num_ref_latents_thw:].contiguous()+ v_non_ref = v[:, :, num_ref_latents_thw:].contiguous()+ x_noise_front = self._process_attn(q_noise_front, k, v, shape) # q_front has attention with ref + cond + noisy+ x_noise_back = self._process_attn(q_noise_back, k, v, shape) # q_back has attention with ref + cond + noisy+ x_noise_maskref = self._process_attn(q_noise_maskref, k_non_ref, v_non_ref, shape) # q_mask has attention with cond+noisy+ x_noise = torch.cat([x_noise_front, x_noise_maskref, x_noise_back], dim=2).contiguous()+ self.enable_bsa = _enable_bsa # recover bsa state+ else:+ x_noise = self._process_attn(q_noise, k, v, shape)+ # merge x_cond and x_noise+ x = torch.cat([x_ref, x_cond, x_noise], dim=2).contiguous()++ else:+ # text to video+ x = self._process_attn(q, k, v, shape)++ x_output_shape = (B, N, C)+ x = x.transpose(1, 2)+ x = x.reshape(x_output_shape)+ x = self.proj(x)++ # calculate attention mask for the given area in reference image+ x_ref_attn_map = None+ if ref_target_masks is not None:+ assert num_cond_latents is not None and num_cond_latents > 0, f"currently, multitalk only supports image to video or video continuation"+ x_ref_attn_map = get_attn_map_with_target(q.permute(0, 2, 1, 3)[:, num_cond_latents_thw:].type_as(x), k.permute(0, 2, 1, 3).type_as(x), shape, ref_target_masks=ref_target_masks, cp_split_hw=self.cp_split_hw)++ if return_kv:+ return x, (k_cache, v_cache), x_ref_attn_map+ else:+ return x, x_ref_attn_map++ def forward_with_kv_cache(self, x: torch.Tensor, shape=None, num_cond_latents=None, kv_cache=None, num_ref_latents=None, ref_img_index=None, mask_frame_range=None, ref_target_masks=None) -> torch.Tensor:+ """+ """+ B, N, C = x.shape+ qkv = self.qkv(x)++ qkv_shape = (B, N, 3, self.num_heads, self.head_dim)+ qkv = qkv.view(qkv_shape).permute((2, 0, 3, 1, 4))+ q, k, v = qkv.unbind(0)+ q, k = self.q_norm(q), self.k_norm(k)++ N_t, N_h, N_w = shape+ k_cache, v_cache = kv_cache+ assert k_cache.shape[0] == v_cache.shape[0] and k_cache.shape[0] in [1, B]+ if k_cache.shape[0] == 1:+ k_cache = k_cache.repeat(B, 1, 1, 1)+ v_cache = v_cache.repeat(B, 1, 1, 1)++ if num_cond_latents is not None and num_cond_latents > 0:+ k_full = torch.cat([k_cache, k], dim=2).contiguous()+ v_full = torch.cat([v_cache, v], dim=2).contiguous()+ q_padding = torch.cat([torch.empty_like(k_cache), q], dim=2).contiguous()+ q_padding, k_full = self.rope_3d(q_padding, k_full, (N_t + num_cond_latents, N_h, N_w), ref_img_index, num_ref_latents)+ q = q_padding[:, :, -N:].contiguous()++ start_noise, end_noise, num_noisy_frames = 0, 0, N_t+ if mask_frame_range is not None and mask_frame_range > 0:+ start_noise = ref_img_index - mask_frame_range - num_cond_latents + num_ref_latents+ end_noise = ref_img_index + mask_frame_range - num_cond_latents + num_ref_latents + 1++ if start_noise >= 0 and end_noise > start_noise and end_noise <= num_noisy_frames:+ # remove attention with the reference image in the target range, preventing repeated actions.+ _enable_bsa = self.enable_bsa+ self.enable_bsa = False # close bsa to prevent the temporal dimension from being divisible by bsa chunks++ num_ref_latents_thw = (N // N_t)+ start_pos = start_noise * (N // N_t)+ end_pos = end_noise * (N // N_t)+ q_noise_front = q[:, :, :start_pos].contiguous()+ q_noise_maskref = q[:, :, start_pos:end_pos].contiguous()+ q_noise_back = q[:, :, end_pos:].contiguous()+ k_non_ref = k_full[:, :, num_ref_latents_thw:].contiguous()+ v_non_ref = v_full[:, :, num_ref_latents_thw:].contiguous()+ x_noise_front = self._process_attn(q_noise_front, k_full, v_full, shape) # q_front --> ref+cond+noisy+ x_noise_back = self._process_attn(q_noise_back, k_full, v_full, shape) # q_back --> ref+cond+noisy+ x_noise_maskref = self._process_attn(q_noise_maskref, k_non_ref, v_non_ref, shape) # q_mask --> cond+noisy+ x = torch.cat([x_noise_front, x_noise_maskref, x_noise_back], dim=2).contiguous()+ self.enable_bsa = _enable_bsa # recover bsa state+ else:+ x = self._process_attn(q, k_full, v_full, shape)++ x_output_shape = (B, N, C)+ x = x.transpose(1, 2)+ x = x.reshape(x_output_shape)+ x = self.proj(x)++ # calculate attention mask for the given area in reference image+ x_ref_attn_map = None+ if ref_target_masks is not None:+ assert num_cond_latents is not None and num_cond_latents > 0, f"currently, multitalk only supports image to video or video continuation"+ x_ref_attn_map = get_attn_map_with_target(q.permute(0, 2, 1, 3).type_as(x), k_full.permute(0, 2, 1, 3).type_as(x), shape, ref_target_masks=ref_target_masks, cp_split_hw=self.cp_split_hw)++ return x, x_ref_attn_map+++class SingleStreamAttention(nn.Module):+ def __init__(+ self,+ dim: int,+ encoder_hidden_states_dim: int,+ num_heads: int,+ qkv_bias: bool,+ qk_norm: bool,+ attn_drop: float = 0.0,+ proj_drop: float = 0.0,+ eps: float = 1e-6,+ class_range: int = 24,+ class_interval: int = 4,+ cp_split_hw: Optional[List[int]] = None,+ enable_flashattn3: bool = False,+ enable_flashattn2: bool = False,+ enable_xformers: bool = False,+ ) -> None:+ super().__init__()+ assert dim % num_heads == 0, "dim should be divisible by num_heads"+ self.dim = dim+ self.encoder_hidden_states_dim = encoder_hidden_states_dim+ self.num_heads = num_heads+ self.head_dim = dim // num_heads+ self.scale = self.head_dim**-0.5+ self.cp_split_hw = cp_split_hw+ self.enable_flashattn3 = enable_flashattn3+ self.enable_flashattn2 = enable_flashattn2+ self.enable_xformers = enable_xformers++ self.q_linear = nn.Linear(dim, dim, bias=qkv_bias)+ self.q_norm = RMSNorm_FP32(self.head_dim, eps=eps) if qk_norm else nn.Identity()++ self.attn_drop = nn.Dropout(attn_drop)+ self.proj = nn.Linear(dim, dim)+ self.proj_drop = nn.Dropout(proj_drop)++ self.kv_linear = nn.Linear(encoder_hidden_states_dim, dim * 2, bias=qkv_bias)+ self.k_norm = RMSNorm_FP32(self.head_dim, eps=eps) if qk_norm else nn.Identity()++ # multitalk related params+ self.class_interval = class_interval+ self.class_range = class_range+ self.rope_h1 = (0, self.class_interval)+ self.rope_h2 = (self.class_range - self.class_interval, self.class_range)+ self.rope_bak = int(self.class_range // 2)+ self.rope_1d = RotaryPositionalEmbedding1D(self.head_dim)++ def _process_cross_attn(self, x, cond, frames_num=None, x_ref_attn_map=None):++ N_t = frames_num+ out_dtype = x.dtype+ x = rearrange(x, "B (N_t S) C -> (B N_t) S C", N_t=N_t)++ # get q for hidden_state+ B, N, C = x.shape+ q = self.q_linear(x)+ q_shape = (B, N, self.num_heads, self.head_dim)+ q = q.view(q_shape).permute((0, 2, 1, 3)) # [B, H, N, D]+ q = self.q_norm(q)++ # multitalk with rope1d pe+ if x_ref_attn_map is not None:+ max_values = x_ref_attn_map.max(1).values[:, None, None]+ min_values = x_ref_attn_map.min(1).values[:, None, None]+ max_min_values = torch.cat([max_values, min_values], dim=2)+ if self.cp_split_hw is not None and self.cp_split_hw[0] * self.cp_split_hw[1] > 1:+ max_min_values = context_parallel_util.gather_cp(max_min_values, 1)+ human1_max_value, human1_min_value = max_min_values[0, :, 0].max(), max_min_values[0, :, 1].min()+ human2_max_value, human2_min_value = max_min_values[1, :, 0].max(), max_min_values[1, :, 1].min()++ human1 = normalize_and_scale(x_ref_attn_map[0], (human1_min_value, human1_max_value), (self.rope_h1[0], self.rope_h1[1]))+ human2 = normalize_and_scale(x_ref_attn_map[1], (human2_min_value, human2_max_value), (self.rope_h2[0], self.rope_h2[1]))+ back = torch.full((x_ref_attn_map.size(1),), self.rope_bak, dtype=human1.dtype).to(human1.device)+ max_indices = x_ref_attn_map.argmax(dim=0)+ normalized_map = torch.stack([human1, human2, back], dim=1)+ normalized_pos = normalized_map[range(x_ref_attn_map.size(1)), max_indices]++ q = rearrange(q, "(B N_t) H S C -> B H (N_t S) C", N_t=N_t)+ q = self.rope_1d(q, normalized_pos)+ q = rearrange(q, "B H (N_t S) C -> (B N_t) H S C", N_t=N_t)++ # get kv from encoder_hidden_states+ _, N_a, _ = cond.shape+ encoder_kv = self.kv_linear(cond)+ encoder_kv_shape = (B, N_a, 2, self.num_heads, self.head_dim)+ encoder_kv = encoder_kv.view(encoder_kv_shape).permute((2, 0, 3, 1, 4))++ encoder_k, encoder_v = encoder_kv.unbind(0)+ encoder_k = self.k_norm(encoder_k)+++ # multitalk with rope1d pe+ if x_ref_attn_map is not None:+ per_frame = torch.zeros(N_a, dtype=encoder_k.dtype).to(encoder_k.device)+ per_frame[:per_frame.size(0)//2] = (self.rope_h1[0] + self.rope_h1[1]) / 2+ per_frame[per_frame.size(0)//2:] = (self.rope_h2[0] + self.rope_h2[1]) / 2+ encoder_pos = torch.concat([per_frame]*N_t, dim=0)+ encoder_k = rearrange(encoder_k, "(B N_t) H S C -> B H (N_t S) C", N_t=N_t)+ encoder_k = self.rope_1d(encoder_k, encoder_pos)+ encoder_k = rearrange(encoder_k, "B H (N_t S) C -> (B N_t) H S C", N_t=N_t)++ # Input tensors must be in format ``[B, M, H, K]``, where B is the batch size, M \+ # the sequence length, H the number of heads, and K the embeding size per head+++ if self.enable_flashattn3:+ from flash_attn_interface import flash_attn_func+ q = rearrange(q, "B H S D -> B S H D").contiguous()+ encoder_k = rearrange(encoder_k, "B H S D -> B S H D").contiguous()+ encoder_v = rearrange(encoder_v, "B H S D -> B S H D").contiguous()+ x, *_ = flash_attn_func(+ q,+ encoder_k,+ encoder_v,+ softmax_scale=self.scale,+ )+ x = rearrange(x, "B S H D -> B H S D")+ elif self.enable_flashattn2:+ from flash_attn import flash_attn_func+ q = rearrange(q, "B H S D -> B S H D")+ encoder_k = rearrange(encoder_k, "B H S D -> B S H D")+ encoder_v = rearrange(encoder_v, "B H S D -> B S H D")+ x = flash_attn_func(+ q,+ encoder_k,+ encoder_v,+ dropout_p=0.0,+ softmax_scale=self.scale,+ )+ x = rearrange(x, "B S H D -> B H S D")+ elif self.enable_xformers:+ import xformers.ops+ q = rearrange(q, "B H M K -> B M H K")+ encoder_k = rearrange(encoder_k, "B H M K -> B M H K")+ encoder_v = rearrange(encoder_v, "B H M K -> B M H K")+ x = xformers.ops.memory_efficient_attention(q, encoder_k, encoder_v, attn_bias=None, op=None,)+ x = rearrange(x, "B M H K -> B H M K")++ # linear transform+ x_output_shape = (B, N, C)+ x = x.transpose(1, 2)+ x = x.reshape(x_output_shape)+ x = self.proj(x)+ x = self.proj_drop(x)++ # reshape x to origin shape+ x = rearrange(x, "(B N_t) S C -> B (N_t S) C", N_t=N_t)++ return x.type(out_dtype)++ def forward(self, x, cond, shape=None, num_cond_latents=None, x_ref_attn_map=None, human_num=None):++ B, N, C = x.shape+ if (num_cond_latents is None or num_cond_latents == 0):+ # text to video+ output = self._process_cross_attn(x, cond, shape[0], x_ref_attn_map)+ return None, output+ elif num_cond_latents is not None and num_cond_latents > 0:+ # image to video or video continuation+ assert shape is not None, "SHOULD pass in the shape"+ num_cond_latents_thw = num_cond_latents * (N // shape[0])+ x_noise = x[:, num_cond_latents_thw:]+ cond = rearrange(cond, "(B N_t) M C -> B N_t M C", B=B)+ cond = cond[:, num_cond_latents:]+ cond = rearrange(cond, "B N_t M C -> (B N_t) M C")+ frames_num = shape[0] - num_cond_latents+ if human_num is not None and human_num == 2:+ # multitalk mode+ output_noise = self._process_cross_attn(x_noise, cond, frames_num, x_ref_attn_map)+ else:+ # singletalk mode+ output_noise = self._process_cross_attn(x_noise, cond, frames_num)+ output_cond = torch.zeros((B, num_cond_latents_thw, C), dtype=output_noise.dtype, device=output_noise.device)+ return output_cond, output_noise+ else:+ raise NotImplementedError\ No newline at end of filediff --git a/longcat_video/modules/avatar/blocks.py b/longcat_video/modules/avatar/blocks.pynew file mode 100644index 0000000..d3a31eb--- /dev/null+++ b/longcat_video/modules/avatar/blocks.py@@ -0,0 +1,88 @@+import torch+import torch.nn as nn++from einops import rearrange+from diffusers import ConfigMixin, ModelMixin+++class AudioProjModel(ModelMixin, ConfigMixin):+ def __init__(+ self,+ seq_len=5,+ seq_len_vf=12,+ blocks=12,+ channels=768,+ intermediate_dim=512,+ output_dim=768,+ context_tokens=32,+ norm_output_audio=True,+ enable_compile=False,+ ):+ super().__init__()++ self.seq_len = seq_len+ self.blocks = blocks+ self.channels = channels+ self.input_dim = seq_len * blocks * channels+ self.input_dim_vf = seq_len_vf * blocks * channels+ self.intermediate_dim = intermediate_dim+ self.context_tokens = context_tokens+ self.output_dim = output_dim++ # define multiple linear layers+ self.proj1 = nn.Linear(self.input_dim, intermediate_dim)+ self.proj1_vf = nn.Linear(self.input_dim_vf, intermediate_dim)+ self.proj2 = nn.Linear(intermediate_dim, intermediate_dim)+ self.proj3 = nn.Linear(intermediate_dim, context_tokens * output_dim)+ self.norm = nn.LayerNorm(output_dim) if norm_output_audio else nn.Identity()+ self.flops = 0.0+ self.enable_compile = enable_compile++ def forward(self, audio_embeds, audio_embeds_vf):+ video_length = audio_embeds.shape[1] + audio_embeds_vf.shape[1]+ B, _, _, S, C = audio_embeds.shape++ # process audio of first frame+ audio_embeds = rearrange(audio_embeds, "bz f w b c -> (bz f) w b c")+ batch_size, window_size, blocks, channels = audio_embeds.shape+ audio_embeds = audio_embeds.view(batch_size, window_size * blocks * channels)++ # process audio of latter frame+ audio_embeds_vf = rearrange(audio_embeds_vf, "bz f w b c -> (bz f) w b c")+ batch_size_vf, window_size_vf, blocks_vf, channels_vf = audio_embeds_vf.shape+ audio_embeds_vf = audio_embeds_vf.view(batch_size_vf, window_size_vf * blocks_vf * channels_vf)++ # first projection+ B1, _ = audio_embeds.shape+ audio_embeds = torch.relu(self.proj1(audio_embeds))+ if not self.enable_compile:+ self.flops += B1 * self.input_dim * self.intermediate_dim * 2++ B1_vf, _ = audio_embeds_vf.shape+ audio_embeds_vf = torch.relu(self.proj1_vf(audio_embeds_vf))+ if not self.enable_compile:+ self.flops += B1_vf * self.input_dim_vf * self.intermediate_dim * 2++ audio_embeds = rearrange(audio_embeds, "(bz f) c -> bz f c", bz=B)+ audio_embeds_vf = rearrange(audio_embeds_vf, "(bz f) c -> bz f c", bz=B)+ audio_embeds_c = torch.concat([audio_embeds, audio_embeds_vf], dim=1)+ batch_size_c, N_t, C_a = audio_embeds_c.shape+ audio_embeds_c = audio_embeds_c.view(batch_size_c*N_t, C_a)++ # second projection+ B2, _ = audio_embeds_c.shape+ audio_embeds_c = torch.relu(self.proj2(audio_embeds_c))+ if not self.enable_compile:+ self.flops += B2 * self.intermediate_dim * self.intermediate_dim * 2++ # third projection+ B3, _ = audio_embeds_c.shape+ context_tokens = self.proj3(audio_embeds_c).reshape(batch_size_c*N_t, self.context_tokens, self.output_dim)+ if not self.enable_compile:+ self.flops += B3 * self.intermediate_dim * (self.context_tokens * self.output_dim) * 2++ # normalization and reshape+ context_tokens = self.norm(context_tokens)+ context_tokens = rearrange(context_tokens, "(bz f) m c -> bz f m c", f=video_length)++ return context_tokens\ No newline at end of filediff --git a/longcat_video/modules/avatar/longcat_video_dit_avatar.py b/longcat_video/modules/avatar/longcat_video_dit_avatar.pynew file mode 100644index 0000000..a30136a--- /dev/null+++ b/longcat_video/modules/avatar/longcat_video_dit_avatar.py@@ -0,0 +1,535 @@+from typing import List, Optional, Tuple++import torch+import torch.nn as nn+import torch.amp as amp++import numpy as np+from einops import rearrange++from diffusers.configuration_utils import ConfigMixin, register_to_config+from diffusers.models.modeling_utils import ModelMixin++from safetensors.torch import load_file++from ..lora_utils import create_lora_network+from ...context_parallel import context_parallel_util+from ..attention import MultiHeadCrossAttention+from ..blocks import TimestepEmbedder, CaptionEmbedder, PatchEmbed3D, FeedForwardSwiGLU, FinalLayer_FP32, LayerNorm_FP32, modulate_fp32++from .attention import Attention, SingleStreamAttention+from .blocks import AudioProjModel+++class LongCatAvatarSingleStreamBlock(nn.Module):+ def __init__(+ self,+ hidden_size: int,+ num_heads: int,+ mlp_ratio: int,+ adaln_tembed_dim: int,+ enable_flashattn3: bool = False,+ enable_flashattn2: bool = False,+ enable_xformers: bool = False,+ enable_bsa: bool = False,+ bsa_params=None,+ cp_split_hw=None,+ # avatar config+ output_dim=768,+ audio_prenorm=True,+ class_range=24,+ class_interval=4+ ):+ super().__init__()++ self.hidden_size = hidden_size++ # scale and gate modulation+ self.adaLN_modulation = nn.Sequential(+ nn.SiLU(),+ nn.Linear(adaln_tembed_dim, 6 * hidden_size, bias=True)+ )+ self.audio_adaLN_modulation = nn.Sequential(+ nn.SiLU(),+ nn.Linear(adaln_tembed_dim, 3 * hidden_size, bias=True)+ )++ self.mod_norm_attn = LayerNorm_FP32(hidden_size, eps=1e-6, elementwise_affine=False)+ self.mod_norm_ffn = LayerNorm_FP32(hidden_size, eps=1e-6, elementwise_affine=False)+ self.pre_crs_attn_norm = LayerNorm_FP32(hidden_size, eps=1e-6, elementwise_affine=True)++ self.pre_video_crs_attn_norm = LayerNorm_FP32(hidden_size, eps=1e-6, elementwise_affine=True)+ self.pre_audio_crs_attn_norm = LayerNorm_FP32(output_dim, eps=1e-6, elementwise_affine=True) if audio_prenorm else nn.Identity()++ self.attn = Attention(+ dim=hidden_size,+ num_heads=num_heads,+ enable_flashattn3=enable_flashattn3,+ enable_flashattn2=enable_flashattn2,+ enable_xformers=enable_xformers,+ enable_bsa=enable_bsa,+ bsa_params=bsa_params,+ cp_split_hw=cp_split_hw+ )+ self.cross_attn = MultiHeadCrossAttention(+ dim=hidden_size,+ num_heads=num_heads,+ enable_flashattn3=enable_flashattn3,+ enable_flashattn2=enable_flashattn2,+ enable_xformers=enable_xformers+ )++ self.audio_cross_attn = SingleStreamAttention(+ dim=hidden_size,+ encoder_hidden_states_dim=output_dim,+ num_heads=num_heads,+ qk_norm=True,+ qkv_bias=True,+ class_range=class_range,+ class_interval=class_interval,+ cp_split_hw=cp_split_hw,+ enable_flashattn3=enable_flashattn3,+ enable_flashattn2=enable_flashattn2,+ enable_xformers=enable_xformers+ )++ self.ffn = FeedForwardSwiGLU(dim=hidden_size, hidden_dim=int(hidden_size * mlp_ratio))++ def forward(+ self,+ x,+ y,+ t,+ y_seqlen,+ latent_shape,+ num_cond_latents=None,+ return_kv=False,+ kv_cache=None,+ skip_crs_attn=False,+ # avatar related params+ num_ref_latents=None,+ audio_hidden_states=None,+ ref_img_index=None,+ mask_frame_range=None,+ token_ref_target_masks=None,+ human_num=None,+ ):+ """+ x: [B, N, C]+ y: [1, N_valid_tokens, C]+ t: [B, T, C_t]+ y_seqlen: [B]; type of a list+ latent_shape: latent shape of a single item+ """+ x_dtype = x.dtype++ B, N, C = x.shape+ T, _, _ = latent_shape # S != T*H*W in case of CP split on H*W.++ # compute modulation params in fp32+ with amp.autocast(device_type='cuda', dtype=torch.float32):+ shift_msa, scale_msa, gate_msa, \+ shift_mlp, scale_mlp, gate_mlp = \+ self.adaLN_modulation(t).unsqueeze(2).chunk(6, dim=-1) # [B, T, 1, C]++ # self attn with modulation+ x_m = modulate_fp32(self.mod_norm_attn, x.view(B, T, -1, C), shift_msa, scale_msa).view(B, N, C)++ if kv_cache is not None:+ kv_cache = (kv_cache[0].to(x.device), kv_cache[1].to(x.device))+ attn_outputs = self.attn.forward_with_kv_cache(x_m, shape=latent_shape, num_cond_latents=num_cond_latents, kv_cache=kv_cache, num_ref_latents=num_ref_latents, \+ ref_img_index=ref_img_index, mask_frame_range=mask_frame_range, ref_target_masks=token_ref_target_masks)+ else:+ attn_outputs = self.attn(x_m, shape=latent_shape, num_cond_latents=num_cond_latents, return_kv=return_kv, num_ref_latents=num_ref_latents, \+ ref_img_index=ref_img_index, mask_frame_range=mask_frame_range, ref_target_masks=token_ref_target_masks)++ if return_kv:+ x_s, kv_cache, x_ref_attn_map = attn_outputs+ else:+ x_s, x_ref_attn_map = attn_outputs++ with amp.autocast(device_type='cuda', dtype=torch.float32):+ x = x + (gate_msa * x_s.view(B, -1, N//T, C)).view(B, -1, C) # [B, N, C]+ x = x.to(x_dtype)++ # text cross attn+ if not skip_crs_attn:+ if kv_cache is not None:+ num_cond_latents = None+ x = x + self.cross_attn(self.pre_crs_attn_norm(x), y, y_seqlen, num_cond_latents=num_cond_latents, shape=latent_shape)++ # audio cross attn+ if not skip_crs_attn:+ if kv_cache is not None:+ num_cond_latents = 0++ with amp.autocast(device_type='cuda', dtype=torch.float32):+ audio_shift_mca, audio_scale_mca, audio_gate_mca = \+ self.audio_adaLN_modulation(t[:, num_cond_latents:]).unsqueeze(2).chunk(3, dim=-1) # [B, T, 1, C]++ audio_output_cond, audio_output_noise = self.audio_cross_attn(self.pre_video_crs_attn_norm(x), self.pre_audio_crs_attn_norm(audio_hidden_states), \+ shape=latent_shape, num_cond_latents=num_cond_latents, x_ref_attn_map=x_ref_attn_map, human_num=human_num)++ with amp.autocast(device_type='cuda', dtype=torch.float32):+ audio_output_noise = modulate_fp32(self.mod_norm_attn, audio_output_noise.view(B, T-num_cond_latents, -1, C), audio_shift_mca, audio_scale_mca).view(B, -1, C)+ audio_add_x = (audio_gate_mca * audio_output_noise.view(B, T-num_cond_latents, -1, C)).view(B, -1, C) # [B, N, C]+ if audio_output_cond is not None:+ audio_add_x = torch.cat([audio_output_cond, audio_add_x], dim=1).contiguous()+ x = x + audio_add_x+ x = x.to(x_dtype)++ # ffn with modulation+ x_m = modulate_fp32(self.mod_norm_ffn, x.view(B, -1, N//T, C), shift_mlp, scale_mlp).view(B, -1, C)+ x_s = self.ffn(x_m)+ with amp.autocast(device_type='cuda', dtype=torch.float32):+ x = x + (gate_mlp * x_s.view(B, -1, N//T, C)).view(B, -1, C) # [B, N, C]+ x = x.to(x_dtype)++ if return_kv:+ return x, kv_cache+ else:+ return x+++class LongCatVideoAvatarTransformer3DModel(+ ModelMixin, ConfigMixin+):+ _supports_gradient_checkpointing = True++ @register_to_config+ def __init__(+ self,+ in_channels: int = 16,+ out_channels: int = 16,+ hidden_size: int = 4096,+ depth: int = 48,+ num_heads: int = 32,+ caption_channels: int = 4096,+ mlp_ratio: int = 4,+ adaln_tembed_dim: int = 512,+ frequency_embedding_size: int = 256,+ # default params+ patch_size: Tuple[int] = (1, 2, 2),+ # attention config+ enable_flashattn3: bool = False,+ enable_flashattn2: bool = False,+ enable_xformers: bool = False,+ enable_bsa: bool = False,+ bsa_params: dict = None,+ cp_split_hw: Optional[List[int]] = None,+ text_tokens_zero_pad: bool = False,+ # avatar config+ audio_window: int = 5,+ intermediate_dim: int = 512,+ output_dim: int = 768,+ context_tokens: int = 32,+ vae_scale: int = 4,+ audio_prenorm: bool = False,+ class_range: int = 24,+ class_interval: int = 4+ ) -> None:+ super().__init__()++ self.patch_size = patch_size+ self.in_channels = in_channels+ self.out_channels = out_channels+ self.cp_split_hw = cp_split_hw+ self.vae_scale = vae_scale+ self.audio_window = audio_window++ self.x_embedder = PatchEmbed3D(patch_size, in_channels, hidden_size)+ self.t_embedder = TimestepEmbedder(t_embed_dim=adaln_tembed_dim, frequency_embedding_size=frequency_embedding_size)+ self.y_embedder = CaptionEmbedder(+ in_channels=caption_channels,+ hidden_size=hidden_size,+ )++ self.blocks = nn.ModuleList(+ [+ LongCatAvatarSingleStreamBlock(+ hidden_size=hidden_size,+ num_heads=num_heads,+ mlp_ratio=mlp_ratio,+ adaln_tembed_dim=adaln_tembed_dim,+ enable_flashattn3=enable_flashattn3,+ enable_flashattn2=enable_flashattn2,+ enable_xformers=enable_xformers,+ enable_bsa=enable_bsa,+ bsa_params=bsa_params,+ cp_split_hw=cp_split_hw,+ output_dim=output_dim,+ audio_prenorm=audio_prenorm,+ class_range=class_range,+ class_interval=class_interval+ )+ for i in range(depth)+ ]+ )++ self.audio_proj = AudioProjModel(+ seq_len=audio_window,+ seq_len_vf=audio_window+vae_scale-1,+ intermediate_dim=intermediate_dim,+ output_dim=output_dim,+ context_tokens=context_tokens+ )++ self.final_layer = FinalLayer_FP32(+ hidden_size,+ np.prod(self.patch_size),+ out_channels,+ adaln_tembed_dim,+ )++ self.gradient_checkpointing = False+ self.text_tokens_zero_pad = text_tokens_zero_pad++ self.lora_dict = {}+ self.active_loras = []++ def load_lora(self, lora_path, lora_key, multiplier=1.0, lora_network_dim=128, lora_network_alpha=64):+ lora_network_state_dict_loaded = load_file(lora_path, device="cpu")+ lora_network = create_lora_network(+ transformer=self,+ lora_network_state_dict_loaded=lora_network_state_dict_loaded,+ multiplier=multiplier,+ network_dim=lora_network_dim,+ network_alpha=lora_network_alpha,+ )++ lora_network.load_state_dict(lora_network_state_dict_loaded, strict=True)++ self.lora_dict[lora_key] = lora_network++ def enable_loras(self, lora_key_list=[]):+ self.disable_all_loras()++ module_loras = {} # {module_name: [lora1, lora2, ...]}+ model_device = next(self.parameters()).device+ model_dtype = next(self.parameters()).dtype++ for lora_key in lora_key_list:+ if lora_key in self.lora_dict:+ for lora in self.lora_dict[lora_key].loras:+ lora.to(model_device, dtype=model_dtype, non_blocking=True)+ module_name = lora.lora_name.replace("lora___lorahyphen___", "").replace("___lorahyphen___", ".")+ if module_name not in module_loras:+ module_loras[module_name] = []+ module_loras[module_name].append(lora)+ self.active_loras.append(lora_key)++ for module_name, loras in module_loras.items():+ module = self._get_module_by_name(module_name)+ if not hasattr(module, 'org_forward'):+ module.org_forward = module.forward+ module.forward = self._create_multi_lora_forward(module, loras)++ def _create_multi_lora_forward(self, module, loras):+ def multi_lora_forward(x, *args, **kwargs):+ weight_dtype = x.dtype+ org_output = module.org_forward(x, *args, **kwargs)++ total_lora_output = 0+ for lora in loras:+ if lora.use_lora:+ lx = lora.lora_down(x.to(lora.lora_down.weight.dtype))+ lx = lora.lora_up(lx)+ lora_output = lx.to(weight_dtype) * lora.multiplier * lora.alpha_scale+ total_lora_output += lora_output++ return org_output + total_lora_output++ return multi_lora_forward++ def _get_module_by_name(self, module_name):+ try:+ module = self+ for part in module_name.split('.'):+ module = getattr(module, part)+ return module+ except AttributeError as e:+ raise ValueError(f"Cannot find module: {module_name}, error: {e}")++ def disable_all_loras(self):+ for name, module in self.named_modules():+ if hasattr(module, 'org_forward'):+ module.forward = module.org_forward+ delattr(module, 'org_forward')++ for lora_key, lora_network in self.lora_dict.items():+ for lora in lora_network.loras:+ lora.to("cpu")++ self.active_loras.clear()++ def enable_bsa(self,):+ for block in self.blocks:+ block.attn.enable_bsa = True++ def disable_bsa(self,):+ for block in self.blocks:+ block.attn.enable_bsa = False++ def forward(+ self,+ hidden_states,+ timestep,+ encoder_hidden_states,+ encoder_attention_mask=None,+ num_cond_latents=0,+ return_kv=False,+ kv_cache_dict={},+ skip_crs_attn=False,+ offload_kv_cache=False,+ # avatar related params+ audio_embs=None,+ num_ref_latents=None,+ ref_img_index=None,+ mask_frame_range=None,+ ref_target_masks=None+ ):++ B, _, T, H, W = hidden_states.shape++ N_t = T // self.patch_size[0]+ N_h = H // self.patch_size[1]+ N_w = W // self.patch_size[2]++ assert self.patch_size[0]==1, "Currently, 3D x_embedder should not compress the temporal dimension."++ # expand the shape of timestep from [B] to [B, T]+ if len(timestep.shape) == 1:+ timestep = timestep.unsqueeze(1).expand(-1, N_t) # [B, T]++ dtype = self.x_embedder.proj.weight.dtype+ hidden_states = hidden_states.to(dtype)+ timestep = timestep.to(dtype)+ encoder_hidden_states = encoder_hidden_states.to(dtype)++ hidden_states = self.x_embedder(hidden_states) # [B, N, C]++ with amp.autocast(device_type='cuda', dtype=torch.float32):+ t = self.t_embedder(timestep.float().flatten(), dtype=torch.float32).reshape(B, N_t, -1) # [B, T, C_t]++ encoder_hidden_states = self.y_embedder(encoder_hidden_states) # [B, 1, N_token, C]++ # get audio token+ audio_cond = audio_embs.to(device=hidden_states.device, dtype=hidden_states.dtype)+ first_frame_audio_emb_s = audio_cond[:, :1, ...] # [B, 1, W, S, C_a]++ latter_frame_audio_emb = audio_cond[:, 1:, ...] # [B, T-1, W, S, C_a]+ latter_frame_audio_emb = rearrange(latter_frame_audio_emb, "b (n_t n) w s c -> b n_t n w s c", n=self.vae_scale)+ middle_index = self.audio_window // 2+ latter_first_frame_audio_emb = latter_frame_audio_emb[:, :, :1, :middle_index+1, ...]+ latter_first_frame_audio_emb = rearrange(latter_first_frame_audio_emb, "b n_t n w s c -> b n_t (n w) s c")++ latter_last_frame_audio_emb = latter_frame_audio_emb[:, :, -1:, middle_index:, ...]+ latter_last_frame_audio_emb = rearrange(latter_last_frame_audio_emb, "b n_t n w s c -> b n_t (n w) s c")++ latter_middle_frame_audio_emb = latter_frame_audio_emb[:, :, 1:-1, middle_index:middle_index+1, ...]+ latter_middle_frame_audio_emb = rearrange(latter_middle_frame_audio_emb, "b n_t n w s c -> b n_t (n w) s c")+ latter_frame_audio_emb_s = torch.concat([latter_first_frame_audio_emb, latter_middle_frame_audio_emb, latter_last_frame_audio_emb], dim=2) # [B, (T-1)//vae_scale, W-1+vae_scale, S, C_a]+ audio_hidden_states = self.audio_proj(first_frame_audio_emb_s, latter_frame_audio_emb_s) # B T 32 768++ if num_ref_latents is not None and num_ref_latents > 0:+ audio_start_ref = audio_hidden_states[:, [0], :, :] # padding+ audio_hidden_states = torch.cat([audio_start_ref, audio_hidden_states], dim=1).contiguous()+ audio_hidden_states = audio_hidden_states[:, -N_t:]++ human_num = None+ if ref_target_masks is not None:+ # multitalk+ human_num = len(audio_hidden_states)+ audio_hidden_states = torch.concat(audio_hidden_states.split(1), dim=2) # B T 32 768 --> # 1 T B*32 768+ audio_hidden_states = audio_hidden_states.squeeze(0)+ else:+ audio_hidden_states = rearrange(audio_hidden_states, "b t n c -> (b t) n c")++ # convert ref_target_masks to token_ref_target_masks+ # 计算target mask 时会把ref image token 进行 gather,因此这里不需要CP+ token_ref_target_masks = None+ if ref_target_masks is not None:+ ref_target_masks = ref_target_masks.unsqueeze(0).to(torch.float32) # [1, B, H, W]; cast for interpolation+ token_ref_target_masks = nn.functional.interpolate(ref_target_masks, size=(N_h, N_w), mode='nearest') # [1, B, N_h, N_w]+ token_ref_target_masks = token_ref_target_masks.squeeze(0) # [B, N_h, N_w]+ token_ref_target_masks = (token_ref_target_masks > 0)+ token_ref_target_masks = token_ref_target_masks.view(token_ref_target_masks.shape[0], -1) # [B, N_h, N_w] --> [B, N_h * N_w]+ token_ref_target_masks = token_ref_target_masks.to(dtype)++ if self.text_tokens_zero_pad and encoder_attention_mask is not None:+ encoder_hidden_states = encoder_hidden_states * encoder_attention_mask[:, None, :, None]+ encoder_attention_mask = (encoder_attention_mask * 0 + 1).to(encoder_attention_mask.dtype)++ if encoder_attention_mask is not None:+ encoder_attention_mask = encoder_attention_mask.squeeze(1).squeeze(1)+ encoder_hidden_states = encoder_hidden_states.squeeze(1).masked_select(encoder_attention_mask.unsqueeze(-1) != 0).view(1, -1, hidden_states.shape[-1]) # [1, N_valid_tokens, C]+ y_seqlens = encoder_attention_mask.sum(dim=1).tolist() # [B]+ else:+ y_seqlens = [encoder_hidden_states.shape[2]] * encoder_hidden_states.shape[0]+ encoder_hidden_states = encoder_hidden_states.squeeze(1).view(1, -1, hidden_states.shape[-1])++ if self.cp_split_hw[0] * self.cp_split_hw[1] > 1:+ hidden_states = rearrange(hidden_states, "B (T H W) C -> B T H W C", T=N_t, H=N_h, W=N_w)+ hidden_states = context_parallel_util.split_cp_2d(hidden_states, seq_dim_hw=(2, 3), split_hw=self.cp_split_hw)+ hidden_states = rearrange(hidden_states, "B T H W C -> B (T H W) C")++ # blocks+ kv_cache_dict_ret = {}+ for i, block in enumerate(self.blocks):+ if torch.is_grad_enabled() and self.gradient_checkpointing:+ block_outputs = self._gradient_checkpointing_func(+ block, hidden_states, encoder_hidden_states, t, y_seqlens,+ (N_t, N_h, N_w), num_cond_latents, return_kv, kv_cache_dict.get(i, None), skip_crs_attn, num_ref_latents, audio_hidden_states, ref_img_index, mask_frame_range, token_ref_target_masks, human_num+ )+ else:+ block_outputs = block(+ hidden_states, encoder_hidden_states, t, y_seqlens,+ (N_t, N_h, N_w), num_cond_latents, return_kv, kv_cache_dict.get(i, None), skip_crs_attn, num_ref_latents, audio_hidden_states, ref_img_index, mask_frame_range, token_ref_target_masks, human_num+ )++ if return_kv:+ hidden_states, kv_cache = block_outputs+ if offload_kv_cache:+ kv_cache_dict_ret[i] = (kv_cache[0].cpu(), kv_cache[1].cpu())+ else:+ kv_cache_dict_ret[i] = (kv_cache[0].contiguous(), kv_cache[1].contiguous())+ else:+ hidden_states = block_outputs++ hidden_states = self.final_layer(hidden_states, t, (N_t, N_h, N_w)) # [B, N, C=T_p*H_p*W_p*C_out]++ if self.cp_split_hw[0] * self.cp_split_hw[1] > 1:+ hidden_states = context_parallel_util.gather_cp_2d(hidden_states, shape=(N_t, N_h, N_w), split_hw=self.cp_split_hw)++ hidden_states = self.unpatchify(hidden_states, N_t, N_h, N_w) # [B, C_out, H, W]++ # cast to float32 for better accuracy+ hidden_states = hidden_states.to(torch.float32)++ if return_kv:+ return hidden_states, kv_cache_dict_ret+ else:+ return hidden_states+++ def unpatchify(self, x, N_t, N_h, N_w):+ """+ Args:+ x (torch.Tensor): of shape [B, N, C]++ Return:+ x (torch.Tensor): of shape [B, C_out, T, H, W]+ """+ T_p, H_p, W_p = self.patch_size+ x = rearrange(+ x,+ "B (N_t N_h N_w) (T_p H_p W_p C_out) -> B C_out (N_t T_p) (N_h H_p) (N_w W_p)",+ N_t=N_t,+ N_h=N_h,+ N_w=N_w,+ T_p=T_p,+ H_p=H_p,+ W_p=W_p,+ C_out=self.out_channels,+ )+ return x\ No newline at end of filediff --git a/longcat_video/modules/avatar/rope_3d.py b/longcat_video/modules/avatar/rope_3d.pynew file mode 100644index 0000000..4027b87--- /dev/null+++ b/longcat_video/modules/avatar/rope_3d.py@@ -0,0 +1,169 @@+# References:+# https://github.com/facebookresearch/fairseq/blob/main/fairseq/modules/rotary_positional_embedding.py++import numpy as np++import torch+import torch.nn as nn++from einops import rearrange, repeat++from ...context_parallel import context_parallel_util+++def broadcat(tensors, dim=-1):+ num_tensors = len(tensors)+ shape_lens = set(list(map(lambda t: len(t.shape), tensors)))+ assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"+ shape_len = list(shape_lens)[0]+ dim = (dim + shape_len) if dim < 0 else dim+ dims = list(zip(*map(lambda t: list(t.shape), tensors)))+ expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]+ assert all(+ [*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]+ ), "invalid dimensions for broadcastable concatentation"+ max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))+ expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))+ expanded_dims.insert(dim, (dim, dims[dim]))+ expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))+ tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))+ return torch.cat(tensors, dim=dim)+++def rotate_half(x):+ x = rearrange(x, "... (d r) -> ... d r", r=2)+ x1, x2 = x.unbind(dim=-1)+ x = torch.stack((-x2, x1), dim=-1)+ return rearrange(x, "... d r -> ... (d r)")+++class RotaryPositionalEmbedding(nn.Module):++ def __init__(self,+ head_dim,+ cp_split_hw=None+ ):+ """Rotary positional embedding for 3D+ Reference : https://blog.eleuther.ai/rotary-embeddings/+ Paper: https://arxiv.org/pdf/2104.09864.pdf+ Args:+ dim: Dimension of embedding+ base: Base value for exponential+ """+ super().__init__()+ self.head_dim = head_dim+ assert self.head_dim % 8 == 0, 'Dim must be a multiply of 8 for 3D RoPE.'+ self.cp_split_hw = cp_split_hw+ # We take the assumption that the longest side of grid will not larger than 512, i.e, 512 * 8 = 4098 input pixels+ self.base = 10000+ self.freqs_dict = {}++ def register_grid_size(self, grid_size, key_name, frame_index=None, num_ref_latents=None):++ if key_name not in self.freqs_dict:+ self.freqs_dict.update({+ key_name: self.precompute_freqs_cis_3d(grid_size, frame_index, num_ref_latents)+ })++ def precompute_freqs_cis_3d(self, grid_size, frame_index=None, num_ref_latents=None):+ num_frames, height, width = grid_size+ dim_t = self.head_dim - 4 * (self.head_dim // 6)+ dim_h = 2 * (self.head_dim // 6)+ dim_w = 2 * (self.head_dim // 6)+ freqs_t = 1.0 / (self.base ** (torch.arange(0, dim_t, 2)[: (dim_t // 2)].float() / dim_t))+ freqs_h = 1.0 / (self.base ** (torch.arange(0, dim_h, 2)[: (dim_h // 2)].float() / dim_h))+ freqs_w = 1.0 / (self.base ** (torch.arange(0, dim_w, 2)[: (dim_w // 2)].float() / dim_w))+ if frame_index is not None and num_ref_latents is not None:+ grid_t = torch.concat([torch.tensor([frame_index], dtype=torch.float32), torch.arange(0, num_frames-num_ref_latents, dtype=torch.float32)], dim=0)+ else:+ grid_t = np.linspace(0, num_frames, num_frames, endpoint=False, dtype=np.float32)+ grid_t = torch.from_numpy(grid_t).float()+ grid_h = np.linspace(0, height, height, endpoint=False, dtype=np.float32)+ grid_w = np.linspace(0, width, width, endpoint=False, dtype=np.float32)+ grid_h = torch.from_numpy(grid_h).float()+ grid_w = torch.from_numpy(grid_w).float()+ freqs_t = torch.einsum("..., f -> ... f", grid_t, freqs_t)+ freqs_h = torch.einsum("..., f -> ... f", grid_h, freqs_h)+ freqs_w = torch.einsum("..., f -> ... f", grid_w, freqs_w)+ freqs_t = repeat(freqs_t, "... n -> ... (n r)", r=2)+ freqs_h = repeat(freqs_h, "... n -> ... (n r)", r=2)+ freqs_w = repeat(freqs_w, "... n -> ... (n r)", r=2)+ freqs = broadcat((freqs_t[:, None, None, :], freqs_h[None, :, None, :], freqs_w[None, None, :, :]), dim=-1)+ # (T H W D)+ freqs = rearrange(freqs, "T H W D -> (T H W) D")+ if self.cp_split_hw[0] * self.cp_split_hw[1] > 1:+ with torch.no_grad():+ freqs = rearrange(freqs, "(T H W) D -> T H W D", T=num_frames, H=height, W=width)+ freqs = context_parallel_util.split_cp_2d(freqs, seq_dim_hw=(1, 2), split_hw=self.cp_split_hw)+ freqs = rearrange(freqs, "T H W D -> (T H W) D")++ return freqs++ def forward(self, q, k, grid_size, frame_index=None, num_ref_latents=None):+ """3D RoPE.++ Args:+ query: [B, head, seq, head_dim]+ key: [B, head, seq, head_dim]+ Returns:+ query and key with the same shape as input.+ """+ key_name = '.'.join([str(i) for i in grid_size]) + f"-{str(frame_index)}-{str(num_ref_latents)}"+ if key_name not in self.freqs_dict:+ self.register_grid_size(grid_size, key_name, frame_index, num_ref_latents)++ freqs_cis = self.freqs_dict[key_name].to(q.device)+ q_, k_ = q.float(), k.float()+ freqs_cis = freqs_cis.float().to(q.device)+ cos, sin = freqs_cis.cos(), freqs_cis.sin()+ cos, sin = rearrange(cos, 'n d -> 1 1 n d'), rearrange(sin, 'n d -> 1 1 n d')+ q_ = (q_ * cos) + (rotate_half(q_) * sin)+ k_ = (k_ * cos) + (rotate_half(k_) * sin)++ return q_.type_as(q), k_.type_as(k)+++class RotaryPositionalEmbedding1D(nn.Module):++ def __init__(self,+ head_dim+ ):+ """Rotary positional embedding for 1D+ Args:+ dim: Dimension of embedding+ base: Base value for exponential+ """+ super().__init__()+ self.head_dim = head_dim+ self.base = 10000++ def precompute_freqs_cis_1d(self, pos_indices):++ freqs = 1.0 / (self.base ** (torch.arange(0, self.head_dim, 2)[: (self.head_dim // 2)].float() / self.head_dim))++ freqs = freqs.to(pos_indices.device)+ freqs = torch.einsum("..., f -> ... f", pos_indices.float(), freqs)+ freqs = repeat(freqs, "... n -> ... (n r)", r=2)++ return freqs++ def forward(self, x, pos_indices):+ """1D RoPE.++ Args:+ query (torch.tensor): [B, head, seq, head_dim]+ pos_indices (torch.tensor): [seq,]+ Returns:+ query with the same shape as input.+ """+ freqs_cis = self.precompute_freqs_cis_1d(pos_indices)++ x_ = x.float()++ freqs_cis = freqs_cis.float().to(x.device)+ cos, sin = freqs_cis.cos(), freqs_cis.sin()+ cos, sin = rearrange(cos, 'n d -> 1 1 n d'), rearrange(sin, 'n d -> 1 1 n d')+ x_ = (x_ * cos) + (rotate_half(x_) * sin)++ return x_.type_as(x)+\ No newline at end of filediff --git a/longcat_video/pipeline_longcat_video_avatar.py b/longcat_video/pipeline_longcat_video_avatar.pynew file mode 100644index 0000000..ec22c07--- /dev/null+++ b/longcat_video/pipeline_longcat_video_avatar.py@@ -0,0 +1,1446 @@+import os+from typing import Any, Dict, List, Optional, Union, Literal++import gc+import math+import torch+import loguru+import numpy as np+from einops import rearrange+import torch.nn.functional as F+from tqdm import tqdm+from PIL import Image+from diffusers.video_processor import VideoProcessor+from diffusers.image_processor import PipelineImageInput+from transformers import AutoTokenizer, UMT5EncoderModel++from longcat_video.modules.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler+from longcat_video.modules.autoencoder_kl_wan import AutoencoderKLWan+from longcat_video.modules.avatar.longcat_video_dit_avatar import LongCatVideoAvatarTransformer3DModel+from longcat_video.context_parallel import context_parallel_util+from longcat_video.utils.bukcet_config import get_bucket_config++import ftfy+import regex as re+import html++# -------- avatar related --------+import scipy.signal as ss+import pyloudnorm as pyln+from longcat_video.audio_process.wav2vec2 import Wav2Vec2ModelWrapper+from transformers import Wav2Vec2FeatureExtractor+from diffusers.image_processor import is_valid_image, is_valid_image_imagelist+import warnings+++def torch_gc():+ torch.cuda.empty_cache()+ torch.cuda.ipc_collect()++# 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")++def basic_clean(text):+ text = ftfy.fix_text(text)+ text = html.unescape(html.unescape(text))+ return text.strip()+++def whitespace_clean(text):+ text = re.sub(r"\s+", " ", text)+ text = text.strip()+ return text+++def prompt_clean(text):+ text = whitespace_clean(basic_clean(text))+ return text++def preprocess_video(self, video, height: Optional[int] = None, width: Optional[int] = None, resize_mode: Optional[str] = 'crop') -> torch.Tensor:+ r"""+ hack diffusers.video_processor.VideoProcessor to support the parameter of resize_mode+ """+ if isinstance(video, list) and isinstance(video[0], np.ndarray) and video[0].ndim == 5:+ warnings.warn(+ "Passing `video` as a list of 5d np.ndarray is deprecated."+ "Please concatenate the list along the batch dimension and pass it as a single 5d np.ndarray",+ FutureWarning,+ )+ video = np.concatenate(video, axis=0)+ if isinstance(video, list) and isinstance(video[0], torch.Tensor) and video[0].ndim == 5:+ warnings.warn(+ "Passing `video` as a list of 5d torch.Tensor is deprecated."+ "Please concatenate the list along the batch dimension and pass it as a single 5d torch.Tensor",+ FutureWarning,+ )+ video = torch.cat(video, axis=0)++ # ensure the input is a list of videos:+ # - if it is a batch of videos (5d torch.Tensor or np.ndarray), it is converted to a list of videos (a list of 4d torch.Tensor or np.ndarray)+ # - if it is a single video, it is converted to a list of one video.+ if isinstance(video, (np.ndarray, torch.Tensor)) and video.ndim == 5:+ video = list(video)+ elif isinstance(video, list) and is_valid_image(video[0]) or is_valid_image_imagelist(video):+ video = [video]+ elif isinstance(video, list) and is_valid_image_imagelist(video[0]):+ video = video+ else:+ raise ValueError(+ "Input is in incorrect format. Currently, we only support numpy.ndarray, torch.Tensor, PIL.Image.Image"+ )++ video = torch.stack([self.preprocess(img, height=height, width=width, resize_mode=resize_mode) for img in video], dim=0)+ video = video.permute(0, 2, 1, 3, 4)++ return video++class LongCatVideoAvatarPipeline:+ r"""+ Pipeline for text-to-video generation using LongCatVideo.++ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).++ """++ def __init__(+ self,+ tokenizer: AutoTokenizer,+ text_encoder: UMT5EncoderModel,+ vae: AutoencoderKLWan,+ scheduler: FlowMatchEulerDiscreteScheduler,+ dit: LongCatVideoAvatarTransformer3DModel,+ audio_encoder: Wav2Vec2ModelWrapper,+ wav2vec_feature_extractor: Wav2Vec2FeatureExtractor+ ):+ self.vae = vae+ self.text_encoder = text_encoder+ self.tokenizer = tokenizer+ self.scheduler = scheduler+ self.dit = dit+ self.device = "cuda"++ self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4+ self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)+ self.video_processor.preprocess_video = preprocess_video++ self._num_timesteps = 1000+ self._num_distill_sample_steps = 50++ self.audio_encoder=audio_encoder+ self.wav2vec_feature_extractor = wav2vec_feature_extractor++ def _get_t5_prompt_embeds(+ self,+ prompt: Union[str, List[str]] = None,+ num_videos_per_prompt: int = 1,+ max_sequence_length: int = 512,+ device: Optional[torch.device] = None,+ dtype: Optional[torch.dtype] = None,+ ):+ dtype = dtype or self.text_encoder.dtype++ prompt = [prompt] if isinstance(prompt, str) else prompt+ prompt = [prompt_clean(u) for u in 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_attention_mask=True,+ return_tensors="pt",+ )+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask++ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)+ mask = mask.to(device=device)+ mask = torch.cat([mask]*num_videos_per_prompt, dim=0)++ # 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, 1, seq_len, -1)++ return prompt_embeds, mask++ 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,+ max_sequence_length: int = 512,+ 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+ 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+ """++ prompt = [prompt] if isinstance(prompt, str) else prompt+ batch_size = len(prompt)++ prompt_embeds, prompt_attention_mask = 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:+ 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)}."+ )++ negative_prompt_embeds, negative_prompt_attention_mask = 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,+ )+ else:+ negative_prompt_embeds = None+ negative_prompt_attention_mask = None++ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask++ def check_inputs(+ self,+ prompt,+ negative_prompt,+ height,+ width,+ scale_factor_spatial+ ):+ # Check height and width divisibility+ if height % scale_factor_spatial != 0 or width % scale_factor_spatial != 0:+ raise ValueError(f"`height and width` have to be divisible by {scale_factor_spatial} but are {height} and {width}.")++ # Check prompt validity+ if prompt is None:+ raise ValueError("Cannot leave `prompt` undefined.")++ if 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)}")++ # Check negative prompt validity+ if negative_prompt is not None and (not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)):+ raise ValueError(f"`negative_prompt has to be of type str or list` but is {type(negative_prompt)}")++ def prepare_latents(+ self,+ image: Optional[torch.Tensor] = None,+ video: Optional[torch.Tensor] = None,+ batch_size: int = 1,+ num_channels_latents: int = 16,+ height: int = 480,+ width: int = 832,+ num_frames: int = 93,+ num_cond_frames: int = 0,+ dtype: Optional[torch.dtype] = None,+ device: Optional[torch.device] = None,+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,+ latents: Optional[torch.Tensor] = None,+ num_cond_frames_added: int = 0,+ need_encode: bool = True+ ) -> torch.Tensor:+ if (image is not None) and (video is not None):+ raise ValueError("Cannot provide both `image and video` at the same time. Please provide only one.")+ if latents is not None:+ latents = latents.to(device=device, dtype=dtype)+ else:+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1+ shape = (+ batch_size,+ num_channels_latents,+ num_latent_frames,+ int(height) // self.vae_scale_factor_spatial,+ int(width) // self.vae_scale_factor_spatial,+ )+ 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."+ )++ # Generate random noise with shape latent_shape+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)++ if image is not None or video is not None:+ if isinstance(generator, list):+ if 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."+ )+ condition_data = image if image is not None else video+ num_cond_latents = 1 + (num_cond_frames - 1) // self.vae_scale_factor_temporal++ if need_encode:+ is_image = image is not None+ cond_latents = []+ for i in range(batch_size):+ gen = generator[i] if isinstance(generator, list) else generator+ if is_image:+ encoded_input = condition_data[i].unsqueeze(0).unsqueeze(2)+ else:+ encoded_input = condition_data[i][:, -(num_cond_frames-num_cond_frames_added):].unsqueeze(0)+ if num_cond_frames_added > 0:+ pad_front = encoded_input[:, :, 0:1].repeat(1, 1, num_cond_frames_added, 1, 1)+ encoded_input = torch.cat([pad_front, encoded_input], dim=2)+ assert encoded_input.shape[2] == num_cond_frames+ latent = retrieve_latents(self.vae.encode(encoded_input), gen, sample_mode="argmax")+ cond_latents.append(latent)++ cond_latents = torch.cat(cond_latents, dim=0).to(dtype)+ cond_latents = self.normalize_latents(cond_latents)+ else:+ cond_latents = condition_data[:, :, -num_cond_latents:]++ latents[:, :, :num_cond_latents] = cond_latents++ return latents++ @property+ def text_guidance_scale(self):+ return self._text_guidance_scale++ @property+ def audio_guidance_scale(self):+ return self._audio_guidance_scale++ @property+ def do_classifier_free_guidance(self):+ return self._text_guidance_scale > 1.0 or self._audio_guidance_scale > 1.0++ @property+ def num_timesteps(self):+ return self._num_timesteps++ @property+ def num_distill_sample_steps(self):+ return self._num_distill_sample_steps++ @property+ def current_timestep(self):+ return self._current_timestep++ @property+ def interrupt(self):+ return self._interrupt++ @property+ def attention_kwargs(self):+ return self._attention_kwargs++ def get_timesteps_sigmas(self, sampling_steps: int, use_distill: bool=False):+ if use_distill:+ distill_indices = torch.arange(1, self.num_distill_sample_steps + 1, dtype=torch.float32)+ distill_indices = (distill_indices * (self.num_timesteps // self.num_distill_sample_steps)).round().long()++ inference_indices = np.linspace(0, self.num_distill_sample_steps, num=sampling_steps, endpoint=False)+ inference_indices = np.floor(inference_indices).astype(np.int64)++ sigmas = torch.flip(distill_indices, [0])[inference_indices].float() / self.num_timesteps+ else:+ sigmas = torch.linspace(1, 0.001, sampling_steps)+ sigmas = sigmas.to(torch.float32)+ return sigmas++ def _update_kv_cache_dict(self, kv_cache_dict):+ self.kv_cache_dict = kv_cache_dict++ def _cache_clean_latents(self, cond_latents, model_max_length, offload_kv_cache, device, dtype, audio_embs, num_cond_latents, num_ref_latents, ref_img_index):+ timestep = torch.zeros(cond_latents.shape[0], cond_latents.shape[2]).to(device=device, dtype=dtype)+ # make null prompt tensor(skip_crs_attn=True, so tensors below will not be actually used)+ empty_embeds = torch.zeros([cond_latents.shape[0], 1, model_max_length, self.text_encoder.config.d_model], device=device, dtype=dtype)+ _, kv_cache_dict = self.dit(+ hidden_states=cond_latents,+ timestep=timestep,+ encoder_hidden_states=empty_embeds,+ num_cond_latents=num_cond_latents,+ return_kv=True,+ skip_crs_attn=True,+ offload_kv_cache=offload_kv_cache,+ audio_embs=audio_embs,+ num_ref_latents=num_ref_latents,+ ref_img_index=ref_img_index+ )+ self._update_kv_cache_dict(kv_cache_dict)++ def _get_kv_cache_dict(self):+ return self.kv_cache_dict++ def _clear_cache(self):+ self.kv_cache_dict = None+ gc.collect()+ torch.cuda.empty_cache()++ def get_condition_shape(self, condition, resolution, scale_factor_spatial=32):+ bucket_config = get_bucket_config(resolution, scale_factor_spatial=scale_factor_spatial)++ obj = condition[0] if isinstance(condition, list) and condition else condition+ try:+ height = getattr(obj, "height")+ width = getattr(obj, "width")+ except AttributeError:+ raise ValueError("Unsupported condition type")++ ratio = height / width+ # Find the closest bucket+ closest_bucket = sorted(list(bucket_config.keys()), key=lambda x: abs(float(x) - ratio))[0]+ target_h, target_w = bucket_config[closest_bucket][0]+ return target_h, target_w++ def optimized_scale(self, positive_flat, negative_flat):+ """ from CFG-zero paper+ """+ # Calculate dot production+ dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)+ # Squared norm of uncondition+ squared_norm = torch.sum(negative_flat ** 2, dim=1, keepdim=True) + 1e-8+ # st_star = v_condˆT * v_uncond / ||v_uncond||ˆ2+ st_star = dot_product / squared_norm+ return st_star++ def normalize_latents(self, latents):+ latents_mean = (+ torch.tensor(self.vae.config.latents_mean)+ .view(1, self.vae.config.z_dim, 1, 1, 1)+ .to(latents.device, latents.dtype)+ )+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(+ latents.device, latents.dtype+ )+ return (latents - latents_mean) * latents_std++ def denormalize_latents(self, latents):+ latents_mean = (+ torch.tensor(self.vae.config.latents_mean)+ .view(1, self.vae.config.z_dim, 1, 1, 1)+ .to(latents.device, latents.dtype)+ )+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(+ latents.device, latents.dtype+ )+ return latents / latents_std + latents_mean++ def _loudness_norm(self, audio_array, sr=16000, lufs=-23, threshold=100):+ meter = pyln.Meter(sr)+ loudness = meter.integrated_loudness(audio_array)+ if abs(loudness) > threshold:+ return audio_array+ normalized_audio = pyln.normalize.loudness(audio_array, loudness, lufs)+ return normalized_audio++ def _add_noise_floor(self, audio, noise_db=-45):+ noise_amp = 10 ** (noise_db / 20)+ noise = np.random.randn(len(audio)) * noise_amp+ return audio + noise++ def _smooth_transients(self, audio, sr=16000):+ b, a = ss.butter(3, 3000 / (sr/2))+ return ss.lfilter(b, a, audio)++ def _resize_and_centercrop_tensor(self, mask: torch.Tensor, target_h: int, target_w: int, resize_mode: str = 'crop'):+ """+ mask: Tensor, shape [3, H, W], dtype=float, device=gpu/cpu+ return: [3, target_h, target_w]+ """++ if resize_mode == 'default':+ mask_resized = F.interpolate(+ mask.unsqueeze(0), # [1, 3, H, W]+ size=(new_h, new_w),+ mode="bilinear",+ align_corners=False+ ).squeeze(0)+ return mask_resized++ elif resize_mode == 'crop':+ _, H, W = mask.shape+ ratio = target_w / target_h # 1+ src_ratio = W / H # > 1++ if ratio > src_ratio:+ new_w = target_w+ new_h = int(H * target_w / W)+ else:+ new_h = target_h+ new_w = int(W * target_h / H)++ mask_resized = F.interpolate(+ mask.unsqueeze(0), # [1, 3, H, W]+ size=(new_h, new_w),+ mode="bilinear",+ align_corners=False+ ).squeeze(0)++ top = (new_h - target_h) // 2+ left = (new_w - target_w) // 2++ mask_resized_cropped = mask_resized[:, top:top + target_h, left:left + target_w]+ return mask_resized_cropped++ else:+ raise NotImplementedError(f"Not supported resize_mode {resize_mode}")++ @torch.no_grad()+ def get_audio_embedding(self, speech_array, fps=32, device='cpu', sample_rate=16000):++ audio_duration = len(speech_array) / sample_rate+ video_length = audio_duration * fps++ # speech preprocess+ speech_array = self._loudness_norm(speech_array, sample_rate)+ speech_array = self._add_noise_floor(speech_array)+ speech_array = self._smooth_transients(speech_array)++ # wav2vec_feature_extractor+ audio_feature = np.squeeze(+ self.wav2vec_feature_extractor(speech_array, sampling_rate=sample_rate).input_values+ )+ audio_feature = torch.from_numpy(audio_feature).float().to(device=device)+ audio_feature = audio_feature.unsqueeze(0)++ # audio embedding+ embeddings = self.audio_encoder(audio_feature, seq_len=int(video_length), output_hidden_states=True)++ audio_emb = torch.stack(embeddings.hidden_states[1:], dim=1).squeeze(0)+ audio_emb = rearrange(audio_emb, "b s d -> s b d").contiguous() # T, 12, 768+ return audio_emb++ @torch.no_grad()+ def generate_at2v(+ self,+ prompt: Union[str, List[str]] = None,+ negative_prompt: Union[str, List[str]] = None,+ height: int = 480,+ width: int = 832,+ num_frames: int = 93,+ num_inference_steps: int = 50,+ use_distill: bool = False,+ text_guidance_scale: float = 4.0,+ audio_guidance_scale: float = 4.0,+ num_videos_per_prompt: Optional[int] = 1,+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,+ latents: Optional[torch.Tensor] = None,+ output_type: Optional[str] = "np",+ attention_kwargs: Optional[Dict[str, Any]] = None,+ max_sequence_length: int = 512,+ # avatar related params+ audio_emb: torch.Tensor = None+ ):+ r"""+ Generates video frames from text prompt using diffusion process.++ Args:+ prompt (`str or List[str]`):+ Text prompt(s) for video content generation.+ negative_prompt (`str or List[str]`, *optional*):+ Negative prompt(s) for content exclusion. If not provided, uses empty string.+ height (`int`, *optional*, defaults to 480):+ Height of each video frame. Must be divisible by 16.+ width (`int`, *optional*, defaults to 832):+ Width of each video frame. Must be divisible by 16.+ num_frames (`int`, *optional*, defaults to 93):+ Number of frames to generate for the video. Should satisfy (num_frames - 1) % vae_scale_factor_temporal == 0.+ num_inference_steps (`int`, *optional*, defaults to 50):+ Number of diffusion sampling steps. Higher values improve quality but slow generation.+ use_distill (`bool`, *optional*, defaults to False):+ Whether to use distillation sampling schedule.+ text_guidance_scale (`float`, *optional*, defaults to 4.0):+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.+ audio_guidance_scale (`float`, *optional*, defaults to 4.0):+ Classifier-free guidance scale. Controls audio adherence. Larger values may lead to exaggerated mouth.+ num_videos_per_prompt (`int`, *optional*, defaults to 1):+ Number of videos to generate per prompt.+ generator (`torch.Generator or List[torch.Generator]`, *optional*):+ Random seed generator(s) for noise generation.+ latents (`torch.Tensor`, *optional*):+ Precomputed latent tensor. If not provided, random latents are generated.+ output_type (`str`, *optional*, defaults to "np"):+ Output format type. "np" for numpy array, "latent" for latent tensor.+ attention_kwargs (`Dict[str, Any]`, *optional*):+ Additional attention parameters for the model.+ max_sequence_length (`int`, *optional*, defaults to 512):+ Maximum sequence length for text encoding.+ audio_emb (`torch.Tensor`):+ Audio embedding to driven the lip movements and body motions of character.++ Returns:+ np.ndarray or torch.Tensor:+ Generated video frames. If output_type is "np", returns numpy array of shape (B, N, H, W, C).+ If output_type is "latent", returns latent tensor.+ """++ # 1. Check inputs. Raise error if not correct+ scale_factor_spatial = self.vae_scale_factor_spatial * 2+ if self.dit.cp_split_hw is not None:+ scale_factor_spatial *= max(self.dit.cp_split_hw)+ self.check_inputs(+ prompt,+ negative_prompt,+ height,+ width,+ scale_factor_spatial+ )++ if num_frames % self.vae_scale_factor_temporal != 1:+ loguru.logger.warning(+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."+ )+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1+ num_frames = max(num_frames, 1)++ self._text_guidance_scale = text_guidance_scale+ self._audio_guidance_scale = audio_guidance_scale+ self._attention_kwargs = attention_kwargs+ self._current_timestep = None+ self._interrupt = False++ device = self.device++ # 2. Define call parameters+ if isinstance(prompt, str):+ batch_size = 1+ else:+ batch_size = len(prompt)+++ # 3. Encode inputs+ dit_dtype = self.dit.dtype++ if context_parallel_util.get_cp_rank() == 0:+ (+ prompt_embeds,+ prompt_attention_mask,+ negative_prompt_embeds,+ negative_prompt_attention_mask,+ ) = self.encode_prompt(+ prompt=prompt,+ negative_prompt=negative_prompt,+ do_classifier_free_guidance=self.do_classifier_free_guidance,+ num_videos_per_prompt=num_videos_per_prompt,+ max_sequence_length=max_sequence_length,+ dtype=dit_dtype,+ device=device,+ )+ if context_parallel_util.get_cp_size() > 1:+ context_parallel_util.cp_broadcast(prompt_embeds)+ context_parallel_util.cp_broadcast(prompt_attention_mask)+ if self.do_classifier_free_guidance:+ context_parallel_util.cp_broadcast(negative_prompt_embeds)+ context_parallel_util.cp_broadcast(negative_prompt_attention_mask)+ elif context_parallel_util.get_cp_size() > 1:+ caption_channels = self.text_encoder.config.d_model+ prompt_embeds = torch.zeros([batch_size, 1, max_sequence_length, caption_channels], dtype=dit_dtype, device=device)+ prompt_attention_mask = torch.zeros([batch_size, max_sequence_length], dtype=torch.int64, device=device)+ context_parallel_util.cp_broadcast(prompt_embeds)+ context_parallel_util.cp_broadcast(prompt_attention_mask)+ if self.do_classifier_free_guidance:+ negative_prompt_embeds = torch.zeros([batch_size, 1, max_sequence_length, caption_channels], dtype=dit_dtype, device=device)+ negative_prompt_attention_mask = torch.zeros([batch_size, max_sequence_length], dtype=torch.int64, device=device)+ context_parallel_util.cp_broadcast(negative_prompt_embeds)+ context_parallel_util.cp_broadcast(negative_prompt_attention_mask)++ audio_cond_embs = torch.cat([audio_emb] * num_videos_per_prompt, dim=0)+ if self.do_classifier_free_guidance:+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)+ audio_unond_embs = torch.zeros_like(audio_cond_embs)+ audio_cond_embs = torch.cat([audio_cond_embs, audio_cond_embs], dim=0)++ # 4. Prepare timesteps+ sigmas = self.get_timesteps_sigmas(num_inference_steps, use_distill=use_distill)+ self.scheduler.set_timesteps(num_inference_steps, sigmas=sigmas, device=device)+ timesteps = self.scheduler.timesteps++ # 5. Prepare latent variables+ num_channels_latents = self.dit.config.in_channels++ latents = self.prepare_latents(+ batch_size=batch_size * num_videos_per_prompt,+ num_channels_latents=num_channels_latents,+ height=height,+ width=width,+ num_frames=num_frames,+ dtype=torch.float32,+ device=device,+ generator=generator,+ latents=latents,+ )+ if context_parallel_util.get_cp_size() > 1:+ context_parallel_util.cp_broadcast(latents)++ # 6. Denoising loop+ if context_parallel_util.get_cp_size() > 1:+ torch.distributed.barrier(group=context_parallel_util.get_cp_group())++ with tqdm(total=len(timesteps), desc="Denoising") as progress_bar:+ for i, t in enumerate(timesteps):+ if self.interrupt:+ continue++ self._current_timestep = t++ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents+ latent_model_input = latent_model_input.to(dit_dtype)++ timestep = t.expand(latent_model_input.shape[0]).to(dit_dtype)++ noise_pred = self.dit(+ hidden_states=latent_model_input,+ timestep=timestep,+ encoder_hidden_states=prompt_embeds,+ encoder_attention_mask=prompt_attention_mask,+ audio_embs=audio_cond_embs+ )++ if self.do_classifier_free_guidance:+ timestep_uncond = t.expand(latents.shape[0]).to(dit_dtype)+ noise_pred_uncond = self.dit(+ hidden_states=latents,+ timestep=timestep_uncond,+ encoder_hidden_states=negative_prompt_embeds,+ encoder_attention_mask=negative_prompt_attention_mask,+ audio_embs=audio_unond_embs+ )++ noise_pred_uncond_text, noise_pred_cond = noise_pred.chunk(2)++ noise_pred = noise_pred_uncond + text_guidance_scale * (noise_pred_cond - noise_pred_uncond_text) + audio_guidance_scale * (noise_pred_uncond_text - noise_pred_uncond)++ # negate for scheduler compatibility+ noise_pred = -noise_pred++ # compute the previous noisy sample x_t -> x_t-1+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]++ # call the callback, if provided+ if i == len(timesteps) - 1 or (i + 1) % self.scheduler.order == 0:+ progress_bar.update()++ self._current_timestep = None++ if output_type == 'latent':+ return latents++ if output_type == 'both':+ latents_ = latents.clone()++ latents = latents.to(self.vae.dtype)+ latents = self.denormalize_latents(latents)+ output_video = self.vae.decode(latents, return_dict=False)[0]+ output_video = self.video_processor.postprocess_video(output_video)++ if output_type == 'both':+ return (output_video, latents_)+ else:+ return output_video+++ @torch.no_grad()+ def generate_ai2v(+ self,+ image: PipelineImageInput,+ prompt: Union[str, List[str]] = None,+ negative_prompt: Union[str, List[str]] = None,+ resolution: Literal["480p", "720p"] = "480p",+ num_frames: int = 93,+ num_inference_steps: int = 50,+ use_distill: bool = False,+ text_guidance_scale: float = 4.0,+ audio_guidance_scale: float = 4.0,+ num_videos_per_prompt: Optional[int] = 1,+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,+ latents: Optional[torch.Tensor] = None,+ output_type: Optional[str] = "np",+ attention_kwargs: Optional[Dict[str, Any]] = None,+ max_sequence_length: int = 512,+ # avatar related params+ audio_emb: torch.Tensor = None,+ ref_target_masks: torch.Tensor = None,+ resize_mode: Optional[str] = "crop", # "default" / "crop"+ ):+ r"""+ Generates video frames from an input image and text prompt using diffusion process.++ Args:+ image (`PipelineImageInput`):+ Input image for video generation.+ prompt (`str or List[str]`, *optional*):+ Text prompt(s) for video content generation.+ negative_prompt (`str or List[str]`, *optional*):+ Negative prompt(s) for content exclusion. If not provided, uses empty string.+ resolution (`Literal["480p", "720p"]`, *optional*, defaults to "480p"):+ Target video resolution. Determines output frame size.+ num_frames (`int`, *optional*, defaults to 93):+ Number of frames to generate for the video. Should satisfy (num_frames - 1) % vae_scale_factor_temporal == 0.+ num_inference_steps (`int`, *optional*, defaults to 50):+ Number of diffusion sampling steps. Higher values improve quality but slow generation.+ use_distill (`bool`, *optional*, defaults to False):+ Whether to use distillation sampling schedule.+ text_guidance_scale (`float`, *optional*, defaults to 4.0):+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.+ audio_guidance_scale (`float`, *optional*, defaults to 4.0):+ Classifier-free guidance scale. Controls audio adherence. Larger values may lead to exaggerated mouth.+ num_videos_per_prompt (`int`, *optional*, defaults to 1):+ Number of videos to generate per prompt.+ generator (`torch.Generator or List[torch.Generator]`, *optional*):+ Random seed generator(s) for noise generation.+ latents (`torch.Tensor`, *optional*):+ Precomputed latent tensor. If not provided, random latents are generated.+ output_type (`str`, *optional*, defaults to "np"):+ Output format type. "np" for numpy array, "latent" for latent tensor.+ attention_kwargs (`Dict[str, Any]`, *optional*):+ Additional attention parameters for the model.+ max_sequence_length (`int`, *optional*, defaults to 512):+ Maximum sequence length for text encoding.+ audio_emb (`torch.Tensor`):+ Audio embedding to driven the lip movements and body motions of character.+ ref_target_masks(`torch.Tensor`, *optional*, defaults to None):+ Mask used in dual-speaker audio-driven mode.+ resize_mode(`str`, *optional*):+ Output format type. "default" for resize, "crop" for shorter-length resize and centercrop.++ Returns:+ np.ndarray or torch.Tensor:+ Generated video frames. If output_type is "np", returns numpy array of shape (B, N, H, W, C).+ If output_type is "latent", returns latent tensor.+ """++ # 1. Check inputs. Raise error if not correct+ scale_factor_spatial = self.vae_scale_factor_spatial * 2+ if self.dit.cp_split_hw is not None:+ scale_factor_spatial *= max(self.dit.cp_split_hw)+ height, width = self.get_condition_shape(image, resolution, scale_factor_spatial=scale_factor_spatial)+ self.check_inputs(+ prompt,+ negative_prompt,+ height,+ width,+ scale_factor_spatial+ )+ assert resize_mode in ['default', 'crop'], f"Unsupported resize_mode {resize_mode}, and you can only choose from [default, crop]"++ if num_frames % self.vae_scale_factor_temporal != 1:+ loguru.logger.warning(+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."+ )+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1+ num_frames = max(num_frames, 1)+++ self._text_guidance_scale = text_guidance_scale+ self._audio_guidance_scale = audio_guidance_scale+ self._attention_kwargs = attention_kwargs+ self._current_timestep = None+ self._interrupt = False++ device = self.device++ # 2. Define call parameters+ if isinstance(prompt, str):+ batch_size = 1+ else:+ batch_size = len(prompt)+++ # 3. Encode inputs+ dit_dtype = self.dit.dtype++ if context_parallel_util.get_cp_rank() == 0:+ (+ prompt_embeds,+ prompt_attention_mask,+ negative_prompt_embeds,+ negative_prompt_attention_mask,+ ) = self.encode_prompt(+ prompt=prompt,+ negative_prompt=negative_prompt,+ do_classifier_free_guidance=self.do_classifier_free_guidance,+ num_videos_per_prompt=num_videos_per_prompt,+ max_sequence_length=max_sequence_length,+ dtype=dit_dtype,+ device=device,+ )+ if context_parallel_util.get_cp_size() > 1:+ context_parallel_util.cp_broadcast(prompt_embeds)+ context_parallel_util.cp_broadcast(prompt_attention_mask)+ if self.do_classifier_free_guidance:+ context_parallel_util.cp_broadcast(negative_prompt_embeds)+ context_parallel_util.cp_broadcast(negative_prompt_attention_mask)+ elif context_parallel_util.get_cp_size() > 1:+ caption_channels = self.text_encoder.config.d_model+ prompt_embeds = torch.zeros([batch_size, 1, max_sequence_length, caption_channels], dtype=dit_dtype, device=device)+ prompt_attention_mask = torch.zeros([batch_size, max_sequence_length], dtype=torch.int64, device=device)+ context_parallel_util.cp_broadcast(prompt_embeds)+ context_parallel_util.cp_broadcast(prompt_attention_mask)+ if self.do_classifier_free_guidance:+ negative_prompt_embeds = torch.zeros([batch_size, 1, max_sequence_length, caption_channels], dtype=dit_dtype, device=device)+ negative_prompt_attention_mask = torch.zeros([batch_size, max_sequence_length], dtype=torch.int64, device=device)+ context_parallel_util.cp_broadcast(negative_prompt_embeds)+ context_parallel_util.cp_broadcast(negative_prompt_attention_mask)++ audio_cond_embs = torch.cat([audio_emb] * num_videos_per_prompt, dim=0)+ if self.do_classifier_free_guidance:+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)+ audio_unond_embs = torch.zeros_like(audio_cond_embs)+ audio_cond_embs = torch.cat([audio_cond_embs, audio_cond_embs], dim=0)++ # 4. Prepare timesteps+ sigmas = self.get_timesteps_sigmas(num_inference_steps, use_distill=use_distill)+ self.scheduler.set_timesteps(num_inference_steps, sigmas=sigmas, device=device)+ timesteps = self.scheduler.timesteps++ # 5. Prepare latent variables+ image = self.video_processor.preprocess(image, height=height, width=width, resize_mode=resize_mode)+ image = image.to(device=device, dtype=prompt_embeds.dtype)++ num_channels_latents = self.dit.config.in_channels++ latents = self.prepare_latents(+ image=image,+ batch_size=batch_size * num_videos_per_prompt,+ num_channels_latents=num_channels_latents,+ height=height,+ width=width,+ num_frames=num_frames,+ num_cond_frames=1,+ dtype=torch.float32,+ device=device,+ generator=generator,+ latents=latents,+ )+ if context_parallel_util.get_cp_size() > 1:+ context_parallel_util.cp_broadcast(latents)++ # 6. Prepare ref_target_masks to latent size+ if ref_target_masks is not None:+ ref_target_masks = self._resize_and_centercrop_tensor(ref_target_masks, height, width, resize_mode)++ # 7. Denoising loop+ if context_parallel_util.get_cp_size() > 1:+ torch.distributed.barrier(group=context_parallel_util.get_cp_group())++ with tqdm(total=len(timesteps), desc="Denoising") as progress_bar:+ for i, t in enumerate(timesteps):+ if self.interrupt:+ continue++ self._current_timestep = t++ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents+ latent_model_input = latent_model_input.to(dit_dtype)++ timestep = t.expand(latent_model_input.shape[0]).to(dit_dtype)+ timestep = timestep.unsqueeze(-1).repeat(1, latent_model_input.shape[2])+ timestep[:, :1] = 0++ if self.do_classifier_free_guidance and ref_target_masks is not None:+ # Multitalk mode+ noise_pred_uncond_text = self.dit(+ hidden_states=latent_model_input[:1],+ timestep=timestep[:1],+ encoder_hidden_states=prompt_embeds[:1],+ encoder_attention_mask=prompt_attention_mask[:1],+ num_cond_latents=1,+ audio_embs=audio_cond_embs[:2],+ ref_target_masks=ref_target_masks+ )+ noise_pred_cond = self.dit(+ hidden_states=latent_model_input[1:],+ timestep=timestep[1:],+ encoder_hidden_states=prompt_embeds[1:],+ encoder_attention_mask=prompt_attention_mask[1:],+ num_cond_latents=1,+ audio_embs=audio_cond_embs[2:],+ ref_target_masks=ref_target_masks+ )+ noise_pred = torch.cat([noise_pred_uncond_text, noise_pred_cond])+ else:+ # Singletalk mode+ noise_pred = self.dit(+ hidden_states=latent_model_input,+ timestep=timestep,+ encoder_hidden_states=prompt_embeds,+ encoder_attention_mask=prompt_attention_mask,+ num_cond_latents=1,+ audio_embs=audio_cond_embs+ )++ if self.do_classifier_free_guidance:+ timestep_uncond = t.expand(latents.shape[0]).to(dit_dtype)+ timestep_uncond = timestep_uncond.unsqueeze(-1).repeat(1, latent_model_input.shape[2])+ timestep_uncond[:, :1] = 0++ noise_pred_uncond = self.dit(+ hidden_states=latents,+ timestep=timestep_uncond,+ encoder_hidden_states=negative_prompt_embeds,+ encoder_attention_mask=negative_prompt_attention_mask,+ num_cond_latents=1,+ audio_embs=audio_unond_embs,+ ref_target_masks=ref_target_masks+ )++ noise_pred_uncond_text, noise_pred_cond = noise_pred.chunk(2)++ noise_pred = noise_pred_uncond + text_guidance_scale * (noise_pred_cond - noise_pred_uncond_text) + audio_guidance_scale * (noise_pred_uncond_text - noise_pred_uncond)++ # negate for scheduler compatibility+ noise_pred = -noise_pred++ # compute the previous noisy sample x_t -> x_t-1+ latents[:, :, 1:] = self.scheduler.step(noise_pred[:, :, 1:], t, latents[:, :, 1:], return_dict=False)[0]++ # call the callback, if provided+ if i == len(timesteps) - 1 or (i + 1) % self.scheduler.order == 0:+ progress_bar.update()++ self._current_timestep = None++ if output_type == 'latent':+ return latents++ if output_type == 'both':+ latents_ = latents.clone()++ latents = latents.to(self.vae.dtype)+ latents = self.denormalize_latents(latents)+ output_video = self.vae.decode(latents, return_dict=False)[0]+ output_video = self.video_processor.postprocess_video(output_video)++ if output_type == 'both':+ return (output_video, latents_)+ else:+ return output_video+++ @torch.no_grad()+ def generate_avc(+ self,+ video: List[Image.Image],+ video_latent: torch.Tensor,+ prompt: Union[str, List[str]] = None,+ negative_prompt: Union[str, List[str]] = None,+ height: int = 480,+ width: int = 832,+ num_frames: int = 93,+ num_cond_frames: int = 13,+ num_inference_steps: int = 50,+ use_distill: bool = False,+ text_guidance_scale: float = 4.0,+ audio_guidance_scale: float = 4.0,+ num_videos_per_prompt: Optional[int] = 1,+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,+ latents: Optional[torch.Tensor] = None,+ output_type: Optional[str] = "np",+ attention_kwargs: Optional[Dict[str, Any]] = None,+ max_sequence_length: int = 512,+ use_kv_cache=True,+ offload_kv_cache=False,+ enhance_hf=True,+ # avatar related params+ audio_emb: torch.Tensor = None,+ ref_latent: torch.Tensor = None,+ ref_img_index: int = None,+ mask_frame_range: int = None,+ ref_target_masks: torch.Tensor = None,+ resize_mode: Optional[str] = "crop", # "default" / "crop"+ ):+ r"""+ Generates video frames from a source video and text prompt using diffusion process with spatio-temporal conditioning.++ Args:+ video (`List[Image.Image]`):+ Input video frames for conditioning.+ prompt (`str or List[str]`, *optional*):+ Text prompt(s) for video content generation.+ negative_prompt (`str or List[str]`, *optional*):+ Negative prompt(s) for content exclusion. If not provided, uses empty string.+ num_frames (`int`, *optional*, defaults to 93):+ Number of frames to generate for the video. Should satisfy (num_frames - 1) % vae_scale_factor_temporal == 0.+ num_cond_frames (`int`, *optional*, defaults to 13):+ Number of conditioning frames from the input video.+ num_inference_steps (`int`, *optional*, defaults to 50):+ Number of diffusion sampling steps. Higher values improve quality but slow generation.+ use_distill (`bool`, *optional*, defaults to False):+ Whether to use distillation sampling schedule.+ text_guidance_scale (`float`, *optional*, defaults to 4.0):+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.+ audio_guidance_scale (`float`, *optional*, defaults to 4.0):+ Classifier-free guidance scale. Controls audio adherence. Larger values may lead to exaggerated mouth.+ num_videos_per_prompt (`int`, *optional*, defaults to 1):+ Number of videos to generate per prompt.+ generator (`torch.Generator or List[torch.Generator]`, *optional*):+ Random seed generator(s) for noise generation.+ latents (`torch.Tensor`, *optional*):+ Precomputed latent tensor. If not provided, random latents are generated.+ output_type (`str`, *optional*, defaults to "np"):+ Output format type. "np" for numpy array, "latent" for latent tensor.+ attention_kwargs (`Dict[str, Any]`, *optional*):+ Additional attention parameters for the model.+ max_sequence_length (`int`, *optional*, defaults to 512):+ Maximum sequence length for text encoding.+ use_kv_cache (`bool`, *optional*, defaults to True):+ Whether to use key-value cache for faster inference.+ offload_kv_cache (`bool`, *optional*, defaults to False):+ Whether to offload key-value cache to CPU to save VRAM.+ enhance_hf (`bool`, *optional*, defaults to True):+ Whether to use enhanced high-frequency denoising schedule.+ audio_emb (`torch.Tensor`):+ Audio embedding to driven the lip movements and body motions of character.+ ref_latent (`torch.Tensor`):+ The latent of reference anchor image when generate long video.+ ref_img_index (`int`, *optional*, defaults to 10)+ The insertion position of the reference image relative to the noisy latent along the temporal dimension.+ mask_frame_range (`int`, *optional*, defaults to 0)+ The attention masking range for the reference image.+ ref_target_masks(`torch.Tensor`, *optional*, defaults to None):+ Mask used in dual-speaker audio-driven mode.+ resize_mode(`str`, *optional*):+ Output format type. "default" for resize, "crop" for shorter-length resize and centercrop.++ Returns:+ np.ndarray or torch.Tensor:+ Generated video frames. If output_type is "np", returns numpy array of shape (B, N, H, W, C).+ If output_type is "latent", returns latent tensor.+ """++ # 1. Check inputs. Raise error if not correct+ assert not (use_distill and enhance_hf), "use_distill and enhance_hf cannot both be True"+ scale_factor_spatial = self.vae_scale_factor_spatial * 2+ if self.dit.cp_split_hw is not None:+ scale_factor_spatial *= max(self.dit.cp_split_hw)++ self.check_inputs(+ prompt,+ negative_prompt,+ height,+ width,+ scale_factor_spatial+ )+ assert resize_mode in ['default', 'crop'], f"Unsupported resize_mode {resize_mode}, and you can choose from [default, crop]"++ if num_frames % self.vae_scale_factor_temporal != 1:+ loguru.logger.warning(+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."+ )+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1+ num_frames = max(num_frames, 1)++ self._text_guidance_scale = text_guidance_scale+ self._audio_guidance_scale = audio_guidance_scale+ self._attention_kwargs = attention_kwargs+ self._current_timestep = None+ self._interrupt = False++ device = self.device++ # 2. Define call parameters+ if isinstance(prompt, str):+ batch_size = 1+ else:+ batch_size = len(prompt)++ # 3. Encode inputs+ dit_dtype = self.dit.dtype++ if context_parallel_util.get_cp_rank() == 0:+ (+ prompt_embeds,+ prompt_attention_mask,+ negative_prompt_embeds,+ negative_prompt_attention_mask,+ ) = self.encode_prompt(+ prompt=prompt,+ negative_prompt=negative_prompt,+ do_classifier_free_guidance=self.do_classifier_free_guidance,+ num_videos_per_prompt=num_videos_per_prompt,+ max_sequence_length=max_sequence_length,+ dtype=dit_dtype,+ device=device,+ )+ if context_parallel_util.get_cp_size() > 1:+ context_parallel_util.cp_broadcast(prompt_embeds)+ context_parallel_util.cp_broadcast(prompt_attention_mask)+ if self.do_classifier_free_guidance:+ context_parallel_util.cp_broadcast(negative_prompt_embeds)+ context_parallel_util.cp_broadcast(negative_prompt_attention_mask)+ elif context_parallel_util.get_cp_size() > 1:+ caption_channels = self.text_encoder.config.d_model+ prompt_embeds = torch.zeros([batch_size, 1, max_sequence_length, caption_channels], dtype=dit_dtype, device=device)+ prompt_attention_mask = torch.zeros([batch_size, max_sequence_length], dtype=torch.int64, device=device)+ context_parallel_util.cp_broadcast(prompt_embeds)+ context_parallel_util.cp_broadcast(prompt_attention_mask)+ if self.do_classifier_free_guidance:+ negative_prompt_embeds = torch.zeros([batch_size, 1, max_sequence_length, caption_channels], dtype=dit_dtype, device=device)+ negative_prompt_attention_mask = torch.zeros([batch_size, max_sequence_length], dtype=torch.int64, device=device)+ context_parallel_util.cp_broadcast(negative_prompt_embeds)+ context_parallel_util.cp_broadcast(negative_prompt_attention_mask)++ audio_cond_embs = torch.cat([audio_emb] * num_videos_per_prompt, dim=0)+ if self.do_classifier_free_guidance:+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)+ audio_unond_embs = torch.zeros_like(audio_cond_embs)+ audio_cond_embs = torch.cat([audio_cond_embs, audio_cond_embs], dim=0)++ # 4. Prepare timesteps+ sigmas = self.get_timesteps_sigmas(num_inference_steps, use_distill=use_distill)+ self.scheduler.set_timesteps(num_inference_steps, sigmas=sigmas, device=device)+ timesteps = self.scheduler.timesteps++ if enhance_hf:+ tail_uniform_start = 500+ tail_uniform_end = 0+ num_tail_uniform_steps = 10+ timesteps_uniform_tail = list(np.linspace(tail_uniform_start, tail_uniform_end, num_tail_uniform_steps, dtype=np.float32, endpoint=(tail_uniform_end != 0)))+ timesteps_uniform_tail = [torch.tensor(t, device=device).unsqueeze(0) for t in timesteps_uniform_tail]+ filtered_timesteps = [timestep.unsqueeze(0) for timestep in timesteps if timestep > tail_uniform_start]+ timesteps = torch.cat(filtered_timesteps + timesteps_uniform_tail)+ self.scheduler.timesteps = timesteps+ self.scheduler.sigmas = torch.cat([timesteps / 1000, torch.zeros(1, device=timesteps.device)])++ # 5. Prepare latent variables+ video = self.video_processor.preprocess_video(self.video_processor, video, height=height, width=width, resize_mode=resize_mode)+ video = video.to(device=device, dtype=prompt_embeds.dtype)+ cond_videos = video[:, :, -num_cond_frames:]+ cond_videos_latents = retrieve_latents(self.vae.encode(cond_videos), generator, sample_mode="argmax")+ cond_videos_latents = self.normalize_latents(cond_videos_latents)+++ num_channels_latents = self.dit.config.in_channels+ latents = self.prepare_latents(+ video=video_latent,+ batch_size=batch_size * num_videos_per_prompt,+ num_channels_latents=num_channels_latents,+ height=height,+ width=width,+ num_frames=num_frames,+ num_cond_frames=num_cond_frames,+ dtype=dit_dtype,+ device=device,+ generator=generator,+ latents=latents,+ need_encode=False+ )+ if context_parallel_util.get_cp_size() > 1:+ context_parallel_util.cp_broadcast(latents)++ num_cond_latents = 1 + (num_cond_frames - 1) // self.vae_scale_factor_temporal++ # 6. Prepare ref_target_masks from source size to latent size+ if ref_target_masks is not None:+ ref_target_masks = self._resize_and_centercrop_tensor(ref_target_masks, height, width, resize_mode)++ # 7. Add reference image+ if ref_latent is not None:+ num_cond_latents += 1+ num_ref_latents = 1+ latents = torch.cat([ref_latent, latents], dim=2)++ # 8. Denoising loop+ if context_parallel_util.get_cp_size() > 1:+ torch.distributed.barrier(group=context_parallel_util.get_cp_group())++ if use_kv_cache:+ cond_latents = latents[:, :, :num_cond_latents]+ self._cache_clean_latents(cond_latents, max_sequence_length, offload_kv_cache=offload_kv_cache, device=self.device, dtype=dit_dtype, \+ audio_embs=audio_emb, num_cond_latents=num_cond_latents, num_ref_latents=num_ref_latents, ref_img_index=ref_img_index)+ kv_cache_dict = self._get_kv_cache_dict()+ latents = latents[:, :, num_cond_latents:]+ else:+ kv_cache_dict = {}++ with tqdm(total=len(timesteps), desc="Denoising") as progress_bar:+ for i, t in enumerate(timesteps):+ if self.interrupt:+ continue++ self._current_timestep = t++ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents+ latent_model_input = latent_model_input.to(dit_dtype)++ timestep = t.expand(latent_model_input.shape[0]).to(dit_dtype)+ timestep = timestep.unsqueeze(-1).repeat(1, latent_model_input.shape[2])+ if not use_kv_cache:+ timestep[:, :num_cond_latents] = 0++ if self.do_classifier_free_guidance and ref_target_masks is not None:+ # Multitalk mode+ noise_pred_uncond_text = self.dit(+ hidden_states=latent_model_input[:1],+ timestep=timestep[:1],+ encoder_hidden_states=prompt_embeds[:1],+ encoder_attention_mask=prompt_attention_mask[:1],+ num_cond_latents=num_cond_latents,+ kv_cache_dict=kv_cache_dict,+ audio_embs=audio_cond_embs[:2],+ num_ref_latents=num_ref_latents,+ ref_img_index=ref_img_index,+ mask_frame_range=mask_frame_range,+ ref_target_masks=ref_target_masks+ )+ noise_pred_cond = self.dit(+ hidden_states=latent_model_input[1:],+ timestep=timestep[1:],+ encoder_hidden_states=prompt_embeds[1:],+ encoder_attention_mask=prompt_attention_mask[1:],+ num_cond_latents=num_cond_latents,+ kv_cache_dict=kv_cache_dict,+ audio_embs=audio_cond_embs[2:],+ num_ref_latents=num_ref_latents,+ ref_img_index=ref_img_index,+ mask_frame_range=mask_frame_range,+ ref_target_masks=ref_target_masks+ )+ noise_pred = torch.cat([noise_pred_uncond_text, noise_pred_cond])+ else:+ # Singletalk mode+ noise_pred = self.dit(+ hidden_states=latent_model_input,+ timestep=timestep,+ encoder_hidden_states=prompt_embeds,+ encoder_attention_mask=prompt_attention_mask,+ num_cond_latents=num_cond_latents,+ kv_cache_dict=kv_cache_dict,+ audio_embs=audio_cond_embs,+ num_ref_latents=num_ref_latents,+ ref_img_index=ref_img_index,+ mask_frame_range=mask_frame_range+ )++ if self.do_classifier_free_guidance:+ timestep_uncond = t.expand(latents.shape[0]).to(dit_dtype)+ timestep_uncond = timestep_uncond.unsqueeze(-1).repeat(1, latent_model_input.shape[2])+ if not use_kv_cache:+ timestep_uncond[:, :num_cond_latents] = 0++ noise_pred_uncond = self.dit(+ hidden_states=latents,+ timestep=timestep_uncond,+ encoder_hidden_states=negative_prompt_embeds,+ encoder_attention_mask=negative_prompt_attention_mask,+ num_cond_latents=num_cond_latents,+ kv_cache_dict=kv_cache_dict,+ audio_embs=audio_unond_embs,+ num_ref_latents=num_ref_latents,+ ref_img_index=ref_img_index,+ mask_frame_range=mask_frame_range,+ ref_target_masks=ref_target_masks+ )++ noise_pred_uncond_text, noise_pred_cond = noise_pred.chunk(2)++ noise_pred = noise_pred_uncond + text_guidance_scale * (noise_pred_cond - noise_pred_uncond_text) + audio_guidance_scale * (noise_pred_uncond_text - noise_pred_uncond)++ # negate for scheduler compatibility+ noise_pred = -noise_pred++ # compute the previous noisy sample x_t -> x_t-1+ if use_kv_cache:+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]+ else:+ latents[:, :, num_cond_latents:] = self.scheduler.step(noise_pred[:, :, num_cond_latents:], t, latents[:, :, num_cond_latents:], return_dict=False)[0]++ # call the callback, if provided+ if i == len(timesteps) - 1 or (i + 1) % self.scheduler.order == 0:+ progress_bar.update()++ if use_kv_cache:+ latents = torch.cat([cond_latents, latents], dim=2)++ if ref_latent is not None:+ latents = latents[:, :, num_ref_latents:]+ num_cond_latents -= 1++ latents[:, :, :num_cond_latents] = cond_videos_latents++ self._current_timestep = None++ if output_type == 'latent':+ return latents++ if output_type == 'both':+ latents_ = latents.clone()++ latents = latents.to(self.vae.dtype)+ latents = self.denormalize_latents(latents)+ output_video = self.vae.decode(latents, return_dict=False)[0]+ output_video = self.video_processor.postprocess_video(output_video)++ if output_type == 'both':+ return (output_video, latents_)+ else:+ return output_video+++++ def to(self, device: str | torch.device):+ """+ Move pipeline to specified device.++ Args:+ device: Target device string++ Returns:+ Self+ """+ self.device = device+ if self.dit is not None:+ self.dit = self.dit.to(device, non_blocking=True)+ if hasattr(self.dit, 'lora_dict') and self.dit.lora_dict:+ for lora_key, lora_network in self.dit.lora_dict.items():+ for lora in lora_network.loras:+ lora.to(device, non_blocking=True)+ if self.text_encoder is not None:+ self.text_encoder = self.text_encoder.to(device, non_blocking=True)+ if self.vae is not None:+ self.vae = self.vae.to(device, non_blocking=True)+ return self+\ No newline at end of filediff --git a/requirements_avatar.txt b/requirements_avatar.txtnew file mode 100644index 0000000..3833ff1--- /dev/null+++ b/requirements_avatar.txt@@ -0,0 +1,19 @@+scikit-learn==1.6.1+scikit-image==0.25.2+scipy==1.15.3+soundfile==0.13.1+soxr==0.5.0.post1+librosa==0.11.0+libsndfile1==0.0.1+sympy==1.13.1+audio-separator==0.30.2+pyloudnorm==0.1.1+nvidia-ml-py==13.580.65+tzdata==2025.2+onnx==1.18.0+onnxruntime==1.16.3+tritonserverclient==0.0.6+openai==1.75.0+numpy==1.26.4+cffi==2.0.0+chardet==5.2.0\ No newline at end of filediff --git a/run_demo_avatar_multi_audio_to_video.py b/run_demo_avatar_multi_audio_to_video.pynew file mode 100644index 0000000..2cf14d1--- /dev/null+++ b/run_demo_avatar_multi_audio_to_video.py@@ -0,0 +1,452 @@+import os+import json+import time+import math+import random+import argparse+import datetime+import PIL.Image+import numpy as np+from pathlib import Path++import torch+import torch.distributed as dist++from transformers import AutoTokenizer, UMT5EncoderModel+from diffusers.utils import load_image++from longcat_video.pipeline_longcat_video_avatar import LongCatVideoAvatarPipeline+from longcat_video.modules.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler+from longcat_video.modules.autoencoder_kl_wan import AutoencoderKLWan+from longcat_video.modules.avatar.longcat_video_dit_avatar import LongCatVideoAvatarTransformer3DModel+from longcat_video.context_parallel import context_parallel_util++# -------- avatar related --------+import librosa+import soundfile as sf+from longcat_video.audio_process.wav2vec2 import Wav2Vec2ModelWrapper+from longcat_video.audio_process.torch_utils import save_video_ffmpeg+from transformers import Wav2Vec2FeatureExtractor+from audio_separator.separator import Separator+++def torch_gc():+ torch.cuda.empty_cache()+ torch.cuda.ipc_collect()++def generate_random_uid():+ timestamp_part = str(int(time.time()))[-6:]+ random_part = str(random.randint(100000, 999999))+ uid = timestamp_part + random_part+ return uid++def extract_vocal_from_speech(source_path, target_path, vocal_separator, audio_output_dir_temp):+ if source_path is None:+ return None++ outputs = vocal_separator.separate(source_path)+ if len(outputs) <= 0:+ print("Audio separate failed. Using raw audio.")+ return None++ default_vocal_path = audio_output_dir_temp / "vocals" / outputs[0]+ default_vocal_path = default_vocal_path.resolve().as_posix()+ cmd = f"mv '{default_vocal_path}' '{target_path}'"+ os.system(cmd)+ return target_path++def audio_prepare_multi(left_temp_vocal_path, right_temp_vocal_path, generate_duration, left_raw_speech_path, right_raw_speech_path, sample_rate=16000, audio_type='para'):+ left_speech_array, right_speech_array = None, None+ if left_temp_vocal_path is not None:+ left_speech_array, sr = librosa.load(left_temp_vocal_path, sr=sample_rate)+ left_raw_speech_array, _ = librosa.load(left_raw_speech_path, sr=sample_rate)++ if right_temp_vocal_path is not None:+ right_speech_array, sr = librosa.load(right_temp_vocal_path, sr=sample_rate)+ right_raw_speech_array, _ = librosa.load(right_raw_speech_path, sr=sample_rate)++ if left_speech_array is None:+ left_speech_array = np.zeros_like(right_speech_array)+ left_raw_speech_array = np.zeros_like(right_raw_speech_array)++ if right_speech_array is None:+ right_speech_array = np.zeros_like(left_speech_array)+ right_raw_speech_array = np.zeros_like(left_raw_speech_array)++ if audio_type == 'add':+ left_speech_array_ext = np.concatenate([left_speech_array, np.zeros_like(right_speech_array)])+ right_speech_array_ext = np.concatenate([np.zeros_like(left_speech_array), right_speech_array])+ merge_raw_speech = np.concatenate([left_raw_speech_array, np.zeros_like(right_raw_speech_array)]) + \+ np.concatenate([np.zeros_like(left_raw_speech_array), right_raw_speech_array])+ elif audio_type == 'para':+ left_speech_array_ext = left_speech_array+ right_speech_array_ext = right_speech_array+ merge_raw_speech = left_raw_speech_array + right_raw_speech_array+ else:+ raise NotImplementedError(f"Unsupported audio_type of {audio_type}")++ assert len(left_speech_array_ext) == len(right_speech_array_ext), f"The two speech lengths should be equal"+++ source_duraion = len(left_speech_array_ext) / sr+ added_sample_nums = math.ceil((generate_duration - source_duraion) * sr)+ if added_sample_nums > 0:+ left_speech_array_ext = np.append(left_speech_array_ext, [0.]*added_sample_nums)+ right_speech_array_ext = np.append(right_speech_array_ext, [0.]*added_sample_nums)++ return left_speech_array_ext, right_speech_array_ext, merge_raw_speech+++def generate(args):++ # load parsed args+ input_json = args.input_json+ checkpoint_dir = args.checkpoint_dir+ context_parallel_size = args.context_parallel_size+ num_inference_steps = args.num_inference_steps+ text_guidance_scale = args.text_guidance_scale+ audio_guidance_scale = args.audio_guidance_scale+ resolution = args.resolution+ num_segments = max(1, args.num_segments)+ output_dir = args.output_dir++ # set up default inference params+ save_fps = 16+ num_frames = 93+ num_cond_frames = 13+ audio_stride = 2++ if resolution == '480p':+ height, width = 480, 832+ elif resolution == '720p':+ height, width = 768, 1280++ # case setup+ with open(input_json, 'r', encoding='utf-8') as f:+ input_data = json.load(f)+ prompt = input_data['prompt']+ negative_prompt = "Close-up, 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"+ left_raw_speech_path = input_data['cond_audio'].get('person1', None)+ right_raw_speech_path = input_data['cond_audio'].get('person2', None)+ assert left_raw_speech_path is not None or right_raw_speech_path is not None, f"At least one speech is required."+ left_person_bbox, right_person_bbox = None, None+ if 'bbox' in input_data:+ # bbox: [left_y_min, left_x_min, left_y_max, left_x_max]+ # x and y coordinates correspond to the width and height dimensions, respectively+ left_person_bbox = input_data['bbox'].get('person1', None)+ right_person_bbox = input_data['bbox'].get('person2', None)+ audio_type = 'para'+ if 'audio_type' in input_data:+ audio_type = input_data.get('audio_type', 'para')++ # prepare distributed environment+ rank = int(os.environ['RANK'])+ num_gpus = torch.cuda.device_count()+ local_rank = rank % num_gpus+ torch.cuda.set_device(local_rank)+ dist.init_process_group(backend="nccl", timeout=datetime.timedelta(seconds=3600*24))+ global_rank = dist.get_rank()+ num_processes = dist.get_world_size()++ # initialize context parallel+ context_parallel_util.init_context_parallel(context_parallel_size=context_parallel_size, global_rank=global_rank, world_size=num_processes)+ cp_rank = context_parallel_util.get_cp_rank()+ cp_size = context_parallel_util.get_cp_size()+ cp_split_hw = context_parallel_util.get_optimal_split(cp_size)++ # initialize models+ tokenizer = AutoTokenizer.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="tokenizer", torch_dtype=torch.bfloat16)+ text_encoder = UMT5EncoderModel.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="text_encoder", torch_dtype=torch.bfloat16)+ vae = AutoencoderKLWan.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="vae", torch_dtype=torch.bfloat16)+ scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="scheduler", torch_dtype=torch.bfloat16)+ dit = LongCatVideoAvatarTransformer3DModel.from_pretrained(checkpoint_dir, subfolder="avatar_multi", cp_split_hw=cp_split_hw, torch_dtype=torch.bfloat16)++ # initialize audio models+ wav2vec_path = os.path.join(checkpoint_dir, 'chinese-wav2vec2-base')+ audio_encoder = Wav2Vec2ModelWrapper(wav2vec_path).to(local_rank)+ audio_encoder.feature_extractor._freeze_parameters()++ wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(wav2vec_path, local_files_only=True)+ vocal_separator_path = os.path.join(checkpoint_dir, 'vocal_separator/Kim_Vocal_2.onnx')+ audio_output_dir_temp = f"./audio_temp_file"+ os.makedirs(audio_output_dir_temp, exist_ok=True)+ audio_output_dir_temp = Path(audio_output_dir_temp)+ audio_separator_model_path = os.path.dirname(vocal_separator_path)+ audio_separator_model_name = os.path.basename(vocal_separator_path)+ vocal_separator = Separator(+ output_dir=audio_output_dir_temp / "vocals",+ output_single_stem="vocals",+ model_file_dir=audio_separator_model_path,+ )+ vocal_separator.load_model(audio_separator_model_name)+++ # initialize pipeline+ pipe = LongCatVideoAvatarPipeline(+ tokenizer = tokenizer,+ text_encoder = text_encoder,+ vae = vae,+ scheduler = scheduler,+ dit = dit,+ audio_encoder=audio_encoder,+ wav2vec_feature_extractor=wav2vec_feature_extractor+ )+ pipe.to(local_rank)++ global_seed = 42+ seed = global_seed + global_rank++ generator = torch.Generator(device=local_rank)+ generator.manual_seed(seed)++ if cp_rank == 0:+ # extract vocal+ sr = 16000+ left_temp_vocal_path = extract_vocal_from_speech(left_raw_speech_path, f"/tmp/temp_speech_{generate_random_uid()}_{global_rank}_vocal.wav", vocal_separator, audio_output_dir_temp)+ right_temp_vocal_path = extract_vocal_from_speech(right_raw_speech_path, f"/tmp/temp_speech_{generate_random_uid()}_{global_rank}_vocal.wav", vocal_separator, audio_output_dir_temp)++ # prepare each vocal and synthesize the sum audio+ generate_duration = num_frames / save_fps + (num_segments-1) * (num_frames-num_cond_frames) / save_fps+ left_speech_array_ext, right_speech_array_ext, merge_speech = audio_prepare_multi(left_temp_vocal_path, right_temp_vocal_path, generate_duration, \+ left_raw_speech_path, right_raw_speech_path, sample_rate=sr, audio_type=audio_type)+ merge_speech_path = f"/tmp/temp_speech_{generate_random_uid()}_{global_rank}_merge.wav"+ sf.write(merge_speech_path, merge_speech, 16000)++ left_full_audio_emb = pipe.get_audio_embedding(left_speech_array_ext, fps=save_fps*audio_stride, device=local_rank, sample_rate=sr)+ right_full_audio_emb = pipe.get_audio_embedding(right_speech_array_ext, fps=save_fps*audio_stride, device=local_rank, sample_rate=sr)+ if torch.isnan(left_full_audio_emb).any() or torch.isnan(right_full_audio_emb).any():+ raise ValueError(f"broken audio embedding with nan values")++ assert left_full_audio_emb.shape == right_full_audio_emb.shape, f"Inconsistent audio embedding shape."++ if context_parallel_util.get_cp_size() > 1:+ full_audio_emb_shape_list = list(left_full_audio_emb.size())+ full_audio_emb_tensor_shape_list = torch.tensor(full_audio_emb_shape_list, dtype=torch.int64, device=left_full_audio_emb.device)+ context_parallel_util.cp_broadcast(full_audio_emb_tensor_shape_list)+ context_parallel_util.cp_broadcast(left_full_audio_emb)+ context_parallel_util.cp_broadcast(right_full_audio_emb)++ if left_temp_vocal_path is not None and os.path.exists(left_temp_vocal_path):+ os.remove(left_temp_vocal_path)+ if right_temp_vocal_path is not None and os.path.exists(right_temp_vocal_path):+ os.remove(right_temp_vocal_path)++ elif context_parallel_util.get_cp_size() > 1:+ full_audio_emb_tensor_shape_list = torch.zeros(3, dtype=torch.int64, device=local_rank)+ context_parallel_util.cp_broadcast(full_audio_emb_tensor_shape_list)+ full_audio_emb_shape_list = full_audio_emb_tensor_shape_list.tolist()+ left_full_audio_emb = torch.zeros(*full_audio_emb_shape_list, dtype=torch.float32, device=local_rank)+ context_parallel_util.cp_broadcast(left_full_audio_emb)+ right_full_audio_emb = torch.zeros(*full_audio_emb_shape_list, dtype=torch.float32, device=local_rank)+ context_parallel_util.cp_broadcast(right_full_audio_emb)+++ indices = torch.arange(2 * 2 + 1) - 2+ audio_start_idx = 0+ audio_end_idx = audio_start_idx + audio_stride * num_frames++ # get audio embedding for the first clip+ center_indices = torch.arange(audio_start_idx, audio_end_idx, audio_stride).unsqueeze(1) + indices.unsqueeze(0)+ center_indices = torch.clamp(center_indices, min=0, max=left_full_audio_emb.shape[0]-1)+ left_audio_emb = left_full_audio_emb[center_indices][None,...].to(local_rank)+ right_audio_emb = right_full_audio_emb[center_indices][None,...].to(local_rank)+ audio_embs = torch.cat([left_audio_emb, right_audio_emb])+++ # ==============================+ # ai2v (480P)+ # ==============================+ image_path = input_data['cond_image']+ image = load_image(image_path)+ (src_width, src_height) = image.size+++ # define human / background mask+ background_mask = torch.zeros([src_height, src_width])+ human_mask1 = torch.zeros([src_height, src_width])+ human_mask2 = torch.zeros([src_height, src_width])+ if left_person_bbox is None and right_person_bbox is None:+ face_scale = 0.1+ left_y_min, left_y_max = int(src_height * face_scale), int(src_height * (1 - face_scale))+ right_y_min, right_y_max = left_y_min, left_y_max+ src_width = src_width // 2+ left_x_min, left_x_max = int(src_width * face_scale), int(src_width * (1 - face_scale))+ right_x_min, right_x_max = int(src_width * face_scale + src_width), int(src_width * (1 - face_scale) + src_width)+ elif left_person_bbox is not None and right_person_bbox is not None:+ left_y_min, left_x_min, left_y_max, left_x_max = left_person_bbox+ right_y_min, right_x_min, right_y_max, right_x_max = right_person_bbox+ else:+ raise NotImplementedError(f"Not supported bbox type.")+ human_mask1[left_y_min:left_y_max, left_x_min:left_x_max] = 1+ human_mask2[right_y_min:right_y_max, right_x_min:right_x_max] = 1+ background_mask += human_mask1+ background_mask += human_mask2+ background_mask = torch.where(background_mask > 0, torch.tensor(0), torch.tensor(1))+ ref_target_masks = torch.stack([human_mask1, human_mask2, background_mask], dim=0).to(local_rank)++ # generate video+ output_tuple = pipe.generate_ai2v(+ image=image,+ prompt=prompt,+ negative_prompt=negative_prompt,+ resolution=resolution,+ num_frames=num_frames,+ num_inference_steps=num_inference_steps,+ text_guidance_scale=text_guidance_scale,+ audio_guidance_scale=audio_guidance_scale,+ output_type='both',+ generator=generator,+ audio_emb=audio_embs,+ ref_target_masks=ref_target_masks+ )+ output, latent = output_tuple+ output = output[0]+ video = [(output[i] * 255).astype(np.uint8) for i in range(output.shape[0])]+ video = [PIL.Image.fromarray(img) for img in video]++ if cp_rank == 0:+ output_tensor = torch.from_numpy(np.array(video))+ save_video_ffmpeg(output_tensor, os.path.join(output_dir, "ai2v_demo_1"), merge_speech_path, fps=save_fps, quality=5)+ del output+ torch_gc()++ if context_parallel_util.get_cp_size() > 1:+ torch.distributed.barrier(group=context_parallel_util.get_cp_group())++ # =========================================+ # long video generation (480P)+ # =========================================+ # load parsed long video args+ ref_img_index = args.ref_img_index+ mask_frame_range = args.mask_frame_range++ width, height = video[0].size+ current_video = video+ ref_latent = latent[:, :, :1].clone()+ all_generated_frames = video++ for segment_idx in range(1, num_segments):+ if local_rank == 0:+ print(f"Generating segment {segment_idx+1}/{num_segments}...")++ # prepare audio embedding for the next clip+ audio_start_idx = audio_start_idx + audio_stride * (num_frames - num_cond_frames)+ audio_end_idx = audio_start_idx + audio_stride * num_frames+ center_indices = torch.arange(audio_start_idx, audio_end_idx, audio_stride).unsqueeze(1) + indices.unsqueeze(0)+ center_indices = torch.clamp(center_indices, min=0, max=left_full_audio_emb.shape[0]-1)+ left_audio_emb = left_full_audio_emb[center_indices][None,...].to(local_rank)+ right_audio_emb = right_full_audio_emb[center_indices][None,...].to(local_rank)+ audio_embs = torch.cat([left_audio_emb, right_audio_emb])++ output_tuple = pipe.generate_avc(+ video=current_video,+ video_latent=latent,+ prompt=prompt,+ negative_prompt=negative_prompt,+ height=height,+ width=width,+ num_frames=num_frames,+ num_cond_frames=num_cond_frames,+ num_inference_steps=num_inference_steps,+ text_guidance_scale=text_guidance_scale,+ audio_guidance_scale=audio_guidance_scale,+ generator=generator,+ output_type='both',+ use_kv_cache=True,+ offload_kv_cache=False,+ enhance_hf=True,+ audio_emb=audio_embs,+ ref_latent=ref_latent,+ ref_img_index=ref_img_index,+ mask_frame_range=mask_frame_range,+ ref_target_masks=ref_target_masks+ )+ output, latent = output_tuple++ output = output[0]+ new_video = [(output[i] * 255).astype(np.uint8) for i in range(output.shape[0])]+ new_video = [PIL.Image.fromarray(img) for img in new_video]+ del output++ all_generated_frames.extend(new_video[num_cond_frames:])++ current_video = new_video++ if cp_rank == 0:+ output_tensor = torch.from_numpy(np.array(all_generated_frames))+ save_video_ffmpeg(output_tensor, os.path.join(output_dir, f"video_continue_{segment_idx+1}"), merge_speech_path, fps=save_fps, quality=5)+ del output_tensor++ if cp_rank == 0 and os.path.exists(merge_speech_path):+ os.remove(merge_speech_path)++++def _parse_args():+ parser = argparse.ArgumentParser()+ parser.add_argument(+ '--input_json',+ type=str,+ default='assets/avatar/multi_example_1.json',+ )+ parser.add_argument(+ '--output_dir',+ type=str,+ default='./outputs_avatar_multi'+ )+ parser.add_argument(+ '--resolution',+ type=str,+ default='480p',+ choices=['480p', '720p']+ )+ parser.add_argument(+ '--num_segments',+ type=int,+ default=1+ )+ parser.add_argument(+ '--num_inference_steps',+ type=int,+ default=50+ )+ parser.add_argument(+ '--ref_img_index',+ type=int,+ default=10+ )+ parser.add_argument(+ '--mask_frame_range',+ type=int,+ default=3+ )+ parser.add_argument(+ '--text_guidance_scale',+ type=float,+ default=4.0+ )+ parser.add_argument(+ '--audio_guidance_scale',+ type=float,+ default=4.0+ )++ parser.add_argument(+ "--context_parallel_size",+ type=int,+ default=1,+ )+ parser.add_argument(+ "--checkpoint_dir",+ type=str,+ default="./weights/LongCat-Video-Avatar",+ )++ args = parser.parse_args()++ return args+++if __name__ == "__main__":+ args = _parse_args()+ generate(args)\ No newline at end of filediff --git a/run_demo_avatar_single_audio_to_video.py b/run_demo_avatar_single_audio_to_video.pynew file mode 100644index 0000000..aec2f5f--- /dev/null+++ b/run_demo_avatar_single_audio_to_video.py@@ -0,0 +1,390 @@+import os+import json+import time+import math+import random+import argparse+import datetime+import PIL.Image+import numpy as np+from pathlib import Path++import torch+import torch.distributed as dist++from transformers import AutoTokenizer, UMT5EncoderModel+from diffusers.utils import load_image++from longcat_video.pipeline_longcat_video_avatar import LongCatVideoAvatarPipeline+from longcat_video.modules.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler+from longcat_video.modules.autoencoder_kl_wan import AutoencoderKLWan+from longcat_video.modules.avatar.longcat_video_dit_avatar import LongCatVideoAvatarTransformer3DModel+from longcat_video.context_parallel import context_parallel_util++# -------- avatar related --------+import librosa+from longcat_video.audio_process.wav2vec2 import Wav2Vec2ModelWrapper+from longcat_video.audio_process.torch_utils import save_video_ffmpeg+from transformers import Wav2Vec2FeatureExtractor+from audio_separator.separator import Separator+++def torch_gc():+ torch.cuda.empty_cache()+ torch.cuda.ipc_collect()++def generate_random_uid():+ timestamp_part = str(int(time.time()))[-6:]+ random_part = str(random.randint(100000, 999999))+ uid = timestamp_part + random_part+ return uid++def extract_vocal_from_speech(source_path, target_path, vocal_separator, audio_output_dir_temp):+ outputs = vocal_separator.separate(source_path)+ if len(outputs) <= 0:+ print("Audio separate failed. Using raw audio.")+ return None++ default_vocal_path = audio_output_dir_temp / "vocals" / outputs[0]+ default_vocal_path = default_vocal_path.resolve().as_posix()+ cmd = f"mv '{default_vocal_path}' '{target_path}'"+ os.system(cmd)+ return target_path++def generate(args):++ # load parsed args+ input_json = args.input_json+ checkpoint_dir = args.checkpoint_dir+ context_parallel_size = args.context_parallel_size+ stage_1 = args.stage_1+ num_inference_steps = args.num_inference_steps+ text_guidance_scale = args.text_guidance_scale+ audio_guidance_scale = args.audio_guidance_scale+ resolution = args.resolution+ num_segments = max(1, args.num_segments)+ output_dir = args.output_dir++ # set up default inference params+ save_fps = 16+ num_frames = 93+ num_cond_frames = 13+ audio_stride = 2++ if resolution == '480p':+ height, width = 480, 832+ elif resolution == '720p':+ height, width = 768, 1280++ # case setup+ with open(input_json, 'r', encoding='utf-8') as f:+ input_data = json.load(f)+ prompt = input_data['prompt']+ negative_prompt = "Close-up, 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"+ raw_speech_path = input_data['cond_audio']['person1']++ # prepare distributed environment+ rank = int(os.environ['RANK'])+ num_gpus = torch.cuda.device_count()+ local_rank = rank % num_gpus+ torch.cuda.set_device(local_rank)+ dist.init_process_group(backend="nccl", timeout=datetime.timedelta(seconds=3600*24))+ global_rank = dist.get_rank()+ num_processes = dist.get_world_size()++ # initialize context parallel+ context_parallel_util.init_context_parallel(context_parallel_size=context_parallel_size, global_rank=global_rank, world_size=num_processes)+ cp_rank = context_parallel_util.get_cp_rank()+ cp_size = context_parallel_util.get_cp_size()+ cp_split_hw = context_parallel_util.get_optimal_split(cp_size)++ # initialize models+ tokenizer = AutoTokenizer.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="tokenizer", torch_dtype=torch.bfloat16)+ text_encoder = UMT5EncoderModel.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="text_encoder", torch_dtype=torch.bfloat16)+ vae = AutoencoderKLWan.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="vae", torch_dtype=torch.bfloat16)+ scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(os.path.join(checkpoint_dir, '..', 'LongCat-Video'), subfolder="scheduler", torch_dtype=torch.bfloat16)+ dit = LongCatVideoAvatarTransformer3DModel.from_pretrained(checkpoint_dir, subfolder="avatar_single", cp_split_hw=cp_split_hw, torch_dtype=torch.bfloat16)++ # initialize audio models+ wav2vec_path = os.path.join(checkpoint_dir, 'chinese-wav2vec2-base')+ audio_encoder = Wav2Vec2ModelWrapper(wav2vec_path).to(local_rank)+ audio_encoder.feature_extractor._freeze_parameters()++ wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(wav2vec_path, local_files_only=True)+ vocal_separator_path = os.path.join(checkpoint_dir, 'vocal_separator/Kim_Vocal_2.onnx')+ audio_output_dir_temp = f"./audio_temp_file"+ os.makedirs(audio_output_dir_temp, exist_ok=True)+ audio_output_dir_temp = Path(audio_output_dir_temp)+ audio_separator_model_path = os.path.dirname(vocal_separator_path)+ audio_separator_model_name = os.path.basename(vocal_separator_path)+ vocal_separator = Separator(+ output_dir=audio_output_dir_temp / "vocals",+ output_single_stem="vocals",+ model_file_dir=audio_separator_model_path,+ )+ vocal_separator.load_model(audio_separator_model_name)+++ # initialize pipeline+ pipe = LongCatVideoAvatarPipeline(+ tokenizer = tokenizer,+ text_encoder = text_encoder,+ vae = vae,+ scheduler = scheduler,+ dit = dit,+ audio_encoder=audio_encoder,+ wav2vec_feature_extractor=wav2vec_feature_extractor+ )+ pipe.to(local_rank)++ global_seed = 42+ seed = global_seed + global_rank++ generator = torch.Generator(device=local_rank)+ generator.manual_seed(seed)++ if cp_rank == 0:+ # extract vocal+ temp_vocal_path = extract_vocal_from_speech(raw_speech_path, f"/tmp/temp_speech_{generate_random_uid()}_{global_rank}_vocal.wav", vocal_separator, audio_output_dir_temp)+ assert temp_vocal_path is not None and os.path.exists(temp_vocal_path), f"No vocal detected"++ # audio padding to target length+ generate_duration = num_frames / save_fps + (num_segments-1)*(num_frames-num_cond_frames) / save_fps+ speech_array, sr = librosa.load(temp_vocal_path, sr=16000)+ source_duraion = len(speech_array) / sr+ added_sample_nums = math.ceil((generate_duration - source_duraion) * sr)+ if added_sample_nums > 0:+ speech_array = np.append(speech_array, [0.]*added_sample_nums)++ # audio embedding+ full_audio_emb = pipe.get_audio_embedding(speech_array, fps=save_fps*audio_stride, device=local_rank, sample_rate=sr)+ if torch.isnan(full_audio_emb).any():+ raise ValueError(f"broken audio embedding with nan values")++ if context_parallel_util.get_cp_size() > 1:+ full_audio_emb_shape_list = list(full_audio_emb.size())+ full_audio_emb_tensor_shape_list = torch.tensor(full_audio_emb_shape_list, dtype=torch.int64, device=full_audio_emb.device)+ context_parallel_util.cp_broadcast(full_audio_emb_tensor_shape_list)+ context_parallel_util.cp_broadcast(full_audio_emb)++ if os.path.exists(temp_vocal_path):+ os.remove(temp_vocal_path)++ elif context_parallel_util.get_cp_size() > 1:+ full_audio_emb_tensor_shape_list = torch.zeros(3, dtype=torch.int64, device=local_rank)+ context_parallel_util.cp_broadcast(full_audio_emb_tensor_shape_list)+ full_audio_emb_shape_list = full_audio_emb_tensor_shape_list.tolist()+ full_audio_emb = torch.zeros(*full_audio_emb_shape_list, dtype=torch.float32, device=local_rank)+ context_parallel_util.cp_broadcast(full_audio_emb)++ # prepare audio embedding for the first clip+ indices = torch.arange(2 * 2 + 1) - 2+ audio_start_idx = 0+ audio_end_idx = audio_start_idx + audio_stride * num_frames++ center_indices = torch.arange(audio_start_idx, audio_end_idx, audio_stride).unsqueeze(1) + indices.unsqueeze(0)+ center_indices = torch.clamp(center_indices, min=0, max=full_audio_emb.shape[0]-1)+ audio_emb = full_audio_emb[center_indices][None,...].to(local_rank)+++ if local_rank == 0:+ print(f"Generating segment 1/{num_segments}...")++ if stage_1 == 'at2v':+ # ==============================+ # at2v (480P)+ # ==============================+ output_tuple = pipe.generate_at2v(+ prompt=prompt,+ negative_prompt=negative_prompt,+ height=height,+ width=width,+ num_frames=num_frames,+ num_inference_steps=num_inference_steps,+ text_guidance_scale=text_guidance_scale,+ audio_guidance_scale=audio_guidance_scale,+ generator=generator,+ output_type='both',+ audio_emb=audio_emb+ )+ output, latent = output_tuple+ output = output[0]+ video = [(output[i] * 255).astype(np.uint8) for i in range(output.shape[0])]+ video = [PIL.Image.fromarray(img) for img in video]++ if cp_rank == 0:+ output_tensor = torch.from_numpy(np.array(video))+ save_video_ffmpeg(output_tensor, os.path.join(output_dir, "at2v_demo_1"), raw_speech_path, fps=save_fps, quality=5)+ del output+ torch_gc()++ elif stage_1 == 'ai2v':+ # ==============================+ # ai2v (480P)+ # ==============================+ image_path = input_data['cond_image']+ image = load_image(image_path)+ output_tuple = pipe.generate_ai2v(+ image=image,+ prompt=prompt,+ negative_prompt=negative_prompt,+ resolution=resolution,+ num_frames=num_frames,+ num_inference_steps=num_inference_steps,+ text_guidance_scale=text_guidance_scale,+ audio_guidance_scale=audio_guidance_scale,+ output_type='both',+ generator=generator,+ audio_emb=audio_emb+ )+ output, latent = output_tuple+ output = output[0]+ video = [(output[i] * 255).astype(np.uint8) for i in range(output.shape[0])]+ video = [PIL.Image.fromarray(img) for img in video]++ if cp_rank == 0:+ output_tensor = torch.from_numpy(np.array(video))+ save_video_ffmpeg(output_tensor, os.path.join(output_dir, "ai2v_demo_1"), raw_speech_path, fps=save_fps, quality=5)+ del output+ torch_gc()+ else:+ raise NotImplementedError(f"Not supported type of stage_1: {stage_1}")++ if context_parallel_util.get_cp_size() > 1:+ torch.distributed.barrier(group=context_parallel_util.get_cp_group())++ # =========================================+ # long video generation (480P)+ # =========================================+ # load parsed long video args+ ref_img_index = args.ref_img_index+ mask_frame_range = args.mask_frame_range++ width, height = video[0].size+ current_video = video+ ref_latent = latent[:, :, :1].clone()+ all_generated_frames = video++ for segment_idx in range(1, num_segments):+ if local_rank == 0:+ print(f"Generating segment {segment_idx+1}/{num_segments}...")++ # prepare audio embedding for the next clip+ audio_start_idx = audio_start_idx + audio_stride * (num_frames - num_cond_frames)+ audio_end_idx = audio_start_idx + audio_stride * num_frames+ center_indices = torch.arange(audio_start_idx, audio_end_idx, audio_stride).unsqueeze(1) + indices.unsqueeze(0)+ center_indices = torch.clamp(center_indices, min=0, max=full_audio_emb.shape[0]-1)+ audio_emb = full_audio_emb[center_indices][None,...].to(local_rank)++ output_tuple = pipe.generate_avc(+ video=current_video,+ video_latent=latent,+ prompt=prompt,+ negative_prompt=negative_prompt,+ height=height,+ width=width,+ num_frames=num_frames,+ num_cond_frames=num_cond_frames,+ num_inference_steps=num_inference_steps,+ text_guidance_scale=text_guidance_scale,+ audio_guidance_scale=audio_guidance_scale,+ generator=generator,+ output_type='both',+ use_kv_cache=True,+ offload_kv_cache=False,+ enhance_hf=True,+ audio_emb=audio_emb,+ ref_latent=ref_latent,+ ref_img_index=ref_img_index,+ mask_frame_range=mask_frame_range+ )+ output, latent = output_tuple++ output = output[0]+ new_video = [(output[i] * 255).astype(np.uint8) for i in range(output.shape[0])]+ new_video = [PIL.Image.fromarray(img) for img in new_video]+ del output++ all_generated_frames.extend(new_video[num_cond_frames:])++ current_video = new_video++ if cp_rank == 0:+ output_tensor = torch.from_numpy(np.array(all_generated_frames))+ save_video_ffmpeg(output_tensor, os.path.join(output_dir, f"video_continue_{segment_idx+1}"), raw_speech_path, fps=save_fps, quality=5)+ del output_tensor+++def _parse_args():+ parser = argparse.ArgumentParser()+ parser.add_argument(+ '--input_json',+ type=str,+ default='assets/avatar/single_example_1.json'+ )+ parser.add_argument(+ '--output_dir',+ type=str,+ default='./outputs_avatar_single'+ )+ parser.add_argument(+ '--resolution',+ type=str,+ default='480p',+ choices=['480p', '720p']+ )+ parser.add_argument(+ '--num_segments',+ type=int,+ default=1+ )+ parser.add_argument(+ '--num_inference_steps',+ type=int,+ default=50+ )+ parser.add_argument(+ '--ref_img_index',+ type=int,+ default=10+ )+ parser.add_argument(+ '--mask_frame_range',+ type=int,+ default=3+ )+ parser.add_argument(+ '--text_guidance_scale',+ type=float,+ default=4.0+ )+ parser.add_argument(+ '--audio_guidance_scale',+ type=float,+ default=4.0+ )+ parser.add_argument(+ '--stage_1',+ type=str,+ default='ai2v',+ choices=['ai2v', 'at2v']+ )+ parser.add_argument(+ "--context_parallel_size",+ type=int,+ default=1,+ )+ parser.add_argument(+ "--checkpoint_dir",+ type=str,+ default="./weights/LongCat-Video-Avatar",+ )++ args = parser.parse_args()++ return args+++if __name__ == "__main__":+ args = _parse_args()+ generate(args)\ No newline at end of file