Python
added experimental longcat
deepbeepmeep96e343894d3f
diff --git a/models/longcat/__init__.py b/models/longcat/__init__.pynew file mode 100644index 0000000..8b13789--- /dev/null+++ b/models/longcat/__init__.py@@ -0,0 +1 @@+diff --git a/models/longcat/audio_process/torch_utils.py b/models/longcat/audio_process/torch_utils.pynew file mode 100644index 0000000..600f8a6--- /dev/null+++ b/models/longcat/audio_process/torch_utils.py@@ -0,0 +1,228 @@+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++import gc++def torch_gc():+ gc.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(qk_list, ref_target_masks, attn_bias=None):++ # compute cross-reference attention maps between query features and reference key features.+ noise_q, ref_k = qk_list+ 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):+ 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)++ qk_list[:] = []+ del attn+ del x_ref_attn_map_source++ 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+ ref_k = key[:, :x_seqlens]+ noise_q = noise_q.contiguous()++ _, 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):+ qk_list = [+ noise_q[:, :, i * split_chunk:(i + 1) * split_chunk, :],+ ref_k[:, :, i * split_chunk:(i + 1) * split_chunk, :],+ ]+ x_ref_attn_maps_perhead = calculate_x_ref_attn_map(qk_list, 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)diff --git a/models/longcat/audio_process/wav2vec2.py b/models/longcat/audio_process/wav2vec2.pynew file mode 100644index 0000000..b88246d--- /dev/null+++ b/models/longcat/audio_process/wav2vec2.py@@ -0,0 +1,262 @@+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 safetensors.torch import load_file++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='cpu', 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, 'model.safetensors')+ if not os.path.exists(model_path):+ model_path = os.path.join(config_path, 'pytorch_model.bin')++ if model_path.endswith(".safetensors"):+ state_dict = load_file(model_path, device="cpu")+ else:+ state_dict = torch.load(model_path, map_location="cpu")++ config.name_or_path = config_path+ config = copy.deepcopy(config) # We do not want to modify the config inplace in from_pretrained.+ try:+ config = Wav2Vec2Mode._autoset_attn_implementation(config, use_flash_attention_2=False)+ except TypeError:+ config = Wav2Vec2Mode._autoset_attn_implementation(config)++ # 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/models/longcat/configs/longcat_avatar.json b/models/longcat/configs/longcat_avatar.jsonnew file mode 100644index 0000000..79f470d--- /dev/null+++ b/models/longcat/configs/longcat_avatar.json@@ -0,0 +1,37 @@+{+ "_class_name": "LongCatVideoAvatarTransformer3DModel",+ "_diffusers_version": "0.32.0",+ "adaln_tembed_dim": 512,+ "bsa_params":{+ "sparsity": 0.9375,+ "chunk_3d_shape_q": [4, 4, 4],+ "chunk_3d_shape_k": [4, 4, 4]+ },+ "caption_channels": 4096,+ "cp_split_hw": null,+ "depth": 48,+ "enable_bsa": false,+ "enable_flashattn3": false,+ "enable_flashattn2": true,+ "enable_xformers": false,+ "frequency_embedding_size": 256,+ "hidden_size": 4096,+ "in_channels": 16,+ "text_tokens_zero_pad": true,+ "mlp_ratio": 4,+ "num_heads": 32,+ "out_channels": 16,+ "patch_size": [+ 1,+ 2,+ 2+ ],+ "audio_window": 5,+ "intermediate_dim": 512,+ "output_dim": 768,+ "context_tokens": 32,+ "vae_scale": 4,+ "audio_prenorm": false,+ "class_range": 24,+ "class_interval": 4+}diff --git a/models/longcat/configs/longcat_scheduler.json b/models/longcat/configs/longcat_scheduler.jsonnew file mode 100644index 0000000..6858df8--- /dev/null+++ b/models/longcat/configs/longcat_scheduler.json@@ -0,0 +1,8 @@+{+ "_class_name": "FlowMatchEulerDiscreteScheduler",+ "_diffusers_version": "0.33.0.dev0",+ "shift": 12.0,+ "use_dynamic_shifting": false,+ "invert_sigmas": false,+ "time_shift_type": "linear"+}diff --git a/models/longcat/configs/longcat_vae.json b/models/longcat/configs/longcat_vae.jsonnew file mode 100644index 0000000..fe988ee--- /dev/null+++ b/models/longcat/configs/longcat_vae.json@@ -0,0 +1,56 @@+{+ "_class_name": "AutoencoderKLWan",+ "_diffusers_version": "0.33.0.dev0",+ "attn_scales": [],+ "base_dim": 96,+ "dim_mult": [+ 1,+ 2,+ 4,+ 4+ ],+ "dropout": 0.0,+ "latents_mean": [+ -0.7571,+ -0.7089,+ -0.9113,+ 0.1075,+ -0.1745,+ 0.9653,+ -0.1517,+ 1.5508,+ 0.4134,+ -0.0715,+ 0.5517,+ -0.3632,+ -0.1922,+ -0.9497,+ 0.2503,+ -0.2921+ ],+ "latents_std": [+ 2.8184,+ 1.4541,+ 2.3275,+ 2.6558,+ 1.2196,+ 1.7708,+ 2.6052,+ 2.0743,+ 3.2687,+ 2.1526,+ 2.8652,+ 1.5579,+ 1.6382,+ 1.1253,+ 2.8251,+ 1.916+ ],+ "num_res_blocks": 2,+ "temperal_downsample": [+ false,+ true,+ true+ ],+ "z_dim": 16+}diff --git a/models/longcat/configs/longcat_video.json b/models/longcat/configs/longcat_video.jsonnew file mode 100644index 0000000..d5ccd38--- /dev/null+++ b/models/longcat/configs/longcat_video.json@@ -0,0 +1,28 @@+{+ "_class_name": "LongCatVideoTransformer3DModel",+ "_diffusers_version": "0.32.0",+ "adaln_tembed_dim": 512,+ "bsa_params":{+ "sparsity": 0.9375,+ "chunk_3d_shape_q": [4, 4, 4],+ "chunk_3d_shape_k": [4, 4, 4]+ },+ "caption_channels": 4096,+ "cp_split_hw": null,+ "depth": 48,+ "enable_bsa": false,+ "enable_flashattn3": false,+ "enable_flashattn2": true,+ "frequency_embedding_size": 256,+ "hidden_size": 4096,+ "in_channels": 16,+ "text_tokens_zero_pad": true,+ "mlp_ratio": 4,+ "num_heads": 32,+ "out_channels": 16,+ "patch_size": [+ 1,+ 2,+ 2+ ]+}diff --git a/models/longcat/longcat_handler.py b/models/longcat/longcat_handler.pynew file mode 100644index 0000000..83c6338--- /dev/null+++ b/models/longcat/longcat_handler.py@@ -0,0 +1,196 @@+import os+import torch+from shared.utils import files_locator as fl+++def get_longcat_text_encoder_filename(text_encoder_quantization):+ text_encoder_filename = "umt5-xxl/models_t5_umt5-xxl-enc-bf16.safetensors"+ if text_encoder_quantization == "int8":+ text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_int8")+ return fl.locate_file(text_encoder_filename, True)+++class family_handler:+ @staticmethod+ def query_supported_types():+ return ["longcat_video", "longcat_avatar"]++ @staticmethod+ def query_family_maps():+ return {}, {}++ @staticmethod+ def query_model_family():+ return "longcat"++ @staticmethod+ def query_family_infos():+ return {"longcat": (60, "LongCat")}++ @staticmethod+ def register_lora_cli_args(parser):+ parser.add_argument(+ "--lora-dir-longcat",+ type=str,+ default=os.path.join("loras", "longcat"),+ help="Path to a directory that contains LongCat Video LoRAs",+ )+ parser.add_argument(+ "--lora-dir-longcat-avatar",+ type=str,+ default=os.path.join("loras", "longcat_avatar"),+ help="Path to a directory that contains LongCat Avatar LoRAs",+ )++ @staticmethod+ def get_lora_dir(base_model_type, args):+ if base_model_type == "longcat_avatar":+ return args.lora_dir_longcat_avatar+ return args.lora_dir_longcat++ @staticmethod+ def query_model_def(base_model_type, model_def):+ extra_model_def = {+ "frames_minimum": 5,+ "frames_steps": 4,+ "sliding_window": True,+ "guidance_max_phases": 1,+ "image_prompt_types_allowed": "TSVL",+ "video_continuation": True,+ "sample_solvers": [+ ("Auto (Continuation = Enhanced HF)", "auto"),+ ("Default", ""),+ ("Enhanced HF", "enhance_hf"),+ ("Distill", "distill"),+ ],+ }++ if base_model_type == "longcat_video":+ extra_model_def.update(+ {+ "fps": 15,+ "profiles_dir": ["longcat_video"],+ }+ )+ elif base_model_type == "longcat_avatar":+ extra_model_def.update(+ {+ "fps": 16,+ "profiles_dir": [base_model_type],+ "audio_guide_label": "Voice to follow",+ "audio_guide2_label": "Voice to follow #2",+ "audio_guidance": True,+ "any_audio_prompt": True,+ "audio_prompt_choices": True,+ "image_ref_choices": {+ "choices": [("None", ""), ("Anchor Reference Image", "KI")],+ "letters_filter": "KI",+ "visible": True,+ "label": "Anchor Reference Image",+ },+ "reference_image_enabled": True,+ "no_background_removal": True,+ "image_prompt_types_allowed": "TSVL",+ }+ )+++ return extra_model_def++ @staticmethod+ def get_rgb_factors(base_model_type):+ from shared.RGB_factors import get_rgb_factors++ return get_rgb_factors("wan")++ @staticmethod+ def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization):+ text_encoder_filename = get_longcat_text_encoder_filename(text_encoder_quantization)+ download_def = [+ {+ "repoId": "DeepBeepMeep/Wan2.1",+ "sourceFolderList": ["umt5-xxl", "chinese-wav2vec2-base"],+ "fileList": [+ ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"]+ + computeList(text_encoder_filename),+ [+ "config.json",+ "preprocessor_config.json",+ "pytorch_model.bin",+ "readme.txt",+ ],+ ],+ }+ ]+ download_def += [+ {+ "repoId": "DeepBeepMeep/Wan2.1",+ "sourceFolderList": [""],+ "fileList": [["Wan2.1_VAE_bf16.safetensors"]],+ }+ ]+ return download_def++ @staticmethod+ def load_model(+ model_filename,+ model_type,+ base_model_type,+ model_def,+ quantizeTransformer=False,+ text_encoder_quantization=None,+ dtype=torch.bfloat16,+ VAE_dtype=torch.float32,+ mixed_precision_transformer=False,+ save_quantized=False,+ submodel_no_list=None,+ override_text_encoder=None,+ **kwargs,+ ):+ from .longcat_main import LongCatModel++ longcat_model = LongCatModel(+ checkpoint_dir="ckpts",+ model_filename=model_filename,+ model_type=model_type,+ model_def=model_def,+ base_model_type=base_model_type,+ text_encoder_filename=get_longcat_text_encoder_filename(text_encoder_quantization)+ if override_text_encoder is None+ else override_text_encoder,+ quantizeTransformer=quantizeTransformer,+ dtype=dtype,+ VAE_dtype=VAE_dtype,+ mixed_precision_transformer=mixed_precision_transformer,+ save_quantized=save_quantized,+ )++ pipe = {+ "transformer": longcat_model.transformer,+ "vae": longcat_model.vae,+ "text_encoder": longcat_model.text_encoder.model,+ }+ if longcat_model.audio_encoder is not None:+ pipe["wav2vec"] = longcat_model.audio_encoder++ return longcat_model, pipe++ @staticmethod+ def update_default_settings(base_model_type, model_def, ui_defaults):+ ui_defaults.update(+ {+ "guidance_scale": 4.0,+ "num_inference_steps": 50,+ "audio_guidance_scale": 4.0,+ "sliding_window_overlap": 13,++ }+ )+ if base_model_type == "longcat_video":+ ui_defaults.update({"video_length": 93})++ if base_model_type in ["longcat_avatar"]:+ ui_defaults.update({"video_length": 93, "video_prompt_type": ""})++ if ui_defaults.get("sample_solver", "") == "":+ ui_defaults["sample_solver"] = "auto"diff --git a/models/longcat/longcat_main.py b/models/longcat/longcat_main.pynew file mode 100644index 0000000..1fd10bc--- /dev/null+++ b/models/longcat/longcat_main.py@@ -0,0 +1,846 @@+import json+import math+import gc+from typing import Optional, List++import numpy as np+import torch+from accelerate import init_empty_weights+from mmgp import offload+from tqdm import tqdm+import librosa+import pyloudnorm as pyln+import scipy.signal as ss+from transformers import Wav2Vec2FeatureExtractor++from shared.utils import files_locator as fl+from ..wan.modules.t5 import T5EncoderModel+from .modules.longcat_video_dit import LongCatVideoTransformer3DModel+from .modules.avatar.longcat_video_dit_avatar import LongCatVideoAvatarTransformer3DModel+from .modules.autoencoder_kl_wan import AutoencoderKLWan+from .modules.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler+from .audio_process.wav2vec2 import Wav2Vec2ModelWrapper+from ..qwen.convert_diffusers_qwen_vae import convert_state_dict+++def _load_json_config(path):+ with open(path, "r", encoding="utf-8") as f:+ cfg = json.load(f)+ cfg.pop("_class_name", None)+ cfg.pop("_diffusers_version", None)+ return cfg+++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)+ if hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":+ return encoder_output.latent_dist.mode()+ if hasattr(encoder_output, "latents"):+ return encoder_output.latents+ raise AttributeError("Could not access latents of provided encoder_output")+++def optimized_scale(positive_flat, negative_flat):+ dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)+ squared_norm = torch.sum(negative_flat ** 2, dim=1, keepdim=True) + 1e-8+ return dot_product / squared_norm+++class LongCatModel:+ def __init__(+ self,+ checkpoint_dir,+ model_filename=None,+ model_type=None,+ model_def=None,+ base_model_type=None,+ text_encoder_filename=None,+ quantizeTransformer=False,+ save_quantized=False,+ dtype=torch.bfloat16,+ VAE_dtype=torch.float32,+ mixed_precision_transformer=False,+ **kwargs,+ ):+ self.device = torch.device("cuda")+ self.dtype = dtype+ self.VAE_dtype = VAE_dtype+ self.model_def = model_def or {}+ self.base_model_type = base_model_type+ self.is_avatar = base_model_type in ["longcat_avatar"]+ self.sparse_attention_enabled = bool(self.model_def.get("sparse_attention", False))+ self._interrupt = False+ self._reference_image = None++ text_encoder_path = text_encoder_filename or fl.locate_file(+ "umt5-xxl/models_t5_umt5-xxl-enc-bf16.safetensors", True+ )+ self.text_encoder = T5EncoderModel(+ text_len=512,+ dtype=dtype,+ device=torch.device("cpu"),+ checkpoint_path=text_encoder_path,+ tokenizer_path=fl.locate_folder("umt5-xxl"),+ shard_fn=None,+ )++ transformer_config_path = (+ "models/longcat/configs/longcat_avatar.json"+ if self.is_avatar+ else "models/longcat/configs/longcat_video.json"+ )+ transformer_cfg = _load_json_config(transformer_config_path)+ if self.sparse_attention_enabled:+ transformer_cfg["enable_bsa"] = True+ sparse_params = self.model_def.get("sparse_attention_params")+ if isinstance(sparse_params, dict) and sparse_params:+ bsa_params = dict(transformer_cfg.get("bsa_params") or {})+ bsa_params.update(sparse_params)+ transformer_cfg["bsa_params"] = bsa_params+ transformer_cls = (+ LongCatVideoAvatarTransformer3DModel+ if self.is_avatar+ else LongCatVideoTransformer3DModel+ )+ with init_empty_weights():+ transformer = transformer_cls(**transformer_cfg)+ model_path = model_filename[0] if isinstance(model_filename, (list, tuple)) else model_filename+ if model_path is None:+ raise ValueError("Missing LongCat transformer weights path.")+ offload.load_model_data(transformer, model_path, writable_tensors=False)+ transformer._model_dtype = dtype+ transformer.eval().requires_grad_(False)+ self.transformer = transformer+ if save_quantized:+ from wgp import save_quantized_model++ save_quantized_model(transformer, model_type, model_path, dtype, transformer_config_path)++ vae_cfg_path = "models/longcat/configs/longcat_vae.json"+ vae_weights = self.model_def.get("vae_URL")+ if vae_weights:+ vae_weights = fl.locate_file(vae_weights)+ else:+ for candidate in ["Wan2.1_VAE_bf16.safetensors", "Wan2.1_VAE.safetensors", "longcat_vae_bf16.safetensors"]:+ vae_weights = fl.locate_file(candidate, error_if_none=False)+ if vae_weights:+ break+ if not vae_weights:+ raise FileNotFoundError("Unable to locate a compatible VAE weights file for LongCat.")+ def preprocess_vae_sd(sd):+ return convert_state_dict(sd)++ self.vae = offload.fast_load_transformers_model(+ vae_weights,+ modelClass=AutoencoderKLWan,+ defaultConfigPath=fl.locate_file(vae_cfg_path),+ preprocess_sd=preprocess_vae_sd,+ default_dtype=VAE_dtype,+ )+ self.vae = self.vae.to(dtype=VAE_dtype, device="cpu")+ self.vae._model_dtype = VAE_dtype+ self.vae._dtype = VAE_dtype+ self.vae.eval().requires_grad_(False)++ scheduler_cfg = _load_json_config("models/longcat/configs/longcat_scheduler.json")+ self.scheduler = FlowMatchEulerDiscreteScheduler(**scheduler_cfg)+ self.num_timesteps = 1000+ self.num_distill_sample_steps = 50++ if self.is_avatar:+ wav2vec_folder = fl.locate_folder("chinese-wav2vec2-base")+ self.audio_encoder = Wav2Vec2ModelWrapper(wav2vec_folder)+ self.audio_encoder.eval().requires_grad_(False)+ if hasattr(self.audio_encoder, "feature_extractor"):+ self.audio_encoder.feature_extractor._freeze_parameters()+ self.wav2vec_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(+ wav2vec_folder, local_files_only=True+ )+ else:+ self.audio_encoder = None+ self.wav2vec_feature_extractor = None++ self.vae_scale_factor_temporal = getattr(self.vae.config, "scale_factor_temporal", 4)+ self.vae_scale_factor_spatial = getattr(self.vae.config, "scale_factor_spatial", 8)+ self.transformer._interrupt_check = lambda: self._interrupt++ def prepare_preview_payload(self, latents, preview_meta=None):+ if not torch.is_tensor(latents):+ return None+ return {"latents": latents.float()}++ def _apply_vae_tiling(self, VAE_tile_size):+ if not hasattr(self.vae, "enable_tiling"):+ return+ if VAE_tile_size is None or VAE_tile_size == 0:+ if hasattr(self.vae, "disable_tiling"):+ self.vae.disable_tiling()+ return+ if isinstance(VAE_tile_size, dict):+ tile = VAE_tile_size.get("tile_sample_min_size", None)+ else:+ tile = int(VAE_tile_size)+ if tile and tile > 0:+ stride = max(16, int(tile * 0.75))+ self.vae.enable_tiling(+ tile_sample_min_height=tile,+ tile_sample_min_width=tile,+ tile_sample_stride_height=stride,+ tile_sample_stride_width=stride,+ )++ def _validate_sparse_attention(self, latents):+ if not self.sparse_attention_enabled:+ return+ bsa_params = getattr(self.transformer.config, "bsa_params", None) or {}+ chunk_shape_q = bsa_params.get("chunk_3d_shape_q")+ chunk_shape_k = bsa_params.get("chunk_3d_shape_k")+ chunk_shape = chunk_shape_q or chunk_shape_k+ if not chunk_shape or latents.dim() != 5:+ self.transformer.disable_bsa()+ self.sparse_attention_enabled = False+ print("Sparse attention disabled: missing BSA parameters.")+ return+ attn_mode = offload.shared_state.get("_attention", "auto")+ require_grid_divisible = False+ if attn_mode == "flash":+ require_grid_divisible = True+ elif attn_mode == "auto":+ try:+ from shared.attention import flash_attn_bsa_3d+ except Exception:+ flash_attn_bsa_3d = None+ require_grid_divisible = flash_attn_bsa_3d is not None++ patch_t, patch_h, patch_w = self.transformer.config.patch_size+ n_t = latents.shape[2] // patch_t+ n_h = latents.shape[3] // patch_h+ n_w = latents.shape[4] // patch_w+ cp_split_hw = getattr(self.transformer.config, "cp_split_hw", None)+ if cp_split_hw:+ if n_h % cp_split_hw[0] != 0 or n_w % cp_split_hw[1] != 0:+ self.transformer.disable_bsa()+ self.sparse_attention_enabled = False+ print("Sparse attention disabled: cp_split_hw does not divide token grid.")+ return+ if require_grid_divisible:+ shape_q = chunk_shape_q or chunk_shape+ shape_k = chunk_shape_k or chunk_shape+ if (+ n_t % shape_q[0] != 0+ or n_h % shape_q[1] != 0+ or n_w % shape_q[2] != 0+ or n_t % shape_k[0] != 0+ or n_h % shape_k[1] != 0+ or n_w % shape_k[2] != 0+ ):+ self.transformer.disable_bsa()+ self.sparse_attention_enabled = False+ print("Sparse attention disabled: flash BSA needs token grid divisible by chunk shape.")++ def _encode_prompt(+ self,+ prompt,+ negative_prompt,+ num_videos_per_prompt=1,+ max_length=512,+ device=None,+ dtype=None,+ ):+ device = device or self.device+ dtype = dtype or self.dtype+ prompt_list = [prompt] if isinstance(prompt, str) else prompt+ batch_size = len(prompt_list)+ ids, mask = self.text_encoder.tokenizer(+ prompt_list,+ return_mask=True,+ add_special_tokens=True,+ )+ ids = ids.to(device)+ mask = mask.to(device)+ prompt_embeds = self.text_encoder.model(ids, mask).to(dtype)+ seq_len = prompt_embeds.shape[1]+ prompt_embeds = prompt_embeds.unsqueeze(1)+ if num_videos_per_prompt > 1:+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1, 1)+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, 1, seq_len, -1)+ mask = mask.repeat(num_videos_per_prompt, 1)++ neg_embeds = None+ neg_mask = None+ if negative_prompt is not None:+ neg_list = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt+ if len(neg_list) == 1 and batch_size > 1:+ neg_list = neg_list * batch_size+ ids, neg_mask = self.text_encoder.tokenizer(+ neg_list,+ return_mask=True,+ add_special_tokens=True,+ )+ ids = ids.to(device)+ neg_mask = neg_mask.to(device)+ neg_embeds = self.text_encoder.model(ids, neg_mask).to(dtype)+ neg_embeds = neg_embeds.unsqueeze(1)+ if num_videos_per_prompt > 1:+ neg_embeds = neg_embeds.repeat(1, num_videos_per_prompt, 1, 1)+ neg_embeds = neg_embeds.view(batch_size * num_videos_per_prompt, 1, seq_len, -1)+ neg_mask = neg_mask.repeat(num_videos_per_prompt, 1)++ return prompt_embeds, mask, neg_embeds, neg_mask++ def _prepare_latents(+ self,+ batch_size,+ num_channels_latents,+ height,+ width,+ num_frames,+ dtype,+ device,+ generator,+ latents=None,+ image=None,+ video=None,+ num_cond_frames=0,+ ):+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1+ if latents is None:+ shape = (+ batch_size,+ num_channels_latents,+ num_latent_frames,+ int(height) // self.vae_scale_factor_spatial,+ int(width) // self.vae_scale_factor_spatial,+ )+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)+ else:+ latents = latents.to(device=device, dtype=dtype)++ num_cond_latents = 0+ if image is not None or video is not None:+ cond_latents = []+ for i in range(batch_size):+ if image is not None:+ encoded_input = image[i].unsqueeze(0).unsqueeze(2)+ else:+ encoded_input = video[i][:, -num_cond_frames:].unsqueeze(0)+ latent = retrieve_latents(+ self.vae.encode(encoded_input),+ generator,+ sample_mode="argmax",+ )+ cond_latents.append(latent)+ cond_latents = torch.cat(cond_latents, dim=0).to(dtype)+ cond_latents = self.normalize_latents(cond_latents)+ num_cond_latents = 1 + (num_cond_frames - 1) // self.vae_scale_factor_temporal+ latents[:, :, :num_cond_latents] = cond_latents[:, :, :num_cond_latents]+ return latents, num_cond_latents++ 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 = (+ 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 = (+ 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 not np.isfinite(loudness) or loudness > threshold:+ return audio_array+ return pyln.normalize.loudness(audio_array, loudness, lufs)++ def _add_noise_floor(self, audio_array, noise_level=0.0001):+ noise = np.random.normal(0, noise_level, size=audio_array.shape)+ return audio_array + noise++ def _smooth_transients(self, audio_array, sr=16000):+ b, a = ss.butter(3, 3000 / (sr / 2))+ return ss.lfilter(b, a, audio_array)++ @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_array = self._loudness_norm(speech_array, sample_rate)+ speech_array = self._add_noise_floor(speech_array)+ speech_array = self._smooth_transients(speech_array, sample_rate)++ audio_feature = np.squeeze(+ self.wav2vec_feature_extractor(speech_array, sampling_rate=sample_rate).input_values+ )+ audio_feature = np.nan_to_num(audio_feature, nan=0.0, posinf=0.0, neginf=0.0)+ audio_feature = torch.from_numpy(audio_feature).float().to(device=device)+ audio_feature = audio_feature.unsqueeze(0)++ 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 = audio_emb.permute(1, 0, 2).contiguous()+ audio_emb = torch.nan_to_num(audio_emb, nan=0.0, posinf=0.0, neginf=0.0)+ return audio_emb++ def _build_audio_windows(self, audio_path, frame_num, fps, window_start_frame_no, audio_stride):+ speech_array, sr = librosa.load(audio_path, sr=16000)+ target_len = int(frame_num / fps * sr)+ if len(speech_array) < target_len:+ pad = target_len - len(speech_array)+ speech_array = np.pad(speech_array, (0, pad), mode="constant")++ full_audio_emb = self._get_audio_embedding(speech_array, fps=fps * audio_stride, device="cpu", sample_rate=sr)+ if torch.isnan(full_audio_emb).any():+ raise ValueError("Audio embedding contains NaNs.")++ audio_start_idx = window_start_frame_no * audio_stride+ audio_end_idx = audio_start_idx + audio_stride * frame_num+ window = self.transformer.audio_window if hasattr(self.transformer, "audio_window") else 5+ offsets = torch.arange(window) - window // 2+ centers = torch.arange(audio_start_idx, audio_end_idx, audio_stride).unsqueeze(1) + offsets.unsqueeze(0)+ centers = torch.clamp(centers, min=0, max=full_audio_emb.shape[0] - 1)+ audio_emb = full_audio_emb[centers][None, ...]+ return audio_emb++ def _build_ref_target_masks(self, height, width, speakers_bboxes=None):+ if not speakers_bboxes:+ return None+ human_masks = []+ background_mask = torch.zeros([height, width])+ for _, person_bbox in speakers_bboxes.items():+ y_min, x_min, y_max, x_max = person_bbox+ x_min, y_min, x_max, y_max = max(x_min, 5), max(y_min, 5), min(x_max, 95), min(y_max, 95)+ x_min, y_min, x_max, y_max = (+ int(height * x_min / 100),+ int(width * y_min / 100),+ int(height * x_max / 100),+ int(width * y_max / 100),+ )+ human_mask = torch.zeros([height, width])+ human_mask[int(x_min) : int(x_max), int(y_min) : int(y_max)] = 1+ background_mask += human_mask+ human_masks.append(human_mask)+ background_mask = torch.where(background_mask > 0, torch.tensor(0), torch.tensor(1))+ human_masks.append(background_mask)+ return torch.stack(human_masks, dim=0)++ def get_timesteps_sigmas(self, sampling_steps, use_distill=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, dtype=torch.float32)+ return sigmas.to(dtype=torch.float32, device="cpu")++ @torch.no_grad()+ def generate(+ self,+ seed=None,+ input_prompt="",+ n_prompt="",+ sampling_steps=50,+ input_ref_images=None,+ input_frames=None,+ input_frames2=None,+ input_masks=None,+ input_masks2=None,+ input_video=None,+ image_start=None,+ image_end=None,+ frame_num=93,+ batch_size=1,+ height=480,+ width=832,+ guide_scale=4.0,+ audio_cfg_scale=None,+ joint_pass=False,+ VAE_tile_size=None,+ prefix_frames_count=0,+ conditioning_latents_size=0,+ callback=None,+ cfg_star_switch=False,+ cfg_zero_step=-1,+ audio_guide=None,+ audio_guide2=None,+ fps=None,+ window_start_frame_no=0,+ **kwargs,+ ):+ if self._interrupt:+ return None++ if seed is None or seed == -1:+ seed = torch.seed() % (2**32 - 1)+ generator = torch.Generator(device=self.device)+ generator.manual_seed(seed)++ if fps is None or fps == 0:+ fps = self.model_def.get("fps", 15 if not self.is_avatar else 16)++ if frame_num % self.vae_scale_factor_temporal != 1:+ frame_num = frame_num // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1+ frame_num = max(frame_num, 1)++ sample_solver = kwargs.get("sample_solver", self.model_def.get("sample_solver", "auto"))+ if sample_solver in (None, ""):+ sample_solver = "auto"++ prompt_embeds, prompt_mask, neg_embeds, neg_mask = self._encode_prompt(+ input_prompt,+ n_prompt if n_prompt is not None else "",+ device=self.device,+ dtype=self.dtype,+ )++ any_guidance = guide_scale is not None and guide_scale > 1+ if self.is_avatar:+ if audio_cfg_scale is None:+ audio_cfg_scale = 1.0+ any_guidance = any_guidance or audio_cfg_scale > 1++ reference_image_enabled = self.is_avatar and bool(+ kwargs.get("reference_image_enabled", self.model_def.get("reference_image_enabled", True))+ )+ reference_features_enabled = reference_image_enabled++ ref_img_index = kwargs.get("ref_img_index", self.model_def.get("ref_img_index", 10))+ mask_frame_range = kwargs.get("mask_frame_range", self.model_def.get("mask_frame_range", 3))+ if not reference_features_enabled:+ ref_img_index = None+ mask_frame_range = None++ ref_image = None+ if reference_image_enabled:+ if input_ref_images is not None:+ ref_list = input_ref_images if isinstance(input_ref_images, list) else [input_ref_images]+ if len(ref_list) > 0:+ ref_image = ref_list[0]+ window_no = kwargs.get("window_no", None)+ if window_no == 1:+ if ref_image is not None:+ self._reference_image = (+ ref_image.detach().to("cpu") if torch.is_tensor(ref_image) else ref_image+ )+ else:+ self._reference_image = None+ if ref_image is None and self._reference_image is not None:+ ref_image = self._reference_image++ cond_video = None+ num_cond_frames = 0+ if input_video is not None:+ cond_video = input_video+ num_cond_frames = max(int(prefix_frames_count or 0), 0)++ self._apply_vae_tiling(VAE_tile_size)++ if cond_video is not None:+ cond_video = cond_video.to(device=self.device, dtype=self.VAE_dtype)+ if cond_video.dim() == 4:+ cond_video = cond_video.unsqueeze(0)+ cond_video_frames = cond_video.shape[2]+ if num_cond_frames <= 0:+ cond_video = None+ num_cond_frames = 0+ else:+ num_cond_frames = min(num_cond_frames, cond_video_frames)++ if sample_solver not in ("auto", "default", "enhance_hf", "distill"):+ raise ValueError(f"Unsupported scheduler '{sample_solver}' for LongCat.")+ use_distill = sample_solver == "distill"+ enhance_hf = sample_solver == "enhance_hf"+ if sample_solver == "auto":+ enhance_hf = cond_video is not None and num_cond_frames > 0+ if use_distill and enhance_hf:+ raise ValueError("distill and enhance_hf schedules cannot both be enabled.")++ image_cond = None+ ref_latent = None+ num_ref_latents = 0+ if reference_image_enabled and ref_image is not None:+ if not torch.is_tensor(ref_image):+ ref_image = torch.from_numpy(np.array(ref_image)).float().div_(127.5).sub_(1.).movedim(-1, 0)+ ref_image = ref_image.to(device=self.device, dtype=self.VAE_dtype)+ if ref_image.dim() == 3:+ ref_image = ref_image.unsqueeze(0)+ if ref_image.dim() == 5 and ref_image.shape[2] == 1:+ ref_image = ref_image.squeeze(2)+ if ref_image.dim() != 4:+ raise ValueError("reference image must be CHW or BCHW for LongCat.")+ if ref_image.shape[0] == 1 and batch_size > 1:+ ref_image = ref_image.repeat(batch_size, 1, 1, 1)+ elif ref_image.shape[0] != batch_size:+ raise ValueError("reference image batch size does not match prompts.")+ if cond_video is None:+ image_cond = ref_image+ else:+ ref_image_5d = ref_image.unsqueeze(2)+ ref_latent = retrieve_latents(self.vae.encode(ref_image_5d), generator, sample_mode="argmax")+ ref_latent = self.normalize_latents(ref_latent).to(torch.float32)+ num_ref_latents = 1++ cond_image_frames = 1 if image_cond is not None else num_cond_frames+ latents, num_cond_latents = self._prepare_latents(+ batch_size=batch_size,+ num_channels_latents=self.transformer.config.in_channels,+ height=height,+ width=width,+ num_frames=frame_num,+ dtype=torch.float32,+ device=self.device,+ generator=generator,+ latents=None,+ image=image_cond,+ video=None if image_cond is not None else cond_video,+ num_cond_frames=cond_image_frames,+ )+ if reference_image_enabled and ref_latent is None and self.is_avatar and num_cond_latents > 1:+ ref_latent = latents[:, :, :1].clone()+ num_ref_latents = 1+ if ref_latent is not None:+ num_cond_latents += num_ref_latents+ latents = torch.cat([ref_latent, latents], dim=2)+ self._validate_sparse_attention(latents)++ sigmas = self.get_timesteps_sigmas(sampling_steps, use_distill=use_distill)+ self.scheduler.set_timesteps(sampling_steps, sigmas=sigmas, device=self.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=self.device, dtype=torch.float32).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 / self.num_timesteps, torch.zeros(1, device=timesteps.device)]+ )++ audio_emb = None+ ref_target_masks = None+ if self.is_avatar:+ if audio_guide is None:+ raise ValueError("Audio guide is required for LongCat Avatar.")+ audio_stride = 2+ audio_emb = self._build_audio_windows(+ audio_guide, frame_num, fps, window_start_frame_no, audio_stride+ )+ if self.base_model_type == "longcat_avatar_multi":+ if audio_guide2 is None:+ raise ValueError("Second audio guide is required for LongCat Avatar Multi.")+ audio_emb2 = self._build_audio_windows(+ audio_guide2, frame_num, fps, window_start_frame_no, audio_stride+ )+ audio_emb = torch.cat([audio_emb, audio_emb2], dim=0)+ speakers_bboxes = kwargs.get("speakers_bboxes")+ ref_target_masks = self._build_ref_target_masks(height, width, speakers_bboxes)+ if ref_target_masks is not None:+ ref_target_masks = ref_target_masks.to(self.device)+ audio_emb = audio_emb.to(self.device, dtype=self.dtype)++ latents = latents.to(self.device, dtype=self.dtype)+ prompt_embeds = prompt_embeds.to(self.device)+ prompt_mask = prompt_mask.to(self.device)+ if neg_embeds is None:+ neg_embeds = prompt_embeds+ neg_mask = prompt_mask+ else:+ neg_embeds = neg_embeds.to(self.device)+ neg_mask = neg_mask.to(self.device)++ ref_kwargs = {}+ if self.is_avatar and num_ref_latents > 0:+ ref_kwargs = {+ "num_ref_latents": num_ref_latents,+ "ref_img_index": ref_img_index,+ "mask_frame_range": mask_frame_range,+ }++ with tqdm(total=len(timesteps), desc="Denoising") as progress_bar:+ for i, t in enumerate(timesteps):+ if self._interrupt:+ return None+ def _aborted(outputs):+ if outputs is None:+ return True+ if isinstance(outputs, (list, tuple)):+ return any(item is None for item in outputs)+ return outputs is None++ timestep = t.expand(latents.shape[0]).to(self.dtype)+ if num_cond_latents > 0:+ timestep = timestep[:, None].expand(-1, latents.shape[2]).clone()+ timestep[:, :num_cond_latents] = 0++ if self.is_avatar and audio_emb is not None and any_guidance:+ audio_cond = audio_emb.to(self.device, dtype=self.dtype)+ audio_uncond = torch.zeros_like(audio_cond)+ x_list = [latents, latents, latents]+ ctx_list = [prompt_embeds, neg_embeds, neg_embeds]+ mask_list = [prompt_mask, neg_mask, neg_mask]+ audio_list = [audio_cond, audio_cond, audio_uncond]+ ref_list = [ref_target_masks, ref_target_masks, ref_target_masks]+ if joint_pass:+ outputs = self.transformer(+ hidden_states=x_list,+ timestep=[timestep] * len(x_list),+ encoder_hidden_states=ctx_list,+ encoder_attention_mask=mask_list,+ num_cond_latents=[num_cond_latents] * len(x_list),+ audio_embs=audio_list,+ ref_target_masks=ref_list,+ **ref_kwargs,+ )+ if _aborted(outputs):+ return None+ else:+ outputs = []+ for x_i, ctx_i, mask_i, audio_i, ref_i in zip(+ x_list, ctx_list, mask_list, audio_list, ref_list+ ):+ output = self.transformer(+ hidden_states=x_i,+ timestep=timestep,+ encoder_hidden_states=ctx_i,+ encoder_attention_mask=mask_i,+ num_cond_latents=num_cond_latents,+ audio_embs=audio_i,+ ref_target_masks=ref_i,+ **ref_kwargs,+ )+ if _aborted(output):+ return None+ outputs.append(output)+ noise_pred_cond, noise_pred_uncond_text, noise_pred_uncond = outputs+ noise_pred = (+ noise_pred_uncond+ + guide_scale * (noise_pred_cond - noise_pred_uncond_text)+ + audio_cfg_scale * (noise_pred_uncond_text - noise_pred_uncond)+ )+ elif any_guidance:+ x_list = [latents, latents]+ ctx_list = [prompt_embeds, neg_embeds]+ mask_list = [prompt_mask, neg_mask]+ if joint_pass:+ outputs = self.transformer(+ hidden_states=x_list,+ timestep=[timestep] * len(x_list),+ encoder_hidden_states=ctx_list,+ encoder_attention_mask=mask_list,+ num_cond_latents=[num_cond_latents] * len(x_list),+ **ref_kwargs,+ )+ if _aborted(outputs):+ return None+ else:+ outputs = []+ for x_i, ctx_i, mask_i in zip(x_list, ctx_list, mask_list):+ output = self.transformer(+ hidden_states=x_i,+ timestep=timestep,+ encoder_hidden_states=ctx_i,+ encoder_attention_mask=mask_i,+ num_cond_latents=num_cond_latents,+ **ref_kwargs,+ )+ if _aborted(output):+ return None+ outputs.append(output)+ noise_pred_cond, noise_pred_uncond = outputs+ if cfg_star_switch:+ positive_flat = noise_pred_cond.view(latents.shape[0], -1)+ negative_flat = noise_pred_uncond.view(latents.shape[0], -1)+ st_star = optimized_scale(positive_flat, negative_flat).view(latents.shape[0], 1, 1, 1)+ if cfg_zero_step >= 0 and i <= cfg_zero_step:+ noise_pred = noise_pred_cond * 0.0+ else:+ noise_pred_uncond = noise_pred_uncond * st_star+ noise_pred = noise_pred_uncond + guide_scale * (noise_pred_cond - noise_pred_uncond)+ else:+ noise_pred = noise_pred_uncond + guide_scale * (noise_pred_cond - noise_pred_uncond)+ else:+ noise_pred = self.transformer(+ hidden_states=latents,+ timestep=timestep,+ encoder_hidden_states=prompt_embeds,+ encoder_attention_mask=prompt_mask,+ num_cond_latents=num_cond_latents,+ audio_embs=audio_emb if self.is_avatar else None,+ ref_target_masks=ref_target_masks if self.is_avatar else None,+ **ref_kwargs,+ )+ if _aborted(noise_pred):+ return None++ noise_pred = -noise_pred++ if num_cond_latents > 0:+ latents[:, :, num_cond_latents:] = self.scheduler.step(+ noise_pred[:, :, num_cond_latents:],+ t,+ latents[:, :, num_cond_latents:],+ return_dict=False,+ )[0]+ else:+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]++ if callback is not None:+ callback(i, latents.squeeze(0))+ progress_bar.update()++ if num_ref_latents > 0:+ latents = latents[:, :, num_ref_latents:]+ num_cond_latents -= num_ref_latents++ latent_slice = None+ return_latent_slice = kwargs.get("return_latent_slice")+ if return_latent_slice is not None:+ latent_slice = latents[:, :, return_latent_slice].detach().to("cpu")++ latents = latents.to(self.vae.dtype)+ latents = self.denormalize_latents(latents)+ video = self.vae.decode(latents, return_dict=False)[0].clamp(-1, 1)+ if video.dim() == 5:+ video = video[0]++ if latent_slice is not None:+ return {"x": video, "latent_slice": latent_slice}+ return videodiff --git a/models/longcat/modules/__init__.py b/models/longcat/modules/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/models/longcat/modules/attention.py b/models/longcat/modules/attention.pynew file mode 100644index 0000000..54639c0--- /dev/null+++ b/models/longcat/modules/attention.py@@ -0,0 +1,248 @@+from typing import List, Optional++import torch+import torch.nn as nn++from shared.attention import pay_attention, pay_sparse_attention+from .rope_3d import RotaryPositionalEmbedding+from .blocks import RMSNorm_FP32+++def _run_attention(x_list, out_dtype, **attn_kwargs):+ q, k, v = x_list+ if out_dtype in (torch.float16, torch.bfloat16):+ attn_dtype = out_dtype+ else:+ attn_dtype = torch.bfloat16+ if q.dtype != attn_dtype:+ q = q.to(attn_dtype)+ k = k.to(attn_dtype)+ v = v.to(attn_dtype)+ x_list[:] = [q, k, v]+ x = pay_attention(x_list, **attn_kwargs)+ x_list[:] = []+ if x.dtype != out_dtype:+ x = x.to(out_dtype)+ return x+++def _run_sparse_attention(x_list, out_dtype, shape, bsa_params, **attn_kwargs):+ q, k, v = x_list+ if out_dtype in (torch.float16, torch.bfloat16):+ attn_dtype = out_dtype+ else:+ attn_dtype = torch.bfloat16+ if q.dtype != attn_dtype:+ q = q.to(attn_dtype)+ k = k.to(attn_dtype)+ v = v.to(attn_dtype)+ x_list[:] = [q, k, v]+ x = pay_sparse_attention(x_list, shape=shape, bsa_params=bsa_params, **attn_kwargs)+ x_list[:] = []+ if x.dtype != out_dtype:+ x = x.to(out_dtype)+ return x+++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+ )++ def _process_attn(self, q, k, v, shape, out_dtype):+ """+ function wrapper to do attention with q, k, v+ """+ if self.enable_bsa:+ return _run_sparse_attention([q, k, v], out_dtype, shape, self.bsa_params)+ return _run_attention([q, k, v], out_dtype)++ def forward(self, x: torch.Tensor, shape=None, num_cond_latents=None, return_kv=False) -> torch.Tensor:+ """+ """+ B, N, C = x.shape+ out_dtype = x.dtype+ qkv = self.qkv(x)+ if qkv.dtype != out_dtype:+ qkv = qkv.to(out_dtype)++ qkv_shape = (B, N, 3, self.num_heads, self.head_dim)+ qkv = qkv.view(qkv_shape)+ q, k, v = qkv.unbind(2)+ 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)++ # cond mode+ if num_cond_latents is not None and num_cond_latents > 0:+ num_cond_latents_thw = num_cond_latents * (N // shape[0])+ # 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, out_dtype)+ # process the noise tokens+ q_noise = q[:, num_cond_latents_thw:].contiguous()+ x_noise = self._process_attn(q_noise, k, v, shape, out_dtype)+ # merge x_cond and x_noise+ x = torch.cat([x_cond, x_noise], dim=1).contiguous()+ else:+ x = self._process_attn(q, k, v, shape, out_dtype)++ x_output_shape = (B, N, C)+ x = x.reshape(x_output_shape)+ x = self.proj(x)++ if return_kv:+ return x, (k_cache, v_cache)+ else:+ return x++ def forward_with_kv_cache(self, x: torch.Tensor, shape=None, num_cond_latents=None, kv_cache=None) -> torch.Tensor:+ """+ """+ B, N, C = x.shape+ out_dtype = x.dtype+ qkv = self.qkv(x)+ if qkv.dtype != out_dtype:+ qkv = qkv.to(out_dtype)++ qkv_shape = (B, N, 3, self.num_heads, self.head_dim)+ qkv = qkv.view(qkv_shape)+ q, k, v = qkv.unbind(2)+ q, k = self.q_norm(q), self.k_norm(k)++ T, H, W = shape+ k_cache, v_cache = kv_cache+ if k_cache.shape[0] == 1 and B > 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=1).contiguous()+ v_full = torch.cat([v_cache, v], dim=1).contiguous()+ q_padding = torch.cat([torch.empty_like(k_cache), q], dim=1).contiguous()+ q_padding, k_full = self.rope_3d(q_padding, k_full, (T + num_cond_latents, H, W))+ q = q_padding[:, -N:].contiguous()+ else:+ k_full = k+ v_full = v++ x = self._process_attn(q, k_full, v_full, shape, out_dtype)++ x_output_shape = (B, N, C)+ x = x.reshape(x_output_shape)+ x = self.proj(x)++ return x+++class MultiHeadCrossAttention(nn.Module):+ def __init__(+ self,+ dim,+ num_heads,+ enable_flashattn3=False,+ enable_flashattn2=False,+ enable_xformers=False,+ ):+ super(MultiHeadCrossAttention, self).__init__()+ assert dim % num_heads == 0, "d_model must be divisible by num_heads"++ self.dim = dim+ self.num_heads = num_heads+ self.head_dim = dim // num_heads++ self.q_linear = nn.Linear(dim, dim)+ self.kv_linear = nn.Linear(dim, dim * 2)+ self.proj = nn.Linear(dim, dim)++ self.q_norm = RMSNorm_FP32(self.head_dim, eps=1e-6)+ self.k_norm = RMSNorm_FP32(self.head_dim, eps=1e-6)++ self.enable_flashattn3 = enable_flashattn3+ self.enable_flashattn2 = enable_flashattn2+ self.enable_xformers = enable_xformers++ def _process_cross_attn(self, x, cond, kv_seqlen):+ B, N, C = x.shape+ assert C == self.dim and cond.shape[2] == self.dim+ out_dtype = x.dtype++ q = self.q_linear(x).view(B, N, self.num_heads, self.head_dim)+ if q.dtype != out_dtype:+ q = q.to(out_dtype)+ kv = self.kv_linear(cond).view(B, -1, 2, self.num_heads, self.head_dim)+ if kv.dtype != out_dtype:+ kv = kv.to(out_dtype)+ k, v = kv.unbind(2)++ q, k = self.q_norm(q), self.k_norm(k)++ k_lens = kv_seqlen+ if k_lens is not None:+ if isinstance(k_lens, torch.Tensor):+ k_lens = k_lens.tolist() if B > 1 else k_lens.to(q.device)+ elif isinstance(k_lens, list) and B == 1:+ k_lens = torch.tensor(k_lens, device=q.device)++ x = _run_attention([q, k, v], out_dtype, k_lens=k_lens, cross_attn=True)+ x = x.view(B, N, C)+ x = self.proj(x)+ return x++ def forward(self, x, cond, kv_seqlen, num_cond_latents=None, shape=None):+ """+ x: [B, N, C]+ cond: [B, M, C]+ """+ if num_cond_latents is None or num_cond_latents == 0:+ return self._process_cross_attn(x, cond, kv_seqlen)+ else:+ B, N, C = x.shape+ if num_cond_latents is not None and num_cond_latents > 0:+ 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:] # [B, N_noise, C]+ output_noise = self._process_cross_attn(x_noise, cond, kv_seqlen) # [B, N_noise, C]+ output = torch.cat([+ torch.zeros((B, num_cond_latents_thw, C), dtype=output_noise.dtype, device=output_noise.device),+ output_noise+ ], dim=1).contiguous()+ else:+ raise NotImplementedError++ return outputdiff --git a/models/longcat/modules/autoencoder_kl_wan.py b/models/longcat/modules/autoencoder_kl_wan.pynew file mode 100644index 0000000..4e87863--- /dev/null+++ b/models/longcat/modules/autoencoder_kl_wan.py@@ -0,0 +1,1440 @@+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++from typing import List, Optional, Tuple, Union++import torch+import torch.nn as nn+import torch.nn.functional as F+import torch.utils.checkpoint++from diffusers.configuration_utils import ConfigMixin, register_to_config+from diffusers.loaders import FromOriginalModelMixin+from diffusers.utils import logging+from diffusers.utils.accelerate_utils import apply_forward_hook+from diffusers.models.activations import get_activation+from diffusers.models.modeling_outputs import AutoencoderKLOutput+from diffusers.models.modeling_utils import ModelMixin+from diffusers.models.autoencoders.vae import DecoderOutput, DiagonalGaussianDistribution+++logger = logging.get_logger(__name__) # pylint: disable=invalid-name++CACHE_T = 2+++class AvgDown3D(nn.Module):+ def __init__(+ self,+ in_channels,+ out_channels,+ factor_t,+ factor_s=1,+ ):+ super().__init__()+ self.in_channels = in_channels+ self.out_channels = out_channels+ self.factor_t = factor_t+ self.factor_s = factor_s+ self.factor = self.factor_t * self.factor_s * self.factor_s++ assert in_channels * self.factor % out_channels == 0+ self.group_size = in_channels * self.factor // out_channels++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t+ pad = (0, 0, 0, 0, pad_t, 0)+ x = F.pad(x, pad)+ B, C, T, H, W = x.shape+ x = x.view(+ B,+ C,+ T // self.factor_t,+ self.factor_t,+ H // self.factor_s,+ self.factor_s,+ W // self.factor_s,+ self.factor_s,+ )+ x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous()+ x = x.view(+ B,+ C * self.factor,+ T // self.factor_t,+ H // self.factor_s,+ W // self.factor_s,+ )+ x = x.view(+ B,+ self.out_channels,+ self.group_size,+ T // self.factor_t,+ H // self.factor_s,+ W // self.factor_s,+ )+ x = x.mean(dim=2)+ return x+++class DupUp3D(nn.Module):+ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ factor_t,+ factor_s=1,+ ):+ super().__init__()+ self.in_channels = in_channels+ self.out_channels = out_channels++ self.factor_t = factor_t+ self.factor_s = factor_s+ self.factor = self.factor_t * self.factor_s * self.factor_s++ assert out_channels * self.factor % in_channels == 0+ self.repeats = out_channels * self.factor // in_channels++ def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:+ x = x.repeat_interleave(self.repeats, dim=1)+ x = x.view(+ x.size(0),+ self.out_channels,+ self.factor_t,+ self.factor_s,+ self.factor_s,+ x.size(2),+ x.size(3),+ x.size(4),+ )+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()+ x = x.view(+ x.size(0),+ self.out_channels,+ x.size(2) * self.factor_t,+ x.size(4) * self.factor_s,+ x.size(6) * self.factor_s,+ )+ if first_chunk:+ x = x[:, :, self.factor_t - 1 :, :, :]+ return x+++class WanCausalConv3d(nn.Conv3d):+ r"""+ A custom 3D causal convolution layer with feature caching support.++ This layer extends the standard Conv3D layer by ensuring causality in the time dimension and handling feature+ caching for efficient inference.++ Args:+ in_channels (int): Number of channels in the input image+ out_channels (int): Number of channels produced by the convolution+ kernel_size (int or tuple): Size of the convolving kernel+ stride (int or tuple, optional): Stride of the convolution. Default: 1+ padding (int or tuple, optional): Zero-padding added to all three sides of the input. Default: 0+ """++ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ kernel_size: Union[int, Tuple[int, int, int]],+ stride: Union[int, Tuple[int, int, int]] = 1,+ padding: Union[int, Tuple[int, int, int]] = 0,+ ) -> None:+ super().__init__(+ in_channels=in_channels,+ out_channels=out_channels,+ kernel_size=kernel_size,+ stride=stride,+ padding=padding,+ )++ # Set up causal padding+ self._padding = (self.padding[2], self.padding[2], self.padding[1], self.padding[1], 2 * self.padding[0], 0)+ self.padding = (0, 0, 0)++ def forward(self, x, cache_x=None):+ padding = list(self._padding)+ if cache_x is not None and self._padding[4] > 0:+ cache_x = cache_x.to(x.device)+ x = torch.cat([cache_x, x], dim=2)+ padding[4] -= cache_x.shape[2]+ x = F.pad(x, padding)+ return super().forward(x)+++class WanRMS_norm(nn.Module):+ r"""+ A custom RMS normalization layer.++ Args:+ dim (int): The number of dimensions to normalize over.+ channel_first (bool, optional): Whether the input tensor has channels as the first dimension.+ Default is True.+ images (bool, optional): Whether the input represents image data. Default is True.+ bias (bool, optional): Whether to include a learnable bias term. Default is False.+ """++ def __init__(self, dim: int, channel_first: bool = True, images: bool = True, bias: bool = False) -> None:+ super().__init__()+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)++ self.channel_first = channel_first+ self.scale = dim**0.5+ self.gamma = nn.Parameter(torch.ones(shape))+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.0++ def forward(self, x):+ return F.normalize(x, dim=(1 if self.channel_first else -1)) * self.scale * self.gamma + self.bias+++class WanUpsample(nn.Upsample):+ r"""+ Perform upsampling while ensuring the output tensor has the same data type as the input.++ Args:+ x (torch.Tensor): Input tensor to be upsampled.++ Returns:+ torch.Tensor: Upsampled tensor with the same data type as the input.+ """++ def forward(self, x):+ return super().forward(x.float()).type_as(x)+++class WanResample(nn.Module):+ r"""+ A custom resampling module for 2D and 3D data.++ Args:+ dim (int): The number of input/output channels.+ mode (str): The resampling mode. Must be one of:+ - 'none': No resampling (identity operation).+ - 'upsample2d': 2D upsampling with nearest-exact interpolation and convolution.+ - 'upsample3d': 3D upsampling with nearest-exact interpolation, convolution, and causal 3D convolution.+ - 'downsample2d': 2D downsampling with zero-padding and convolution.+ - 'downsample3d': 3D downsampling with zero-padding, convolution, and causal 3D convolution.+ """++ def __init__(self, dim: int, mode: str, upsample_out_dim: int = None) -> None:+ super().__init__()+ self.dim = dim+ self.mode = mode++ # default to dim //2+ if upsample_out_dim is None:+ upsample_out_dim = dim // 2++ # layers+ if mode == "upsample2d":+ self.resample = nn.Sequential(+ WanUpsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),+ nn.Conv2d(dim, upsample_out_dim, 3, padding=1),+ )+ elif mode == "upsample3d":+ self.resample = nn.Sequential(+ WanUpsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),+ nn.Conv2d(dim, upsample_out_dim, 3, padding=1),+ )+ self.time_conv = WanCausalConv3d(dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))++ elif mode == "downsample2d":+ self.resample = nn.Sequential(nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2)))+ elif mode == "downsample3d":+ self.resample = nn.Sequential(nn.ZeroPad2d((0, 1, 0, 1)), nn.Conv2d(dim, dim, 3, stride=(2, 2)))+ self.time_conv = WanCausalConv3d(dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0))++ else:+ self.resample = nn.Identity()++ def forward(self, x, feat_cache=None, feat_idx=[0]):+ b, c, t, h, w = x.size()+ if self.mode == "upsample3d":+ if feat_cache is not None:+ idx = feat_idx[0]+ if feat_cache[idx] is None:+ feat_cache[idx] = "Rep"+ feat_idx[0] += 1+ else:+ cache_x = x[:, :, -CACHE_T:, :, :].clone()+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None and feat_cache[idx] != "Rep":+ # cache last frame of last two chunk+ cache_x = torch.cat(+ [feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2+ )+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None and feat_cache[idx] == "Rep":+ cache_x = torch.cat([torch.zeros_like(cache_x).to(cache_x.device), cache_x], dim=2)+ if feat_cache[idx] == "Rep":+ x = self.time_conv(x)+ else:+ x = self.time_conv(x, feat_cache[idx])+ feat_cache[idx] = cache_x+ feat_idx[0] += 1++ x = x.reshape(b, 2, c, t, h, w)+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]), 3)+ x = x.reshape(b, c, t * 2, h, w)+ t = x.shape[2]+ x = x.permute(0, 2, 1, 3, 4).reshape(b * t, c, h, w)+ x = self.resample(x)+ x = x.view(b, t, x.size(1), x.size(2), x.size(3)).permute(0, 2, 1, 3, 4)++ if self.mode == "downsample3d":+ if feat_cache is not None:+ idx = feat_idx[0]+ if feat_cache[idx] is None:+ feat_cache[idx] = x.clone()+ feat_idx[0] += 1+ else:+ cache_x = x[:, :, -1:, :, :].clone()+ x = self.time_conv(torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))+ feat_cache[idx] = cache_x+ feat_idx[0] += 1+ return x+++class WanResidualBlock(nn.Module):+ r"""+ A custom residual block module.++ Args:+ in_dim (int): Number of input channels.+ out_dim (int): Number of output channels.+ dropout (float, optional): Dropout rate for the dropout layer. Default is 0.0.+ non_linearity (str, optional): Type of non-linearity to use. Default is "silu".+ """++ def __init__(+ self,+ in_dim: int,+ out_dim: int,+ dropout: float = 0.0,+ non_linearity: str = "silu",+ ) -> None:+ super().__init__()+ self.in_dim = in_dim+ self.out_dim = out_dim+ self.nonlinearity = get_activation(non_linearity)++ # layers+ self.norm1 = WanRMS_norm(in_dim, images=False)+ self.conv1 = WanCausalConv3d(in_dim, out_dim, 3, padding=1)+ self.norm2 = WanRMS_norm(out_dim, images=False)+ self.dropout = nn.Dropout(dropout)+ self.conv2 = WanCausalConv3d(out_dim, out_dim, 3, padding=1)+ self.conv_shortcut = WanCausalConv3d(in_dim, out_dim, 1) if in_dim != out_dim else nn.Identity()++ def forward(self, x, feat_cache=None, feat_idx=[0]):+ # Apply shortcut connection+ h = self.conv_shortcut(x)++ # First normalization and activation+ x = self.norm1(x)+ x = self.nonlinearity(x)++ if feat_cache is not None:+ idx = feat_idx[0]+ cache_x = x[:, :, -CACHE_T:, :, :].clone()+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:+ cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2)++ x = self.conv1(x, feat_cache[idx])+ feat_cache[idx] = cache_x+ feat_idx[0] += 1+ else:+ x = self.conv1(x)++ # Second normalization and activation+ x = self.norm2(x)+ x = self.nonlinearity(x)++ # Dropout+ x = self.dropout(x)++ if feat_cache is not None:+ idx = feat_idx[0]+ cache_x = x[:, :, -CACHE_T:, :, :].clone()+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:+ cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2)++ x = self.conv2(x, feat_cache[idx])+ feat_cache[idx] = cache_x+ feat_idx[0] += 1+ else:+ x = self.conv2(x)++ # Add residual connection+ return x + h+++class WanAttentionBlock(nn.Module):+ r"""+ Causal self-attention with a single head.++ Args:+ dim (int): The number of channels in the input tensor.+ """++ def __init__(self, dim):+ super().__init__()+ self.dim = dim++ # layers+ self.norm = WanRMS_norm(dim)+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)+ self.proj = nn.Conv2d(dim, dim, 1)++ def forward(self, x):+ identity = x+ batch_size, channels, time, height, width = x.size()++ x = x.permute(0, 2, 1, 3, 4).reshape(batch_size * time, channels, height, width)+ x = self.norm(x)++ # compute query, key, value+ qkv = self.to_qkv(x)+ qkv = qkv.reshape(batch_size * time, 1, channels * 3, -1)+ qkv = qkv.permute(0, 1, 3, 2).contiguous()+ q, k, v = qkv.chunk(3, dim=-1)++ # apply attention+ x = F.scaled_dot_product_attention(q, k, v)++ x = x.squeeze(1).permute(0, 2, 1).reshape(batch_size * time, channels, height, width)++ # output projection+ x = self.proj(x)++ # Reshape back: [(b*t), c, h, w] -> [b, c, t, h, w]+ x = x.view(batch_size, time, channels, height, width)+ x = x.permute(0, 2, 1, 3, 4)++ return x + identity+++class WanMidBlock(nn.Module):+ """+ Middle block for WanVAE encoder and decoder.++ Args:+ dim (int): Number of input/output channels.+ dropout (float): Dropout rate.+ non_linearity (str): Type of non-linearity to use.+ """++ def __init__(self, dim: int, dropout: float = 0.0, non_linearity: str = "silu", num_layers: int = 1):+ super().__init__()+ self.dim = dim++ # Create the components+ resnets = [WanResidualBlock(dim, dim, dropout, non_linearity)]+ attentions = []+ for _ in range(num_layers):+ attentions.append(WanAttentionBlock(dim))+ resnets.append(WanResidualBlock(dim, dim, dropout, non_linearity))+ self.attentions = nn.ModuleList(attentions)+ self.resnets = nn.ModuleList(resnets)++ self.gradient_checkpointing = False++ def forward(self, x, feat_cache=None, feat_idx=[0]):+ # First residual block+ x = self.resnets[0](x, feat_cache, feat_idx)++ # Process through attention and residual blocks+ for attn, resnet in zip(self.attentions, self.resnets[1:]):+ if attn is not None:+ x = attn(x)++ x = resnet(x, feat_cache, feat_idx)++ return x+++class WanResidualDownBlock(nn.Module):+ def __init__(self, in_dim, out_dim, dropout, num_res_blocks, temperal_downsample=False, down_flag=False):+ super().__init__()++ # Shortcut path with downsample+ self.avg_shortcut = AvgDown3D(+ in_dim,+ out_dim,+ factor_t=2 if temperal_downsample else 1,+ factor_s=2 if down_flag else 1,+ )++ # Main path with residual blocks and downsample+ resnets = []+ for _ in range(num_res_blocks):+ resnets.append(WanResidualBlock(in_dim, out_dim, dropout))+ in_dim = out_dim+ self.resnets = nn.ModuleList(resnets)++ # Add the final downsample block+ if down_flag:+ mode = "downsample3d" if temperal_downsample else "downsample2d"+ self.downsampler = WanResample(out_dim, mode=mode)+ else:+ self.downsampler = None++ def forward(self, x, feat_cache=None, feat_idx=[0]):+ x_copy = x.clone()+ for resnet in self.resnets:+ x = resnet(x, feat_cache, feat_idx)+ if self.downsampler is not None:+ x = self.downsampler(x, feat_cache, feat_idx)++ return x + self.avg_shortcut(x_copy)+++class WanEncoder3d(nn.Module):+ r"""+ A 3D encoder module.++ Args:+ dim (int): The base number of channels in the first layer.+ z_dim (int): The dimensionality of the latent space.+ dim_mult (list of int): Multipliers for the number of channels in each block.+ num_res_blocks (int): Number of residual blocks in each block.+ attn_scales (list of float): Scales at which to apply attention mechanisms.+ temperal_downsample (list of bool): Whether to downsample temporally in each block.+ dropout (float): Dropout rate for the dropout layers.+ non_linearity (str): Type of non-linearity to use.+ """++ def __init__(+ self,+ in_channels: int = 3,+ dim=128,+ z_dim=4,+ dim_mult=[1, 2, 4, 4],+ num_res_blocks=2,+ attn_scales=[],+ temperal_downsample=[True, True, False],+ dropout=0.0,+ non_linearity: str = "silu",+ is_residual: bool = False, # wan 2.2 vae use a residual downblock+ ):+ super().__init__()+ self.dim = dim+ self.z_dim = z_dim+ self.dim_mult = dim_mult+ self.num_res_blocks = num_res_blocks+ self.attn_scales = attn_scales+ self.temperal_downsample = temperal_downsample+ self.nonlinearity = get_activation(non_linearity)++ # dimensions+ dims = [dim * u for u in [1] + dim_mult]+ scale = 1.0++ # init block+ self.conv_in = WanCausalConv3d(in_channels, dims[0], 3, padding=1)++ # downsample blocks+ self.down_blocks = nn.ModuleList([])+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):+ # residual (+attention) blocks+ if is_residual:+ self.down_blocks.append(+ WanResidualDownBlock(+ in_dim,+ out_dim,+ dropout,+ num_res_blocks,+ temperal_downsample=temperal_downsample[i] if i != len(dim_mult) - 1 else False,+ down_flag=i != len(dim_mult) - 1,+ )+ )+ else:+ for _ in range(num_res_blocks):+ self.down_blocks.append(WanResidualBlock(in_dim, out_dim, dropout))+ if scale in attn_scales:+ self.down_blocks.append(WanAttentionBlock(out_dim))+ in_dim = out_dim++ # downsample block+ if i != len(dim_mult) - 1:+ mode = "downsample3d" if temperal_downsample[i] else "downsample2d"+ self.down_blocks.append(WanResample(out_dim, mode=mode))+ scale /= 2.0++ # middle blocks+ self.mid_block = WanMidBlock(out_dim, dropout, non_linearity, num_layers=1)++ # output blocks+ self.norm_out = WanRMS_norm(out_dim, images=False)+ self.conv_out = WanCausalConv3d(out_dim, z_dim, 3, padding=1)++ self.gradient_checkpointing = False++ def forward(self, x, feat_cache=None, feat_idx=[0]):+ if feat_cache is not None:+ idx = feat_idx[0]+ cache_x = x[:, :, -CACHE_T:, :, :].clone()+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:+ # cache last frame of last two chunk+ cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2)+ x = self.conv_in(x, feat_cache[idx])+ feat_cache[idx] = cache_x+ feat_idx[0] += 1+ else:+ x = self.conv_in(x)++ ## downsamples+ for layer in self.down_blocks:+ if feat_cache is not None:+ x = layer(x, feat_cache, feat_idx)+ else:+ x = layer(x)++ ## middle+ x = self.mid_block(x, feat_cache, feat_idx)++ ## head+ x = self.norm_out(x)+ x = self.nonlinearity(x)+ if feat_cache is not None:+ idx = feat_idx[0]+ cache_x = x[:, :, -CACHE_T:, :, :].clone()+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:+ # cache last frame of last two chunk+ cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2)+ x = self.conv_out(x, feat_cache[idx])+ feat_cache[idx] = cache_x+ feat_idx[0] += 1+ else:+ x = self.conv_out(x)+ return x+++class WanResidualUpBlock(nn.Module):+ """+ A block that handles upsampling for the WanVAE decoder.++ Args:+ in_dim (int): Input dimension+ out_dim (int): Output dimension+ num_res_blocks (int): Number of residual blocks+ dropout (float): Dropout rate+ temperal_upsample (bool): Whether to upsample on temporal dimension+ up_flag (bool): Whether to upsample or not+ non_linearity (str): Type of non-linearity to use+ """++ def __init__(+ self,+ in_dim: int,+ out_dim: int,+ num_res_blocks: int,+ dropout: float = 0.0,+ temperal_upsample: bool = False,+ up_flag: bool = False,+ non_linearity: str = "silu",+ ):+ super().__init__()+ self.in_dim = in_dim+ self.out_dim = out_dim++ if up_flag:+ self.avg_shortcut = DupUp3D(+ in_dim,+ out_dim,+ factor_t=2 if temperal_upsample else 1,+ factor_s=2,+ )+ else:+ self.avg_shortcut = None++ # create residual blocks+ resnets = []+ current_dim = in_dim+ for _ in range(num_res_blocks + 1):+ resnets.append(WanResidualBlock(current_dim, out_dim, dropout, non_linearity))+ current_dim = out_dim++ self.resnets = nn.ModuleList(resnets)++ # Add upsampling layer if needed+ if up_flag:+ upsample_mode = "upsample3d" if temperal_upsample else "upsample2d"+ self.upsampler = WanResample(out_dim, mode=upsample_mode, upsample_out_dim=out_dim)+ else:+ self.upsampler = None++ self.gradient_checkpointing = False++ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):+ """+ Forward pass through the upsampling block.++ Args:+ x (torch.Tensor): Input tensor+ feat_cache (list, optional): Feature cache for causal convolutions+ feat_idx (list, optional): Feature index for cache management++ Returns:+ torch.Tensor: Output tensor+ """+ x_copy = x.clone()++ for resnet in self.resnets:+ if feat_cache is not None:+ x = resnet(x, feat_cache, feat_idx)+ else:+ x = resnet(x)++ if self.upsampler is not None:+ if feat_cache is not None:+ x = self.upsampler(x, feat_cache, feat_idx)+ else:+ x = self.upsampler(x)++ if self.avg_shortcut is not None:+ x = x + self.avg_shortcut(x_copy, first_chunk=first_chunk)++ return x+++class WanUpBlock(nn.Module):+ """+ A block that handles upsampling for the WanVAE decoder.++ Args:+ in_dim (int): Input dimension+ out_dim (int): Output dimension+ num_res_blocks (int): Number of residual blocks+ dropout (float): Dropout rate+ upsample_mode (str, optional): Mode for upsampling ('upsample2d' or 'upsample3d')+ non_linearity (str): Type of non-linearity to use+ """++ def __init__(+ self,+ in_dim: int,+ out_dim: int,+ num_res_blocks: int,+ dropout: float = 0.0,+ upsample_mode: Optional[str] = None,+ non_linearity: str = "silu",+ ):+ super().__init__()+ self.in_dim = in_dim+ self.out_dim = out_dim++ # Create layers list+ resnets = []+ # Add residual blocks and attention if needed+ current_dim = in_dim+ for _ in range(num_res_blocks + 1):+ resnets.append(WanResidualBlock(current_dim, out_dim, dropout, non_linearity))+ current_dim = out_dim++ self.resnets = nn.ModuleList(resnets)++ # Add upsampling layer if needed+ self.upsamplers = None+ if upsample_mode is not None:+ self.upsamplers = nn.ModuleList([WanResample(out_dim, mode=upsample_mode)])++ self.gradient_checkpointing = False++ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=None):+ """+ Forward pass through the upsampling block.++ Args:+ x (torch.Tensor): Input tensor+ feat_cache (list, optional): Feature cache for causal convolutions+ feat_idx (list, optional): Feature index for cache management++ Returns:+ torch.Tensor: Output tensor+ """+ for resnet in self.resnets:+ if feat_cache is not None:+ x = resnet(x, feat_cache, feat_idx)+ else:+ x = resnet(x)++ if self.upsamplers is not None:+ if feat_cache is not None:+ x = self.upsamplers[0](x, feat_cache, feat_idx)+ else:+ x = self.upsamplers[0](x)+ return x+++class WanDecoder3d(nn.Module):+ r"""+ A 3D decoder module.++ Args:+ dim (int): The base number of channels in the first layer.+ z_dim (int): The dimensionality of the latent space.+ dim_mult (list of int): Multipliers for the number of channels in each block.+ num_res_blocks (int): Number of residual blocks in each block.+ attn_scales (list of float): Scales at which to apply attention mechanisms.+ temperal_upsample (list of bool): Whether to upsample temporally in each block.+ dropout (float): Dropout rate for the dropout layers.+ non_linearity (str): Type of non-linearity to use.+ """++ def __init__(+ self,+ dim=128,+ z_dim=4,+ dim_mult=[1, 2, 4, 4],+ num_res_blocks=2,+ attn_scales=[],+ temperal_upsample=[False, True, True],+ dropout=0.0,+ non_linearity: str = "silu",+ out_channels: int = 3,+ is_residual: bool = False,+ ):+ super().__init__()+ self.dim = dim+ self.z_dim = z_dim+ self.dim_mult = dim_mult+ self.num_res_blocks = num_res_blocks+ self.attn_scales = attn_scales+ self.temperal_upsample = temperal_upsample++ self.nonlinearity = get_activation(non_linearity)++ # dimensions+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]++ # init block+ self.conv_in = WanCausalConv3d(z_dim, dims[0], 3, padding=1)++ # middle blocks+ self.mid_block = WanMidBlock(dims[0], dropout, non_linearity, num_layers=1)++ # upsample blocks+ self.up_blocks = nn.ModuleList([])+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):+ # residual (+attention) blocks+ if i > 0 and not is_residual:+ # wan vae 2.1+ in_dim = in_dim // 2++ # determine if we need upsampling+ up_flag = i != len(dim_mult) - 1+ # determine upsampling mode, if not upsampling, set to None+ upsample_mode = None+ if up_flag and temperal_upsample[i]:+ upsample_mode = "upsample3d"+ elif up_flag:+ upsample_mode = "upsample2d"+ # Create and add the upsampling block+ if is_residual:+ up_block = WanResidualUpBlock(+ in_dim=in_dim,+ out_dim=out_dim,+ num_res_blocks=num_res_blocks,+ dropout=dropout,+ temperal_upsample=temperal_upsample[i] if up_flag else False,+ up_flag=up_flag,+ non_linearity=non_linearity,+ )+ else:+ up_block = WanUpBlock(+ in_dim=in_dim,+ out_dim=out_dim,+ num_res_blocks=num_res_blocks,+ dropout=dropout,+ upsample_mode=upsample_mode,+ non_linearity=non_linearity,+ )+ self.up_blocks.append(up_block)++ # output blocks+ self.norm_out = WanRMS_norm(out_dim, images=False)+ self.conv_out = WanCausalConv3d(out_dim, out_channels, 3, padding=1)++ self.gradient_checkpointing = False++ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):+ ## conv1+ if feat_cache is not None:+ idx = feat_idx[0]+ cache_x = x[:, :, -CACHE_T:, :, :].clone()+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:+ # cache last frame of last two chunk+ cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2)+ x = self.conv_in(x, feat_cache[idx])+ feat_cache[idx] = cache_x+ feat_idx[0] += 1+ else:+ x = self.conv_in(x)++ ## middle+ x = self.mid_block(x, feat_cache, feat_idx)++ ## upsamples+ for up_block in self.up_blocks:+ x = up_block(x, feat_cache, feat_idx, first_chunk=first_chunk)++ ## head+ x = self.norm_out(x)+ x = self.nonlinearity(x)+ if feat_cache is not None:+ idx = feat_idx[0]+ cache_x = x[:, :, -CACHE_T:, :, :].clone()+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:+ # cache last frame of last two chunk+ cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2)+ x = self.conv_out(x, feat_cache[idx])+ feat_cache[idx] = cache_x+ feat_idx[0] += 1+ else:+ x = self.conv_out(x)+ return x+++def patchify(x, patch_size):+ if patch_size == 1:+ return x++ if x.dim() != 5:+ raise ValueError(f"Invalid input shape: {x.shape}")+ # x shape: [batch_size, channels, frames, height, width]+ batch_size, channels, frames, height, width = x.shape++ # Ensure height and width are divisible by patch_size+ if height % patch_size != 0 or width % patch_size != 0:+ raise ValueError(f"Height ({height}) and width ({width}) must be divisible by patch_size ({patch_size})")++ # Reshape to [batch_size, channels, frames, height//patch_size, patch_size, width//patch_size, patch_size]+ x = x.view(batch_size, channels, frames, height // patch_size, patch_size, width // patch_size, patch_size)++ # Rearrange to [batch_size, channels * patch_size * patch_size, frames, height//patch_size, width//patch_size]+ x = x.permute(0, 1, 6, 4, 2, 3, 5).contiguous()+ x = x.view(batch_size, channels * patch_size * patch_size, frames, height // patch_size, width // patch_size)++ return x+++def unpatchify(x, patch_size):+ if patch_size == 1:+ return x++ if x.dim() != 5:+ raise ValueError(f"Invalid input shape: {x.shape}")+ # x shape: [batch_size, (channels * patch_size * patch_size), frame, height, width]+ batch_size, c_patches, frames, height, width = x.shape+ channels = c_patches // (patch_size * patch_size)++ # Reshape to [b, c, patch_size, patch_size, f, h, w]+ x = x.view(batch_size, channels, patch_size, patch_size, frames, height, width)++ # Rearrange to [b, c, f, h * patch_size, w * patch_size]+ x = x.permute(0, 1, 4, 5, 3, 6, 2).contiguous()+ x = x.view(batch_size, channels, frames, height * patch_size, width * patch_size)++ return x+++class AutoencoderKLWan(ModelMixin, ConfigMixin, FromOriginalModelMixin):+ r"""+ A VAE model with KL loss for encoding videos into latents and decoding latent representations into videos.+ Introduced in [Wan 2.1].++ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented+ for all models (such as downloading or saving).+ """++ _supports_gradient_checkpointing = False++ @register_to_config+ def __init__(+ self,+ base_dim: int = 96,+ decoder_base_dim: Optional[int] = None,+ z_dim: int = 16,+ dim_mult: Tuple[int] = [1, 2, 4, 4],+ num_res_blocks: int = 2,+ attn_scales: List[float] = [],+ temperal_downsample: List[bool] = [False, True, True],+ dropout: float = 0.0,+ latents_mean: List[float] = [+ -0.7571,+ -0.7089,+ -0.9113,+ 0.1075,+ -0.1745,+ 0.9653,+ -0.1517,+ 1.5508,+ 0.4134,+ -0.0715,+ 0.5517,+ -0.3632,+ -0.1922,+ -0.9497,+ 0.2503,+ -0.2921,+ ],+ latents_std: List[float] = [+ 2.8184,+ 1.4541,+ 2.3275,+ 2.6558,+ 1.2196,+ 1.7708,+ 2.6052,+ 2.0743,+ 3.2687,+ 2.1526,+ 2.8652,+ 1.5579,+ 1.6382,+ 1.1253,+ 2.8251,+ 1.9160,+ ],+ is_residual: bool = False,+ in_channels: int = 3,+ out_channels: int = 3,+ patch_size: Optional[int] = None,+ scale_factor_temporal: Optional[int] = 4,+ scale_factor_spatial: Optional[int] = 8,+ ) -> None:+ super().__init__()++ self.z_dim = z_dim+ self.temperal_downsample = temperal_downsample+ self.temperal_upsample = temperal_downsample[::-1]++ if decoder_base_dim is None:+ decoder_base_dim = base_dim++ self.encoder = WanEncoder3d(+ in_channels=in_channels,+ dim=base_dim,+ z_dim=z_dim * 2,+ dim_mult=dim_mult,+ num_res_blocks=num_res_blocks,+ attn_scales=attn_scales,+ temperal_downsample=temperal_downsample,+ dropout=dropout,+ is_residual=is_residual,+ )+ self.quant_conv = WanCausalConv3d(z_dim * 2, z_dim * 2, 1)+ self.post_quant_conv = WanCausalConv3d(z_dim, z_dim, 1)++ self.decoder = WanDecoder3d(+ dim=decoder_base_dim,+ z_dim=z_dim,+ dim_mult=dim_mult,+ num_res_blocks=num_res_blocks,+ attn_scales=attn_scales,+ temperal_upsample=self.temperal_upsample,+ dropout=dropout,+ out_channels=out_channels,+ is_residual=is_residual,+ )++ self.spatial_compression_ratio = scale_factor_spatial++ # When decoding a batch of video latents at a time, one can save memory by slicing across the batch dimension+ # to perform decoding of a single video latent at a time.+ self.use_slicing = False++ # When decoding spatially large video latents, the memory requirement is very high. By breaking the video latent+ # frames spatially into smaller tiles and performing multiple forward passes for decoding, and then blending the+ # intermediate tiles together, the memory requirement can be lowered.+ self.use_tiling = False++ # The minimal tile height and width for spatial tiling to be used+ self.tile_sample_min_height = 256+ self.tile_sample_min_width = 256++ # The minimal distance between two spatial tiles+ self.tile_sample_stride_height = 192+ self.tile_sample_stride_width = 192++ # Precompute and cache conv counts for encoder and decoder for clear_cache speedup+ self._cached_conv_counts = {+ "decoder": sum(isinstance(m, WanCausalConv3d) for m in self.decoder.modules())+ if self.decoder is not None+ else 0,+ "encoder": sum(isinstance(m, WanCausalConv3d) for m in self.encoder.modules())+ if self.encoder is not None+ else 0,+ }++ @staticmethod+ def get_VAE_tile_size(vae_config, device_mem_capacity, mixed_precision):+ if vae_config == 0:+ if mixed_precision:+ device_mem_capacity = device_mem_capacity / 2+ if device_mem_capacity >= 24000:+ use_vae_config = 1+ elif device_mem_capacity >= 8000:+ use_vae_config = 2+ else:+ use_vae_config = 3+ else:+ use_vae_config = vae_config++ if use_vae_config == 1:+ return 0+ if use_vae_config == 2:+ return 256+ return 128++ def enable_tiling(+ self,+ tile_sample_min_height: Optional[int] = None,+ tile_sample_min_width: Optional[int] = None,+ tile_sample_stride_height: Optional[float] = None,+ tile_sample_stride_width: Optional[float] = None,+ ) -> None:+ r"""+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow+ processing larger images.++ Args:+ tile_sample_min_height (`int`, *optional*):+ The minimum height required for a sample to be separated into tiles across the height dimension.+ tile_sample_min_width (`int`, *optional*):+ The minimum width required for a sample to be separated into tiles across the width dimension.+ tile_sample_stride_height (`int`, *optional*):+ The minimum amount of overlap between two consecutive vertical tiles. This is to ensure that there are+ no tiling artifacts produced across the height dimension.+ tile_sample_stride_width (`int`, *optional*):+ The stride between two consecutive horizontal tiles. This is to ensure that there are no tiling+ artifacts produced across the width dimension.+ """+ self.use_tiling = True+ self.tile_sample_min_height = tile_sample_min_height or self.tile_sample_min_height+ self.tile_sample_min_width = tile_sample_min_width or self.tile_sample_min_width+ self.tile_sample_stride_height = tile_sample_stride_height or self.tile_sample_stride_height+ self.tile_sample_stride_width = tile_sample_stride_width or self.tile_sample_stride_width++ def disable_tiling(self) -> None:+ r"""+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing+ decoding in one step.+ """+ self.use_tiling = False++ def enable_slicing(self) -> None:+ r"""+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.+ """+ self.use_slicing = True++ def disable_slicing(self) -> None:+ r"""+ Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing+ decoding in one step.+ """+ self.use_slicing = False++ def clear_cache(self):+ # Use cached conv counts for decoder and encoder to avoid re-iterating modules each call+ self._conv_num = self._cached_conv_counts["decoder"]+ self._conv_idx = [0]+ self._feat_map = [None] * self._conv_num+ # cache encode+ self._enc_conv_num = self._cached_conv_counts["encoder"]+ self._enc_conv_idx = [0]+ self._enc_feat_map = [None] * self._enc_conv_num++ def _encode(self, x: torch.Tensor):+ _, _, num_frame, height, width = x.shape++ self.clear_cache()+ if self.config.patch_size is not None:+ x = patchify(x, patch_size=self.config.patch_size)++ if self.use_tiling and (width > self.tile_sample_min_width or height > self.tile_sample_min_height):+ return self.tiled_encode(x)++ iter_ = 1 + (num_frame - 1) // 4+ for i in range(iter_):+ self._enc_conv_idx = [0]+ if i == 0:+ out = self.encoder(x[:, :, :1, :, :], feat_cache=self._enc_feat_map, feat_idx=self._enc_conv_idx)+ else:+ out_ = self.encoder(+ x[:, :, 1 + 4 * (i - 1) : 1 + 4 * i, :, :],+ feat_cache=self._enc_feat_map,+ feat_idx=self._enc_conv_idx,+ )+ out = torch.cat([out, out_], 2)++ enc = self.quant_conv(out)+ self.clear_cache()+ return enc++ @apply_forward_hook+ def encode(+ self, x: torch.Tensor, return_dict: bool = True+ ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:+ r"""+ Encode a batch of images into latents.++ Args:+ x (`torch.Tensor`): Input batch of images.+ return_dict (`bool`, *optional*, defaults to `True`):+ Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.++ Returns:+ The latent representations of the encoded videos. If `return_dict` is True, a+ [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.+ """+ if self.use_slicing and x.shape[0] > 1:+ encoded_slices = [self._encode(x_slice) for x_slice in x.split(1)]+ h = torch.cat(encoded_slices)+ else:+ h = self._encode(x)+ posterior = DiagonalGaussianDistribution(h)++ if not return_dict:+ return (posterior,)+ return AutoencoderKLOutput(latent_dist=posterior)++ def _decode(self, z: torch.Tensor, return_dict: bool = True):+ _, _, num_frame, height, width = z.shape+ tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio+ tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio++ if self.use_tiling and (width > tile_latent_min_width or height > tile_latent_min_height):+ return self.tiled_decode(z, return_dict=return_dict)++ self.clear_cache()+ x = self.post_quant_conv(z)+ for i in range(num_frame):+ self._conv_idx = [0]+ if i == 0:+ out = self.decoder(+ x[:, :, i : i + 1, :, :], feat_cache=self._feat_map, feat_idx=self._conv_idx, first_chunk=True+ )+ else:+ out_ = self.decoder(x[:, :, i : i + 1, :, :], feat_cache=self._feat_map, feat_idx=self._conv_idx)+ out = torch.cat([out, out_], 2)++ if self.config.patch_size is not None:+ out = unpatchify(out, patch_size=self.config.patch_size)++ out = torch.clamp(out, min=-1.0, max=1.0)++ self.clear_cache()+ if not return_dict:+ return (out,)++ return DecoderOutput(sample=out)++ @apply_forward_hook+ def decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:+ r"""+ Decode a batch of images.++ Args:+ z (`torch.Tensor`): Input batch of latent vectors.+ return_dict (`bool`, *optional*, defaults to `True`):+ Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.++ Returns:+ [`~models.vae.DecoderOutput`] or `tuple`:+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is+ returned.+ """+ if self.use_slicing and z.shape[0] > 1:+ decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]+ decoded = torch.cat(decoded_slices)+ else:+ decoded = self._decode(z).sample++ if not return_dict:+ return (decoded,)+ return DecoderOutput(sample=decoded)++ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:+ blend_extent = min(a.shape[-2], b.shape[-2], blend_extent)+ for y in range(blend_extent):+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (+ y / blend_extent+ )+ return b++ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:+ blend_extent = min(a.shape[-1], b.shape[-1], blend_extent)+ for x in range(blend_extent):+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (+ x / blend_extent+ )+ return b++ def tiled_encode(self, x: torch.Tensor) -> AutoencoderKLOutput:+ r"""Encode a batch of images using a tiled encoder.++ Args:+ x (`torch.Tensor`): Input batch of videos.++ Returns:+ `torch.Tensor`:+ The latent representation of the encoded videos.+ """+ _, _, num_frames, height, width = x.shape+ latent_height = height // self.spatial_compression_ratio+ latent_width = width // self.spatial_compression_ratio++ tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio+ tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio+ tile_latent_stride_height = self.tile_sample_stride_height // self.spatial_compression_ratio+ tile_latent_stride_width = self.tile_sample_stride_width // self.spatial_compression_ratio++ blend_height = tile_latent_min_height - tile_latent_stride_height+ blend_width = tile_latent_min_width - tile_latent_stride_width++ # Split x into overlapping tiles and encode them separately.+ # The tiles have an overlap to avoid seams between tiles.+ rows = []+ for i in range(0, height, self.tile_sample_stride_height):+ row = []+ for j in range(0, width, self.tile_sample_stride_width):+ self.clear_cache()+ time = []+ frame_range = 1 + (num_frames - 1) // 4+ for k in range(frame_range):+ self._enc_conv_idx = [0]+ if k == 0:+ tile = x[:, :, :1, i : i + self.tile_sample_min_height, j : j + self.tile_sample_min_width]+ else:+ tile = x[+ :,+ :,+ 1 + 4 * (k - 1) : 1 + 4 * k,+ i : i + self.tile_sample_min_height,+ j : j + self.tile_sample_min_width,+ ]+ tile = self.encoder(tile, feat_cache=self._enc_feat_map, feat_idx=self._enc_conv_idx)+ tile = self.quant_conv(tile)+ time.append(tile)+ row.append(torch.cat(time, dim=2))+ rows.append(row)+ self.clear_cache()++ result_rows = []+ for i, row in enumerate(rows):+ result_row = []+ for j, tile in enumerate(row):+ # blend the above tile and the left tile+ # to the current tile and add the current tile to the result row+ if i > 0:+ tile = self.blend_v(rows[i - 1][j], tile, blend_height)+ if j > 0:+ tile = self.blend_h(row[j - 1], tile, blend_width)+ result_row.append(tile[:, :, :, :tile_latent_stride_height, :tile_latent_stride_width])+ result_rows.append(torch.cat(result_row, dim=-1))++ enc = torch.cat(result_rows, dim=3)[:, :, :, :latent_height, :latent_width]+ return enc++ def tiled_decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:+ r"""+ Decode a batch of images using a tiled decoder.++ Args:+ z (`torch.Tensor`): Input batch of latent vectors.+ return_dict (`bool`, *optional*, defaults to `True`):+ Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.++ Returns:+ [`~models.vae.DecoderOutput`] or `tuple`:+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is+ returned.+ """+ _, _, num_frames, height, width = z.shape+ sample_height = height * self.spatial_compression_ratio+ sample_width = width * self.spatial_compression_ratio++ tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio+ tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio+ tile_latent_stride_height = self.tile_sample_stride_height // self.spatial_compression_ratio+ tile_latent_stride_width = self.tile_sample_stride_width // self.spatial_compression_ratio++ blend_height = self.tile_sample_min_height - self.tile_sample_stride_height+ blend_width = self.tile_sample_min_width - self.tile_sample_stride_width++ # Split z into overlapping tiles and decode them separately.+ # The tiles have an overlap to avoid seams between tiles.+ rows = []+ for i in range(0, height, tile_latent_stride_height):+ row = []+ for j in range(0, width, tile_latent_stride_width):+ self.clear_cache()+ time = []+ for k in range(num_frames):+ self._conv_idx = [0]+ tile = z[:, :, k : k + 1, i : i + tile_latent_min_height, j : j + tile_latent_min_width]+ tile = self.post_quant_conv(tile)+ decoded = self.decoder(tile, feat_cache=self._feat_map, feat_idx=self._conv_idx)+ time.append(decoded)+ row.append(torch.cat(time, dim=2))+ rows.append(row)+ self.clear_cache()++ result_rows = []+ for i, row in enumerate(rows):+ result_row = []+ for j, tile in enumerate(row):+ # blend the above tile and the left tile+ # to the current tile and add the current tile to the result row+ if i > 0:+ tile = self.blend_v(rows[i - 1][j], tile, blend_height)+ if j > 0:+ tile = self.blend_h(row[j - 1], tile, blend_width)+ result_row.append(tile[:, :, :, : self.tile_sample_stride_height, : self.tile_sample_stride_width])+ result_rows.append(torch.cat(result_row, dim=-1))++ dec = torch.cat(result_rows, dim=3)[:, :, :, :sample_height, :sample_width]++ if not return_dict:+ return (dec,)+ return DecoderOutput(sample=dec)++ def forward(+ self,+ sample: torch.Tensor,+ sample_posterior: bool = False,+ return_dict: bool = True,+ generator: Optional[torch.Generator] = None,+ ) -> Union[DecoderOutput, torch.Tensor]:+ """+ Args:+ sample (`torch.Tensor`): Input sample.+ return_dict (`bool`, *optional*, defaults to `True`):+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.+ """+ x = sample+ posterior = self.encode(x).latent_dist+ if sample_posterior:+ z = posterior.sample(generator=generator)+ else:+ z = posterior.mode()+ dec = self.decode(z, return_dict=return_dict)+ return decdiff --git a/models/longcat/modules/avatar/attention.py b/models/longcat/modules/avatar/attention.pynew file mode 100644index 0000000..1787088--- /dev/null+++ b/models/longcat/modules/avatar/attention.py@@ -0,0 +1,412 @@+from typing import List, Optional++import torch+import torch.nn as nn++from einops import rearrange++from shared.attention import pay_attention, pay_sparse_attention+from .rope_3d import RotaryPositionalEmbedding+from ..blocks import RMSNorm_FP32+from ...audio_process.torch_utils import get_attn_map_with_target+from .rope_3d import RotaryPositionalEmbedding1D+++def _run_attention(x_list, out_dtype, **attn_kwargs):+ q, k, v = x_list+ if out_dtype in (torch.float16, torch.bfloat16):+ attn_dtype = out_dtype+ else:+ attn_dtype = torch.bfloat16+ if q.dtype != attn_dtype:+ q = q.to(attn_dtype)+ k = k.to(attn_dtype)+ v = v.to(attn_dtype)+ x_list[:] = [q, k, v]+ x = pay_attention(x_list, **attn_kwargs)+ x_list[:] = []+ if x.dtype != out_dtype:+ x = x.to(out_dtype)+ return x+++def _run_sparse_attention(x_list, out_dtype, shape, bsa_params, **attn_kwargs):+ q, k, v = x_list+ if out_dtype in (torch.float16, torch.bfloat16):+ attn_dtype = out_dtype+ else:+ attn_dtype = torch.bfloat16+ if q.dtype != attn_dtype:+ q = q.to(attn_dtype)+ k = k.to(attn_dtype)+ v = v.to(attn_dtype)+ x_list[:] = [q, k, v]+ x = pay_sparse_attention(x_list, shape=shape, bsa_params=bsa_params, **attn_kwargs)+ x_list[:] = []+ if x.dtype != out_dtype:+ x = x.to(out_dtype)+ return x+++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+ )++ def _process_attn(self, q, k, v, shape, out_dtype):+ """+ function wrapper to do attention with q, k, v+ """+ if self.enable_bsa:+ return _run_sparse_attention([q, k, v], out_dtype, shape, self.bsa_params)+ return _run_attention([q, k, v], out_dtype)++ 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+ out_dtype = x.dtype+ qkv = self.qkv(x)+ if qkv.dtype != out_dtype:+ qkv = qkv.to(out_dtype)++ qkv_shape = (B, N, 3, self.num_heads, self.head_dim)+ qkv = qkv.view(qkv_shape)+ q, k, v = qkv.unbind(2)+ 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, out_dtype)+ # process the noise tokens+ q_noise = q[:, num_cond_latents_thw:].contiguous()+ x_noise = self._process_attn(q_noise, k, v, shape, out_dtype)+ # merge x_cond and x_noise+ x = torch.cat([x_cond, x_noise], dim=1).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, out_dtype)+ x_cond = self._process_attn(q_cond, k_cond, v_cond, shape, out_dtype)+ if num_cond_latents == N_t:+ x = torch.cat([x_ref, x_cond], dim=1).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.+ 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, out_dtype) # q_front has attention with ref + cond + noisy+ x_noise_back = self._process_attn(q_noise_back, k, v, shape, out_dtype) # q_back has attention with ref + cond + noisy+ x_noise_maskref = self._process_attn(q_noise_maskref, k_non_ref, v_non_ref, shape, out_dtype) # q_mask has attention with cond+noisy+ x_noise = torch.cat([x_noise_front, x_noise_maskref, x_noise_back], dim=1).contiguous()+ else:+ x_noise = self._process_attn(q_noise, k, v, shape, out_dtype)+ # merge x_cond and x_noise+ x = torch.cat([x_ref, x_cond, x_noise], dim=1).contiguous()++ else:+ # text to video+ x = self._process_attn(q, k, v, shape, out_dtype)++ x_output_shape = (B, N, C)+ 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[:, num_cond_latents_thw:].type_as(x),+ k.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+ out_dtype = x.dtype+ qkv = self.qkv(x)+ if qkv.dtype != out_dtype:+ qkv = qkv.to(out_dtype)++ qkv_shape = (B, N, 3, self.num_heads, self.head_dim)+ qkv = qkv.view(qkv_shape)+ q, k, v = qkv.unbind(2)+ q, k = self.q_norm(q), self.k_norm(k)++ N_t, N_h, N_w = shape+ k_cache, v_cache = kv_cache+ 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=1).contiguous()+ v_full = torch.cat([v_cache, v], dim=1).contiguous()+ q_padding = torch.cat([torch.empty_like(k_cache), q], dim=1).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()+ else:+ k_full = k+ v_full = v++ 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.+ 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, out_dtype) # q_front --> ref+cond+noisy+ x_noise_back = self._process_attn(q_noise_back, k_full, v_full, shape, out_dtype) # q_back --> ref+cond+noisy+ x_noise_maskref = self._process_attn(q_noise_maskref, k_non_ref, v_non_ref, shape, out_dtype) # q_mask --> cond+noisy+ x = torch.cat([x_noise_front, x_noise_maskref, x_noise_back], dim=1).contiguous()+ else:+ x = self._process_attn(q, k_full, v_full, shape, out_dtype)++ x_output_shape = (B, N, C)+ 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.type_as(x),+ k_full.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).view(B, N, self.num_heads, self.head_dim)+ if q.dtype != out_dtype:+ q = q.to(out_dtype)+ 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)+ 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) S H C -> B (N_t S) H C", N_t=N_t)+ q = self.rope_1d(q, normalized_pos)+ q = rearrange(q, "B (N_t S) H C -> (B N_t) S H C", N_t=N_t)++ # get kv from encoder_hidden_states+ _, N_a, _ = cond.shape+ encoder_kv = self.kv_linear(cond).view(B, N_a, 2, self.num_heads, self.head_dim)+ if encoder_kv.dtype != out_dtype:+ encoder_kv = encoder_kv.to(out_dtype)+ encoder_k, encoder_v = encoder_kv.unbind(2)+ 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) S H C -> B (N_t S) H C", N_t=N_t)+ encoder_k = self.rope_1d(encoder_k, encoder_pos)+ encoder_k = rearrange(encoder_k, "B (N_t S) H C -> (B N_t) S H C", N_t=N_t)++ x = _run_attention([q, encoder_k, encoder_v], out_dtype, cross_attn=True)++ # linear transform+ x_output_shape = (B, N, C)+ 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 NotImplementedErrordiff --git a/models/longcat/modules/avatar/blocks.py b/models/longcat/modules/avatar/blocks.pynew file mode 100644index 0000000..d3a31eb--- /dev/null+++ b/models/longcat/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/models/longcat/modules/avatar/longcat_video_dit_avatar.py b/models/longcat/modules/avatar/longcat_video_dit_avatar.pynew file mode 100644index 0000000..568b780--- /dev/null+++ b/models/longcat/modules/avatar/longcat_video_dit_avatar.py@@ -0,0 +1,615 @@+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 ..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))+ self.ffn_mult = self.ffn.ffn_mult+ self.ffn_chunk_min = 128++ def _apply_ffn_chunked(self, ffn_in: torch.Tensor) -> torch.Tensor:+ _, seq_len, dim = ffn_in.shape+ if seq_len < self.ffn_chunk_min:+ return self.ffn(ffn_in)+ ffn_in_flat = ffn_in.reshape(-1, dim)+ chunk_size = max(int(seq_len // self.ffn_mult), 1)+ if chunk_size >= ffn_in_flat.shape[0]:+ return self.ffn(ffn_in)+ for ffn_chunk in torch.split(ffn_in_flat, chunk_size, dim=0):+ ffn_chunk[...] = self.ffn(ffn_chunk)+ return ffn_in++ 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._apply_ffn_chunked(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 = []+ self._interrupt_check = None++ 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+ ):+ x_list = hidden_states if isinstance(hidden_states, list) else [hidden_states]+ joint_pass = isinstance(hidden_states, list)++ if not isinstance(encoder_hidden_states, list):+ encoder_hidden_states = [encoder_hidden_states] * len(x_list)+ if not isinstance(encoder_attention_mask, list):+ encoder_attention_mask = [encoder_attention_mask] * len(x_list)+ if not isinstance(timestep, list):+ timestep = [timestep] * len(x_list)+ if not isinstance(num_cond_latents, list):+ num_cond_latents = [num_cond_latents] * len(x_list)+ if not isinstance(kv_cache_dict, list):+ kv_cache_dict = [kv_cache_dict] * len(x_list)+ if not isinstance(audio_embs, list):+ audio_embs = [audio_embs] * len(x_list)+ if not isinstance(ref_target_masks, list):+ ref_target_masks = [ref_target_masks] * len(x_list)++ dtype = self.x_embedder.proj.weight.dtype+ t_list = []+ enc_list = []+ y_seqlens_list = []+ latent_shapes = []+ audio_hidden_states_list = []+ token_ref_target_masks_list = []+ human_num_list = []++ for idx, (x, step, enc, mask, audio_cond, ref_masks) in enumerate(+ zip(x_list, timestep, encoder_hidden_states, encoder_attention_mask, audio_embs, ref_target_masks)+ ):+ B, _, T, H, W = x.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."++ if len(step.shape) == 1:+ step = step.unsqueeze(1).expand(-1, N_t)++ x = x.to(dtype)+ step = step.to(dtype)+ enc = enc.to(dtype)++ x = self.x_embedder(x)++ with amp.autocast(device_type='cuda', dtype=torch.float32):+ t = self.t_embedder(step.float().flatten(), torch.float32).reshape(B, N_t, -1)+ t = t.to(torch.float32)++ enc = self.y_embedder(enc)++ # audio tokens+ audio_hidden_states = None+ human_num = None+ token_ref_target_masks = None+ if audio_cond is not None:+ audio_cond = audio_cond.to(device=x.device, dtype=x.dtype)+ first_frame_audio_emb_s = audio_cond[:, :1, ...]++ latter_frame_audio_emb = audio_cond[:, 1:, ...]+ 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+ )+ audio_hidden_states = self.audio_proj(first_frame_audio_emb_s, latter_frame_audio_emb_s)++ if num_ref_latents is not None and num_ref_latents > 0:+ audio_start_ref = audio_hidden_states[:, [0], :, :]+ audio_hidden_states = torch.cat([audio_start_ref, audio_hidden_states], dim=1).contiguous()+ audio_hidden_states = audio_hidden_states[:, -N_t:]++ if ref_masks is not None:+ human_num = len(audio_hidden_states)+ audio_hidden_states = torch.concat(audio_hidden_states.split(1), dim=2)+ audio_hidden_states = audio_hidden_states.squeeze(0)+ else:+ audio_hidden_states = rearrange(audio_hidden_states, "b t n c -> (b t) n c")++ if ref_masks is not None:+ ref_masks = ref_masks.unsqueeze(0).to(torch.float32)+ token_ref_target_masks = nn.functional.interpolate(ref_masks, size=(N_h, N_w), mode='nearest')+ token_ref_target_masks = token_ref_target_masks.squeeze(0)+ 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).to(dtype)++ if self.text_tokens_zero_pad and mask is not None:+ enc = enc * mask[:, None, :, None]++ if mask is not None:+ if mask.dim() > 2:+ mask = mask.squeeze(1).squeeze(1)+ y_seqlens = mask.sum(dim=1).to(torch.int64).tolist()+ else:+ y_seqlens = [enc.shape[2]] * enc.shape[0]++ enc = enc.squeeze(1)++ x_list[idx] = x+ t_list.append(t)+ enc_list.append(enc)+ y_seqlens_list.append(y_seqlens)+ latent_shapes.append((N_t, N_h, N_w))+ audio_hidden_states_list.append(audio_hidden_states)+ token_ref_target_masks_list.append(token_ref_target_masks)+ human_num_list.append(human_num)++ kv_cache_dict_ret = [dict() for _ in x_list] if return_kv else None+ for block_idx, block in enumerate(self.blocks):+ if self._interrupt_check is not None and self._interrupt_check():+ return [None] * len(x_list) if joint_pass else None+ for i in range(len(x_list)):+ if torch.is_grad_enabled() and self.gradient_checkpointing:+ block_outputs = self._gradient_checkpointing_func(+ block,+ x_list[i],+ enc_list[i],+ t_list[i],+ y_seqlens_list[i],+ latent_shapes[i],+ num_cond_latents[i],+ return_kv,+ kv_cache_dict[i].get(block_idx, None) if kv_cache_dict[i] is not None else None,+ skip_crs_attn,+ num_ref_latents,+ audio_hidden_states_list[i],+ ref_img_index,+ mask_frame_range,+ token_ref_target_masks_list[i],+ human_num_list[i],+ )+ else:+ block_outputs = block(+ x_list[i],+ enc_list[i],+ t_list[i],+ y_seqlens_list[i],+ latent_shapes[i],+ num_cond_latents[i],+ return_kv,+ kv_cache_dict[i].get(block_idx, None) if kv_cache_dict[i] is not None else None,+ skip_crs_attn,+ num_ref_latents,+ audio_hidden_states_list[i],+ ref_img_index,+ mask_frame_range,+ token_ref_target_masks_list[i],+ human_num_list[i],+ )++ if return_kv:+ x_list[i], kv_cache = block_outputs+ if offload_kv_cache:+ kv_cache_dict_ret[i][block_idx] = (kv_cache[0].cpu(), kv_cache[1].cpu())+ else:+ kv_cache_dict_ret[i][block_idx] = (kv_cache[0].contiguous(), kv_cache[1].contiguous())+ else:+ x_list[i] = block_outputs++ if self._interrupt_check is not None and self._interrupt_check():+ return [None] * len(x_list) if joint_pass else None++ outputs = []+ for x, t, latent_shape in zip(x_list, t_list, latent_shapes):+ x = self.final_layer(x, t, latent_shape)+ x = self.unpatchify(x, *latent_shape)+ outputs.append(x.to(torch.float32))++ if return_kv:+ return (outputs if joint_pass else outputs[0]), (kv_cache_dict_ret if joint_pass else kv_cache_dict_ret[0])+ return outputs if joint_pass else outputs[0]+++ 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 xdiff --git a/models/longcat/modules/avatar/rope_3d.py b/models/longcat/modules/avatar/rope_3d.pynew file mode 100644index 0000000..4405ba3--- /dev/null+++ b/models/longcat/modules/avatar/rope_3d.py@@ -0,0 +1,171 @@+# References:+# https://github.com/facebookresearch/fairseq/blob/main/fairseq/modules/rotary_positional_embedding.py++import torch+import torch.nn as nn++from einops import rearrange, repeat++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_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1)+ return torch.stack((-x_imag, x_real), dim=-1).flatten(-2)+++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)+ cpu = torch.device("cpu")+ freqs_t = 1.0 / (+ self.base ** (torch.arange(0, dim_t, 2, device=cpu, dtype=torch.float32)[: (dim_t // 2)] / dim_t)+ )+ freqs_h = 1.0 / (+ self.base ** (torch.arange(0, dim_h, 2, device=cpu, dtype=torch.float32)[: (dim_h // 2)] / dim_h)+ )+ freqs_w = 1.0 / (+ self.base ** (torch.arange(0, dim_w, 2, device=cpu, dtype=torch.float32)[: (dim_w // 2)] / dim_w)+ )+ if frame_index is not None and num_ref_latents is not None:+ grid_t = torch.concat(+ [+ torch.tensor([frame_index], device=cpu, dtype=torch.float32),+ torch.arange(0, num_frames - num_ref_latents, device=cpu, dtype=torch.float32),+ ],+ dim=0,+ )+ else:+ grid_t = torch.arange(num_frames, device=cpu, dtype=torch.float32)+ grid_h = torch.arange(height, device=cpu, dtype=torch.float32)+ grid_w = torch.arange(width, device=cpu, dtype=torch.float32)+ 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")++ 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 = self.freqs_dict[key_name].to(device=q.device, dtype=torch.float32)+ cos = freqs.cos().unsqueeze(0).unsqueeze(2)+ sin = freqs.sin().unsqueeze(0).unsqueeze(2)++ q_out = q.float()+ k_out = k.float()+ q_rot = rotate_half(q_out)+ k_rot = rotate_half(k_out)+ q_out.mul_(cos).add_(q_rot.mul_(sin))+ k_out.mul_(cos).add_(k_rot.mul_(sin))++ return q_out.to(q.dtype), k_out.to(k.dtype)+++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, seq, head, 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_out = x.float()++ freqs_cis = freqs_cis.float().to(x.device)+ cos = freqs_cis.cos().unsqueeze(0).unsqueeze(2)+ sin = freqs_cis.sin().unsqueeze(0).unsqueeze(2)+ x_rot = rotate_half(x_out)+ x_out.mul_(cos).add_(x_rot.mul_(sin))++ return x_out.to(x.dtype)+diff --git a/models/longcat/modules/block_sparse_attention/__init__.py b/models/longcat/modules/block_sparse_attention/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/models/longcat/modules/block_sparse_attention/bsa_interface.py b/models/longcat/modules/block_sparse_attention/bsa_interface.pynew file mode 100644index 0000000..17be0fd--- /dev/null+++ b/models/longcat/modules/block_sparse_attention/bsa_interface.py@@ -0,0 +1,658 @@+import os+import torch+import torch.nn.functional as F+import triton+import triton.language as tl+import math++from .common import _attn_fwd_gating, _attn_bwd_preprocess, configs_gating_preset+from .flash_attn_bsa_varlen_mask import (+ _attn_fwd_bsa_varlen, _attn_fwd_bsa_varlen_align, _attn_bwd_dkdv_bsa_varlen_wrapper, _attn_bwd_dq_bsa_varlen_wrapper, _attn_bwd_dq_bsa_varlen_align_wrapper,+ configs_fwd_bsa_varlen_preset, configs_fwd_bsa_varlen_align_preset, configs_bwd_dkdv_bsa_varlen_preset, configs_bwd_dq_bsa_varlen_preset, configs_bwd_dq_bsa_varlen_align_preset+)++from .communicate import p2p_communicate++torch._dynamo.config.cache_size_limit = 32++def is_cuda():+ return triton.runtime.driver.active.get_current_target().backend == "cuda"++def supports_tma():+ return is_cuda() and torch.cuda.get_device_capability()[0] >= 9++HAS_TMA_DESC = "nv_tma_desc_type" in dir(tl)++if HAS_TMA_DESC:+ print("TMA benchmarks will be running with experimental grid constant TMA descriptor.", )+else:+ print("TMA benchmarks will be running without grid constant TMA descriptor.", )+++# TmaAutoTuneHelper used in htyu's PR #5622+class TmaAutoTuneHelper:++ # duck typing wrapper to implement the same interface as TmaDescKernelParam in Triton PR #4498+ class KernelParamWrapper:++ def __init__(self, desc):+ self.desc = desc++ def tma_desc_cpu_ptr(self):+ return self.desc.data_ptr()++ TMA_SIZE = 128++ def __init__(self):+ self.fill_1d_tma_descriptor_inner = (triton.runtime.driver.active.utils.fill_1d_tma_descriptor)+ self.fill_2d_tma_descriptor_inner = (triton.runtime.driver.active.utils.fill_2d_tma_descriptor)+ if HAS_TMA_DESC:+ self.descriptors = {}+ else:+ self.cuda_descriptors = {}++ # Call this method outside of the lambda function for grid size+ def init_tma_descriptor(self, name):+ if HAS_TMA_DESC:+ self.descriptors[name] = torch.empty(TmaAutoTuneHelper.TMA_SIZE, device="cpu", dtype=torch.int8)+ else:+ self.cuda_descriptors[name] = torch.empty(TmaAutoTuneHelper.TMA_SIZE, device="cuda", dtype=torch.int8)++ # Call this method inside the lambda function for grid size+ def fill_1d_tma_descriptor(self, name, ptr, dim, block_dim, element_size):+ if HAS_TMA_DESC:+ desc_x = self.descriptors[name]+ assert desc_x.data_ptr() % 64 == 0+ self.fill_1d_tma_descriptor_inner(ptr, dim, block_dim, element_size, desc_x.data_ptr())+ else:+ desc_x = self.cuda_descriptors[name]+ buf_x = torch.empty_like(desc_x, device="cpu", pin_memory=True)+ self.fill_1d_tma_descriptor_inner(ptr, dim, block_dim, element_size, buf_x.data_ptr())+ desc_x.copy_(buf_x, non_blocking=True)++ # Call this method inside the lambda function for grid size+ def fill_2d_tma_descriptor(self, name, ptr, dim1, dim0, block_dim1, block_dim0, element_size):+ if HAS_TMA_DESC:+ desc_x = self.descriptors[name]+ assert desc_x.data_ptr() % 64 == 0+ self.fill_2d_tma_descriptor_inner(ptr, dim1, dim0, block_dim1, block_dim0, element_size, desc_x.data_ptr())+ else:+ desc_x = self.cuda_descriptors[name]+ buf_x = torch.empty_like(desc_x, device="cpu", pin_memory=True)+ self.fill_2d_tma_descriptor_inner(ptr, dim1, dim0, block_dim1, block_dim0, element_size, buf_x.data_ptr())+ desc_x.copy_(buf_x, non_blocking=True)++ def get_tma_descriptor_kernel_param(self, name):+ if HAS_TMA_DESC:+ assert self.descriptors[name] is not None+ return self.KernelParamWrapper(self.descriptors[name])+ else:+ assert self.cuda_descriptors[name] is not None+ return self.cuda_descriptors[name]+++def create_mask_from_indices_kernel(+ block_indices,+ block_mask,+ stride_bz, stride_bh, stride_bm, stride_bs,+ stride_mz, stride_mh, stride_mm, stride_mn,+ H,+):+ i_zh, i_m, i_s = tl.program_id(0), tl.program_id(1), tl.program_id(2)+ i_z, i_h = i_zh // H, i_zh % H++ off_b = i_z.to(tl.int64) * stride_bz + i_h.to(tl.int64) * stride_bh + i_m.to(tl.int64) * stride_bm + i_s.to(tl.int64) * stride_bs++ b_i = tl.load(block_indices + off_b)++ off_m = i_z.to(tl.int64) * stride_mz + i_h.to(tl.int64) * stride_mh + i_m.to(tl.int64) * stride_mm + b_i.to(tl.int64) * stride_mn++ b_m = 1+ tl.store(block_mask + off_m, b_m.to(block_mask.dtype.element_ty))++def create_mask_from_indices_triton(+ block_indices,+ N_cols+):+ B, H, N_rows, S = block_indices.shape+ block_mask = torch.zeros((B, H, N_rows, N_cols), dtype=torch.bool, device=block_indices.device)+ create_mask_from_indices_kernel[(B * H, N_rows, S)](+ block_indices,+ block_mask,+ block_indices.stride(0), block_indices.stride(1), block_indices.stride(2), block_indices.stride(3),+ block_mask.stride(0), block_mask.stride(1), block_mask.stride(2), block_mask.stride(3),+ H,+ )+ return block_mask+++def create_mask_from_indices_varlen(block_indices, N_cols_mask):++ B, H, M, _ = block_indices.shape+ device = block_indices.device++ mask = torch.zeros((B, H, M, N_cols_mask), dtype=torch.bool, device=device)++ valid = block_indices < N_cols_mask++ b_idx = torch.arange(B, device=device)[:, None, None, None].expand_as(block_indices)+ h_idx = torch.arange(H, device=device)[None, :, None, None].expand_as(block_indices)+ m_idx = torch.arange(M, device=device)[None, None, :, None].expand_as(block_indices)++ valid_coords = (b_idx[valid], h_idx[valid], m_idx[valid], block_indices[valid])++ mask[valid_coords] = True++ return mask+++def create_indices_k_from_indices_q_varlen(+ block_indices,+ N_cols_mask # indicate the number of the last dimension of the bool mask, since this information cannot be determined by block_indices, which may contain invalid elements+):+ block_mask_qk = create_mask_from_indices_varlen(block_indices, N_cols_mask)+ B, H, M, N = block_mask_qk.shape+ block_mask_kq = block_mask_qk.permute(0, 1, 3, 2)+ indices = torch.arange(M, device=block_indices.device).view(1, 1, 1, -1).expand_as(block_mask_kq)+ block_indices_k = torch.where(block_mask_kq, indices, M)+ block_indices_k, _ = torch.sort(block_indices_k, dim=-1)++ block_indices_k_lens = (block_indices_k < M).sum(dim=-1)++ return block_indices_k, block_indices_k_lens++++def mean_pooling_compression(+ x: torch.Tensor,+ block_size: int+) -> torch.Tensor:+ B, H, S = x.shape[:3]+ num_block = math.ceil(S / block_size)+ if S % block_size != 0:+ x = F.pad(x, (0, 0, 0, num_block * block_size - S))+ x_cmp = x.view(B, H, num_block, block_size, -1).mean(dim=3)+ return x_cmp+++def cal_score(q, k):+ k_transposed = k.transpose(-1, -2) # [b, h, d, s_k]+ score = torch.matmul(q, k_transposed) # [b, h, s_q, s_k]+ return score++def cal_score_triton(q, k):+ B, H, s_q, D = q.shape+ s_k = k.shape[2]++ score = torch.empty(B, H, s_q, s_k, device=q.device, dtype=q.dtype)++ kernel_config = {} if os.environ.get('TRITON_AUTOTUNE_ENBALE', '0') == '1' else configs_gating_preset['default']++ grid = lambda args: (triton.cdiv(s_q, args["BLOCK_M"]), B * H, 1)+ _attn_fwd_gating[grid](+ q, k, score,+ q.stride(0), q.stride(1), q.stride(2), q.stride(3),+ k.stride(0), k.stride(1), k.stride(2), k.stride(3),+ score.stride(0), score.stride(1), score.stride(2), score.stride(3),+ H, s_q, s_k,+ HEAD_DIM=D,+ **kernel_config+ )+ return score+++def get_select_indices_topk(q, k, sparsity):+ score = cal_score(q, k)+ block_indices, block_indices_lens = get_select_indices_topk_from_score(score, sparsity)+ return block_indices, block_indices_lens+++def get_select_indices_topk_from_score(score, sparsity):+ num_selected = int((1 - sparsity) * score.shape[-1])+ block_indices = torch.topk(score, num_selected)[1]++ block_indices_lens = torch.full(+ (block_indices.shape[0], block_indices.shape[1], block_indices.shape[2]),+ num_selected,+ dtype=torch.int32,+ device=block_indices.device+ )++ return block_indices, block_indices_lens+++def get_select_indices_cdf(q, k, cdf_threshold):+ score = cal_score(q, k)+ head_dim = q.shape[-1]+ block_indices, block_indices_lens = get_select_indices_cdf_from_score(score, cdf_threshold, 1 / head_dim**0.5)+ return block_indices, block_indices_lens+++def get_select_indices_cdf_from_score(score, cdf_threshold, sm_scale):+ weights = torch.softmax(score * sm_scale, dim=-1)++ B, H, Sq, Sk = weights.shape+ cdf_threshold = torch.full((H,), cdf_threshold, device=weights.device).view(1, H, 1, 1).expand(B, -1, Sq, -1)+ weights_sorted = torch.sort(weights, dim=-1, descending=True)+ cdf = torch.cumsum(weights_sorted.values, dim=-1)+ num_selected = torch.searchsorted(cdf, cdf_threshold, right=True)++ return weights_sorted.indices, num_selected.squeeze(-1)+++def get_select_indices_cdf_topk(q, k, sparsity, cdf_threshold):+ score = cal_score(q, k)+ head_dim = q.shape[-1]+ block_indices, block_indices_lens = get_select_indices_cdf_topk_from_score(score, sparsity, cdf_threshold, 1 / head_dim**0.5)+ return block_indices, block_indices_lens+++def get_select_indices_cdf_topk_from_score(score, sparsity, cdf_threshold, sm_scale):+ weights = torch.softmax(score * sm_scale, dim=-1)++ B, H, Sq, Sk = weights.shape+ cdf_threshold = torch.full((H,), cdf_threshold, device=weights.device).view(1, H, 1, 1).expand(B, -1, Sq, -1)+ weights_sorted = torch.sort(weights, dim=-1, descending=True)+ cdf = torch.cumsum(weights_sorted.values, dim=-1)+ num_selected = torch.searchsorted(cdf, cdf_threshold, right=True)++ # max(cdf, topk)+ num_selected_topk = int((1 - sparsity) * score.shape[-1])+ num_selected[num_selected < num_selected_topk] = num_selected_topk++ return weights_sorted.indices, num_selected.squeeze(-1)++def get_select_indices(q, k, sparsity, cdf_threshold):+ if sparsity is not None and cdf_threshold is None:+ block_indices, block_indices_lens = get_select_indices_topk(q, k, sparsity)+ elif sparsity is None and cdf_threshold is not None:+ block_indices, block_indices_lens = get_select_indices_cdf(q, k, cdf_threshold)+ elif sparsity is not None and cdf_threshold is not None:+ block_indices, block_indices_lens = get_select_indices_cdf_topk(q, k, sparsity, cdf_threshold)+ else:+ raise ValueError+ return block_indices, block_indices_lens++def get_select_indices_from_score(score, sparsity, cdf_threshold):+ if sparsity is not None and cdf_threshold is None:+ block_indices, block_indices_lens = get_select_indices_topk_from_score(score, sparsity)+ elif sparsity is None and cdf_threshold is not None:+ block_indices, block_indices_lens = get_select_indices_cdf_from_score(score, cdf_threshold)+ elif sparsity is not None and cdf_threshold is not None:+ block_indices, block_indices_lens = get_select_indices_cdf_topk_from_score(score, sparsity, cdf_threshold)+ else:+ raise ValueError+ return block_indices, block_indices_lens++def attn_fwd_bsa_varlen_triton(+ q,+ k,+ v,+ sm_scale,+ block_indices,+ block_indices_lens,+ chunk_size_q,+ chunk_size_k,+ sparsity+):++ B, H, Seq, D = q.shape++ o = torch.empty_like(q)+ M = torch.empty((q.shape[0], q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32)++ grid = lambda args: (triton.cdiv(q.shape[2], args["BLOCK_M"]), q.shape[0] * q.shape[1], 1)++ config_key = 'BLOCK_N_LG=64' if chunk_size_k == 64 else 'default'+ if chunk_size_k > 128:+ fwd_func = _attn_fwd_bsa_varlen+ kernel_config = {} if os.environ.get('TRITON_AUTOTUNE_ENBALE', '0') == '1' else configs_fwd_bsa_varlen_preset[config_key]+ else:+ fwd_func = _attn_fwd_bsa_varlen_align+ kernel_config = {} if os.environ.get('TRITON_AUTOTUNE_ENBALE', '0') == '1' else configs_fwd_bsa_varlen_align_preset[config_key]++ block_indices = block_indices.contiguous()+ block_indices_lens = block_indices_lens.contiguous()++ fwd_func[grid](+ q, k, v, sm_scale, M, o,+ block_indices, # [B, H, M_COMPRESS, S]+ block_indices_lens, # [B, H, M_COMPRESS, S_MAX]+ q.stride(0), q.stride(1), q.stride(2), q.stride(3),+ k.stride(0), k.stride(1), k.stride(2), k.stride(3),+ v.stride(0), v.stride(1), v.stride(2), v.stride(3),+ o.stride(0), o.stride(1), o.stride(2), o.stride(3),+ block_indices.stride(0), block_indices.stride(1), block_indices.stride(2), block_indices.stride(3),+ block_indices_lens.stride(0), block_indices_lens.stride(1), block_indices_lens.stride(2),+ H, Seq,+ D,+ BLOCK_M=chunk_size_q,+ BLOCK_N_LG=chunk_size_k,+ SPARSITY=sparsity,+ **kernel_config+ )++ LN2 = 0.6931471824645996+ lse = M * LN2 # convert back to natural units (M is of base 2)++ return o, lse++def attn_bwd_bsa_varlen_triton(+ do,+ q,+ k,+ v,+ o,+ dq,+ dk,+ dv,+ sm_scale,+ M,+ block_indices,+ block_indices_lens,+ chunk_size_q,+ chunk_size_k,+ sparsity+):+ RCP_LN2 = 1.4426950408889634+ M = M * RCP_LN2 # ln -> log2++ do = do.contiguous()+ # assert q.stride() == k.stride() == v.stride() == o.stride() == do.stride()++ BATCH, N_HEAD, N_CTX, HEAD_DIM = q.shape+ N_CTX_KV = k.shape[-2]++ RCP_LN2 = 1.4426950408889634 # = 1.0 / ln(2) # reciprocal+ arg_k = k+ arg_k = arg_k * (sm_scale * RCP_LN2)++ if min(chunk_size_q, chunk_size_k) >= 128:+ PRE_BLOCK = 128+ else:+ PRE_BLOCK = min(chunk_size_q, chunk_size_k)++ assert N_CTX % PRE_BLOCK == 0+ pre_grid = (N_CTX // PRE_BLOCK, BATCH * N_HEAD)+ delta = torch.empty_like(M)+ _attn_bwd_preprocess[pre_grid](+ o, do,+ delta,+ N_CTX,+ BLOCK_M=PRE_BLOCK,+ HEAD_DIM=HEAD_DIM+ )++ block_indices_k, block_indices_k_lens = create_indices_k_from_indices_q_varlen(+ block_indices=block_indices,+ N_cols_mask=N_CTX_KV // chunk_size_k+ )++ block_indices = block_indices.contiguous()+ block_indices_lens = block_indices_lens.contiguous()+ block_indices_k = block_indices_k.contiguous()+ block_indices_k_lens = block_indices_k_lens.contiguous()++ config_key = 'BLOCK_N_DQ_LG=64' if chunk_size_k == 64 else 'default'+ kernel_config = {} if os.environ.get('TRITON_AUTOTUNE_ENBALE', '0') == '1' else configs_bwd_dkdv_bsa_varlen_preset[config_key]++ grid_dkdv = lambda args: (triton.cdiv(arg_k.shape[2], args["BLOCK_N"]), 1, arg_k.shape[0] * arg_k.shape[1])+ _attn_bwd_dkdv_bsa_varlen_wrapper[grid_dkdv](+ q, arg_k, v, sm_scale, # softmax scale+ do,+ dk, dv,+ M, # lse (log2)+ delta,+ block_indices_k,+ block_indices_k_lens,+ q.stride(0), q.stride(1), q.stride(2), q.stride(3),+ k.stride(0), k.stride(1), k.stride(2), k.stride(3),+ v.stride(0), v.stride(1), v.stride(2), v.stride(3),+ dk.stride(0), dk.stride(1), dk.stride(2), dk.stride(3),+ dv.stride(0), dv.stride(1), dv.stride(2), dv.stride(3),+ do.stride(0), do.stride(1), do.stride(2), do.stride(3),+ M.stride(0), M.stride(1), M.stride(2),+ delta.stride(0), delta.stride(1), delta.stride(2),+ block_indices_k.stride(0), block_indices_k.stride(1), block_indices_k.stride(2), block_indices_k.stride(3),+ block_indices_k_lens.stride(0), block_indices_k_lens.stride(1), block_indices_k_lens.stride(2),+ N_HEAD, N_CTX,+ BLOCK_M=chunk_size_q,+ BLOCK_N_DQ_LG=chunk_size_k,+ HEAD_DIM=HEAD_DIM,+ SPARSITY=sparsity,+ **kernel_config+ )++ config_key = 'BLOCK_N_DQ_LG=64' if chunk_size_k == 64 else 'default'+ if chunk_size_k > 128:+ bwd_dq_func = _attn_bwd_dq_bsa_varlen_wrapper+ kernel_config = {} if os.environ.get('TRITON_AUTOTUNE_ENBALE', '0') == '1' else configs_bwd_dq_bsa_varlen_preset[config_key]+ else:+ bwd_dq_func = _attn_bwd_dq_bsa_varlen_align_wrapper+ kernel_config = {} if os.environ.get('TRITON_AUTOTUNE_ENBALE', '0') == '1' else configs_bwd_dq_bsa_varlen_align_preset[config_key]++ grid_dq = lambda args: (triton.cdiv(q.shape[2], args["BLOCK_M"]), 1, q.shape[0] * q.shape[1])+ bwd_dq_func[grid_dq](+ q, arg_k, v,+ do,+ dq,+ M, # lse (log2)+ delta,+ block_indices,+ block_indices_lens,+ q.stride(0), q.stride(1), q.stride(2), q.stride(3),+ k.stride(0), k.stride(1), k.stride(2), k.stride(3),+ v.stride(0), v.stride(1), v.stride(2), v.stride(3),+ dq.stride(0), dq.stride(1), dq.stride(2), dq.stride(3),+ do.stride(0), do.stride(1), do.stride(2), do.stride(3),+ M.stride(0), M.stride(1), M.stride(2),+ delta.stride(0), delta.stride(1), delta.stride(2),+ block_indices.stride(0), block_indices.stride(1), block_indices.stride(2), block_indices.stride(3),+ block_indices_lens.stride(0), block_indices_lens.stride(1), block_indices_lens.stride(2),+ N_HEAD, N_CTX,+ BLOCK_M=chunk_size_q,+ BLOCK_N_DQ_LG=chunk_size_k,+ HEAD_DIM=HEAD_DIM,+ SPARSITY=sparsity,+ **kernel_config+ )+++def make_block_indices_varlen_cp_list(block_indices, cp_size, num_blocks_k_full):+ """+ Args:+ block_indices: [B, H, num_blocks_q_per_cp_rank, num_blocks_k_full]++ Return:+ a list of [block_indices, block_indices_lens] for k from each cp_rank+ - each block_indices starts from zero+ - block_indices_lens indicates the valid number of elements in the last dimension of block_indices+ """+ res = []+ num_blocks_per_rank = num_blocks_k_full // cp_size+ for i in range(cp_size):+ block_indices_tmp = block_indices.clone()+ min_block_idx = i * num_blocks_per_rank+ block_indices_tmp -= min_block_idx+ block_indices_tmp[block_indices_tmp < 0] = num_blocks_per_rank # block_indices_tmp < 0 indicate invalid indices, set them to num_blocks_per_rank in order to sort them to the tail, so that the first N elements of the block_indices indicated by block_indices_lens are valid++ block_indices_tmp, _ = torch.sort(block_indices_tmp, dim=-1)++ block_indices_tmp_lens = (block_indices_tmp < num_blocks_per_rank).sum(dim=-1)++ res.append([block_indices_tmp, block_indices_tmp_lens])++ return res+++def flash_attn_fwd_softmax_lse_correction(+ softmax_lse: torch.Tensor,+ softmax_lse_per_step: torch.Tensor,+):+ """Merge softmax stats of each step in Attention with context parallelism"""+ max_scale = torch.max(softmax_lse, softmax_lse_per_step)+ min_scale = torch.min(softmax_lse, softmax_lse_per_step)+ lse_diff = min_scale - max_scale+ lse_diff = lse_diff.nan_to_num(nan=0.) # handle cases: tensor(-inf) - tensor(-inf) = tensor(nan); In the current cp implementation, it is possible that lses of 2 cp ranks are both -inf, if no block is selected from both cp ranks. In such cases, the finally corrected lse should remain -inf.+ new_scale = max_scale + torch.log1p(torch.exp(lse_diff)) # a + ln(1 + e^(b - a)) = ln(e^a) + ln(1 + e^(b - a)) = ln(e^a + e^b)+ softmax_lse.copy_(new_scale)+++def flash_attn_fwd_out_correction_init(+ out_init_step: torch.Tensor, # b h s d+ softmax_lse: torch.Tensor, # b h s+ softmax_lse_init_step: torch.Tensor,+):+ """Merge partial outputs of the first step in Attention with context parallelism"""+ softmax_lse_corrected_exp = torch.exp(softmax_lse_init_step - softmax_lse)+ softmax_lse_corrected_exp = softmax_lse_corrected_exp.unsqueeze(-1)+ out_corrected = out_init_step * softmax_lse_corrected_exp+ return out_corrected.to(out_init_step.dtype)++++def flash_attn_fwd_out_correction(+ out: torch.Tensor,+ out_per_step: torch.Tensor,+ softmax_lse: torch.Tensor,+ softmax_lse_per_step: torch.Tensor,+):+ """Merge partial outputs of each step in Attention with context parallelism"""+ softmax_lse_corrected_exp = torch.exp(softmax_lse_per_step - softmax_lse)+ softmax_lse_corrected_exp = softmax_lse_corrected_exp.unsqueeze(-1)+ out_corrected = out_per_step * softmax_lse_corrected_exp+ out.add_(out_corrected)+++def topk_sort(score, num_chunks_selected):+ block_indices = torch.topk(score, num_chunks_selected)[1]+ block_indices, _ = torch.sort(block_indices, dim=-1)+ return block_indices++class _attention_bsa(torch.autograd.Function):++ @staticmethod+ def forward(ctx, q, k, v, chunk_size_q, chunk_size_k, sparsity, cdf_threshold, sm_scale, use_tma=False):+ # shape constraints+ HEAD_DIM_Q, HEAD_DIM_K = q.shape[-1], k.shape[-1]+ # when v is in float8_e5m2 it is transposed.+ HEAD_DIM_V = v.shape[-1]+ assert HEAD_DIM_Q == HEAD_DIM_K and HEAD_DIM_K == HEAD_DIM_V+ assert HEAD_DIM_K in {16, 32, 64, 128, 256}++ # ---------------------- gating ----------------------+ q_cmp = mean_pooling_compression(q, chunk_size_q)+ k_cmp = mean_pooling_compression(k, chunk_size_k)+ block_indices, block_indices_lens = get_select_indices(q_cmp, k_cmp, sparsity, cdf_threshold)++ # ---------------------- bsa ----------------------++ o, lse = attn_fwd_bsa_varlen_triton(+ q, k, v,+ sm_scale, block_indices, block_indices_lens,+ chunk_size_q, chunk_size_k,+ sparsity+ )++ ctx.save_for_backward(q, k, v, o, lse, block_indices, block_indices_lens)+ ctx.sm_scale = sm_scale+ ctx.HEAD_DIM = HEAD_DIM_K+ ctx.chunk_size_q = chunk_size_q+ ctx.chunk_size_k = chunk_size_k+ ctx.use_tma = use_tma+ ctx.sparsity = sparsity++ return o++ @staticmethod+ def backward(ctx, do):+ q, k, v, o, lse, block_indices, block_indices_lens = ctx.saved_tensors++ dq = torch.empty_like(q)+ dk = torch.empty_like(k)+ dv = torch.empty_like(v)++ attn_bwd_bsa_varlen_triton(+ do,+ q,+ k,+ v,+ o,+ dq,+ dk,+ dv,+ ctx.sm_scale,+ lse,+ block_indices,+ block_indices_lens,+ ctx.chunk_size_q,+ ctx.chunk_size_k,+ ctx.sparsity+ )++ return dq, dk, dv, None, None, None, None, None, None++flash_attn_bsa = _attention_bsa.apply++def rearrange_THW_to_3d_block(x, Nt, Nh, Nw, t, h, w, D):+ B, H, _, D = x.shape+ x = x.view(B, H, Nt, t, Nh, h, Nw, w, D)+ x = x.permute(0, 1, 2, 4, 6, 3, 5, 7, 8) # B H Nt Nh Nw t h w D+ return x.contiguous().view(B, H, Nt * Nh * Nw * t * h * w, D)++def rearrange_3d_block_to_THW(x, Nt, Nh, Nw, t, h, w, D):+ B, H, _, D = x.shape+ x = x.view(B, H, Nt, Nh, Nw, t, h, w, D)+ x = x.permute(0, 1, 2, 5, 3, 6, 4, 7, 8) # B H Nt t Nh h Nw w D+ return x.contiguous().view(B, H, Nt * t * Nh * h * Nw * w, D)++def flash_attn_bsa_3d(+ q: torch.Tensor, # [B, H, Sq, D]+ k: torch.Tensor, # [B, H, Skv, D]+ v: torch.Tensor, # [B, H, Skv, D]+ latent_shape_q,+ latent_shape_k,+ # bsa_params+ sparsity=0.875,+ cdf_threshold=None,+ chunk_3d_shape_q=[4, 4, 8],+ chunk_3d_shape_k=[4, 4, 8],+) -> torch.Tensor:+ _, _, Sq, head_dim_q = q.shape+ _, _, Sk, head_dim_k = k.shape++ assert head_dim_q == head_dim_k+ head_dim = head_dim_q++ Tq, Hq, Wq = latent_shape_q+ Tk, Hk, Wk = latent_shape_k++ assert Tq * Hq * Wq == Sq+ assert Tk * Hk * Wk == Sk++ tq, hq, wq = chunk_3d_shape_q+ tk, hk, wk = chunk_3d_shape_k++ assert Tq % tq == 0 and Hq % hq == 0 and Wq % wq == 0+ assert Tk % tk == 0 and Hk % hk == 0 and Wk % wk == 0++ Ntq = Tq // tq+ Nhq = Hq // hq+ Nwq = Wq // wq++ Ntk = Tk // tk+ Nhk = Hk // hk+ Nwk = Wk // wk++ q = rearrange_THW_to_3d_block(q, Ntq, Nhq, Nwq, tq, hq, wq, q.shape[-1])+ k = rearrange_THW_to_3d_block(k, Ntk, Nhk, Nwk, tk, hk, wk, k.shape[-1])+ v = rearrange_THW_to_3d_block(v, Ntk, Nhk, Nwk, tk, hk, wk, v.shape[-1])++ chunk_size_q = tq * hq * wq+ chunk_size_k = tk * hk * wk++ output = flash_attn_bsa(q, k, v, chunk_size_q, chunk_size_k, sparsity, cdf_threshold, 1 / head_dim**0.5)++ output = rearrange_3d_block_to_THW(output, Ntq, Nhq, Nwq, tq, hq, wq, output.shape[-1])+ return outputdiff --git a/models/longcat/modules/block_sparse_attention/common.py b/models/longcat/modules/block_sparse_attention/common.pynew file mode 100644index 0000000..ac817e1--- /dev/null+++ b/models/longcat/modules/block_sparse_attention/common.py@@ -0,0 +1,111 @@+import triton+import triton.language as tl+import os++if os.environ.get('TRITON_AUTOTUNE_ENBALE', '0') == '1':+ autotune = triton.autotune+else:+ def autotune(*args, **kwargs):+ def decorator(func):+ return func+ return decorator++configs_gating_preset = {+ 'default': {+ 'BLOCK_M': 64,+ 'BLOCK_N': 64,+ 'num_stages': 3,+ 'num_warps': 8,+ }+}++configs_gating = [+ triton.Config({'BLOCK_M': BM, 'BLOCK_N': BN}, num_stages=s, num_warps=w) \+ for BM in [64, 128] \+ for BN in [32, 64] \+ for s in [2, 3, 4, 5] \+ for w in [4, 8] \+]++gating_reevaluate_keys = ["M", "N"] if os.environ.get('TRITON_REEVALUATE_KEY', '0') == '1' else []+@autotune(configs_gating, key=gating_reevaluate_keys)+def _attn_fwd_gating(+ Q, K, Out,+ stride_qz, stride_qh, stride_qm, stride_qk,+ stride_kz, stride_kh, stride_kn, stride_kk,+ stride_oz, stride_oh, stride_om, stride_on,+ H, M, N,+ HEAD_DIM: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N: tl.constexpr,+ ):++ tl.static_assert(BLOCK_N <= HEAD_DIM)+ start_m = tl.program_id(0)+ off_hz = tl.program_id(1)+ off_z = off_hz // H+ off_h = off_hz % H+ q_offset = off_z.to(tl.int64) * stride_qz + off_h.to(tl.int64) * stride_qh+ k_offset = off_z.to(tl.int64) * stride_kz + off_h.to(tl.int64) * stride_kh+ o_offset = off_z.to(tl.int64) * stride_oz + off_h.to(tl.int64) * stride_oh++ # block pointers+ Q_block_ptr = tl.make_block_ptr(+ base=Q + q_offset,+ shape=(M, HEAD_DIM),+ strides=(stride_qm, stride_qk),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )++ K_block_ptr = tl.make_block_ptr(+ base=K + k_offset,+ shape=(HEAD_DIM, N),+ strides=(stride_kk, stride_kn),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_N),+ order=(0, 1),+ )+ O_block_ptr = tl.make_block_ptr(+ base=Out + o_offset,+ shape=(M, N),+ strides=(stride_om, stride_on),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, BLOCK_N),+ order=(1, 0),+ )++ # load q: it will stay in SRAM throughout+ q = tl.load(Q_block_ptr, boundary_check=(0,))+ for start_n in range(0, N, BLOCK_N):+ start_n = tl.multiple_of(start_n, BLOCK_N)+ # -- compute qk ----+ k = tl.load(K_block_ptr, boundary_check=(1,))+ qk = tl.dot(q, k)++ tl.store(O_block_ptr, qk.to(Out.type.element_ty), boundary_check=(0, 1))++ K_block_ptr = tl.advance(K_block_ptr, (0, BLOCK_N))+ O_block_ptr = tl.advance(O_block_ptr, (0, BLOCK_N))+++def _attn_bwd_preprocess(+ O, DO,+ Delta, # output+ N_CTX,+ BLOCK_M: tl.constexpr,+ HEAD_DIM: tl.constexpr+ ):++ off_m = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M)+ off_hz = tl.program_id(1)+ off_n = tl.arange(0, HEAD_DIM)+ # load+ o = tl.load(O + off_hz * HEAD_DIM * N_CTX + off_m[:, None] * HEAD_DIM + off_n[None, :])+ do = tl.load(DO + off_hz * HEAD_DIM * N_CTX + off_m[:, None] * HEAD_DIM + off_n[None, :]).to(tl.float32)+ delta = tl.sum(o * do, axis=1)+ # write-back+ tl.store(Delta + off_hz * N_CTX + off_m, delta)diff --git a/models/longcat/modules/block_sparse_attention/communicate.py b/models/longcat/modules/block_sparse_attention/communicate.pynew file mode 100644index 0000000..349855a--- /dev/null+++ b/models/longcat/modules/block_sparse_attention/communicate.py@@ -0,0 +1,43 @@+import torch+++def p2p_communicate(+ rank, send_tensor, send_dst, recv_tensor, recv_src, cp_group, batch_p2p_comm+):+ """Point-to-point communications of KV and dKV in Attention with context parallelism"""+ send_recv_ops = []++ if batch_p2p_comm: # int(os.getenv("NVTE_BATCH_MHA_P2P_COMM", "0")) or (cp_size == 2) why set this?+ if rank % 2 == 0:+ send_op = torch.distributed.P2POp(+ torch.distributed.isend, send_tensor, send_dst, cp_group+ )+ recv_op = torch.distributed.P2POp(+ torch.distributed.irecv, recv_tensor, recv_src, cp_group+ )+ send_recv_ops.append(send_op)+ send_recv_ops.append(recv_op)+ else:+ recv_op = torch.distributed.P2POp(+ torch.distributed.irecv, recv_tensor, recv_src, cp_group+ )+ send_op = torch.distributed.P2POp(+ torch.distributed.isend, send_tensor, send_dst, cp_group+ )+ send_recv_ops.append(recv_op)+ send_recv_ops.append(send_op)+ send_recv_reqs = torch.distributed.batch_isend_irecv(send_recv_ops)+ else:+ if rank % 2 == 0:+ send_op = torch.distributed.isend(send_tensor, send_dst, cp_group)+ recv_op = torch.distributed.irecv(recv_tensor, recv_src, cp_group)+ send_recv_ops.append(send_op)+ send_recv_ops.append(recv_op)+ else:+ recv_op = torch.distributed.irecv(recv_tensor, recv_src, cp_group)+ send_op = torch.distributed.isend(send_tensor, send_dst, cp_group)+ send_recv_ops.append(recv_op)+ send_recv_ops.append(send_op)+ send_recv_reqs = send_recv_ops++ return send_recv_reqsdiff --git a/models/longcat/modules/block_sparse_attention/flash_attn_bsa_varlen_mask.py b/models/longcat/modules/block_sparse_attention/flash_attn_bsa_varlen_mask.pynew file mode 100644index 0000000..64171c7--- /dev/null+++ b/models/longcat/modules/block_sparse_attention/flash_attn_bsa_varlen_mask.py@@ -0,0 +1,946 @@+import triton+import triton.language as tl+import os++from .common import autotune+"""+TRITON_REEVALUATE_KEY=1+- autotune whenever params in reevaluate keys change+- use in benchmark script to fine the best config++TRITON_AUTOTUNE_ENBALE=1+- if set to 0, autotune will not work, and the related params must be passed to the function call.+"""++configs_fwd_bsa_varlen_preset = {+ 'default': {+ 'BLOCK_N': 64,+ 'num_stages': 3,+ 'num_warps': 8,+ },+ 'BLOCK_N_LG=64': {+ 'BLOCK_N': 64,+ 'num_stages': 3,+ 'num_warps': 4,+ },+}+configs_fwd_bsa_varlen = [+ triton.Config({'BLOCK_N': BN}, num_stages=s, num_warps=w) \+ for BN in [32, 64, 128] \+ for s in [2, 3, 4, 5] \+ for w in [4, 8] \+]++fwd_bsa_reevaluate_varlen_keys = ['N_CTX', 'BLOCK_M', 'BLOCK_N_LG', 'SPARSITY'] if os.environ.get('TRITON_REEVALUATE_KEY', '0') == '1' else []+@autotune(list(configs_fwd_bsa_varlen), key=fwd_bsa_reevaluate_varlen_keys)+def _attn_fwd_bsa_varlen(+ Q, K, V, sm_scale, M, Out,+ block_indices, # [B, H, M_COMPRESS, S_MAX]+ block_indices_lens, # [B, H, M_COMPRESS]+ stride_qz, stride_qh, stride_qm, stride_qk,+ stride_kz, stride_kh, stride_kn, stride_kk,+ stride_vz, stride_vh, stride_vn, stride_vk,+ stride_oz, stride_oh, stride_om, stride_ok,+ stride_bz, stride_bh, stride_bm, stride_bs,+ stride_lz, stride_lh, stride_lm,+ H, N_CTX,+ HEAD_DIM: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N_LG: tl.constexpr,+ BLOCK_N: tl.constexpr,+ SPARSITY: tl.constexpr, # not used; just for trigger reevaluate for benchmarking+ ):++ start_m = tl.program_id(0)+ off_hz = tl.program_id(1)+ off_z = off_hz // H+ off_h = off_hz % H++ q_offset = off_z.to(tl.int64) * stride_qz + off_h.to(tl.int64) * stride_qh+ k_offset = off_z.to(tl.int64) * stride_kz + off_h.to(tl.int64) * stride_kh+ v_offset = off_z.to(tl.int64) * stride_vz + off_h.to(tl.int64) * stride_vh+ o_offset = off_z.to(tl.int64) * stride_oz + off_h.to(tl.int64) * stride_oh+ b_offset = off_z.to(tl.int64) * stride_bz + off_h.to(tl.int64) * stride_bh+ l_offset = off_z.to(tl.int64) * stride_lz + off_h.to(tl.int64) * stride_lh++ # block pointers+ Q_block_ptr = tl.make_block_ptr(+ base=Q + q_offset,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_qm, stride_qk),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ V_block_ptr = tl.make_block_ptr(+ base=V + v_offset,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_vn, stride_vk),+ offsets=(0, 0),+ block_shape=(BLOCK_N, HEAD_DIM),+ order=(1, 0),+ )+ KT_block_ptr = tl.make_block_ptr(+ base=K + k_offset,+ shape=(HEAD_DIM, N_CTX),+ strides=(stride_kk, stride_kn),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_N),+ order=(0, 1),+ )+ O_block_ptr = tl.make_block_ptr(+ base=Out + o_offset,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_om, stride_ok),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ block_indices += b_offset + start_m * stride_bm+ block_indices_lens += l_offset + start_m * stride_lm+ # initialize offsets+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)++ # initialize pointer to m and l+ m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")+ l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + 1.0+ acc = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32)+ # load scales+ qk_scale = sm_scale+ qk_scale *= 1.44269504 # 1/ln2; exp2(x/ln2) == exp(x)+ # load q: it will stay in SRAM throughout+ q = tl.load(Q_block_ptr)+ S = tl.load(block_indices_lens)+ for i in range(S):+ block_id = tl.load(block_indices + i * stride_bs).to(tl.int32)+ lo, hi = block_id * BLOCK_N_LG, (block_id + 1) * BLOCK_N_LG+ lo = tl.multiple_of(lo, BLOCK_N)+ KT_block_ptr_i = tl.advance(KT_block_ptr, (0, lo))+ V_block_ptr_i = tl.advance(V_block_ptr, (lo, 0))++ # loop over k, v and update accumulator+ for start_n in range(lo, hi, BLOCK_N):+ start_n = tl.multiple_of(start_n, BLOCK_N)+ # -- compute qk ----+ kT = tl.load(KT_block_ptr_i)+ qkT = tl.dot(q, kT)++ m_ij = tl.maximum(m_i, tl.max(qkT, 1) * qk_scale)+ qkT = qkT * qk_scale - m_ij[:, None]+ p = tl.math.exp2(qkT)++ # -- update m_i and l_i+ alpha = tl.math.exp2(m_i - m_ij)+ l_ij = tl.sum(p, 1)+ # -- update output accumulator --+ acc = acc * alpha[:, None]+ # update acc+ v = tl.load(V_block_ptr_i)+ acc = tl.dot(p.to(v.dtype), v, acc) # keep in log2 domain for FA2 optimization+ # update m_i and l_i+ # place this at the end of the loop to reduce register pressure: https://github.com/triton-lang/triton/commit/ee6abd9+ l_i = l_i * alpha + l_ij # running sum of exp+ m_i = m_ij+ V_block_ptr_i = tl.advance(V_block_ptr_i, (BLOCK_N, 0))+ KT_block_ptr_i = tl.advance(KT_block_ptr_i, (0, BLOCK_N))++ # epilogue+ m_i += tl.math.log2(l_i)+ acc = acc / l_i[:, None]+ m_ptrs = M + off_hz * N_CTX + offs_m+ tl.store(m_ptrs, m_i)+ tl.store(O_block_ptr, acc.to(Out.type.element_ty))++configs_fwd_bsa_varlen_align_preset = {+ 'default': {+ 'num_stages': 3,+ 'num_warps': 8,+ },+ 'BLOCK_N_LG=64': {+ 'num_stages': 3,+ 'num_warps': 4,+ },+}+configs_fwd_bsa_varlen_align = [+ triton.Config({}, num_stages=s, num_warps=w) \+ for s in [2, 3, 4, 5] \+ for w in [4, 8] \+]++fwd_bsa_reevaluate_varlen_align_keys = ['N_CTX', 'BLOCK_M', 'BLOCK_N_LG', 'SPARSITY'] if os.environ.get('TRITON_REEVALUATE_KEY', '0') == '1' else []+@autotune(list(configs_fwd_bsa_varlen_align), key=fwd_bsa_reevaluate_varlen_align_keys)+def _attn_fwd_bsa_varlen_align(+ Q, K, V, sm_scale, M, Out,+ block_indices, # [B, H, M_COMPRESS, S_MAX]+ block_indices_lens, # [B, H, M_COMPRESS]+ stride_qz, stride_qh, stride_qm, stride_qk,+ stride_kz, stride_kh, stride_kn, stride_kk,+ stride_vz, stride_vh, stride_vn, stride_vk,+ stride_oz, stride_oh, stride_om, stride_on,+ stride_bz, stride_bh, stride_bm, stride_bs,+ stride_lz, stride_lh, stride_lm,+ H, N_CTX,+ HEAD_DIM: tl.constexpr,+ BLOCK_M: tl.constexpr,+ BLOCK_N_LG: tl.constexpr,+ SPARSITY: tl.constexpr, # not used; just for trigger reevaluate for benchmarking+ ):++ start_m = tl.program_id(0)+ off_hz = tl.program_id(1)+ off_z = off_hz // H+ off_h = off_hz % H++ q_offset = off_z.to(tl.int64) * stride_qz + off_h.to(tl.int64) * stride_qh+ k_offset = off_z.to(tl.int64) * stride_kz + off_h.to(tl.int64) * stride_kh+ v_offset = off_z.to(tl.int64) * stride_vz + off_h.to(tl.int64) * stride_vh+ o_offset = off_z.to(tl.int64) * stride_oz + off_h.to(tl.int64) * stride_oh+ b_offset = off_z.to(tl.int64) * stride_bz + off_h.to(tl.int64) * stride_bh+ l_offset = off_z.to(tl.int64) * stride_lz + off_h.to(tl.int64) * stride_lh++ # block pointers+ Q_block_ptr = tl.make_block_ptr(+ base=Q + q_offset,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_qm, stride_qk),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ V_block_ptr = tl.make_block_ptr(+ base=V + v_offset,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_vn, stride_vk),+ offsets=(0, 0),+ block_shape=(BLOCK_N_LG, HEAD_DIM),+ order=(1, 0),+ )+ KT_block_ptr = tl.make_block_ptr(+ base=K + k_offset,+ shape=(HEAD_DIM, N_CTX),+ strides=(stride_kk, stride_kn),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_N_LG),+ order=(0, 1),+ )+ O_block_ptr = tl.make_block_ptr(+ base=Out + o_offset,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_om, stride_on),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ block_indices += b_offset + start_m * stride_bm+ block_indices_lens += l_offset + start_m * stride_lm+ # initialize offsets+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)++ # initialize pointer to m and l+ m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")+ l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + 1.0+ acc = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32)+ # load scales+ qk_scale = sm_scale+ qk_scale *= 1.44269504 # 1/ln2; exp2(x/ln2) == exp(x)+ # load q: it will stay in SRAM throughout+ q = tl.load(Q_block_ptr)+ S = tl.load(block_indices_lens)+ for i in range(S):+ block_id = tl.load(block_indices + i * stride_bs).to(tl.int32)+ lo = block_id * BLOCK_N_LG+ lo = tl.multiple_of(lo, BLOCK_N_LG)+ KT_block_ptr_i = tl.advance(KT_block_ptr, (0, lo))+ V_block_ptr_i = tl.advance(V_block_ptr, (lo, 0))++ # -- compute qk ----+ kT = tl.load(KT_block_ptr_i)+ qkT = tl.dot(q, kT)++ m_ij = tl.maximum(m_i, tl.max(qkT, 1) * qk_scale)+ qkT = qkT * qk_scale - m_ij[:, None]+ p = tl.math.exp2(qkT)++ # -- update m_i and l_i+ alpha = tl.math.exp2(m_i - m_ij)+ l_ij = tl.sum(p, 1)+ # -- update output accumulator --+ acc = acc * alpha[:, None]+ # update acc+ v = tl.load(V_block_ptr_i)+ acc = tl.dot(p.to(v.dtype), v, acc) # keep in log2 domain for FA2 optimization+ # update m_i and l_i+ # place this at the end of the loop to reduce register pressure: https://github.com/triton-lang/triton/commit/ee6abd9+ l_i = l_i * alpha + l_ij # running sum of exp+ m_i = m_ij+++ # epilogue+ m_i += tl.math.log2(l_i)+ acc = acc / l_i[:, None]+ m_ptrs = M + off_hz * N_CTX + offs_m+ tl.store(m_ptrs, m_i)+ tl.store(O_block_ptr, acc.to(Out.type.element_ty))+++# The main inner-loop logic for computing dK and dV.+def _attn_bwd_dkdv_bsa_varlen(+ dk, dv,+ k, v,+ Q, DO,+ M, D,+ block_indices,+ block_indices_lens,+ # shared by Q/K/V/DO.+ # stride_tok, stride_d,+ stride_qm, stride_qk,+ stride_dom, stride_dok,+ stride_mm,+ stride_dm,+ stride_bm,+ N_CTX,+ BLOCK_M1: tl.constexpr,+ HEAD_DIM: tl.constexpr,+ ):++ QT_block_ptr = tl.make_block_ptr(+ base=Q,+ shape=(HEAD_DIM, N_CTX),+ strides=(stride_qk, stride_qm),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_M1),+ order=(0, 1),+ )++ DO_block_ptr = tl.make_block_ptr(+ base=DO,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_dom, stride_dok),+ offsets=(0, 0),+ block_shape=(BLOCK_M1, HEAD_DIM),+ order=(1, 0),+ )++ S = tl.load(block_indices_lens)+ for i in range(S):+ block_id = tl.load(block_indices + i * stride_bm).to(tl.int32)+ start_m = block_id * BLOCK_M1+ start_m = tl.multiple_of(start_m, BLOCK_M1)++ QT_block_ptr_i = tl.advance(QT_block_ptr, (0, start_m))+ DO_block_ptr_i = tl.advance(DO_block_ptr, (start_m, 0))++ qT = tl.load(QT_block_ptr_i)+ # Load m before computing qk to reduce pipeline stall.+ offs_m = start_m + tl.arange(0, BLOCK_M1) * stride_mm+ m = tl.load(M + offs_m)+ kqT = tl.dot(k, qT)+ pT = tl.math.exp2(kqT - m[None, :])++ do = tl.load(DO_block_ptr_i)+ # Compute dV.+ ppT = pT+ ppT = ppT.to(v.dtype)+ dv += tl.dot(ppT, do)+ # D (= delta) is pre-divided by ds_scale.+ offs_d = start_m + tl.arange(0, BLOCK_M1) * stride_dm+ Di = tl.load(D + offs_d)+ # Compute dP and dS.+ dpT = tl.dot(v, tl.trans(do)).to(tl.float32)+ dsT = pT * (dpT - Di[None, :])+ dsT = dsT.to(v.dtype)+ dk += tl.dot(dsT, tl.trans(qT))+++ return dk, dv+++# the main inner-loop logic for computing dQ+def _attn_bwd_dq_bsa_varlen(+ dq,+ q, do,+ m, d,+ K, V,+ N_CTX,+ BLOCK_N2: tl.constexpr,+ BLOCK_N_LG: tl.constexpr,+ HEAD_DIM: tl.constexpr,+ block_indices,+ block_indices_lens,+ stride_bn,+ # stride_tok, stride_d,+ stride_kn, stride_kk,+ stride_vn, stride_vk,+ ):++ VT_block_ptr = tl.make_block_ptr(+ base=V,+ shape=(HEAD_DIM, N_CTX),+ strides=(stride_vk, stride_vn),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_N2),+ order=(0, 1),+ )+ KT_block_ptr = tl.make_block_ptr(+ base=K,+ shape=(HEAD_DIM, N_CTX),+ strides=(stride_kk, stride_kn),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_N2),+ order=(0, 1),+ )++ S = tl.load(block_indices_lens)+ for i in range(S):+ block_id = tl.load(block_indices + i * stride_bn).to(tl.int32)+ lo, hi = block_id * BLOCK_N_LG, (block_id + 1) * BLOCK_N_LG+ lo = tl.multiple_of(lo, BLOCK_N2)++ KT_block_ptr_i = tl.advance(KT_block_ptr, (0, lo))+ VT_block_ptr_i = tl.advance(VT_block_ptr, (0, lo))++ for start_n in range(lo, hi, BLOCK_N2):+ start_n = tl.multiple_of(start_n, BLOCK_N2)++ kT = tl.load(KT_block_ptr_i)+ vT = tl.load(VT_block_ptr_i)+ qkT = tl.dot(q, kT)+ p = tl.math.exp2(qkT - m)+ # Compute dP and dS.+ dp = tl.dot(do, vT).to(tl.float32)+ ds = p * (dp - d)+ ds = ds.to(kT.dtype) # https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/flash_attn_triton.py: Converting ds to q.dtype here reduces register pressure and makes it much faster for BLOCK_HEADDIM=128+ # Compute dQ.+ # NOTE: We need to de-scale dq in the end, because kT was pre-scaled.+ dq += tl.dot(ds, tl.trans(kT))+ # Increment pointers.+ KT_block_ptr_i = tl.advance(KT_block_ptr_i, (0, BLOCK_N2))+ VT_block_ptr_i = tl.advance(VT_block_ptr_i, (0, BLOCK_N2))++ return dq++# the main inner-loop logic for computing dQ+def _attn_bwd_dq_bsa_varlen_align(+ dq,+ q, do,+ m, d,+ K, V,+ N_CTX,+ BLOCK_N_LG: tl.constexpr,+ HEAD_DIM: tl.constexpr,+ block_indices,+ block_indices_lens,+ stride_bn,+ stride_kn, stride_kk,+ stride_vn, stride_vk,+ ):++ VT_block_ptr = tl.make_block_ptr(+ base=V,+ shape=(HEAD_DIM, N_CTX),+ strides=(stride_vk, stride_vn),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_N_LG),+ order=(0, 1),+ )+ KT_block_ptr = tl.make_block_ptr(+ base=K,+ shape=(HEAD_DIM, N_CTX),+ strides=(stride_kk, stride_kn),+ offsets=(0, 0),+ block_shape=(HEAD_DIM, BLOCK_N_LG),+ order=(0, 1),+ )++ S = tl.load(block_indices_lens)+ for i in range(S):+ block_id = tl.load(block_indices + i * stride_bn).to(tl.int32)+ lo = block_id * BLOCK_N_LG+ lo = tl.multiple_of(lo, BLOCK_N_LG)++ KT_block_ptr_i = tl.advance(KT_block_ptr, (0, lo))+ VT_block_ptr_i = tl.advance(VT_block_ptr, (0, lo))++ kT = tl.load(KT_block_ptr_i)+ vT = tl.load(VT_block_ptr_i)+ qkT = tl.dot(q, kT)+ p = tl.math.exp2(qkT - m)+ # Compute dP and dS.+ dp = tl.dot(do, vT).to(tl.float32)+ ds = p * (dp - d)+ ds = ds.to(kT.dtype) # https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/flash_attn_triton.py: Converting ds to q.dtype here reduces register pressure and makes it much faster for BLOCK_HEADDIM=128+ # Compute dQ.+ # NOTE: We need to de-scale dq in the end, because kT was pre-scaled.+ dq += tl.dot(ds, tl.trans(kT))+++ return dq++configs_bwd_dkdv_bsa_varlen_preset = {+ 'default': {+ 'BLOCK_N': 128,+ 'num_stages': 2,+ 'num_warps': 8,+ },+ 'BLOCK_N_DQ_LG=64': {+ 'BLOCK_N': 64,+ 'num_stages': 2,+ 'num_warps': 4,+ }+}+configs_bwd_dkdv_bsa_varlen = [+ triton.Config({'BLOCK_N': BN}, num_stages=s, num_warps=w) \+ for BN in [32, 64, 128] \+ for s in [2, 3, 4, 5] \+ for w in [4, 8] \+]+bwd_dkdv_bsa_varlen_reevaluate_keys = ['N_CTX', 'BLOCK_M', 'BLOCK_N_DQ_LG', 'SPARSITY'] if os.environ.get('TRITON_REEVALUATE_KEY', '0') == '1' else []+@autotune(list(configs_bwd_dkdv_bsa_varlen), key=bwd_dkdv_bsa_varlen_reevaluate_keys)+def _attn_bwd_dkdv_bsa_varlen_wrapper(+ Q, K, V, sm_scale, # softmax scale+ DO,+ DK, DV,+ M, # lse (log2)+ D,+ block_indices,+ block_indices_lens,+ # stride_z, stride_h, stride_tok, stride_d, # shared by Q/K/V/DO.+ # qkv+ stride_qz, stride_qh, stride_qm, stride_qk,+ stride_kz, stride_kh, stride_kn, stride_kk,+ stride_vz, stride_vh, stride_vn, stride_vk,+ # dk dv do+ stride_dkz, stride_dkh, stride_dkn, stride_dkk,+ stride_dvz, stride_dvh, stride_dvn, stride_dvk,+ stride_doz, stride_doh, stride_dom, stride_dok,+ # m, d+ stride_mz, stride_mh, stride_mm,+ stride_dz, stride_dh, stride_dm,+ #+ stride_bz, stride_bh, stride_bn, stride_bm, # block_indices+ stride_lz, stride_lh, stride_ln, # block_indices_lens+ #+ H, N_CTX,+ BLOCK_M: tl.constexpr,+ BLOCK_N: tl.constexpr,+ BLOCK_N_DQ_LG: tl.constexpr, # logical block size+ HEAD_DIM: tl.constexpr,+ SPARSITY: tl.constexpr, # not used; just for trigger reevaluate for benchmarking+ ):++ tl.static_assert(BLOCK_N_DQ_LG % BLOCK_N == 0)+ start_n = tl.program_id(0)++ off_hz = tl.program_id(2)+ off_z = off_hz // H+ off_h = off_hz % H++ off_q = off_z.to(tl.int64) * stride_qz + off_h.to(tl.int64) * stride_qh+ off_k = off_z.to(tl.int64) * stride_kz + off_h.to(tl.int64) * stride_kh+ off_v = off_z.to(tl.int64) * stride_vz + off_h.to(tl.int64) * stride_vh++ off_dk = off_z.to(tl.int64) * stride_dkz + off_h.to(tl.int64) * stride_dkh+ off_dv = off_z.to(tl.int64) * stride_dvz + off_h.to(tl.int64) * stride_dvh+ off_do = off_z.to(tl.int64) * stride_doz + off_h.to(tl.int64) * stride_doh++ off_m = off_z.to(tl.int64) * stride_mz + off_h.to(tl.int64) * stride_mh+ off_d = off_z.to(tl.int64) * stride_dz + off_h.to(tl.int64) * stride_dh++ off_block_incides = off_z.to(tl.int64) * stride_bz + off_h.to(tl.int64) * stride_bh+ off_block_incides_lens = off_z.to(tl.int64) * stride_lz + off_h.to(tl.int64) * stride_lh++ # offset pointers for batch/head+ Q += off_q+ K += off_k+ V += off_v+ DO += off_do+ DK += off_dk+ DV += off_dv++ M += off_m+ D += off_d+ block_indices += off_block_incides+ block_indices_lens += off_block_incides_lens++ # ---------------------------------------- [DKDV] ----------------------------------------++ dv = tl.zeros([BLOCK_N, HEAD_DIM], dtype=tl.float32)+ dk = tl.zeros([BLOCK_N, HEAD_DIM], dtype=tl.float32)++ # load K and V: they stay in SRAM throughout the inner loop.++ K_block_ptr = tl.make_block_ptr(+ base=K,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_kn, stride_kk),+ offsets=(start_n * BLOCK_N, 0),+ block_shape=(BLOCK_N, HEAD_DIM),+ order=(1, 0),+ )+ V_block_ptr = tl.make_block_ptr(+ base=V,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_vn, stride_vk),+ offsets=(start_n * BLOCK_N, 0),+ block_shape=(BLOCK_N, HEAD_DIM),+ order=(1, 0),+ )+ DK_block_ptr = tl.make_block_ptr(+ base=DK,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_dkn, stride_dkk),+ offsets=(start_n * BLOCK_N, 0),+ block_shape=(BLOCK_N, HEAD_DIM),+ order=(1, 0),+ )+ DV_block_ptr = tl.make_block_ptr(+ base=DV,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_dvn, stride_dvk),+ offsets=(start_n * BLOCK_N, 0),+ block_shape=(BLOCK_N, HEAD_DIM),+ order=(1, 0),+ )++ k = tl.load(K_block_ptr)+ v = tl.load(V_block_ptr)++ k_compress_idx = start_n * BLOCK_N // BLOCK_N_DQ_LG+ block_indices_i = block_indices + k_compress_idx * stride_bn+ block_indices_lens_i = block_indices_lens + k_compress_idx * stride_ln++ dk, dv = _attn_bwd_dkdv_bsa_varlen(+ dk, dv,+ k, v,+ Q, DO,+ M, D,+ block_indices_i,+ block_indices_lens_i,+ # shared by Q/K/V/DO.+ stride_qm, stride_qk,+ stride_dom, stride_dok,+ stride_mm,+ stride_dm,+ #+ stride_bm,+ N_CTX,+ BLOCK_M,+ HEAD_DIM,+ )++ # Write back dk+ dk *= sm_scale # S = scale * QKT; dK = scale * QdST+ tl.store(DK_block_ptr, dk.to(k.dtype))++ # Write back dv+ tl.store(DV_block_ptr, dv.to(v.dtype))++configs_bwd_dq_bsa_varlen_preset = {+ 'default': {+ 'BLOCK_N_DQ': 64,+ 'num_stages': 2,+ 'num_warps': 8,+ },+ 'BLOCK_N_DQ_LG=64': {+ 'BLOCK_N_DQ': 64,+ 'num_stages': 2,+ 'num_warps': 4,+ },+}+configs_bwd_dq_bsa_varlen = [+ triton.Config({'BLOCK_N_DQ': BN}, num_stages=s, num_warps=w) \+ for BN in [32, 64, 128] \+ for s in [2, 3, 4, 5] \+ for w in [4, 8] \+]+bwd_dq_bsa_varlen_reevaluate_keys = ['N_CTX', 'BLOCK_M', 'BLOCK_N_DQ_LG', 'SPARSITY'] if os.environ.get('TRITON_REEVALUATE_KEY', '0') == '1' else []+@autotune(list(configs_bwd_dq_bsa_varlen), key=bwd_dq_bsa_varlen_reevaluate_keys)+def _attn_bwd_dq_bsa_varlen_wrapper(+ Q, K, V, # softmax scale+ DO,+ DQ,+ M, # lse (log2)+ D,+ block_indices,+ block_indices_lens,+ # stride_z, stride_h, stride_tok, stride_d, # shared by Q/K/V/DO.+ # qkv+ stride_qz, stride_qh, stride_qm, stride_qk,+ stride_kz, stride_kh, stride_kn, stride_kk,+ stride_vz, stride_vh, stride_vn, stride_vk,+ # dq do+ stride_dqz, stride_dqh, stride_dqm, stride_dqk,+ stride_doz, stride_doh, stride_dom, stride_dok,+ # m, d+ stride_mz, stride_mh, stride_mm,+ stride_dz, stride_dh, stride_dm,+ #+ stride_bz, stride_bh, stride_bm, stride_bn, # block_indices+ stride_lz, stride_lh, stride_lm, # block_indices_lens+ #+ H, N_CTX,+ BLOCK_M: tl.constexpr,+ BLOCK_N_DQ_LG: tl.constexpr, # logical block size+ BLOCK_N_DQ: tl.constexpr,+ HEAD_DIM: tl.constexpr,+ SPARSITY: tl.constexpr, # not used; just for trigger reevaluate for benchmarking+ ):++ tl.static_assert(BLOCK_N_DQ_LG % BLOCK_N_DQ == 0)+ tl.static_assert(BLOCK_N_DQ_LG % BLOCK_M == 0)++ LN2: tl.constexpr = 0.6931471824645996 # = ln(2)++ start_m = tl.program_id(0)++ off_hz = tl.program_id(2)+ off_z = off_hz // H+ off_h = off_hz % H++ off_q = off_z.to(tl.int64) * stride_qz + off_h.to(tl.int64) * stride_qh+ off_k = off_z.to(tl.int64) * stride_kz + off_h.to(tl.int64) * stride_kh+ off_v = off_z.to(tl.int64) * stride_vz + off_h.to(tl.int64) * stride_vh++ off_dq = off_z.to(tl.int64) * stride_dqz + off_h.to(tl.int64) * stride_dqh+ off_do = off_z.to(tl.int64) * stride_doz + off_h.to(tl.int64) * stride_doh++ off_m = off_z.to(tl.int64) * stride_mz + off_h.to(tl.int64) * stride_mh+ off_d = off_z.to(tl.int64) * stride_dz + off_h.to(tl.int64) * stride_dh++ off_block_incides = off_z.to(tl.int64) * stride_bz + off_h.to(tl.int64) * stride_bh+ off_block_incides_lens = off_z.to(tl.int64) * stride_lz + off_h.to(tl.int64) * stride_lh++ # offset pointers for batch/head+ Q += off_q+ K += off_k+ V += off_v+ DO += off_do+ DQ += off_dq++ M += off_m+ D += off_d+ block_indices += off_block_incides+ block_indices_lens += off_block_incides_lens++ # ---------------------------------------- [DQ] ----------------------------------------++ Q_block_ptr = tl.make_block_ptr(+ base=Q,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_qm, stride_qk),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ DO_block_ptr = tl.make_block_ptr(+ base=DO,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_dom, stride_dok),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ DQ_block_ptr = tl.make_block_ptr(+ base=DQ,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_dqm, stride_dqk),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )++ q = tl.load(Q_block_ptr)+ do = tl.load(DO_block_ptr)++ dq = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32)++ start_m = start_m * BLOCK_M++ offs_m = start_m + tl.arange(0, BLOCK_M) * stride_mm+ offs_d = start_m + tl.arange(0, BLOCK_M) * stride_dm++ m = tl.load(M + offs_m)+ m = m[:, None]++ d = tl.load(D + offs_d)+ d = d[:, None]++ block_indices_m = block_indices + (start_m // BLOCK_M) * stride_bm+ block_indices_lens_m = block_indices_lens + (start_m // BLOCK_M) * stride_lm++ dq = _attn_bwd_dq_bsa_varlen(+ dq,+ q, do,+ m, d,+ K, V,+ N_CTX,+ BLOCK_N_DQ,+ BLOCK_N_DQ_LG,+ HEAD_DIM,+ block_indices_m,+ block_indices_lens_m,+ stride_bn,+ stride_kn, stride_kk,+ stride_vn, stride_vk,+ )++ # Write back dQ.+ dq *= LN2+ tl.store(DQ_block_ptr, dq.to(q.dtype))++configs_bwd_dq_bsa_varlen_align_preset = {+ 'default': {+ 'num_stages': 2,+ 'num_warps': 8,+ },+ 'BLOCK_N_DQ_LG=64': {+ 'num_stages': 2,+ 'num_warps': 4,+ },+}+configs_bwd_dq_bsa_varlen_align = [+ triton.Config({}, num_stages=s, num_warps=w) \+ for s in [2, 3, 4, 5] \+ for w in [4, 8] \+]+bwd_dq_bsa_varlen_align_reevaluate_keys = ['N_CTX', 'BLOCK_M', 'BLOCK_N_DQ_LG', 'SPARSITY'] if os.environ.get('TRITON_REEVALUATE_KEY', '0') == '1' else []+@autotune(list(configs_bwd_dq_bsa_varlen_align), key=bwd_dq_bsa_varlen_align_reevaluate_keys)+def _attn_bwd_dq_bsa_varlen_align_wrapper(+ Q, K, V, # softmax scale+ DO,+ DQ,+ M, # lse (log2)+ D,+ block_indices,+ block_indices_lens,+ # qkv+ stride_qz, stride_qh, stride_qm, stride_qk,+ stride_kz, stride_kh, stride_kn, stride_kk,+ stride_vz, stride_vh, stride_vn, stride_vk,+ # dq do+ stride_dqz, stride_dqh, stride_dqm, stride_dqk,+ stride_doz, stride_doh, stride_dom, stride_dok,+ # m, d+ stride_mz, stride_mh, stride_mm,+ stride_dz, stride_dh, stride_dm,+ #+ stride_bz, stride_bh, stride_bm, stride_bn, # block_indices+ stride_lz, stride_lh, stride_lm, # block_indices_lens+ #+ H, N_CTX,+ BLOCK_M: tl.constexpr,+ BLOCK_N_DQ_LG: tl.constexpr, # logical block size+ HEAD_DIM: tl.constexpr,+ SPARSITY: tl.constexpr, # not used; just for trigger reevaluate for benchmarking+ ):++ tl.static_assert(BLOCK_N_DQ_LG % BLOCK_N_DQ_LG == 0)+ tl.static_assert(BLOCK_N_DQ_LG % BLOCK_M == 0)++ LN2: tl.constexpr = 0.6931471824645996 # = ln(2)++ start_m = tl.program_id(0)++ off_hz = tl.program_id(2)+ off_z = off_hz // H+ off_h = off_hz % H++ off_q = off_z.to(tl.int64) * stride_qz + off_h.to(tl.int64) * stride_qh+ off_k = off_z.to(tl.int64) * stride_kz + off_h.to(tl.int64) * stride_kh+ off_v = off_z.to(tl.int64) * stride_vz + off_h.to(tl.int64) * stride_vh++ off_dq = off_z.to(tl.int64) * stride_dqz + off_h.to(tl.int64) * stride_dqh+ off_do = off_z.to(tl.int64) * stride_doz + off_h.to(tl.int64) * stride_doh++ off_m = off_z.to(tl.int64) * stride_mz + off_h.to(tl.int64) * stride_mh+ off_d = off_z.to(tl.int64) * stride_dz + off_h.to(tl.int64) * stride_dh++ off_block_incides = off_z.to(tl.int64) * stride_bz + off_h.to(tl.int64) * stride_bh+ off_block_incides_lens = off_z.to(tl.int64) * stride_lz + off_h.to(tl.int64) * stride_lh++ # offset pointers for batch/head+ Q += off_q+ K += off_k+ V += off_v+ DO += off_do+ DQ += off_dq++ M += off_m+ D += off_d+ block_indices += off_block_incides+ block_indices_lens += off_block_incides_lens++ # ---------------------------------------- [DQ] ----------------------------------------++ Q_block_ptr = tl.make_block_ptr(+ base=Q,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_qm, stride_qk),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ DO_block_ptr = tl.make_block_ptr(+ base=DO,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_dom, stride_dok),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )+ DQ_block_ptr = tl.make_block_ptr(+ base=DQ,+ shape=(N_CTX, HEAD_DIM),+ strides=(stride_dqm, stride_dqk),+ offsets=(start_m * BLOCK_M, 0),+ block_shape=(BLOCK_M, HEAD_DIM),+ order=(1, 0),+ )++ q = tl.load(Q_block_ptr)+ do = tl.load(DO_block_ptr)++ dq = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32)++ start_m = start_m * BLOCK_M++ offs_m = start_m + tl.arange(0, BLOCK_M) * stride_mm+ offs_d = start_m + tl.arange(0, BLOCK_M) * stride_dm++ m = tl.load(M + offs_m)+ m = m[:, None]++ # D (= delta) is pre-divided by ds_scale.+ d = tl.load(D + offs_d)+ d = d[:, None]++ block_indices_m = block_indices + (start_m // BLOCK_M) * stride_bm+ block_indices_lens_m = block_indices_lens + (start_m // BLOCK_M) * stride_lm++ dq = _attn_bwd_dq_bsa_varlen_align(+ dq,+ q, do,+ m, d,+ K, V,+ N_CTX,+ BLOCK_N_DQ_LG,+ HEAD_DIM,+ block_indices_m,+ block_indices_lens_m,+ stride_bn,+ stride_kn, stride_kk,+ stride_vn, stride_vk,+ )++ # Write back dQ.+ dq *= LN2+ tl.store(DQ_block_ptr, dq.to(q.dtype))+diff --git a/models/longcat/modules/blocks.py b/models/longcat/modules/blocks.pynew file mode 100644index 0000000..2b1223c--- /dev/null+++ b/models/longcat/modules/blocks.py@@ -0,0 +1,227 @@+# References:+# https://github.com/hpcaitech/Open-Sora+# https://github.com/facebookresearch/DiT/blob/main/models.py+# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py+# https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py#L14+++import math+import torch+import torch.nn as nn+import torch.nn.functional as F+import torch.amp as amp++from typing import Optional+++class FeedForwardSwiGLU(nn.Module):+ def __init__(+ self,+ dim: int,+ hidden_dim: int,+ multiple_of: int = 256,+ ffn_dim_multiplier: Optional[float] = None,+ ):+ super().__init__()+ hidden_dim = int(2 * hidden_dim / 3)+ # custom dim factor multiplier+ if ffn_dim_multiplier is not None:+ hidden_dim = int(ffn_dim_multiplier * hidden_dim)+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)++ self.dim = dim+ self.hidden_dim = hidden_dim+ self.ffn_mult = self.hidden_dim / float(self.dim)+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)++ def forward(self, x):+ return self.w2(F.silu(self.w1(x)) * self.w3(x))+++class RMSNorm_FP32(torch.nn.Module):+ def __init__(self, dim: int, eps: float):+ super().__init__()+ self.eps = eps+ self.weight = nn.Parameter(torch.ones(dim))++ def _norm(self, x):+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)++ def forward(self, x):+ output = self._norm(x.float()).type_as(x)+ return output * self.weight.to(output.dtype)+++class LayerNorm_FP32(nn.LayerNorm):+ def __init__(self, dim, eps, elementwise_affine):+ super().__init__(dim, eps=eps, elementwise_affine=elementwise_affine)++ def forward(self, inputs: torch.Tensor) -> torch.Tensor:+ origin_dtype = inputs.dtype+ out = F.layer_norm(+ inputs.float(),+ self.normalized_shape,+ None if self.weight is None else self.weight.float(),+ None if self.bias is None else self.bias.float() ,+ self.eps+ ).to(origin_dtype)+ return out+++class PatchEmbed3D(nn.Module):+ """Video to Patch Embedding.++ Args:+ patch_size (int): Patch token size. Default: (2,4,4).+ in_chans (int): Number of input video channels. Default: 3.+ embed_dim (int): Number of linear projection output channels. Default: 96.+ norm_layer (nn.Module, optional): Normalization layer. Default: None+ """++ def __init__(+ self,+ patch_size=(2, 4, 4),+ in_chans=3,+ embed_dim=96,+ norm_layer=None,+ flatten=True,+ ):+ super().__init__()+ self.patch_size = patch_size+ self.flatten = flatten++ self.in_chans = in_chans+ self.embed_dim = embed_dim++ self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)+ if norm_layer is not None:+ self.norm = norm_layer(embed_dim)+ else:+ self.norm = None++ def forward(self, x):+ """Forward function."""+ # padding+ _, _, D, H, W = x.size()+ if W % self.patch_size[2] != 0:+ x = F.pad(x, (0, self.patch_size[2] - W % self.patch_size[2]))+ if H % self.patch_size[1] != 0:+ x = F.pad(x, (0, 0, 0, self.patch_size[1] - H % self.patch_size[1]))+ if D % self.patch_size[0] != 0:+ x = F.pad(x, (0, 0, 0, 0, 0, self.patch_size[0] - D % self.patch_size[0]))++ B, C, T, H, W = x.shape+ x = self.proj(x) # (B C T H W)+ if self.norm is not None:+ D, Wh, Ww = x.size(2), x.size(3), x.size(4)+ x = x.flatten(2).transpose(1, 2)+ x = self.norm(x)+ x = x.transpose(1, 2).view(-1, self.embed_dim, D, Wh, Ww)+ if self.flatten:+ x = x.flatten(2).transpose(1, 2) # BCTHW -> BNC+ return x+++def modulate_fp32(norm_func, x, shift, scale):+ # Suppose x is (B, N, D), shift is (B, -1, D), scale is (B, -1, D)+ # ensure the modulation params be fp32+ assert shift.dtype == torch.float32, scale.dtype == torch.float32+ dtype = x.dtype+ x = norm_func(x.to(torch.float32))+ scale = scale + 1.0+ x.mul_(scale).add_(shift)+ return x.to(dtype)+++class FinalLayer_FP32(nn.Module):+ """+ The final layer of DiT.+ """++ def __init__(self, hidden_size, num_patch, out_channels, adaln_tembed_dim):+ super().__init__()+ self.hidden_size = hidden_size+ self.num_patch = num_patch+ self.out_channels = out_channels+ self.adaln_tembed_dim = adaln_tembed_dim++ self.norm_final = LayerNorm_FP32(hidden_size, elementwise_affine=False, eps=1e-6)+ self.linear = nn.Linear(hidden_size, num_patch * out_channels, bias=True)+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(adaln_tembed_dim, 2 * hidden_size, bias=True))++ def forward(self, x, t, latent_shape):+ # timestep shape: [B, T, C]+ t = t.to(torch.float32)+ B, N, C = x.shape+ T, _, _ = latent_shape++ with amp.autocast('cuda', dtype=torch.float32):+ shift, scale = self.adaLN_modulation(t).unsqueeze(2).chunk(2, dim=-1) # [B, T, 1, C]+ x = modulate_fp32(self.norm_final, x.view(B, T, -1, C), shift, scale).view(B, N, C)+ x = self.linear(x)+ return x+++class TimestepEmbedder(nn.Module):+ """+ Embeds scalar timesteps into vector representations.+ """++ def __init__(self, t_embed_dim, frequency_embedding_size=256):+ super().__init__()+ self.t_embed_dim = t_embed_dim+ self.frequency_embedding_size = frequency_embedding_size+ self.mlp = nn.Sequential(+ nn.Linear(frequency_embedding_size, t_embed_dim, bias=True),+ nn.SiLU(),+ nn.Linear(t_embed_dim, t_embed_dim, bias=True),+ )++ @staticmethod+ def timestep_embedding(t, dim, max_period=10000):+ """+ Create sinusoidal timestep embeddings.+ :param t: a 1-D Tensor of N indices, one per batch element.+ These may be fractional.+ :param dim: the dimension of the output.+ :param max_period: controls the minimum frequency of the embeddings.+ :return: an (N, D) Tensor of positional embeddings.+ """+ half = dim // 2+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half)+ freqs = freqs.to(device=t.device)+ args = t[:, None].float() * freqs[None]+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)+ if dim % 2:+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)+ return embedding++ def forward(self, t, dtype):+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)+ if t_freq.dtype != dtype:+ t_freq = t_freq.to(dtype)+ t_emb = self.mlp(t_freq)+ return t_emb+++class CaptionEmbedder(nn.Module):+ """+ Embeds class labels into vector representations.+ """++ def __init__(self, in_channels, hidden_size):+ super().__init__()+ self.in_channels = in_channels+ self.hidden_size = hidden_size+ self.y_proj = nn.Sequential(+ nn.Linear(in_channels, hidden_size, bias=True),+ nn.GELU(approximate="tanh"),+ nn.Linear(hidden_size, hidden_size, bias=True),+ )++ def forward(self, caption):+ B, _, N, C = caption.shape+ caption = self.y_proj(caption)+ return captiondiff --git a/models/longcat/modules/longcat_video_dit.py b/models/longcat/modules/longcat_video_dit.pynew file mode 100644index 0000000..de230c9--- /dev/null+++ b/models/longcat/modules/longcat_video_dit.py@@ -0,0 +1,424 @@+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 .attention import Attention, MultiHeadCrossAttention+from .blocks import TimestepEmbedder, CaptionEmbedder, PatchEmbed3D, FeedForwardSwiGLU, FinalLayer_FP32, LayerNorm_FP32, modulate_fp32+++class LongCatSingleStreamBlock(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+ ):+ 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.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.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.ffn = FeedForwardSwiGLU(dim=hidden_size, hidden_dim=int(hidden_size * mlp_ratio))+ self.ffn_mult = self.ffn.ffn_mult+ self.ffn_chunk_min = 128++ def _apply_ffn_chunked(self, ffn_in: torch.Tensor) -> torch.Tensor:+ _, seq_len, dim = ffn_in.shape+ if seq_len < self.ffn_chunk_min:+ return self.ffn(ffn_in)+ ffn_in_flat = ffn_in.reshape(-1, dim)+ chunk_size = max(int(seq_len // self.ffn_mult), 1)+ if chunk_size >= ffn_in_flat.shape[0]:+ return self.ffn(ffn_in)+ for ffn_chunk in torch.split(ffn_in_flat, chunk_size, dim=0):+ ffn_chunk[...] = self.ffn(ffn_chunk)+ return ffn_in++ def forward(self, x, y, t, y_seqlen, latent_shape, num_cond_latents=None, return_kv=False, kv_cache=None, skip_crs_attn=False):+ """+ 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)+ else:+ attn_outputs = self.attn(x_m, shape=latent_shape, num_cond_latents=num_cond_latents, return_kv=return_kv)++ if return_kv:+ x_s, kv_cache = attn_outputs+ else:+ x_s = 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)++ # 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)++ # 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._apply_ffn_chunked(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 LongCatVideoTransformer3DModel(+ 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,+ ) -> 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.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(+ [+ LongCatSingleStreamBlock(+ 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+ )+ for i in range(depth)+ ]+ )++ 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 = []+ self._interrupt_check = None++ 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+ ):+ x_list = hidden_states if isinstance(hidden_states, list) else [hidden_states]+ joint_pass = isinstance(hidden_states, list)++ if not isinstance(encoder_hidden_states, list):+ encoder_hidden_states = [encoder_hidden_states] * len(x_list)+ if not isinstance(encoder_attention_mask, list):+ encoder_attention_mask = [encoder_attention_mask] * len(x_list)+ if not isinstance(timestep, list):+ timestep = [timestep] * len(x_list)+ if not isinstance(num_cond_latents, list):+ num_cond_latents = [num_cond_latents] * len(x_list)+ if not isinstance(kv_cache_dict, list):+ kv_cache_dict = [kv_cache_dict] * len(x_list)++ dtype = self.x_embedder.proj.weight.dtype+ t_list = []+ enc_list = []+ y_seqlens_list = []+ latent_shapes = []+ for idx, (x, step, enc, mask) in enumerate(zip(x_list, timestep, encoder_hidden_states, encoder_attention_mask)):+ B, _, T, H, W = x.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."++ if len(step.shape) == 1:+ step = step.unsqueeze(1).expand(-1, N_t)++ x = x.to(dtype)+ step = step.to(dtype)+ enc = enc.to(dtype)++ x = self.x_embedder(x)++ with amp.autocast(device_type='cuda', dtype=torch.float32):+ t = self.t_embedder(step.float().flatten(), torch.float32).reshape(B, N_t, -1)+ t = t.to(torch.float32)++ enc = self.y_embedder(enc)++ if self.text_tokens_zero_pad and mask is not None:+ enc = enc * mask[:, None, :, None]++ if mask is not None:+ if mask.dim() > 2:+ mask = mask.squeeze(1).squeeze(1)+ y_seqlens = mask.sum(dim=1).to(torch.int64).tolist()+ else:+ y_seqlens = [enc.shape[2]] * enc.shape[0]++ enc = enc.squeeze(1)++ x_list[idx] = x+ t_list.append(t)+ enc_list.append(enc)+ y_seqlens_list.append(y_seqlens)+ latent_shapes.append((N_t, N_h, N_w))++ kv_cache_dict_ret = [dict() for _ in x_list] if return_kv else None+ for block_idx, block in enumerate(self.blocks):+ if self._interrupt_check is not None and self._interrupt_check():+ return [None] * len(x_list) if joint_pass else None+ for i in range(len(x_list)):+ if torch.is_grad_enabled() and self.gradient_checkpointing:+ block_outputs = self._gradient_checkpointing_func(+ block, x_list[i], enc_list[i], t_list[i], y_seqlens_list[i],+ latent_shapes[i], num_cond_latents[i], return_kv, kv_cache_dict[i].get(block_idx, None) if kv_cache_dict[i] is not None else None, skip_crs_attn+ )+ else:+ block_outputs = block(+ x_list[i], enc_list[i], t_list[i], y_seqlens_list[i],+ latent_shapes[i], num_cond_latents[i], return_kv, kv_cache_dict[i].get(block_idx, None) if kv_cache_dict[i] is not None else None, skip_crs_attn+ )+ if return_kv:+ x_list[i], kv_cache = block_outputs+ if offload_kv_cache:+ kv_cache_dict_ret[i][block_idx] = (kv_cache[0].cpu(), kv_cache[1].cpu())+ else:+ kv_cache_dict_ret[i][block_idx] = (kv_cache[0].contiguous(), kv_cache[1].contiguous())+ else:+ x_list[i] = block_outputs++ if self._interrupt_check is not None and self._interrupt_check():+ return [None] * len(x_list) if joint_pass else None++ outputs = []+ for x, t, latent_shape in zip(x_list, t_list, latent_shapes):+ x = self.final_layer(x, t, latent_shape)+ x = self.unpatchify(x, *latent_shape)+ outputs.append(x.to(torch.float32))++ if return_kv:+ return (outputs if joint_pass else outputs[0]), (kv_cache_dict_ret if joint_pass else kv_cache_dict_ret[0])+ return outputs if joint_pass else outputs[0]+++ 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 xdiff --git a/models/longcat/modules/lora_utils.py b/models/longcat/modules/lora_utils.pynew file mode 100644index 0000000..105a4b1--- /dev/null+++ b/models/longcat/modules/lora_utils.py@@ -0,0 +1,197 @@+# References:+# https://github.com/microsoft/LoRA/blob/main/loralib/layers.py+# https://github.com/cloneofsimo/lora/blob/master/lora_diffusion/lora.py+# https://github.com/bmaltais/kohya_ss++import math+import functools+from collections import defaultdict++from typing import Optional++import torch+++class LoRAUPParallel(torch.nn.Module):+ def __init__(self, blocks):+ super().__init__()+ self.blocks = torch.nn.ModuleList(blocks)++ def forward(self, x):+ assert x.shape[-1] % len(self.blocks) == 0+ xs = torch.chunk(x, len(self.blocks), dim=-1)+ out = torch.cat([self.blocks[i](xs[i]) for i in range(len(self.blocks))], dim=-1)+ return out+++class LoRAModule(torch.nn.Module):+ """+ replaces forward method of the original Linear, instead of replacing the original Linear module.+ """++ def __init__(+ self,+ lora_name,+ org_module: torch.nn.Module,+ multiplier=1.0,+ lora_dim=4,+ alpha=1,+ n_seperate=1+ ):+ super().__init__()+ self.lora_name = lora_name++ assert org_module.__class__.__name__ == "Linear"+ in_dim = org_module.in_features+ out_dim = org_module.out_features++ if n_seperate > 1:+ assert out_dim % n_seperate == 0++ self.lora_dim = lora_dim+ if n_seperate > 1:+ self.lora_down = torch.nn.Linear(in_dim, n_seperate * self.lora_dim, bias=False)+ self.lora_up = LoRAUPParallel([torch.nn.Linear(self.lora_dim, out_dim // n_seperate, bias=False) for _ in range(n_seperate)])+ else:+ self.lora_down = torch.nn.Linear(in_dim, self.lora_dim, bias=False)+ self.lora_up = torch.nn.Linear(self.lora_dim, out_dim, bias=False)++ if type(alpha) == torch.Tensor:+ alpha = alpha.detach().float().numpy() # without casting, bf16 causes error+ alpha = self.lora_dim if alpha is None or alpha == 0 else alpha+ alpha_scale = alpha / self.lora_dim+ self.register_buffer("alpha_scale", torch.tensor(alpha_scale))++ # same as microsoft's+ torch.nn.init.kaiming_uniform_(self.lora_down.weight, a=math.sqrt(5))+ if n_seperate > 1:+ for block in self.lora_up.blocks:+ torch.nn.init.zeros_(block.weight)+ else:+ torch.nn.init.zeros_(self.lora_up.weight)++ self.multiplier = multiplier+ self.use_lora = True++ def set_use_lora(self, use_lora):+ self.use_lora = use_lora+++class LoRANetwork(torch.nn.Module):++ LORA_PREFIX = "lora"+ LORA_HYPHEN = "___lorahyphen___"++ def __init__(+ self,+ model,+ lora_network_state_dict_loaded,+ multiplier: float = 1.0,+ lora_dim: int = 128,+ alpha: float = 64,+ ) -> None:+ super().__init__()+ self.multiplier = multiplier+ self.use_lora = True+ self.lora_dim = lora_dim+ self.alpha = alpha++ print(f"create LoRA network. base dim (rank): {lora_dim}, alpha: {alpha}")++ lora_module_names = set()+ for key in lora_network_state_dict_loaded.keys():+ if key.endswith("lora_down.weight"):+ lora_name = key.split(".lora_down.weight")[0]+ lora_module_names.add(lora_name)++ loras = []+ for lora_name in lora_module_names:+ # Restore the real module name in the model.+ module_name = lora_name.replace("lora___lorahyphen___", "").replace("___lorahyphen___", ".")+ # Find the module.+ try:+ module = model+ for part in module_name.split('.'):+ module = getattr(module, part)+ except Exception as e:+ print(f"Cannot find module: {module_name}, error: {e}")+ continue+ if module.__class__.__name__ != "Linear":+ continue++ # Infer n_seperate.+ n_seperate = 1+ prefix = lora_name + ".lora_up.blocks"+ n_blocks = sum(1 for k in lora_network_state_dict_loaded if k.startswith(prefix))+ if n_blocks > 0:+ n_seperate = n_blocks++ dim = self.lora_dim+ alpha = self.alpha++ lora = LoRAModule(+ lora_name,+ module,+ self.multiplier,+ dim,+ alpha,+ n_seperate=n_seperate+ )+ loras.append(lora)++ self.loras = loras+ for lora in self.loras:+ self.add_module(lora.lora_name, lora)+ print(f"create LoRA for model: {len(self.loras)} modules.")++ # assertion+ names = set()+ for lora in self.loras:+ assert lora.lora_name not in names, f"duplicated lora name: {lora.lora_name}"+ names.add(lora.lora_name)++ def disapply_to(self):+ for lora in self.loras:+ lora.disapply_to()++ def set_multiplier(self, multiplier):+ self.multiplier = multiplier+ for lora in self.loras:+ lora.multiplier = self.multiplier++ def set_use_lora(self, use_lora):+ self.use_lora = use_lora+ for lora in self.loras:+ lora.set_use_lora(use_lora)++ def prepare_optimizer_params(self, lr):+ self.requires_grad_(True)+ all_params = []++ params = []+ for lora in self.loras:+ params.extend(lora.parameters())++ param_data = {"params": params}+ param_data["lr"] = lr+ all_params.append(param_data)++ return all_params+++def create_lora_network(+ transformer,+ lora_network_state_dict_loaded,+ multiplier: float,+ network_dim: Optional[int],+ network_alpha: Optional[float],+):+ network = LoRANetwork(+ transformer,+ lora_network_state_dict_loaded,+ multiplier=multiplier,+ lora_dim=network_dim,+ alpha=network_alpha,+ )+ return network+diff --git a/models/longcat/modules/rope_3d.py b/models/longcat/modules/rope_3d.pynew file mode 100644index 0000000..1b2b14c--- /dev/null+++ b/models/longcat/modules/rope_3d.py@@ -0,0 +1,114 @@+# References:+# https://github.com/facebookresearch/fairseq/blob/main/fairseq/modules/rotary_positional_embedding.py++import torch+import torch.nn as nn++from einops import rearrange, repeat++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_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1)+ return torch.stack((-x_imag, x_real), dim=-1).flatten(-2)+++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 = tuple(grid_size)+ if key not in self.freqs_dict:+ self.freqs_dict[key] = self.precompute_freqs_cis_3d(grid_size)++ def precompute_freqs_cis_3d(self, grid_size):+ 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)+ cpu = torch.device("cpu")+ freqs_t = 1.0 / (+ self.base ** (torch.arange(0, dim_t, 2, device=cpu, dtype=torch.float32)[: (dim_t // 2)] / dim_t)+ )+ freqs_h = 1.0 / (+ self.base ** (torch.arange(0, dim_h, 2, device=cpu, dtype=torch.float32)[: (dim_h // 2)] / dim_h)+ )+ freqs_w = 1.0 / (+ self.base ** (torch.arange(0, dim_w, 2, device=cpu, dtype=torch.float32)[: (dim_w // 2)] / dim_w)+ )+ grid_t = torch.arange(num_frames, device=cpu, dtype=torch.float32)+ grid_h = torch.arange(height, device=cpu, dtype=torch.float32)+ grid_w = torch.arange(width, device=cpu, dtype=torch.float32)+ 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")++ return freqs++ def forward(self, q, k, grid_size):+ """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 = tuple(grid_size)+ if key not in self.freqs_dict:+ self.register_grid_size(grid_size)++ freqs = self.freqs_dict[key].to(device=q.device, dtype=torch.float32)+ cos = freqs.cos().unsqueeze(0).unsqueeze(2)+ sin = freqs.sin().unsqueeze(0).unsqueeze(2)++ q_out = q.float()+ k_out = k.float()+ q_rot = rotate_half(q_out)+ k_rot = rotate_half(k_out)+ q_out.mul_(cos).add_(q_rot.mul_(sin))+ k_out.mul_(cos).add_(k_rot.mul_(sin))++ return q_out.to(q.dtype), k_out.to(k.dtype)diff --git a/models/longcat/modules/scheduling_flow_match_euler_discrete.py b/models/longcat/modules/scheduling_flow_match_euler_discrete.pynew file mode 100644index 0000000..65a32b4--- /dev/null+++ b/models/longcat/modules/scheduling_flow_match_euler_discrete.py@@ -0,0 +1,561 @@+# Copyright 2025 Stability AI, Katherine Crowson and The HuggingFace Team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++import math+from dataclasses import dataclass+from typing import List, Optional, Tuple, Union++import numpy as np+import torch++from diffusers.configuration_utils import ConfigMixin, register_to_config+from diffusers.utils import BaseOutput, is_scipy_available, logging+from diffusers.schedulers.scheduling_utils import SchedulerMixin+++if is_scipy_available():+ import scipy.stats++logger = logging.get_logger(__name__) # pylint: disable=invalid-name+++@dataclass+class FlowMatchEulerDiscreteSchedulerOutput(BaseOutput):+ """+ Output class for the scheduler's `step` function output.++ Args:+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the+ denoising loop.+ """++ prev_sample: torch.FloatTensor+++class FlowMatchEulerDiscreteScheduler(SchedulerMixin, ConfigMixin):+ """+ Euler scheduler.++ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic+ methods the library implements for all schedulers such as loading and saving.++ Args:+ num_train_timesteps (`int`, defaults to 1000):+ The number of diffusion steps to train the model.+ shift (`float`, defaults to 1.0):+ The shift value for the timestep schedule.+ use_dynamic_shifting (`bool`, defaults to False):+ Whether to apply timestep shifting on-the-fly based on the image resolution.+ base_shift (`float`, defaults to 0.5):+ Value to stabilize image generation. Increasing `base_shift` reduces variation and image is more consistent+ with desired output.+ max_shift (`float`, defaults to 1.15):+ Value change allowed to latent vectors. Increasing `max_shift` encourages more variation and image may be+ more exaggerated or stylized.+ base_image_seq_len (`int`, defaults to 256):+ The base image sequence length.+ max_image_seq_len (`int`, defaults to 4096):+ The maximum image sequence length.+ invert_sigmas (`bool`, defaults to False):+ Whether to invert the sigmas.+ shift_terminal (`float`, defaults to None):+ The end value of the shifted timestep schedule.+ use_karras_sigmas (`bool`, defaults to False):+ Whether to use Karras sigmas for step sizes in the noise schedule during sampling.+ use_exponential_sigmas (`bool`, defaults to False):+ Whether to use exponential sigmas for step sizes in the noise schedule during sampling.+ use_beta_sigmas (`bool`, defaults to False):+ Whether to use beta sigmas for step sizes in the noise schedule during sampling.+ time_shift_type (`str`, defaults to "exponential"):+ The type of dynamic resolution-dependent timestep shifting to apply. Either "exponential" or "linear".+ stochastic_sampling (`bool`, defaults to False):+ Whether to use stochastic sampling.+ """++ _compatibles = []+ order = 1++ @register_to_config+ def __init__(+ self,+ num_train_timesteps: int = 1000,+ shift: float = 1.0,+ use_dynamic_shifting: bool = False,+ base_shift: Optional[float] = 0.5,+ max_shift: Optional[float] = 1.15,+ base_image_seq_len: Optional[int] = 256,+ max_image_seq_len: Optional[int] = 4096,+ invert_sigmas: bool = False,+ shift_terminal: Optional[float] = None,+ use_karras_sigmas: Optional[bool] = False,+ use_exponential_sigmas: Optional[bool] = False,+ use_beta_sigmas: Optional[bool] = False,+ time_shift_type: str = "exponential",+ stochastic_sampling: bool = False,+ ):+ if self.config.use_beta_sigmas and not is_scipy_available():+ raise ImportError("Make sure to install scipy if you want to use beta sigmas.")+ if sum([self.config.use_beta_sigmas, self.config.use_exponential_sigmas, self.config.use_karras_sigmas]) > 1:+ raise ValueError(+ "Only one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `config.use_karras_sigmas` can be used."+ )+ if time_shift_type not in {"exponential", "linear"}:+ raise ValueError("`time_shift_type` must either be 'exponential' or 'linear'.")++ timesteps = np.linspace(1, num_train_timesteps, num_train_timesteps, dtype=np.float32)[::-1].copy()+ timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32)++ sigmas = timesteps / num_train_timesteps+ if not use_dynamic_shifting:+ # when use_dynamic_shifting is True, we apply the timestep shifting on the fly based on the image resolution+ sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)++ self.timesteps = sigmas * num_train_timesteps++ self._step_index = None+ self._begin_index = None++ self._shift = shift++ self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication+ self.sigma_min = self.sigmas[-1].item()+ self.sigma_max = self.sigmas[0].item()++ @property+ def shift(self):+ """+ The value used for shifting.+ """+ return self._shift++ @property+ def step_index(self):+ """+ The index counter for current timestep. It will increase 1 after each scheduler step.+ """+ return self._step_index++ @property+ def begin_index(self):+ """+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.+ """+ return self._begin_index++ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index+ def set_begin_index(self, begin_index: int = 0):+ """+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.++ Args:+ begin_index (`int`):+ The begin index for the scheduler.+ """+ self._begin_index = begin_index++ def set_shift(self, shift: float):+ self._shift = shift++ def scale_noise(+ self,+ sample: torch.FloatTensor,+ timestep: Union[float, torch.FloatTensor],+ noise: Optional[torch.FloatTensor] = None,+ ) -> torch.FloatTensor:+ """+ Forward process in flow-matching++ Args:+ sample (`torch.FloatTensor`):+ The input sample.+ timestep (`int`, *optional*):+ The current timestep in the diffusion chain.++ Returns:+ `torch.FloatTensor`:+ A scaled input sample.+ """+ # Make sure sigmas and timesteps have the same device and dtype as original_samples+ sigmas = self.sigmas.to(device=sample.device, dtype=sample.dtype)++ if sample.device.type == "mps" and torch.is_floating_point(timestep):+ # mps does not support float64+ schedule_timesteps = self.timesteps.to(sample.device, dtype=torch.float32)+ timestep = timestep.to(sample.device, dtype=torch.float32)+ else:+ schedule_timesteps = self.timesteps.to(sample.device)+ timestep = timestep.to(sample.device)++ # self.begin_index is None when scheduler is used for training, or pipeline does not implement set_begin_index+ if self.begin_index is None:+ step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timestep]+ elif self.step_index is not None:+ # add_noise is called after first denoising step (for inpainting)+ step_indices = [self.step_index] * timestep.shape[0]+ else:+ # add noise is called before first denoising step to create initial latent(img2img)+ step_indices = [self.begin_index] * timestep.shape[0]++ sigma = sigmas[step_indices].flatten()+ while len(sigma.shape) < len(sample.shape):+ sigma = sigma.unsqueeze(-1)++ sample = sigma * noise + (1.0 - sigma) * sample++ return sample++ def _sigma_to_t(self, sigma):+ return sigma * self.config.num_train_timesteps++ def time_shift(self, mu: float, sigma: float, t: torch.Tensor):+ if self.config.time_shift_type == "exponential":+ return self._time_shift_exponential(mu, sigma, t)+ elif self.config.time_shift_type == "linear":+ return self._time_shift_linear(mu, sigma, t)++ def stretch_shift_to_terminal(self, t: torch.Tensor) -> torch.Tensor:+ r"""+ Stretches and shifts the timestep schedule to ensure it terminates at the configured `shift_terminal` config+ value.++ Reference:+ https://github.com/Lightricks/LTX-Video/blob/a01a171f8fe3d99dce2728d60a73fecf4d4238ae/ltx_video/schedulers/rf.py#L51++ Args:+ t (`torch.Tensor`):+ A tensor of timesteps to be stretched and shifted.++ Returns:+ `torch.Tensor`:+ A tensor of adjusted timesteps such that the final value equals `self.config.shift_terminal`.+ """+ one_minus_z = 1 - t+ scale_factor = one_minus_z[-1] / (1 - self.config.shift_terminal)+ stretched_t = 1 - (one_minus_z / scale_factor)+ return stretched_t++ def set_timesteps(+ self,+ num_inference_steps: Optional[int] = None,+ device: Union[str, torch.device] = None,+ sigmas: Optional[List[float]] = None,+ mu: Optional[float] = None,+ timesteps: Optional[List[float]] = None,+ ):+ """+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).++ Args:+ num_inference_steps (`int`, *optional*):+ The number of diffusion steps used when generating samples with a pre-trained model.+ device (`str` or `torch.device`, *optional*):+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.+ sigmas (`List[float]`, *optional*):+ Custom values for sigmas to be used for each diffusion step. If `None`, the sigmas are computed+ automatically.+ mu (`float`, *optional*):+ Determines the amount of shifting applied to sigmas when performing resolution-dependent timestep+ shifting.+ timesteps (`List[float]`, *optional*):+ Custom values for timesteps to be used for each diffusion step. If `None`, the timesteps are computed+ automatically.+ """+ if self.config.use_dynamic_shifting and mu is None:+ raise ValueError("`mu` must be passed when `use_dynamic_shifting` is set to be `True`")++ if sigmas is not None and timesteps is not None:+ if len(sigmas) != len(timesteps):+ raise ValueError("`sigmas` and `timesteps` should have the same length")++ if num_inference_steps is not None:+ if (sigmas is not None and len(sigmas) != num_inference_steps) or (+ timesteps is not None and len(timesteps) != num_inference_steps+ ):+ raise ValueError(+ "`sigmas` and `timesteps` should have the same length as num_inference_steps, if `num_inference_steps` is provided"+ )+ else:+ num_inference_steps = len(sigmas) if sigmas is not None else len(timesteps)++ self.num_inference_steps = num_inference_steps++ # 1. Prepare default sigmas+ is_timesteps_provided = timesteps is not None++ if is_timesteps_provided:+ timesteps = np.array(timesteps).astype(np.float32)++ if sigmas is None:+ if timesteps is None:+ timesteps = np.linspace(+ self._sigma_to_t(self.sigma_max), self._sigma_to_t(self.sigma_min), num_inference_steps+ )+ sigmas = timesteps / self.config.num_train_timesteps+ else:+ sigmas = np.array(sigmas).astype(np.float32)+ num_inference_steps = len(sigmas)++ # 2. Perform timestep shifting. Either no shifting is applied, or resolution-dependent shifting of+ # "exponential" or "linear" type is applied+ if self.config.use_dynamic_shifting:+ sigmas = self.time_shift(mu, 1.0, sigmas)+ else:+ sigmas = self.shift * sigmas / (1 + (self.shift - 1) * sigmas)++ # 3. If required, stretch the sigmas schedule to terminate at the configured `shift_terminal` value+ if self.config.shift_terminal:+ sigmas = self.stretch_shift_to_terminal(sigmas)++ # 4. If required, convert sigmas to one of karras, exponential, or beta sigma schedules+ if self.config.use_karras_sigmas:+ sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)+ elif self.config.use_exponential_sigmas:+ sigmas = self._convert_to_exponential(in_sigmas=sigmas, num_inference_steps=num_inference_steps)+ elif self.config.use_beta_sigmas:+ sigmas = self._convert_to_beta(in_sigmas=sigmas, num_inference_steps=num_inference_steps)++ # 5. Convert sigmas and timesteps to tensors and move to specified device+ sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32, device=device)+ if not is_timesteps_provided:+ timesteps = sigmas * self.config.num_train_timesteps+ else:+ timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32, device=device)++ # 6. Append the terminal sigma value.+ # If a model requires inverted sigma schedule for denoising but timesteps without inversion, the+ # `invert_sigmas` flag can be set to `True`. This case is only required in Mochi+ if self.config.invert_sigmas:+ sigmas = 1.0 - sigmas+ timesteps = sigmas * self.config.num_train_timesteps+ sigmas = torch.cat([sigmas, torch.ones(1, device=sigmas.device)])+ else:+ sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])++ self.timesteps = timesteps+ self.sigmas = sigmas+ self._step_index = None+ self._begin_index = None++ def index_for_timestep(self, timestep, schedule_timesteps=None):+ if schedule_timesteps is None:+ schedule_timesteps = self.timesteps++ indices = (schedule_timesteps == timestep).nonzero()++ # The sigma index that is taken for the **very** first `step`+ # is always the second index (or the last index if there is only 1)+ # This way we can ensure we don't accidentally skip a sigma in+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)+ pos = 1 if len(indices) > 1 else 0++ return indices[pos].item()++ def _init_step_index(self, timestep):+ if self.begin_index is None:+ if isinstance(timestep, torch.Tensor):+ timestep = timestep.to(self.timesteps.device)+ self._step_index = self.index_for_timestep(timestep)+ else:+ self._step_index = self._begin_index++ def step(+ self,+ model_output: torch.FloatTensor,+ timestep: Union[float, torch.FloatTensor],+ sample: torch.FloatTensor,+ s_churn: float = 0.0,+ s_tmin: float = 0.0,+ s_tmax: float = float("inf"),+ s_noise: float = 1.0,+ generator: Optional[torch.Generator] = None,+ per_token_timesteps: Optional[torch.Tensor] = None,+ return_dict: bool = True,+ ) -> Union[FlowMatchEulerDiscreteSchedulerOutput, Tuple]:+ """+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion+ process from the learned model outputs (most often the predicted noise).++ Args:+ model_output (`torch.FloatTensor`):+ The direct output from learned diffusion model.+ timestep (`float`):+ The current discrete timestep in the diffusion chain.+ sample (`torch.FloatTensor`):+ A current instance of a sample created by the diffusion process.+ s_churn (`float`):+ s_tmin (`float`):+ s_tmax (`float`):+ s_noise (`float`, defaults to 1.0):+ Scaling factor for noise added to the sample.+ generator (`torch.Generator`, *optional*):+ A random number generator.+ per_token_timesteps (`torch.Tensor`, *optional*):+ The timesteps for each token in the sample.+ return_dict (`bool`):+ Whether or not to return a+ [`~schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteSchedulerOutput`] or tuple.++ Returns:+ [`~schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteSchedulerOutput`] or `tuple`:+ If return_dict is `True`,+ [`~schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteSchedulerOutput`] is returned,+ otherwise a tuple is returned where the first element is the sample tensor.+ """++ if (+ isinstance(timestep, int)+ or isinstance(timestep, torch.IntTensor)+ or isinstance(timestep, torch.LongTensor)+ ):+ raise ValueError(+ (+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"+ " `FlowMatchEulerDiscreteScheduler.step()` is not supported. Make sure to pass"+ " one of the `scheduler.timesteps` as a timestep."+ ),+ )++ if self.step_index is None:+ self._init_step_index(timestep)++ # Upcast to avoid precision issues when computing prev_sample+ sample = sample.to(torch.float32)++ if per_token_timesteps is not None:+ per_token_sigmas = per_token_timesteps / self.config.num_train_timesteps++ sigmas = self.sigmas[:, None, None]+ lower_mask = sigmas < per_token_sigmas[None] - 1e-6+ lower_sigmas = lower_mask * sigmas+ lower_sigmas, _ = lower_sigmas.max(dim=0)++ current_sigma = per_token_sigmas[..., None]+ next_sigma = lower_sigmas[..., None]+ dt = current_sigma - next_sigma+ else:+ sigma_idx = self.step_index+ sigma = self.sigmas[sigma_idx]+ sigma_next = self.sigmas[sigma_idx + 1]++ current_sigma = sigma+ next_sigma = sigma_next+ dt = sigma_next - sigma++ if self.config.stochastic_sampling:+ x0 = sample - current_sigma * model_output+ noise = torch.randn_like(sample)+ prev_sample = (1.0 - next_sigma) * x0 + next_sigma * noise+ else:+ prev_sample = sample + dt * model_output++ # upon completion increase step index by one+ self._step_index += 1+ if per_token_timesteps is None:+ # Cast sample back to model compatible dtype+ prev_sample = prev_sample.to(model_output.dtype)++ if not return_dict:+ return (prev_sample,)++ return FlowMatchEulerDiscreteSchedulerOutput(prev_sample=prev_sample)++ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras+ def _convert_to_karras(self, in_sigmas: torch.Tensor, num_inference_steps) -> torch.Tensor:+ """Constructs the noise schedule of Karras et al. (2022)."""++ # Hack to make sure that other schedulers which copy this function don't break+ # TODO: Add this logic to the other schedulers+ if hasattr(self.config, "sigma_min"):+ sigma_min = self.config.sigma_min+ else:+ sigma_min = None++ if hasattr(self.config, "sigma_max"):+ sigma_max = self.config.sigma_max+ else:+ sigma_max = None++ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()++ rho = 7.0 # 7.0 is the value used in the paper+ ramp = np.linspace(0, 1, num_inference_steps)+ min_inv_rho = sigma_min ** (1 / rho)+ max_inv_rho = sigma_max ** (1 / rho)+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho+ return sigmas++ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_exponential+ def _convert_to_exponential(self, in_sigmas: torch.Tensor, num_inference_steps: int) -> torch.Tensor:+ """Constructs an exponential noise schedule."""++ # Hack to make sure that other schedulers which copy this function don't break+ # TODO: Add this logic to the other schedulers+ if hasattr(self.config, "sigma_min"):+ sigma_min = self.config.sigma_min+ else:+ sigma_min = None++ if hasattr(self.config, "sigma_max"):+ sigma_max = self.config.sigma_max+ else:+ sigma_max = None++ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()++ sigmas = np.exp(np.linspace(math.log(sigma_max), math.log(sigma_min), num_inference_steps))+ return sigmas++ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_beta+ def _convert_to_beta(+ self, in_sigmas: torch.Tensor, num_inference_steps: int, alpha: float = 0.6, beta: float = 0.6+ ) -> torch.Tensor:+ """From "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024)"""++ # Hack to make sure that other schedulers which copy this function don't break+ # TODO: Add this logic to the other schedulers+ if hasattr(self.config, "sigma_min"):+ sigma_min = self.config.sigma_min+ else:+ sigma_min = None++ if hasattr(self.config, "sigma_max"):+ sigma_max = self.config.sigma_max+ else:+ sigma_max = None++ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()++ sigmas = np.array(+ [+ sigma_min + (ppf * (sigma_max - sigma_min))+ for ppf in [+ scipy.stats.beta.ppf(timestep, alpha, beta)+ for timestep in 1 - np.linspace(0, 1, num_inference_steps)+ ]+ ]+ )+ return sigmas++ def _time_shift_exponential(self, mu, sigma, t):+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)++ def _time_shift_linear(self, mu, sigma, t):+ return mu / (mu + (1 / t - 1) ** sigma)++ def __len__(self):+ return self.config.num_train_timesteps