Spaces:
Running
Running
bubbliiiing commited on
Commit ·
c2a6cd2
1
Parent(s): b0f1243
Update V5.1
Browse filesFiles changed (33)
- app.py+9-18
- config/easyanimate_video_v5.1_magvit_qwen.yamlAdded+21
- easyanimate/api/api.py+1-1
- easyanimate/api/post_infer.py+2-2
- easyanimate/data/dataset_image_video.py+220-32
- easyanimate/models/__init__.py+3-4
- easyanimate/models/attention.py+60-31
- easyanimate/models/autoencoder_magvit.py+15-117
- easyanimate/models/embeddings.py+3-2
- easyanimate/models/norm.py+16
- easyanimate/models/processor.py+146
- easyanimate/models/transformer3d.py+280-43
- easyanimate/pipeline/pipeline_easyanimate.py+730-486
- easyanimate/pipeline/pipeline_easyanimate_multi_text_encoder_control.py → easyanimate/pipeline/pipeline_easyanimate_control.pyRenamed+448-229
- easyanimate/pipeline/pipeline_easyanimate_inpaint.py
- easyanimate/pipeline/pipeline_easyanimate_multi_text_encoder.pyDeleted-925
- easyanimate/pipeline/pipeline_easyanimate_multi_text_encoder_inpaint.pyDeleted-1334
- easyanimate/ui/ui.py+237-179
- easyanimate/utils/lora_utils.py+42-30
- easyanimate/utils/utils.py+53-33
- easyanimate/vae/ldm/models/autoencoder.py+4-4
- easyanimate/vae/ldm/models/casual3dcnn.py+5-5
- easyanimate/vae/ldm/models/cogvideox_casual3dcnn.py+5-5
- easyanimate/vae/ldm/models/omnigen_casual3dcnn.py+13-9
- easyanimate/vae/ldm/models/omnigen_enc_dec.py+6-2
- easyanimate/vae/ldm/modules/losses/contperceptual.py+20-3
- easyanimate/vae/ldm/modules/vaemodules/__init__.py
- easyanimate/vae/ldm/modules/vaemodules/activations.py
- easyanimate/vae/ldm/modules/vaemodules/common.py+39-5
- easyanimate/vae/ldm/modules/vaemodules/down_blocks.py
- easyanimate/vae/ldm/modules/vaemodules/mid_blocks.py
- easyanimate/vae/ldm/modules/vaemodules/up_blocks.py
- requirements.txt+2-5
18 unmodified lines1920212223244 unmodified lines29303132333435363738396 unmodified lines46474849505152535455565758596061626318 unmodified lines## "sequential_cpu_offload" means that each layer of the model will be moved to the CPU after use,# resulting in slower speeds but saving a large amount of GPU memory.GPU_memory_mode = "model_cpu_offload_and_qfloat8"# Use torch.float16 if GPU does not support torch.bfloat16# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat164 unmodified linesserver_port = 7860# Params below is used when ui_mode = "modelscope"edition = "v5"# Configconfig_path = "config/easyanimate_video_v5_magvit_multi_text_encoder.yaml"# Model path of the pretrained modelmodel_name = "models/Diffusion_Transformer/EasyAnimateV5-12b-zh-InP"# "Inpaint" or "Control"model_type = "Inpaint"# Save dir6 unmodified lineselse:demo, controller = ui(GPU_memory_mode, weight_dtype)# launch gradioapp, _, _ = demo.queue(status_update_rate=1).launch(server_name=server_name,server_port=server_port,prevent_thread_lock=True)# launch apiinfer_forward_api(None, app, controller)update_diffusion_transformer_api(None, app, controller)update_edition_api(None, app, controller)# not close the pythonwhile True:time.sleep(5)18 unmodified lines1920212223242526274 unmodified lines32333435363738394041426 unmodified lines49505152535418 unmodified lines## "sequential_cpu_offload" means that each layer of the model will be moved to the CPU after use,# resulting in slower speeds but saving a large amount of GPU memory.## EasyAnimateV1, V2 and V3 support "model_cpu_offload" "sequential_cpu_offload"# EasyAnimateV4, V5 and V5.1 support "model_cpu_offload" "model_cpu_offload_and_qfloat8" "sequential_cpu_offload"GPU_memory_mode = "model_cpu_offload_and_qfloat8"# Use torch.float16 if GPU does not support torch.bfloat16# ome graphics cards, such as v100, 2080ti, do not support torch.bfloat164 unmodified linesserver_port = 7860# Params below is used when ui_mode = "modelscope"edition = "v5.1"# Configconfig_path = "config/easyanimate_video_v5.1_magvit_qwen.yaml"# Model path of the pretrained modelmodel_name = "models/Diffusion_Transformer/EasyAnimateV5.1-12b-zh-InP"# "Inpaint" or "Control"model_type = "Inpaint"# Save dir6 unmodified lineselse:demo, controller = ui(GPU_memory_mode, weight_dtype)demo.launch(server_name=server_name, server_port=server_port)
123456789101112131415161718192021transformer_additional_kwargs: transformer_type: "EasyAnimateTransformer3DModel" after_norm: false time_position_encoding_type: "3d_rope" resize_inpaint_mask_directly: true enable_text_attention_mask: true enable_clip_in_inpaint: false add_ref_latent_in_control_model: true
vae_kwargs: vae_type: "AutoencoderKLMagvit" mini_batch_encoder: 4 mini_batch_decoder: 1 slice_mag_vae: false slice_compression_vae: false cache_compression_vae: false cache_mag_vae: true
text_encoder_kwargs: enable_multi_text_encoder: false replace_t5_to_llm: true92 unmodified lines9394959697989992 unmodified lineslora_model_path = datas.get('lora_model_path', 'none')lora_alpha_slider = datas.get('lora_alpha_slider', 0.55)prompt_textbox = datas.get('prompt_textbox', None)negative_prompt_textbox = datas.get('negative_prompt_textbox', 'Blurring, mutation, deformation, distortion, dark and solid, comics.')sampler_dropdown = datas.get('sampler_dropdown', 'Euler')sample_step_slider = datas.get('sample_step_slider', 30)resize_method = datas.get('resize_method', "Generate by")92 unmodified lines9394959697989992 unmodified lineslora_model_path = datas.get('lora_model_path', 'none')lora_alpha_slider = datas.get('lora_alpha_slider', 0.55)prompt_textbox = datas.get('prompt_textbox', None)negative_prompt_textbox = datas.get('negative_prompt_textbox', 'Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art.')sampler_dropdown = datas.get('sampler_dropdown', 'Euler')sample_step_slider = datas.get('sample_step_slider', 30)resize_method = datas.get('resize_method', "Generate by")
53 unmodified lines545556575859606162636465666753 unmodified lines# -------------------------- ## Step 1: update edition# -------------------------- #edition = "v5"outputs = post_update_edition(edition)print('Output update edition: ', outputs)# -------------------------- ## Step 2: update edition# -------------------------- #diffusion_transformer_path = "models/Diffusion_Transformer/EasyAnimateV5-12b-zh-InP"outputs = post_diffusion_transformer(diffusion_transformer_path)print('Output update edition: ', outputs)53 unmodified lines545556575859606162636465666753 unmodified lines# -------------------------- ## Step 1: update edition# -------------------------- #edition = "v5.1"outputs = post_update_edition(edition)print('Output update edition: ', outputs)# -------------------------- ## Step 2: update edition# -------------------------- #diffusion_transformer_path = "models/Diffusion_Transformer/EasyAnimateV5.1-12b-zh-InP"outputs = post_diffusion_transformer(diffusion_transformer_path)print('Output update edition: ', outputs)
11 unmodified lines12131415161718192079 unmodified lines10010110210310410578 unmodified lines184185186187188189190164 unmodified lines3553563573583593603611 unmodified line36336436536636736836937037137237323 unmodified lines3973983994004014029 unmodified lines41241341441541641766 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551619 unmodified lines5365375385395405415429 unmodified lines55255355455555655755855956056156256356411 unmodified linesimport cv2import numpy as npimport torchimport torchvision.transforms as transformsfrom decord import VideoReaderfrom func_timeout import FunctionTimedOut, func_timeoutfrom PIL import Imagefrom torch.utils.data import BatchSampler, Samplerfrom torch.utils.data.dataset import Dataset79 unmodified lineselse:raise ValueError(f"The mask_index {mask_index} is not define")return maskclass ImageVideoSampler(BatchSampler):"""A sampler wrapper for grouping images with similar aspect ratio into a same batch.78 unmodified linesvideo_sample_size=512, video_sample_stride=4, video_sample_n_frames=16,image_sample_size=512,video_repeat=0,text_drop_ratio=-1,enable_bucket=False,video_length_drop_start=0.1,video_length_drop_end=0.9,164 unmodified linesreturn sampleclass ImageVideoControlDataset(Dataset):def __init__(self,1 unmodified linevideo_sample_size=512, video_sample_stride=4, video_sample_n_frames=16,image_sample_size=512,video_repeat=0,text_drop_ratio=-1,enable_bucket=False,video_length_drop_start=0.1,video_length_drop_end=0.9,enable_inpaint=False,):# Loading annotations from filesprint(f"loading annotations from {ann_path} ...")23 unmodified linesself.enable_bucket = enable_bucketself.text_drop_ratio = text_drop_ratioself.enable_inpaint = enable_inpaintself.video_length_drop_start = video_length_drop_startself.video_length_drop_end = video_length_drop_end9 unmodified linestransforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),])# Image paramsself.image_sample_size = tuple(image_sample_size) if not isinstance(image_sample_size, int) else (image_sample_size, image_sample_size)66 unmodified lineselse:control_video_id = os.path.join(self.data_root, control_video_id)with VideoReader_contextmanager(control_video_id, num_threads=2) as control_video_reader:try:sample_args = (control_video_reader, batch_index)control_pixel_values = func_timeout(VIDEO_READER_TIMEOUT, get_video_reader_batch, args=sample_args)resized_frames = []for i in range(len(control_pixel_values)):frame = control_pixel_values[i]resized_frame = resize_frame(frame, self.larger_side_of_image_and_video)resized_frames.append(resized_frame)control_pixel_values = np.array(resized_frames)except FunctionTimedOut:raise ValueError(f"Read {idx} timeout.")except Exception as e:raise ValueError(f"Failed to extract frames from video. Error is {e}.")if not self.enable_bucket:control_pixel_values = torch.from_numpy(control_pixel_values).permute(0, 3, 1, 2).contiguous()control_pixel_values = control_pixel_values / 255.del control_video_readerelse:control_pixel_values = control_pixel_valuesif not self.enable_bucket:control_pixel_values = self.video_transforms(control_pixel_values)return pixel_values, control_pixel_values, text, "video"else:image_path, text = data_info['file_path'], data_info['text']if self.data_root is not None:19 unmodified linescontrol_image = self.image_transforms(control_image).unsqueeze(0)else:control_image = np.expand_dims(np.array(control_image), 0)return image, control_image, text, 'image'def __len__(self):return self.length9 unmodified linesif data_type_local != data_type:raise ValueError("data_type_local != data_type")pixel_values, control_pixel_values, name, data_type = self.get_batch(idx)sample["pixel_values"] = pixel_valuessample["control_pixel_values"] = control_pixel_valuessample["text"] = namesample["data_type"] = data_typesample["idx"] = idxif len(sample) > 0:breakexcept Exception as e:11 unmodified lines12131415161718192021222379 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325478 unmodified lines333334335336337338339164 unmodified lines5045055065075085091 unmodified line51151251351451551651751851952052152223 unmodified lines5465475485495505515529 unmodified lines56256356456556656756856957057157257357466 unmodified lines64164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869919 unmodified lines7197207217227237247257269 unmodified lines73673773873974074174274374474574674774874975075175211 unmodified linesimport cv2import numpy as npimport torchimport torch.nn.functional as Fimport torchvision.transforms as transformsfrom decord import VideoReaderfrom einops import rearrangefrom func_timeout import FunctionTimedOut, func_timeoutfrom packaging import version as pverfrom PIL import Imagefrom torch.utils.data import BatchSampler, Samplerfrom torch.utils.data.dataset import Dataset79 unmodified lineselse:raise ValueError(f"The mask_index {mask_index} is not define")return maskclass Camera(object):"""Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py"""def __init__(self, entry):fx, fy, cx, cy = entry[1:5]self.fx = fxself.fy = fyself.cx = cxself.cy = cyw2c_mat = np.array(entry[7:]).reshape(3, 4)w2c_mat_4x4 = np.eye(4)w2c_mat_4x4[:3, :] = w2c_matself.w2c_mat = w2c_mat_4x4self.c2w_mat = np.linalg.inv(w2c_mat_4x4)def custom_meshgrid(*args):"""Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py"""# ref: https://pytorch.org/docs/stable/generated/torch.meshgrid.html?highlight=meshgrid#torch.meshgridif pver.parse(torch.__version__) < pver.parse('1.10'):return torch.meshgrid(*args)else:return torch.meshgrid(*args, indexing='ij')def get_relative_pose(cam_params):"""Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py"""abs_w2cs = [cam_param.w2c_mat for cam_param in cam_params]abs_c2ws = [cam_param.c2w_mat for cam_param in cam_params]cam_to_origin = 0target_cam_c2w = np.array([[1, 0, 0, 0],[0, 1, 0, -cam_to_origin],[0, 0, 1, 0],[0, 0, 0, 1]])abs2rel = target_cam_c2w @ abs_w2cs[0]ret_poses = [target_cam_c2w, ] + [abs2rel @ abs_c2w for abs_c2w in abs_c2ws[1:]]ret_poses = np.array(ret_poses, dtype=np.float32)return ret_posesdef ray_condition(K, c2w, H, W, device):"""Copied from https://github.com/hehao13/CameraCtrl/blob/main/inference.py"""# c2w: B, V, 4, 4# K: B, V, 4B = K.shape[0]j, i = custom_meshgrid(torch.linspace(0, H - 1, H, device=device, dtype=c2w.dtype),torch.linspace(0, W - 1, W, device=device, dtype=c2w.dtype),)i = i.reshape([1, 1, H * W]).expand([B, 1, H * W]) + 0.5 # [B, HxW]j = j.reshape([1, 1, H * W]).expand([B, 1, H * W]) + 0.5 # [B, HxW]fx, fy, cx, cy = K.chunk(4, dim=-1) # B,V, 1zs = torch.ones_like(i) # [B, HxW]xs = (i - cx) / fx * zsys = (j - cy) / fy * zszs = zs.expand_as(ys)directions = torch.stack((xs, ys, zs), dim=-1) # B, V, HW, 3directions = directions / directions.norm(dim=-1, keepdim=True) # B, V, HW, 3rays_d = directions @ c2w[..., :3, :3].transpose(-1, -2) # B, V, 3, HWrays_o = c2w[..., :3, 3] # B, V, 3rays_o = rays_o[:, :, None].expand_as(rays_d) # B, V, 3, HW# c2w @ dirctionsrays_dxo = torch.cross(rays_o, rays_d)plucker = torch.cat([rays_dxo, rays_d], dim=-1)plucker = plucker.reshape(B, c2w.shape[1], H, W, 6) # B, V, H, W, 6# plucker = plucker.permute(0, 1, 4, 2, 3)return pluckerdef process_pose_file(pose_file_path, width=672, height=384, original_pose_width=1280, original_pose_height=720, device='cpu', return_poses=False):"""Modified from https://github.com/hehao13/CameraCtrl/blob/main/inference.py"""with open(pose_file_path, 'r') as f:poses = f.readlines()poses = [pose.strip().split(' ') for pose in poses[1:]]cam_params = [[float(x) for x in pose] for pose in poses]if return_poses:return cam_paramselse:cam_params = [Camera(cam_param) for cam_param in cam_params]sample_wh_ratio = width / heightpose_wh_ratio = original_pose_width / original_pose_height # Assuming placeholder ratios, change as neededif pose_wh_ratio > sample_wh_ratio:resized_ori_w = height * pose_wh_ratiofor cam_param in cam_params:cam_param.fx = resized_ori_w * cam_param.fx / widthelse:resized_ori_h = width / pose_wh_ratiofor cam_param in cam_params:cam_param.fy = resized_ori_h * cam_param.fy / heightintrinsic = np.asarray([[cam_param.fx * width,cam_param.fy * height,cam_param.cx * width,cam_param.cy * height]for cam_param in cam_params], dtype=np.float32)K = torch.as_tensor(intrinsic)[None] # [1, 1, 4]c2ws = get_relative_pose(cam_params) # Assuming this function is defined elsewherec2ws = torch.as_tensor(c2ws)[None] # [1, n_frame, 4, 4]plucker_embedding = ray_condition(K, c2ws, height, width, device=device)[0].permute(0, 3, 1, 2).contiguous() # V, 6, H, Wplucker_embedding = plucker_embedding[None]plucker_embedding = rearrange(plucker_embedding, "b f c h w -> b f h w c")[0]return plucker_embeddingdef process_pose_params(cam_params, width=672, height=384, original_pose_width=1280, original_pose_height=720, device='cpu'):"""Modified from https://github.com/hehao13/CameraCtrl/blob/main/inference.py"""cam_params = [Camera(cam_param) for cam_param in cam_params]sample_wh_ratio = width / heightpose_wh_ratio = original_pose_width / original_pose_height # Assuming placeholder ratios, change as neededif pose_wh_ratio > sample_wh_ratio:resized_ori_w = height * pose_wh_ratiofor cam_param in cam_params:cam_param.fx = resized_ori_w * cam_param.fx / widthelse:resized_ori_h = width / pose_wh_ratiofor cam_param in cam_params:cam_param.fy = resized_ori_h * cam_param.fy / heightintrinsic = np.asarray([[cam_param.fx * width,cam_param.fy * height,cam_param.cx * width,cam_param.cy * height]for cam_param in cam_params], dtype=np.float32)K = torch.as_tensor(intrinsic)[None] # [1, 1, 4]c2ws = get_relative_pose(cam_params) # Assuming this function is defined elsewherec2ws = torch.as_tensor(c2ws)[None] # [1, n_frame, 4, 4]plucker_embedding = ray_condition(K, c2ws, height, width, device=device)[0].permute(0, 3, 1, 2).contiguous() # V, 6, H, Wplucker_embedding = plucker_embedding[None]plucker_embedding = rearrange(plucker_embedding, "b f c h w -> b f h w c")[0]return plucker_embeddingclass ImageVideoSampler(BatchSampler):"""A sampler wrapper for grouping images with similar aspect ratio into a same batch.78 unmodified linesvideo_sample_size=512, video_sample_stride=4, video_sample_n_frames=16,image_sample_size=512,video_repeat=0,text_drop_ratio=0.1,enable_bucket=False,video_length_drop_start=0.1,video_length_drop_end=0.9,164 unmodified linesreturn sampleclass ImageVideoControlDataset(Dataset):def __init__(self,1 unmodified linevideo_sample_size=512, video_sample_stride=4, video_sample_n_frames=16,image_sample_size=512,video_repeat=0,text_drop_ratio=0.1,enable_bucket=False,video_length_drop_start=0.1,video_length_drop_end=0.9,enable_inpaint=False,enable_camera_info=False,):# Loading annotations from filesprint(f"loading annotations from {ann_path} ...")23 unmodified linesself.enable_bucket = enable_bucketself.text_drop_ratio = text_drop_ratioself.enable_inpaint = enable_inpaintself.enable_camera_info = enable_camera_infoself.video_length_drop_start = video_length_drop_startself.video_length_drop_end = video_length_drop_end9 unmodified linestransforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),])if self.enable_camera_info:self.video_transforms_camera = transforms.Compose([transforms.Resize(min(self.video_sample_size)),transforms.CenterCrop(self.video_sample_size)])# Image paramsself.image_sample_size = tuple(image_sample_size) if not isinstance(image_sample_size, int) else (image_sample_size, image_sample_size)66 unmodified lineselse:control_video_id = os.path.join(self.data_root, control_video_id)if self.enable_camera_info:if control_video_id.lower().endswith('.txt'):if not self.enable_bucket:control_pixel_values = torch.zeros_like(pixel_values)control_camera_values = process_pose_file(control_video_id, width=self.video_sample_size[1], height=self.video_sample_size[0])control_camera_values = torch.from_numpy(control_camera_values).permute(0, 3, 1, 2).contiguous()control_camera_values = F.interpolate(control_camera_values, size=(len(video_reader), control_camera_values.size(3)), mode='bilinear', align_corners=True)control_camera_values = self.video_transforms_camera(control_camera_values)else:control_pixel_values = np.zeros_like(pixel_values)control_camera_values = process_pose_file(control_video_id, width=self.video_sample_size[1], height=self.video_sample_size[0], return_poses=True)control_camera_values = torch.from_numpy(np.array(control_camera_values)).unsqueeze(0).unsqueeze(0)control_camera_values = F.interpolate(control_camera_values, size=(len(video_reader), control_camera_values.size(3)), mode='bilinear', align_corners=True)[0][0]control_camera_values = np.array([control_camera_values[index] for index in batch_index])else:if not self.enable_bucket:control_pixel_values = torch.zeros_like(pixel_values)control_camera_values = Noneelse:control_pixel_values = np.zeros_like(pixel_values)control_camera_values = Noneelse:with VideoReader_contextmanager(control_video_id, num_threads=2) as control_video_reader:try:sample_args = (control_video_reader, batch_index)control_pixel_values = func_timeout(VIDEO_READER_TIMEOUT, get_video_reader_batch, args=sample_args)resized_frames = []for i in range(len(control_pixel_values)):frame = control_pixel_values[i]resized_frame = resize_frame(frame, self.larger_side_of_image_and_video)resized_frames.append(resized_frame)control_pixel_values = np.array(resized_frames)except FunctionTimedOut:raise ValueError(f"Read {idx} timeout.")except Exception as e:raise ValueError(f"Failed to extract frames from video. Error is {e}.")if not self.enable_bucket:control_pixel_values = torch.from_numpy(control_pixel_values).permute(0, 3, 1, 2).contiguous()control_pixel_values = control_pixel_values / 255.del control_video_readerelse:control_pixel_values = control_pixel_valuesif not self.enable_bucket:control_pixel_values = self.video_transforms(control_pixel_values)control_camera_values = Nonereturn pixel_values, control_pixel_values, control_camera_values, text, "video"else:image_path, text = data_info['file_path'], data_info['text']if self.data_root is not None:19 unmodified linescontrol_image = self.image_transforms(control_image).unsqueeze(0)else:control_image = np.expand_dims(np.array(control_image), 0)return image, control_image, None, text, 'image'def __len__(self):return self.length9 unmodified linesif data_type_local != data_type:raise ValueError("data_type_local != data_type")pixel_values, control_pixel_values, control_camera_values, name, data_type = self.get_batch(idx)sample["pixel_values"] = pixel_valuessample["control_pixel_values"] = control_pixel_valuessample["text"] = namesample["data_type"] = data_typesample["idx"] = idxif self.enable_camera_info:sample["control_camera_values"] = control_camera_valuesif len(sample) > 0:breakexcept Exception as e:
12345678from .autoencoder_magvit import (AutoencoderKLCogVideoX, AutoencoderKLMagvit, AutoencoderKL)from .transformer3d import (EasyAnimateTransformer3DModel,HunyuanTransformer3DModel,Transformer3DModel)name_to_transformer3d = {"Transformer3DModel": Transformer3DModel,1234567from .autoencoder_magvit import (AutoencoderKL, AutoencoderKLCogVideoX,AutoencoderKLMagvit)from .transformer3d import (EasyAnimateTransformer3DModel,HunyuanTransformer3DModel, Transformer3DModel)name_to_transformer3d = {"Transformer3DModel": Transformer3DModel,
28 unmodified lines293031323334352 unmodified lines383940414243444546474849992 unmodified lines10421043104410451046104710482 unmodified lines1051105210531054105510561 unmodified line105810591060106110621063106410651066106710681069107010711072107310747 unmodified lines108210831084108510861087108810891090109110921093109410955 unmodified lines1101110211031104110511061 unmodified line1108110911101111111211131114111511161117111811195 unmodified lines112511261127112811291130113111321133113428 unmodified linesget_3d_sincos_pos_embed)from diffusers.models.modeling_outputs import Transformer2DModelOutputfrom diffusers.models.modeling_utils import ModelMixinfrom diffusers.models.normalization import (AdaLayerNorm, AdaLayerNormZero,CogVideoXLayerNormZero)from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, loggingfrom diffusers.utils.import_utils import is_xformers_available2 unmodified linesfrom torch import nnfrom .motion_module import PositionalEncoding, get_motion_modulefrom .norm import AdaLayerNormShift, FP32LayerNorm, EasyAnimateLayerNormZerofrom .processor import (EasyAnimateAttnProcessor2_0,LazyKVCompressionProcessor2_0)if is_xformers_available():import xformersimport xformers.ops992 unmodified linesff_bias: bool = True,qk_norm: bool = True,after_norm: bool = False,norm_type: str="fp32_layer_norm"):super().__init__()2 unmodified linestime_embed_dim, dim, norm_elementwise_affine, norm_eps, norm_type=norm_type, bias=True)self.attn1 = Attention(query_dim=dim,dim_head=attention_head_dim,1 unmodified lineqk_norm="layer_norm" if qk_norm else None,eps=1e-6,bias=True,processor=EasyAnimateAttnProcessor2_0(),)self.attn2 = Attention(query_dim=dim,dim_head=attention_head_dim,heads=num_attention_heads,qk_norm="layer_norm" if qk_norm else None,eps=1e-6,bias=True,processor=EasyAnimateAttnProcessor2_0(),)# FFN Partself.norm2 = EasyAnimateLayerNormZero(7 unmodified linesinner_dim=ff_inner_dim,bias=ff_bias,)self.txt_ff = FeedForward(dim,dropout=dropout,activation_fn=activation_fn,final_dropout=final_dropout,inner_dim=ff_inner_dim,bias=ff_bias,)if after_norm:self.norm3 = FP32LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)else:5 unmodified linesencoder_hidden_states: torch.Tensor,temb: torch.Tensor,image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,) -> torch.Tensor:# Normnorm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(1 unmodified line)# Attnattn_hidden_states, attn_encoder_hidden_states = self.attn1(hidden_states=norm_hidden_states,encoder_hidden_states=norm_encoder_hidden_states,image_rotary_emb=image_rotary_emb,attn2=self.attn2,)hidden_states = hidden_states + gate_msa * attn_hidden_statesencoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states5 unmodified lines# FFNif self.norm3 is not None:norm_hidden_states = self.norm3(self.ff(norm_hidden_states))norm_encoder_hidden_states = self.norm3(self.txt_ff(norm_encoder_hidden_states))else:norm_hidden_states = self.ff(norm_hidden_states)norm_encoder_hidden_states = self.txt_ff(norm_encoder_hidden_states)hidden_states = hidden_states + gate_ff * norm_hidden_statesencoder_hidden_states = encoder_hidden_states + enc_gate_ff * norm_encoder_hidden_statesreturn hidden_states, encoder_hidden_states28 unmodified lines293031323334352 unmodified lines3839404142434445464748992 unmodified lines1041104210431044104510461047104810492 unmodified lines10521053105410551056105710581 unmodified line106010611062106310641065106610671068106910701071107210731074107510761077107810797 unmodified lines1087108810891090109110921093109410951096109710981099110011011102110311045 unmodified lines1110111111121113111411151116111711181 unmodified line112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111425 unmodified lines114811491150115111521153115411551156115711581159116011611162116328 unmodified linesget_3d_sincos_pos_embed)from diffusers.models.modeling_outputs import Transformer2DModelOutputfrom diffusers.models.modeling_utils import ModelMixinfrom diffusers.models.normalization import (AdaLayerNorm, AdaLayerNormZero,CogVideoXLayerNormZero)from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, loggingfrom diffusers.utils.import_utils import is_xformers_available2 unmodified linesfrom torch import nnfrom .motion_module import PositionalEncoding, get_motion_modulefrom .norm import AdaLayerNormShift, EasyAnimateLayerNormZero, FP32LayerNormfrom .processor import (EasyAnimateAttnProcessor2_0,EasyAnimateSWAttnProcessor2_0,LazyKVCompressionProcessor2_0)if is_xformers_available():import xformersimport xformers.ops992 unmodified linesff_bias: bool = True,qk_norm: bool = True,after_norm: bool = False,norm_type: str="fp32_layer_norm",is_mmdit_block: bool = True,is_swa: bool = False,):super().__init__()2 unmodified linestime_embed_dim, dim, norm_elementwise_affine, norm_eps, norm_type=norm_type, bias=True)self.is_swa = is_swaself.attn1 = Attention(query_dim=dim,dim_head=attention_head_dim,1 unmodified lineqk_norm="layer_norm" if qk_norm else None,eps=1e-6,bias=True,processor=EasyAnimateAttnProcessor2_0() if not is_swa else EasyAnimateSWAttnProcessor2_0(),)if is_mmdit_block:self.attn2 = Attention(query_dim=dim,dim_head=attention_head_dim,heads=num_attention_heads,qk_norm="layer_norm" if qk_norm else None,eps=1e-6,bias=True,processor=EasyAnimateAttnProcessor2_0() if not is_swa else EasyAnimateSWAttnProcessor2_0(),)else:self.attn2 = None# FFN Partself.norm2 = EasyAnimateLayerNormZero(7 unmodified linesinner_dim=ff_inner_dim,bias=ff_bias,)if is_mmdit_block:self.txt_ff = FeedForward(dim,dropout=dropout,activation_fn=activation_fn,final_dropout=final_dropout,inner_dim=ff_inner_dim,bias=ff_bias,)else:self.txt_ff = Noneif after_norm:self.norm3 = FP32LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)else:5 unmodified linesencoder_hidden_states: torch.Tensor,temb: torch.Tensor,image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,num_frames = None,height = None,width = None) -> torch.Tensor:# Normnorm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(1 unmodified line)# Attnif self.is_swa:attn_hidden_states, attn_encoder_hidden_states = self.attn1(hidden_states=norm_hidden_states,encoder_hidden_states=norm_encoder_hidden_states,image_rotary_emb=image_rotary_emb,attn2=self.attn2,num_frames=num_frames,height=height,width=width,)else:attn_hidden_states, attn_encoder_hidden_states = self.attn1(hidden_states=norm_hidden_states,encoder_hidden_states=norm_encoder_hidden_states,image_rotary_emb=image_rotary_emb,attn2=self.attn2)hidden_states = hidden_states + gate_msa * attn_hidden_statesencoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states5 unmodified lines# FFNif self.norm3 is not None:norm_hidden_states = self.norm3(self.ff(norm_hidden_states))if self.txt_ff is not None:norm_encoder_hidden_states = self.norm3(self.txt_ff(norm_encoder_hidden_states))else:norm_encoder_hidden_states = self.norm3(self.ff(norm_encoder_hidden_states))else:norm_hidden_states = self.ff(norm_hidden_states)if self.txt_ff is not None:norm_encoder_hidden_states = self.txt_ff(norm_encoder_hidden_states)else:norm_encoder_hidden_states = self.ff(norm_encoder_hidden_states)hidden_states = hidden_states + gate_ff * norm_hidden_statesencoder_hidden_states = encoder_hidden_states + enc_gate_ff * norm_encoder_hidden_statesreturn hidden_states, encoder_hidden_states
43 unmodified lines44454647484946 unmodified lines969798991001017 unmodified lines10911011111211311415 unmodified lines13013113213313413513613716 unmodified lines15415515615715815916016134 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527631 unmodified lines30830931031131231341 unmodified lines355356357358359360158 unmodified lines51952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156243 unmodified linesCogVideoXDecoder3D,CogVideoXEncoder3D,CogVideoXSafeConv3d)from ..vae.ldm.models.omnigen_enc_dec import Decoder as omnigen_Mag_Decoderfrom ..vae.ldm.models.omnigen_enc_dec import Encoder as omnigen_Mag_Encoder46 unmodified linesout_channels: int = 3,ch = 128,ch_mult = [ 1,2,4,4 ],use_gc_blocks = None,down_block_types: tuple = None,up_block_types: tuple = None,7 unmodified lineslatent_channels: int = 4,norm_num_groups: int = 32,scaling_factor: float = 0.1825,slice_mag_vae=True,slice_compression_vae=False,cache_compression_vae=False,15 unmodified linesin_channels=in_channels,out_channels=latent_channels,down_block_types=down_block_types,ch = ch,ch_mult = ch_mult,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,16 unmodified linesin_channels=latent_channels,out_channels=out_channels,up_block_types=up_block_types,ch = ch,ch_mult = ch_mult,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,34 unmodified linesif isinstance(module, (omnigen_Mag_Encoder, omnigen_Mag_Decoder)):module.gradient_checkpointing = value@property# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processorsdef attn_processors(self) -> Dict[str, AttentionProcessor]:r"""Returns:`dict` of attention processors: A dictionary containing all attention processors used in the model withindexed by its weight name."""# set recursivelyprocessors = {}def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):if hasattr(module, "get_processor"):processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)for sub_name, child in module.named_children():fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)return processorsfor name, module in self.named_children():fn_recursive_add_processors(name, module, processors)return processors# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processordef set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):r"""Sets the attention processor to use to compute attention.Parameters:processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):The instantiated processor class or a dictionary of processor classes that will be set as the processorfor **all** `Attention` layers.If `processor` is a dict, the key needs to define the path to the corresponding cross attentionprocessor. This is strongly recommended when setting trainable attention processors."""count = len(self.attn_processors.keys())if isinstance(processor, dict) and len(processor) != count:raise ValueError(f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"f" number of attention layers: {count}. Please make sure to pass {count} processor classes.")def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):if hasattr(module, "set_processor"):if not isinstance(processor, dict):module.set_processor(processor)else:module.set_processor(processor.pop(f"{name}.processor"))for sub_name, child in module.named_children():fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)for name, module in self.named_children():fn_recursive_attn_processor(name, module, processor)# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processordef set_default_attn_processor(self):"""Disables custom attention processors and sets the default attention implementation."""if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):processor = AttnAddedKVProcessor()elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):processor = AttnProcessor()else:raise ValueError(f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}")self.set_attn_processor(processor)@apply_forward_hookdef encode(31 unmodified linesmoments = self.quant_conv(h)posterior = DiagonalGaussianDistribution(moments)if not return_dict:return (posterior,)41 unmodified lineselse:decoded = self._decode(z).sampleif not return_dict:return (decoded,)158 unmodified linesreturn DecoderOutput(sample=dec)# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projectionsdef fuse_qkv_projections(self):"""Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,key, value) are fused. For cross-attention modules, key and value projection matrices are fused.<Tip warning={true}>This API is 🧪 experimental.</Tip>"""self.original_attn_processors = Nonefor _, attn_processor in self.attn_processors.items():if "Added" in str(attn_processor.__class__.__name__):raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")self.original_attn_processors = self.attn_processorsfor module in self.modules():if isinstance(module, Attention):module.fuse_projections(fuse=True)# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projectionsdef unfuse_qkv_projections(self):"""Disables the fused QKV projection if enabled.<Tip warning={true}>This API is 🧪 experimental.</Tip>"""if self.original_attn_processors is not None:self.set_attn_processor(self.original_attn_processors)@classmethoddef from_pretrained(cls, pretrained_model_path, subfolder=None, **vae_additional_kwargs):import json43 unmodified lines4445464748495046 unmodified lines9798991001011021037 unmodified lines11111211311411511611715 unmodified lines13313413513613713813914014116 unmodified lines15815916016116216316416516634 unmodified lines20120220320420520620720820921031 unmodified lines24224324424524624724841 unmodified lines290291292293294295296158 unmodified lines45545645745845946043 unmodified linesCogVideoXDecoder3D,CogVideoXEncoder3D,CogVideoXSafeConv3d)from ..vae.ldm.models.omnigen_enc_dec import CausalConv3dfrom ..vae.ldm.models.omnigen_enc_dec import Decoder as omnigen_Mag_Decoderfrom ..vae.ldm.models.omnigen_enc_dec import Encoder as omnigen_Mag_Encoder46 unmodified linesout_channels: int = 3,ch = 128,ch_mult = [ 1,2,4,4 ],block_out_channels = [128, 256, 512, 512],use_gc_blocks = None,down_block_types: tuple = None,up_block_types: tuple = None,7 unmodified lineslatent_channels: int = 4,norm_num_groups: int = 32,scaling_factor: float = 0.1825,force_upcast: float = True,slice_mag_vae=True,slice_compression_vae=False,cache_compression_vae=False,15 unmodified linesin_channels=in_channels,out_channels=latent_channels,down_block_types=down_block_types,ch=ch,ch_mult=ch_mult,block_out_channels=block_out_channels,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,16 unmodified linesin_channels=latent_channels,out_channels=out_channels,up_block_types=up_block_types,ch=ch,ch_mult=ch_mult,block_out_channels=block_out_channels,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,34 unmodified linesif isinstance(module, (omnigen_Mag_Encoder, omnigen_Mag_Decoder)):module.gradient_checkpointing = valuedef _clear_conv_cache(self):for name, module in self.named_modules():if isinstance(module, CausalConv3d):module._clear_conv_cache()@apply_forward_hookdef encode(31 unmodified linesmoments = self.quant_conv(h)posterior = DiagonalGaussianDistribution(moments)self._clear_conv_cache()if not return_dict:return (posterior,)41 unmodified lineselse:decoded = self._decode(z).sampleself._clear_conv_cache()if not return_dict:return (decoded,)158 unmodified linesreturn DecoderOutput(sample=dec)@classmethoddef from_pretrained(cls, pretrained_model_path, subfolder=None, **vae_additional_kwargs):import json
3 unmodified lines45678910113 unmodified linesimport numpy as npimport torchimport torch.nn.functional as Ffrom diffusers.models.embeddings import (PixArtAlphaTextProjection, get_timestep_embedding,TimestepEmbedding, Timesteps)from einops import rearrangefrom torch import nn3 unmodified lines4567891011123 unmodified linesimport numpy as npimport torchimport torch.nn.functional as Ffrom diffusers.models.embeddings import (PixArtAlphaTextProjection,TimestepEmbedding, Timesteps,get_timestep_embedding)from einops import rearrangefrom torch import nn
24 unmodified lines25262728293024 unmodified linesinputs.float(), self.normalized_shape, None, None, self.eps).to(origin_dtype)class PixArtAlphaCombinedTimestepSizeEmbeddings(nn.Module):"""For PixArt-Alpha.24 unmodified lines2526272829303132333435363738394041424344454624 unmodified linesinputs.float(), self.normalized_shape, None, None, self.eps).to(origin_dtype)class EasyAnimateRMSNorm(nn.Module):def __init__(self, hidden_size, eps=1e-6):super().__init__()self.weight = nn.Parameter(torch.ones(hidden_size))self.variance_epsilon = epsdef forward(self, hidden_states):input_dtype = hidden_states.dtypehidden_states = hidden_states.to(torch.float32)variance = hidden_states.pow(2).mean(-1, keepdim=True)hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)return self.weight * hidden_states.to(input_dtype)def extra_repr(self):return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"class PixArtAlphaCombinedTimestepSizeEmbeddings(nn.Module):"""For PixArt-Alpha.
309 unmodified lines310311312309 unmodified lineshidden_states = attn.to_out[1](hidden_states)encoder_hidden_states = attn2.to_out[1](encoder_hidden_states)return hidden_states, encoder_hidden_states309 unmodified lines310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458309 unmodified lineshidden_states = attn.to_out[1](hidden_states)encoder_hidden_states = attn2.to_out[1](encoder_hidden_states)return hidden_states, encoder_hidden_statestry:from flash_attn import flash_attn_func, flash_attn_varlen_funcfrom flash_attn.bert_padding import pad_input, unpad_inputexcept:print("Flash Attention is not installed. Please install with `pip install flash-attn`, if you want to use SWA.")class EasyAnimateSWAttnProcessor2_0:def __init__(self, window_size=1024):self.window_size = window_sizedef __call__(self,attn: Attention,hidden_states: torch.Tensor,encoder_hidden_states: torch.Tensor,attention_mask: Optional[torch.Tensor] = None,image_rotary_emb: Optional[torch.Tensor] = None,num_frames: int = None,height: int = None,width: int = None,attn2: Attention = None,) -> torch.Tensor:text_seq_length = encoder_hidden_states.size(1)batch_size, sequence_length, _ = (hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape)if attn2 is None:hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)query = attn.to_q(hidden_states)key = attn.to_k(hidden_states)value = attn.to_v(hidden_states)inner_dim = key.shape[-1]head_dim = inner_dim // attn.headsquery = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)value = value.view(batch_size, -1, attn.heads, head_dim)if attn.norm_q is not None:query = attn.norm_q(query)if attn.norm_k is not None:key = attn.norm_k(key)if attn2 is not None:query_txt = attn2.to_q(encoder_hidden_states)key_txt = attn2.to_k(encoder_hidden_states)value_txt = attn2.to_v(encoder_hidden_states)inner_dim = key_txt.shape[-1]head_dim = inner_dim // attn.headsquery_txt = query_txt.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)key_txt = key_txt.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)value_txt = value_txt.view(batch_size, -1, attn.heads, head_dim)if attn2.norm_q is not None:query_txt = attn2.norm_q(query_txt)if attn2.norm_k is not None:key_txt = attn2.norm_k(key_txt)query = torch.cat([query_txt, query], dim=2)key = torch.cat([key_txt, key], dim=2)value = torch.cat([value_txt, value], dim=1)# Apply RoPE if neededif image_rotary_emb is not None:query[:, :, text_seq_length:] = apply_rotary_emb(query[:, :, text_seq_length:], image_rotary_emb)if not attn.is_cross_attention:key[:, :, text_seq_length:] = apply_rotary_emb(key[:, :, text_seq_length:], image_rotary_emb)query = query.transpose(1, 2).to(value)key = key.transpose(1, 2).to(value)interval = max((query.size(1) - text_seq_length) // (self.window_size - text_seq_length), 1)cross_key = torch.cat([key[:, :text_seq_length], key[:, text_seq_length::interval]], dim=1)cross_val = torch.cat([value[:, :text_seq_length], value[:, text_seq_length::interval]], dim=1)cross_hidden_states = flash_attn_func(query, cross_key, cross_val, dropout_p=0.0, causal=False)# Split and rearrange to six directionsquerys = torch.tensor_split(query[:, text_seq_length:], 6, 2)keys = torch.tensor_split(key[:, text_seq_length:], 6, 2)values = torch.tensor_split(value[:, text_seq_length:], 6, 2)new_querys = [querys[0]]new_keys = [keys[0]]new_values = [values[0]]for index, mode in enumerate(["bs (f h w) hn hd -> bs (f w h) hn hd","bs (f h w) hn hd -> bs (h f w) hn hd","bs (f h w) hn hd -> bs (h w f) hn hd","bs (f h w) hn hd -> bs (w f h) hn hd","bs (f h w) hn hd -> bs (w h f) hn hd"]):new_querys.append(rearrange(querys[index + 1], mode, f=num_frames, h=height, w=width))new_keys.append(rearrange(keys[index + 1], mode, f=num_frames, h=height, w=width))new_values.append(rearrange(values[index + 1], mode, f=num_frames, h=height, w=width))query = torch.cat(new_querys, dim=2)key = torch.cat(new_keys, dim=2)value = torch.cat(new_values, dim=2)# apply attentionhidden_states = flash_attn_func(query, key, value, dropout_p=0.0, causal=False, window_size=(self.window_size, self.window_size))hidden_states = torch.tensor_split(hidden_states, 6, 2)new_hidden_states = [hidden_states[0]]for index, mode in enumerate(["bs (f w h) hn hd -> bs (f h w) hn hd","bs (h f w) hn hd -> bs (f h w) hn hd","bs (h w f) hn hd -> bs (f h w) hn hd","bs (w f h) hn hd -> bs (f h w) hn hd","bs (w h f) hn hd -> bs (f h w) hn hd"]):new_hidden_states.append(rearrange(hidden_states[index + 1], mode, f=num_frames, h=height, w=width))hidden_states = torch.cat([cross_hidden_states[:, :text_seq_length], torch.cat(new_hidden_states, dim=2)], dim=1) + cross_hidden_stateshidden_states = hidden_states.reshape(batch_size, -1, attn.heads * head_dim)if attn2 is None:# linear projhidden_states = attn.to_out[0](hidden_states)# dropouthidden_states = attn.to_out[1](hidden_states)encoder_hidden_states, hidden_states = hidden_states.split([text_seq_length, hidden_states.size(1) - text_seq_length], dim=1)else:encoder_hidden_states, hidden_states = hidden_states.split([text_seq_length, hidden_states.size(1) - text_seq_length], dim=1)# linear projhidden_states = attn.to_out[0](hidden_states)encoder_hidden_states = attn2.to_out[0](encoder_hidden_states)# dropouthidden_states = attn.to_out[1](hidden_states)encoder_hidden_states = attn2.to_out[1](encoder_hidden_states)return hidden_states, encoder_hidden_states
38 unmodified lines394041424344454695 unmodified lines14214314414514614720 unmodified lines16816917017117217318 unmodified lines192193194195196197199 unmodified lines39739839940040140240340440540640740840941041141219 unmodified lines43243343443543643743827 unmodified lines466467468469470471472473474475476160 unmodified lines6376386396406416426435 unmodified lines64965065165265365465565665765865966066166266366427 unmodified lines69269369469569669771 unmodified lines769770771772773774134 unmodified lines909910911912913914170 unmodified lines10851086108710881089109010915 unmodified lines109710981099110011011102110311041105110611071108110911101111111243 unmodified lines11561157115811591160116116 unmodified lines117811791180118111821183118411855 unmodified lines1191119211931194119511961197119812 unmodified lines121112121213121412151216121712185 unmodified lines1224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124628 unmodified lines12751276127712781279128062 unmodified lines1343134413451346134713482 unmodified lines13511352135313541355135614 unmodified lines13711372137313741375137613775 unmodified lines13831384138513861387138813891390139141 unmodified lines143314341435143638 unmodified linesfrom .attention import (EasyAnimateDiTBlock, HunyuanDiTBlock,SelfAttentionTemporalTransformerBlock,TemporalTransformerBlock, zero_module)from .embeddings import HunyuanCombinedTimestepTextSizeStyleEmbedding, TimePositionalEncodingfrom .norm import AdaLayerNormSinglefrom .patch import (CasualPatchEmbed3D, PatchEmbed3D, PatchEmbedF3D,TemporalUpsampler3D, UnPatch1D)from .resampler import Resampler95 unmodified linesnorm_eps: float = 1e-5,attention_type: str = "default",caption_channels: int = None,# block typebasic_block_type: str = "motionmodule",# enable_uvit20 unmodified linesafter_norm = False,resize_inpaint_mask_directly: bool = False,enable_clip_in_inpaint: bool = True,enable_text_attention_mask: bool = True,add_noise_in_inpaint_model: bool = False,):18 unmodified linesself.time_patch_size = self.patch_size if time_patch_size is None else time_patch_sizeinterpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1interpolation_scale = max(interpolation_scale, 1)if self.casual_3d:self.pos_embed = CasualPatchEmbed3D(199 unmodified linesdef forward(self,hidden_states: torch.Tensor,inpaint_latents: torch.Tensor = None,control_latents: torch.Tensor = None,encoder_hidden_states: Optional[torch.Tensor] = None,clip_encoder_hidden_states: Optional[torch.Tensor] = None,timestep: Optional[torch.LongTensor] = None,added_cond_kwargs: Dict[str, torch.Tensor] = None,class_labels: Optional[torch.LongTensor] = None,cross_attention_kwargs: Dict[str, Any] = None,attention_mask: Optional[torch.Tensor] = None,encoder_attention_mask: Optional[torch.Tensor] = None,clip_attention_mask: Optional[torch.Tensor] = None,return_dict: bool = True,):19 unmodified linesAn attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the maskis kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds largenegative values to the attention scores corresponding to "discard" tokens.encoder_attention_mask ( `torch.Tensor`, *optional*):Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:* Mask `(batch, sequence_length)` True = keep, False = discard.27 unmodified linesattention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0attention_mask = attention_mask.unsqueeze(1)if clip_attention_mask is not None:encoder_attention_mask = torch.cat([encoder_attention_mask, clip_attention_mask], dim=1)# convert encoder_attention_mask to a bias the same way we do for attention_maskif encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:encoder_attention_mask = (1 - encoder_attention_mask.to(encoder_hidden_states.dtype)) * -10000.0encoder_attention_mask = encoder_attention_mask.unsqueeze(1)if inpaint_latents is not None:160 unmodified linesreturn Transformer3DModelOutput(sample=output)@classmethoddef from_pretrained_2d(cls, pretrained_model_path, subfolder=None, patch_size=2, transformer_additional_kwargs={}):if subfolder is not None:pretrained_model_path = os.path.join(pretrained_model_path, subfolder)print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...")5 unmodified linesconfig = json.load(f)from diffusers.utils import WEIGHTS_NAMEmodel = cls.from_config(config, **transformer_additional_kwargs)model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)model_file_safetensors = model_file.replace(".bin", ".safetensors")if os.path.exists(model_file_safetensors):from safetensors.torch import load_file, safe_openstate_dict = load_file(model_file_safetensors)else:if not os.path.isfile(model_file):raise RuntimeError(f"{model_file} does not exist")state_dict = torch.load(model_file, map_location="cpu")if model.state_dict()['pos_embed.proj.weight'].size() != state_dict['pos_embed.proj.weight'].size():new_shape = model.state_dict()['pos_embed.proj.weight'].size()27 unmodified linesparams = [p.numel() if "attn_temporal." in n else 0 for n, p in model.named_parameters()]print(f"### Attn temporal Parameters: {sum(params) / 1e6} M")return modelclass HunyuanTransformer3DModel(ModelMixin, ConfigMixin):71 unmodified linesafter_norm = False,resize_inpaint_mask_directly: bool = False,enable_clip_in_inpaint: bool = True,enable_text_attention_mask: bool = True,add_noise_in_inpaint_model: bool = False,):134 unmodified linescontrol_latents: torch.Tensor = None,clip_encoder_hidden_states: Optional[torch.Tensor]=None,clip_attention_mask: Optional[torch.Tensor]=None,return_dict=True,):"""170 unmodified linesreturn Transformer2DModelOutput(sample=output)@classmethoddef from_pretrained_2d(cls, pretrained_model_path, subfolder=None, patch_size=2, transformer_additional_kwargs={}):if subfolder is not None:pretrained_model_path = os.path.join(pretrained_model_path, subfolder)print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...")5 unmodified linesconfig = json.load(f)from diffusers.utils import WEIGHTS_NAMEmodel = cls.from_config(config, **transformer_additional_kwargs)model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)model_file_safetensors = model_file.replace(".bin", ".safetensors")if os.path.exists(model_file_safetensors):from safetensors.torch import load_file, safe_openstate_dict = load_file(model_file_safetensors)else:if not os.path.isfile(model_file):raise RuntimeError(f"{model_file} does not exist")state_dict = torch.load(model_file, map_location="cpu")if model.state_dict()['pos_embed.proj.weight'].size() != state_dict['pos_embed.proj.weight'].size():new_shape = model.state_dict()['pos_embed.proj.weight'].size()43 unmodified linesparams = [p.numel() if "attn1." in n else 0 for n, p in model.named_parameters()]print(f"### attn1 Parameters: {sum(params) / 1e6} M")return modelclass EasyAnimateTransformer3DModel(ModelMixin, ConfigMixin):16 unmodified linestimestep_activation_fn: str = "silu",freq_shift: int = 0,num_layers: int = 30,dropout: float = 0.0,time_embed_dim: int = 512,text_embed_dim: int = 4096,text_embed_dim_t5: int = 4096,norm_eps: float = 1e-5,5 unmodified linesafter_norm = False,resize_inpaint_mask_directly: bool = False,enable_clip_in_inpaint: bool = True,enable_text_attention_mask: bool = True,add_noise_in_inpaint_model: bool = False,):super().__init__()self.num_heads = num_attention_heads12 unmodified linesself.proj = nn.Conv2d(in_channels, self.inner_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=True)self.text_proj = nn.Linear(text_embed_dim, self.inner_dim)self.text_proj_t5 = nn.Linear(text_embed_dim_t5, self.inner_dim)if ref_channels is not None:self.ref_proj = nn.Conv2d(5 unmodified linesif clip_channels is not None:self.clip_proj = nn.Linear(clip_channels, self.inner_dim)self.transformer_blocks = nn.ModuleList([EasyAnimateDiTBlock(dim=self.inner_dim,num_attention_heads=num_attention_heads,attention_head_dim=attention_head_dim,time_embed_dim=time_embed_dim,dropout=dropout,activation_fn=activation_fn,norm_elementwise_affine=norm_elementwise_affine,norm_eps=norm_eps,after_norm=after_norm)for _ in range(num_layers)])self.norm_final = nn.LayerNorm(self.inner_dim, norm_eps, norm_elementwise_affine)# 5. Output blocks28 unmodified linesref_latents: Optional[torch.Tensor] = None,clip_encoder_hidden_states: Optional[torch.Tensor] = None,clip_attention_mask: Optional[torch.Tensor] = None,return_dict=True,):batch_size, channels, video_length, height, width = hidden_states.size()62 unmodified linesencoder_hidden_states,temb,image_rotary_emb,**ckpt_kwargs,)else:2 unmodified linesencoder_hidden_states=encoder_hidden_states,temb=temb,image_rotary_emb=image_rotary_emb,)hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)14 unmodified linesreturn Transformer2DModelOutput(sample=output)@classmethoddef from_pretrained_2d(cls, pretrained_model_path, subfolder=None, transformer_additional_kwargs={}):if subfolder is not None:pretrained_model_path = os.path.join(pretrained_model_path, subfolder)print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...")5 unmodified linesconfig = json.load(f)from diffusers.utils import WEIGHTS_NAMEmodel = cls.from_config(config, **transformer_additional_kwargs)model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)model_file_safetensors = model_file.replace(".bin", ".safetensors")if os.path.exists(model_file):state_dict = torch.load(model_file, map_location="cpu")elif os.path.exists(model_file_safetensors):41 unmodified linesparams = [p.numel() if "attn1." in n else 0 for n, p in model.named_parameters()]print(f"### attn1 Parameters: {sum(params) / 1e6} M")return model38 unmodified lines39404142434445464795 unmodified lines14314414514614714814920 unmodified lines17017117217317417517617718 unmodified lines196197198199200201202199 unmodified lines40240340440540640740840941041141241341441541641741841942042142242319 unmodified lines44344444544644744844927 unmodified lines477478479480481482483484485486487488160 unmodified lines6496506516526536546556566576585 unmodified lines66466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573627 unmodified lines76476576676776876977071 unmodified lines842843844845846847848134 unmodified lines983984985986987988989170 unmodified lines11601161116211631164116511661167116811695 unmodified lines117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124743 unmodified lines129112921293129412951296129716 unmodified lines131413151316131713181319132013211322132313245 unmodified lines133013311332133313341335133613371338133912 unmodified lines135213531354135513561357135813591360136113621363136413651366136713681369137013715 unmodified lines13771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142128 unmodified lines145014511452145314541455145662 unmodified lines1519152015211522152315241525152615272 unmodified lines15301531153215331534153515361537153814 unmodified lines15531554155515561557155815591560156115625 unmodified lines15681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162741 unmodified lines1669167016711672167338 unmodified linesfrom .attention import (EasyAnimateDiTBlock, HunyuanDiTBlock,SelfAttentionTemporalTransformerBlock,TemporalTransformerBlock, zero_module)from .embeddings import (HunyuanCombinedTimestepTextSizeStyleEmbedding,TimePositionalEncoding)from .norm import AdaLayerNormSingle, EasyAnimateRMSNormfrom .patch import (CasualPatchEmbed3D, PatchEmbed3D, PatchEmbedF3D,TemporalUpsampler3D, UnPatch1D)from .resampler import Resampler95 unmodified linesnorm_eps: float = 1e-5,attention_type: str = "default",caption_channels: int = None,n_query=8,# block typebasic_block_type: str = "motionmodule",# enable_uvit20 unmodified linesafter_norm = False,resize_inpaint_mask_directly: bool = False,enable_clip_in_inpaint: bool = True,position_of_clip_embedding: str = "head",enable_zero_in_inpaint: bool = False,enable_text_attention_mask: bool = True,add_noise_in_inpaint_model: bool = False,):18 unmodified linesself.time_patch_size = self.patch_size if time_patch_size is None else time_patch_sizeinterpolation_scale = self.config.sample_size // 64 # => 64 (= 512 pixart) has interpolation scale 1interpolation_scale = max(interpolation_scale, 1)self.n_query = n_queryif self.casual_3d:self.pos_embed = CasualPatchEmbed3D(199 unmodified linesdef forward(self,hidden_states: torch.Tensor,timestep: Optional[torch.LongTensor] = None,timestep_cond = None,encoder_hidden_states: Optional[torch.Tensor] = None,text_embedding_mask: Optional[torch.Tensor] = None,encoder_hidden_states_t5: Optional[torch.Tensor] = None,text_embedding_mask_t5: Optional[torch.Tensor] = None,image_meta_size = None,style = None,image_rotary_emb: Optional[torch.Tensor] = None,inpaint_latents: torch.Tensor = None,control_latents: torch.Tensor = None,added_cond_kwargs: Dict[str, torch.Tensor] = None,class_labels: Optional[torch.LongTensor] = None,cross_attention_kwargs: Dict[str, Any] = None,attention_mask: Optional[torch.Tensor] = None,clip_encoder_hidden_states: Optional[torch.Tensor] = None,clip_attention_mask: Optional[torch.Tensor] = None,return_dict: bool = True,):19 unmodified linesAn attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the maskis kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds largenegative values to the attention scores corresponding to "discard" tokens.text_embedding_mask ( `torch.Tensor`, *optional*):Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:* Mask `(batch, sequence_length)` True = keep, False = discard.27 unmodified linesattention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0attention_mask = attention_mask.unsqueeze(1)text_embedding_mask = text_embedding_mask.squeeze(1)if clip_attention_mask is not None:text_embedding_mask = torch.cat([text_embedding_mask, clip_attention_mask], dim=1)# convert encoder_attention_mask to a bias the same way we do for attention_maskif text_embedding_mask is not None and text_embedding_mask.ndim == 2:encoder_attention_mask = (1 - text_embedding_mask.to(encoder_hidden_states.dtype)) * -10000.0encoder_attention_mask = encoder_attention_mask.unsqueeze(1)if inpaint_latents is not None:160 unmodified linesreturn Transformer3DModelOutput(sample=output)@classmethoddef from_pretrained_2d(cls, pretrained_model_path, subfolder=None, patch_size=2, transformer_additional_kwargs={},low_cpu_mem_usage=False, torch_dtype=torch.bfloat16):if subfolder is not None:pretrained_model_path = os.path.join(pretrained_model_path, subfolder)print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...")5 unmodified linesconfig = json.load(f)from diffusers.utils import WEIGHTS_NAMEmodel_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)model_file_safetensors = model_file.replace(".bin", ".safetensors")if low_cpu_mem_usage:try:import refrom diffusers.models.modeling_utils import \load_model_dict_into_metafrom diffusers.utils import is_accelerate_availableif is_accelerate_available():import accelerate# Instantiate model with empty weightswith accelerate.init_empty_weights():model = cls.from_config(config, **transformer_additional_kwargs)param_device = "cpu"from safetensors.torch import load_file, safe_openstate_dict = load_file(model_file_safetensors)model._convert_deprecated_attention_blocks(state_dict)# move the params from meta device to cpumissing_keys = set(model.state_dict().keys()) - set(state_dict.keys())if len(missing_keys) > 0:raise ValueError(f"Cannot load {cls} from {pretrained_model_path} because the following keys are"f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass"" `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize"" those weights or else make sure your checkpoint file is correct.")unexpected_keys = load_model_dict_into_meta(model,state_dict,device=param_device,dtype=torch_dtype,model_name_or_path=pretrained_model_path,)if cls._keys_to_ignore_on_load_unexpected is not None:for pat in cls._keys_to_ignore_on_load_unexpected:unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]if len(unexpected_keys) > 0:print(f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}")return modelexcept Exception as e:print(f"The low_cpu_mem_usage mode is not work because {e}. Use low_cpu_mem_usage=False instead.")model = cls.from_config(config, **transformer_additional_kwargs)if os.path.exists(model_file):state_dict = torch.load(model_file, map_location="cpu")elif os.path.exists(model_file_safetensors):from safetensors.torch import load_file, safe_openstate_dict = load_file(model_file_safetensors)else:from safetensors.torch import load_file, safe_openmodel_files_safetensors = glob.glob(os.path.join(pretrained_model_path, "*.safetensors"))state_dict = {}for model_file_safetensors in model_files_safetensors:_state_dict = load_file(model_file_safetensors)for key in _state_dict:state_dict[key] = _state_dict[key]if model.state_dict()['pos_embed.proj.weight'].size() != state_dict['pos_embed.proj.weight'].size():new_shape = model.state_dict()['pos_embed.proj.weight'].size()27 unmodified linesparams = [p.numel() if "attn_temporal." in n else 0 for n, p in model.named_parameters()]print(f"### Attn temporal Parameters: {sum(params) / 1e6} M")model = model.to(torch_dtype)return modelclass HunyuanTransformer3DModel(ModelMixin, ConfigMixin):71 unmodified linesafter_norm = False,resize_inpaint_mask_directly: bool = False,enable_clip_in_inpaint: bool = True,position_of_clip_embedding: str = "full",enable_text_attention_mask: bool = True,add_noise_in_inpaint_model: bool = False,):134 unmodified linescontrol_latents: torch.Tensor = None,clip_encoder_hidden_states: Optional[torch.Tensor]=None,clip_attention_mask: Optional[torch.Tensor]=None,added_cond_kwargs: Dict[str, torch.Tensor] = None,return_dict=True,):"""170 unmodified linesreturn Transformer2DModelOutput(sample=output)@classmethoddef from_pretrained_2d(cls, pretrained_model_path, subfolder=None, transformer_additional_kwargs={},low_cpu_mem_usage=False, torch_dtype=torch.bfloat16):if subfolder is not None:pretrained_model_path = os.path.join(pretrained_model_path, subfolder)print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...")5 unmodified linesconfig = json.load(f)from diffusers.utils import WEIGHTS_NAMEmodel_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)model_file_safetensors = model_file.replace(".bin", ".safetensors")if low_cpu_mem_usage:try:import refrom diffusers.models.modeling_utils import \load_model_dict_into_metafrom diffusers.utils import is_accelerate_availableif is_accelerate_available():import accelerate# Instantiate model with empty weightswith accelerate.init_empty_weights():model = cls.from_config(config, **transformer_additional_kwargs)param_device = "cpu"from safetensors.torch import load_file, safe_openstate_dict = load_file(model_file_safetensors)model._convert_deprecated_attention_blocks(state_dict)# move the params from meta device to cpumissing_keys = set(model.state_dict().keys()) - set(state_dict.keys())if len(missing_keys) > 0:raise ValueError(f"Cannot load {cls} from {pretrained_model_path} because the following keys are"f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass"" `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize"" those weights or else make sure your checkpoint file is correct.")unexpected_keys = load_model_dict_into_meta(model,state_dict,device=param_device,dtype=torch_dtype,model_name_or_path=pretrained_model_path,)if cls._keys_to_ignore_on_load_unexpected is not None:for pat in cls._keys_to_ignore_on_load_unexpected:unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]if len(unexpected_keys) > 0:print(f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}")return modelexcept Exception as e:print(f"The low_cpu_mem_usage mode is not work because {e}. Use low_cpu_mem_usage=False instead.")model = cls.from_config(config, **transformer_additional_kwargs)if os.path.exists(model_file):state_dict = torch.load(model_file, map_location="cpu")elif os.path.exists(model_file_safetensors):from safetensors.torch import load_file, safe_openstate_dict = load_file(model_file_safetensors)else:from safetensors.torch import load_file, safe_openmodel_files_safetensors = glob.glob(os.path.join(pretrained_model_path, "*.safetensors"))state_dict = {}for model_file_safetensors in model_files_safetensors:_state_dict = load_file(model_file_safetensors)for key in _state_dict:state_dict[key] = _state_dict[key]if model.state_dict()['pos_embed.proj.weight'].size() != state_dict['pos_embed.proj.weight'].size():new_shape = model.state_dict()['pos_embed.proj.weight'].size()43 unmodified linesparams = [p.numel() if "attn1." in n else 0 for n, p in model.named_parameters()]print(f"### attn1 Parameters: {sum(params) / 1e6} M")model = model.to(torch_dtype)return modelclass EasyAnimateTransformer3DModel(ModelMixin, ConfigMixin):16 unmodified linestimestep_activation_fn: str = "silu",freq_shift: int = 0,num_layers: int = 30,mmdit_layers: int = 10000,swa_layers: list = None,dropout: float = 0.0,time_embed_dim: int = 512,add_norm_text_encoder: bool = False,text_embed_dim: int = 4096,text_embed_dim_t5: int = 4096,norm_eps: float = 1e-5,5 unmodified linesafter_norm = False,resize_inpaint_mask_directly: bool = False,enable_clip_in_inpaint: bool = True,position_of_clip_embedding: str = "full",enable_text_attention_mask: bool = True,add_noise_in_inpaint_model: bool = False,add_ref_latent_in_control_model: bool = False,):super().__init__()self.num_heads = num_attention_heads12 unmodified linesself.proj = nn.Conv2d(in_channels, self.inner_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=True)if not add_norm_text_encoder:self.text_proj = nn.Linear(text_embed_dim, self.inner_dim)if text_embed_dim_t5 is not None:self.text_proj_t5 = nn.Linear(text_embed_dim_t5, self.inner_dim)else:self.text_proj = nn.Sequential(EasyAnimateRMSNorm(text_embed_dim),nn.Linear(text_embed_dim, self.inner_dim))if text_embed_dim_t5 is not None:self.text_proj_t5 = nn.Sequential(EasyAnimateRMSNorm(text_embed_dim),nn.Linear(text_embed_dim_t5, self.inner_dim))if ref_channels is not None:self.ref_proj = nn.Conv2d(5 unmodified linesif clip_channels is not None:self.clip_proj = nn.Linear(clip_channels, self.inner_dim)self.swa_layers = swa_layersif swa_layers is not None:self.transformer_blocks = nn.ModuleList([EasyAnimateDiTBlock(dim=self.inner_dim,num_attention_heads=num_attention_heads,attention_head_dim=attention_head_dim,time_embed_dim=time_embed_dim,dropout=dropout,activation_fn=activation_fn,norm_elementwise_affine=norm_elementwise_affine,norm_eps=norm_eps,after_norm=after_norm,is_mmdit_block=True if index < mmdit_layers else False,is_swa=True if index in swa_layers else False,)for index in range(num_layers)])else:self.transformer_blocks = nn.ModuleList([EasyAnimateDiTBlock(dim=self.inner_dim,num_attention_heads=num_attention_heads,attention_head_dim=attention_head_dim,time_embed_dim=time_embed_dim,dropout=dropout,activation_fn=activation_fn,norm_elementwise_affine=norm_elementwise_affine,norm_eps=norm_eps,after_norm=after_norm,is_mmdit_block=True if _ < mmdit_layers else False,)for _ in range(num_layers)])self.norm_final = nn.LayerNorm(self.inner_dim, norm_eps, norm_elementwise_affine)# 5. Output blocks28 unmodified linesref_latents: Optional[torch.Tensor] = None,clip_encoder_hidden_states: Optional[torch.Tensor] = None,clip_attention_mask: Optional[torch.Tensor] = None,added_cond_kwargs: Dict[str, torch.Tensor] = None,return_dict=True,):batch_size, channels, video_length, height, width = hidden_states.size()62 unmodified linesencoder_hidden_states,temb,image_rotary_emb,video_length,height // self.patch_size,width // self.patch_size,**ckpt_kwargs,)else:2 unmodified linesencoder_hidden_states=encoder_hidden_states,temb=temb,image_rotary_emb=image_rotary_emb,num_frames=video_length,height=height // self.patch_size,width=width // self.patch_size)hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)14 unmodified linesreturn Transformer2DModelOutput(sample=output)@classmethoddef from_pretrained_2d(cls, pretrained_model_path, subfolder=None, transformer_additional_kwargs={},low_cpu_mem_usage=False, torch_dtype=torch.bfloat16):if subfolder is not None:pretrained_model_path = os.path.join(pretrained_model_path, subfolder)print(f"loaded 3D transformer's pretrained weights from {pretrained_model_path} ...")5 unmodified linesconfig = json.load(f)from diffusers.utils import WEIGHTS_NAMEmodel_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)model_file_safetensors = model_file.replace(".bin", ".safetensors")if low_cpu_mem_usage:try:import refrom diffusers.models.modeling_utils import \load_model_dict_into_metafrom diffusers.utils import is_accelerate_availableif is_accelerate_available():import accelerate# Instantiate model with empty weightswith accelerate.init_empty_weights():model = cls.from_config(config, **transformer_additional_kwargs)param_device = "cpu"from safetensors.torch import load_file, safe_openstate_dict = load_file(model_file_safetensors)model._convert_deprecated_attention_blocks(state_dict)# move the params from meta device to cpumissing_keys = set(model.state_dict().keys()) - set(state_dict.keys())if len(missing_keys) > 0:raise ValueError(f"Cannot load {cls} from {pretrained_model_path} because the following keys are"f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass"" `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize"" those weights or else make sure your checkpoint file is correct.")unexpected_keys = load_model_dict_into_meta(model,state_dict,device=param_device,dtype=torch_dtype,model_name_or_path=pretrained_model_path,)if cls._keys_to_ignore_on_load_unexpected is not None:for pat in cls._keys_to_ignore_on_load_unexpected:unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]if len(unexpected_keys) > 0:print(f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}")return modelexcept Exception as e:print(f"The low_cpu_mem_usage mode is not work because {e}. Use low_cpu_mem_usage=False instead.")model = cls.from_config(config, **transformer_additional_kwargs)if os.path.exists(model_file):state_dict = torch.load(model_file, map_location="cpu")elif os.path.exists(model_file_safetensors):41 unmodified linesparams = [p.numel() if "attn1." in n else 0 for n, p in model.named_parameters()]print(f"### attn1 Parameters: {sum(params) / 1e6} M")model = model.to(torch_dtype)return model
12347 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071724 unmodified lines777879808182838485868788899091929394954 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851 unmodified line1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192 unmodified lines2222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942953 unmodified lines29930030130230330430530630730830931031131218 unmodified lines3313323333343353363373383393403413423433443453463473483493505 unmodified lines3563573583593603613623633643653663673683691 unmodified line3713723733743753761 unmodified line3783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295307 unmodified lines5385395405415425435445455465475489 unmodified lines5585595605615625635645655665675685695705715725736 unmodified lines5805815825835845855865871 unmodified line5895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906912 unmodified lines6946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288291 unmodified line831832833834835836837# Copyright 2023 PixArt-Alpha Authors 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.7 unmodified lines# See the License for the specific language governing permissions and# limitations under the License.import copyimport htmlimport inspectimport reimport urllib.parse as ulfrom dataclasses import dataclassfrom typing import Callable, List, Optional, Tuple, Unionimport numpy as npimport torchfrom diffusers import DiffusionPipeline, ImagePipelineOutputfrom diffusers.image_processor import VaeImageProcessorfrom diffusers.models import AutoencoderKLfrom diffusers.schedulers import DPMSolverMultistepSchedulerfrom diffusers.utils import (BACKENDS_MAPPING, BaseOutput, deprecate,is_bs4_available, is_ftfy_available, logging,replace_example_docstring)from diffusers.utils.torch_utils import randn_tensorfrom einops import rearrangefrom tqdm import tqdmfrom transformers import T5EncoderModel, T5Tokenizerfrom ..models.transformer3d import Transformer3DModellogger = logging.get_logger(__name__) # pylint: disable=invalid-nameif is_bs4_available():from bs4 import BeautifulSoupif is_ftfy_available():import ftfyEXAMPLE_DOC_STRING = """Examples:```py>>> import torch>>> from diffusers import EasyAnimatePipeline>>> # You can replace the checkpoint id with "PixArt-alpha/PixArt-XL-2-512x512" too.>>> pipe = EasyAnimatePipeline.from_pretrained("PixArt-alpha/PixArt-XL-2-1024-MS", torch_dtype=torch.float16)>>> # Enable memory optimizations.>>> pipe.enable_model_cpu_offload()>>> prompt = "A small cactus with a happy face in the Sahara desert.">>> image = pipe(prompt).images[0]```"""# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timestepsdef retrieve_timesteps(scheduler,num_inference_steps: Optional[int] = None,device: Optional[Union[str, torch.device]] = None,timesteps: Optional[List[int]] = None,**kwargs,):"""4 unmodified linesscheduler (`SchedulerMixin`):The scheduler to get timesteps from.num_inference_steps (`int`):The number of diffusion steps used when generating samples with a pre-trained model. If used,`timesteps` must be `None`.device (`str` or `torch.device`, *optional*):The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.timesteps (`List[int]`, *optional*):Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the defaulttimestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`must be `None`.Returns:`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and thesecond element is the number of inference steps."""if timesteps is not None:accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())if not accepts_timesteps:4 unmodified linesscheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)timesteps = scheduler.timestepsnum_inference_steps = len(timesteps)else:scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)timesteps = scheduler.timestepsreturn timesteps, num_inference_steps@dataclassclass EasyAnimatePipelineOutput(BaseOutput):videos: Union[torch.Tensor, np.ndarray]class EasyAnimatePipeline(DiffusionPipeline):r"""Pipeline for text-to-image generation using PixArt-Alpha.This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods thelibrary implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)Args:vae ([`AutoencoderKL`]):Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.text_encoder ([`T5EncoderModel`]):Frozen text-encoder. PixArt-Alpha uses[T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the[t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.tokenizer (`T5Tokenizer`):Tokenizer of class[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).transformer ([`Transformer3DModel`]):A text conditioned `Transformer3DModel` to denoise the encoded image latents.scheduler ([`SchedulerMixin`]):A scheduler to be used in combination with `transformer` to denoise the encoded image latents."""bad_punct_regex = re.compile(r"[" + "#®•©™&@·º½¾¿¡§~" + "\)" + "\(" + "\]" + "\[" + "\}" + "\{" + "\|" + "\\" + "\/" + "\*" + r"]{1,}") # noqa_optional_components = ["tokenizer", "text_encoder"]model_cpu_offload_seq = "text_encoder->transformer->vae"def __init__(self,tokenizer: T5Tokenizer,text_encoder: T5EncoderModel,vae: AutoencoderKL,transformer: Transformer3DModel,scheduler: DPMSolverMultistepScheduler,):super().__init__()self.register_modules(tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler)self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)self.enable_autocast_float8_transformer_flag = False# Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/utils.pydef mask_text_embeddings(self, emb, mask):if emb.shape[0] == 1:keep_index = mask.sum().item()return emb[:, :, :keep_index, :], keep_indexelse:masked_feature = emb * mask[:, None, :, None]return masked_feature, emb.shape[2]# Adapted from diffusers.pipelines.deepfloyd_if.pipeline_if.encode_promptdef encode_prompt(self,prompt: Union[str, List[str]],do_classifier_free_guidance: bool = True,negative_prompt: str = "",num_images_per_prompt: int = 1,device: Optional[torch.device] = None,prompt_embeds: Optional[torch.FloatTensor] = None,negative_prompt_embeds: Optional[torch.FloatTensor] = None,prompt_attention_mask: Optional[torch.FloatTensor] = None,negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,clean_caption: bool = False,max_sequence_length: int = 120,**kwargs,):r"""Encodes the prompt into text encoder hidden states.1 unmodified lineArgs:prompt (`str` or `List[str]`, *optional*):prompt to be encodednegative_prompt (`str` or `List[str]`, *optional*):The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). ForPixArt-Alpha, this should be "".do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):whether to use classifier free guidance or notnum_images_per_prompt (`int`, *optional*, defaults to 1):number of images that should be generated per promptdevice: (`torch.device`, *optional*):torch device to place the resulting embeddings onprompt_embeds (`torch.FloatTensor`, *optional*):Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If notprovided, text embeddings will be generated from `prompt` input argument.negative_prompt_embeds (`torch.FloatTensor`, *optional*):Pre-generated negative text embeddings. For PixArt-Alpha, it's should be the embeddings of the ""string.clean_caption (`bool`, defaults to `False`):If `True`, the function will preprocess and clean the provided caption before encoding.max_sequence_length (`int`, defaults to 120): Maximum sequence length to use for the prompt."""if "mask_feature" in kwargs:deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)if device is None:device = self._execution_deviceif prompt is not None and isinstance(prompt, str):batch_size = 12 unmodified lineselse:batch_size = prompt_embeds.shape[0]# See Section 3.1. of the paper.max_length = max_sequence_lengthif prompt_embeds is None:prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)text_inputs = self.tokenizer(prompt,padding="max_length",max_length=max_length,truncation=True,add_special_tokens=True,return_tensors="pt",)text_input_ids = text_inputs.input_idsuntruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_idsif untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_length - 1 : -1])logger.warning("The following part of your input was truncated because CLIP can only handle sequences up to"f" {max_length} tokens: {removed_text}")prompt_attention_mask = text_inputs.attention_maskprompt_attention_mask = prompt_attention_mask.to(device)prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)prompt_embeds = prompt_embeds[0]if self.text_encoder is not None:dtype = self.text_encoder.dtypeelif self.transformer is not None:dtype = self.transformer.dtypeelse:dtype = Noneprompt_embeds = prompt_embeds.to(dtype=dtype, device=device)bs_embed, seq_len, _ = prompt_embeds.shape# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly methodprompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)prompt_attention_mask = prompt_attention_mask.view(bs_embed, -1)prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)# get unconditional embeddings for classifier free guidanceif do_classifier_free_guidance and negative_prompt_embeds is None:uncond_tokens = [negative_prompt] * batch_sizeuncond_tokens = self._text_preprocessing(uncond_tokens, clean_caption=clean_caption)max_length = prompt_embeds.shape[1]uncond_input = self.tokenizer(uncond_tokens,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,add_special_tokens=True,return_tensors="pt",)negative_prompt_attention_mask = uncond_input.attention_masknegative_prompt_attention_mask = negative_prompt_attention_mask.to(device)negative_prompt_embeds = self.text_encoder(uncond_input.input_ids.to(device), attention_mask=negative_prompt_attention_mask)negative_prompt_embeds = negative_prompt_embeds[0]if do_classifier_free_guidance:# duplicate unconditional embeddings for each generation per prompt, using mps friendly method3 unmodified linesnegative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)negative_prompt_attention_mask = negative_prompt_attention_mask.view(bs_embed, -1)negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)else:negative_prompt_embeds = Nonenegative_prompt_attention_mask = Nonereturn prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargsdef prepare_extra_step_kwargs(self, generator, eta):18 unmodified linesprompt,height,width,negative_prompt,callback_steps,prompt_embeds=None,negative_prompt_embeds=None,):if height % 8 != 0 or width % 8 != 0:raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")if (callback_steps is None) or (callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)):raise ValueError(f"`callback_steps` has to be a positive integer but is {callback_steps} of type"f" {type(callback_steps)}.")if prompt is not None and prompt_embeds is not None:5 unmodified linesraise ValueError("Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.")elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")if prompt is not None and negative_prompt_embeds is not None:raise ValueError(f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"f" {negative_prompt_embeds}. Please make sure to only forward one of the two.")if negative_prompt is not None and negative_prompt_embeds is not None:raise ValueError(1 unmodified linef" {negative_prompt_embeds}. Please make sure to only forward one of the two.")if prompt_embeds is not None and negative_prompt_embeds is not None:if prompt_embeds.shape != negative_prompt_embeds.shape:raise ValueError(1 unmodified linef" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"f" {negative_prompt_embeds.shape}.")# Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessingdef _text_preprocessing(self, text, clean_caption=False):if clean_caption and not is_bs4_available():logger.warn(BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`"))logger.warn("Setting `clean_caption` to False...")clean_caption = Falseif clean_caption and not is_ftfy_available():logger.warn(BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`"))logger.warn("Setting `clean_caption` to False...")clean_caption = Falseif not isinstance(text, (tuple, list)):text = [text]def process(text: str):if clean_caption:text = self._clean_caption(text)text = self._clean_caption(text)else:text = text.lower().strip()return textreturn [process(t) for t in text]# Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_captiondef _clean_caption(self, caption):caption = str(caption)caption = ul.unquote_plus(caption)caption = caption.strip().lower()caption = re.sub("<person>", "person", caption)# urls:caption = re.sub(r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa"",caption,) # regex for urlscaption = re.sub(r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa"",caption,) # regex for urls# html:caption = BeautifulSoup(caption, features="html.parser").text# @<nickname>caption = re.sub(r"@[\w\d]+\b", "", caption)# 31C0—31EF CJK Strokes# 31F0—31FF Katakana Phonetic Extensions# 3200—32FF Enclosed CJK Letters and Months# 3300—33FF CJK Compatibility# 3400—4DBF CJK Unified Ideographs Extension A# 4DC0—4DFF Yijing Hexagram Symbols# 4E00—9FFF CJK Unified Ideographscaption = re.sub(r"[\u31c0-\u31ef]+", "", caption)caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)caption = re.sub(r"[\u3200-\u32ff]+", "", caption)caption = re.sub(r"[\u3300-\u33ff]+", "", caption)caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)######################################################## все виды тире / all types of dash --> "-"caption = re.sub(r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa"-",caption,)# кавычки к одному стандартуcaption = re.sub(r"[`´«»“”¨]", '"', caption)caption = re.sub(r"[‘’]", "'", caption)# "caption = re.sub(r""?", "", caption)# &caption = re.sub(r"&", "", caption)# ip adresses:caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)# article ids:caption = re.sub(r"\d:\d\d\s+$", "", caption)# \ncaption = re.sub(r"\\n", " ", caption)# "#123"caption = re.sub(r"#\d{1,3}\b", "", caption)# "#12345.."caption = re.sub(r"#\d{5,}\b", "", caption)# "123456.."caption = re.sub(r"\b\d{6,}\b", "", caption)# filenames:caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption)#caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFTcaption = re.sub(r"\s+\.\s+", r" ", caption) # " . "# this-is-my-cute-cat / this_is_my_cute_catregex2 = re.compile(r"(?:\-|\_)")if len(re.findall(regex2, caption)) > 3:caption = re.sub(regex2, " ", caption)caption = ftfy.fix_text(caption)caption = html.unescape(html.unescape(caption))caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vccaption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption)caption = re.sub(r"\bpage\s+\d+\b", "", caption)caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a...caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)caption = re.sub(r"\b\s+\:\s+", r": ", caption)caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)caption = re.sub(r"\s+", " ", caption)caption.strip()caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)caption = re.sub(r"^\.\S+$", "", caption)return caption.strip()# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latentsdef prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None):if self.vae.quant_conv.weight.ndim==5:mini_batch_encoder = self.vae.mini_batch_encodermini_batch_decoder = self.vae.mini_batch_decodershape = (batch_size, num_channels_latents, int(video_length // mini_batch_encoder * mini_batch_decoder) if video_length != 1 else 1, height // self.vae_scale_factor, width // self.vae_scale_factor)else:shape = (batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor)7 unmodified lineslatents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)else:latents = latents.to(device)# scale the initial noise by the standard deviation required by the schedulerlatents = latents * self.scheduler.init_noise_sigmareturn latentsdef smooth_output(self, video, mini_batch_encoder, mini_batch_decoder):if video.size()[2] <= mini_batch_encoder:return video9 unmodified linesvideo[:, :, prefix_index_before:-prefix_index_after] = (video[:, :, prefix_index_before:-prefix_index_after] + middle_video) / 2return videodef decode_latents(self, latents):video_length = latents.shape[2]latents = 1 / self.vae.config.scaling_factor * latentsif self.vae.quant_conv.weight.ndim==5:mini_batch_encoder = self.vae.mini_batch_encodermini_batch_decoder = self.vae.mini_batch_decodervideo = self.vae.decode(latents)[0]video = video.clamp(-1, 1)video = self.smooth_output(video, mini_batch_encoder, mini_batch_decoder).cpu().clamp(-1, 1)else:latents = rearrange(latents, "b c f h w -> (b f) c h w")video = []6 unmodified linesvideo = video.cpu().float().numpy()return videodef enable_autocast_float8_transformer(self):self.enable_autocast_float8_transformer_flag = True@torch.no_grad()@replace_example_docstring(EXAMPLE_DOC_STRING)1 unmodified lineself,prompt: Union[str, List[str]] = None,video_length: Optional[int] = None,negative_prompt: str = "",num_inference_steps: int = 20,timesteps: List[int] = None,guidance_scale: float = 4.5,num_images_per_prompt: Optional[int] = 1,height: Optional[int] = None,width: Optional[int] = None,eta: float = 0.0,generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,latents: Optional[torch.FloatTensor] = None,prompt_embeds: Optional[torch.FloatTensor] = None,prompt_attention_mask: Optional[torch.FloatTensor] = None,negative_prompt_embeds: Optional[torch.FloatTensor] = None,negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,output_type: Optional[str] = "latent",return_dict: bool = True,callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,callback_steps: int = 1,clean_caption: bool = True,max_sequence_length: int = 120,comfyui_progressbar: bool = False,**kwargs,) -> Union[EasyAnimatePipelineOutput, Tuple]:"""Function invoked when calling the pipeline for generation.Args:prompt (`str` or `List[str]`, *optional*):The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.instead.negative_prompt (`str` or `List[str]`, *optional*):The prompt or prompts not to guide the image generation. If not defined, one has to pass`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` isless than `1`).num_inference_steps (`int`, *optional*, defaults to 100):The number of denoising steps. More denoising steps usually lead to a higher quality image at theexpense of slower inference.timesteps (`List[int]`, *optional*):Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`timesteps are used. Must be in descending order.guidance_scale (`float`, *optional*, defaults to 7.0):Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).`guidance_scale` is defined as `w` of equation 2. of [ImagenPaper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,usually at the expense of lower image quality.num_images_per_prompt (`int`, *optional*, defaults to 1):The number of images to generate per prompt.height (`int`, *optional*, defaults to self.unet.config.sample_size):The height in pixels of the generated image.width (`int`, *optional*, defaults to self.unet.config.sample_size):The width in pixels of the generated image.eta (`float`, *optional*, defaults to 0.0):Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to[`schedulers.DDIMScheduler`], will be ignored for others.generator (`torch.Generator` or `List[torch.Generator]`, *optional*):One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)to make generation deterministic.latents (`torch.FloatTensor`, *optional*):Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for imagegeneration. Can be used to tweak the same generation with different prompts. If not provided, a latentstensor will ge generated by sampling using the supplied random `generator`.prompt_embeds (`torch.FloatTensor`, *optional*):Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If notprovided, text embeddings will be generated from `prompt` input argument.negative_prompt_embeds (`torch.FloatTensor`, *optional*):Pre-generated negative text embeddings. For PixArt-Alpha this negative prompt should be "". If notprovided, negative_prompt_embeds will be generated from `negative_prompt` input argument.output_type (`str`, *optional*, defaults to `"pil"`):The output format of the generate image. Choose between[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.return_dict (`bool`, *optional*, defaults to `True`):Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.callback (`Callable`, *optional*):A function that will be called every `callback_steps` steps during inference. The function will becalled with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.callback_steps (`int`, *optional*, defaults to 1):The frequency at which the `callback` function will be called. If not specified, the callback will becalled at every step.clean_caption (`bool`, *optional*, defaults to `True`):Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` tobe installed. If the dependencies are not installed, the embeddings will be created from the rawprompt.mask_feature (`bool` defaults to `True`): If set to `True`, the text embeddings will be masked.Examples:Returns:[`~pipelines.ImagePipelineOutput`] or `tuple`:If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` isreturned where the first element is a list with the generated images"""# 1. Check inputs. Raise error if not correctheight = height or self.transformer.config.sample_size * self.vae_scale_factorwidth = width or self.transformer.config.sample_size * self.vae_scale_factor# 2. Default height and width to transformerif prompt is not None and isinstance(prompt, str):batch_size = 1elif prompt is not None and isinstance(prompt, list):2 unmodified linesbatch_size = prompt_embeds.shape[0]device = self._execution_device# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`# corresponds to doing no classifier free guidance.do_classifier_free_guidance = guidance_scale > 1.0# 3. Encode input prompt(prompt_embeds,prompt_attention_mask,negative_prompt_embeds,negative_prompt_attention_mask,) = self.encode_prompt(prompt,do_classifier_free_guidance,negative_prompt=negative_prompt,num_images_per_prompt=num_images_per_prompt,device=device,prompt_embeds=prompt_embeds,negative_prompt_embeds=negative_prompt_embeds,prompt_attention_mask=prompt_attention_mask,negative_prompt_attention_mask=negative_prompt_attention_mask,clean_caption=clean_caption,max_sequence_length=max_sequence_length,)if do_classifier_free_guidance:prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)# 4. Prepare timestepstimesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)# 5. Prepare latents.latent_channels = self.transformer.config.in_channelslatents = self.prepare_latents(batch_size * num_images_per_prompt,latent_channels,video_length,height,width,prompt_embeds.dtype,device,generator,latents,)# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipelineextra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)# 6.1 Prepare micro-conditions.added_cond_kwargs = {"resolution": None, "aspect_ratio": None}if self.transformer.config.sample_size == 128:resolution = torch.tensor([height, width]).repeat(batch_size * num_images_per_prompt, 1)aspect_ratio = torch.tensor([float(height / width)]).repeat(batch_size * num_images_per_prompt, 1)resolution = resolution.to(dtype=prompt_embeds.dtype, device=device)aspect_ratio = aspect_ratio.to(dtype=prompt_embeds.dtype, device=device)if do_classifier_free_guidance:resolution = torch.cat([resolution, resolution], dim=0)aspect_ratio = torch.cat([aspect_ratio, aspect_ratio], dim=0)added_cond_kwargs = {"resolution": resolution, "aspect_ratio": aspect_ratio}torch.cuda.empty_cache()if self.enable_autocast_float8_transformer_flag:origin_weight_dtype = self.transformer.dtypeself.transformer = self.transformer.to(torch.float8_e4m3fn)# 7. Denoising loopnum_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)if comfyui_progressbar:from comfy.utils import ProgressBarpbar = ProgressBar(num_inference_steps)with self.progress_bar(total=num_inference_steps) as progress_bar:for i, t in enumerate(timesteps):latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latentslatent_model_input = self.scheduler.scale_model_input(latent_model_input, t)current_timestep = tif not torch.is_tensor(current_timestep):# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can# This would be a good case for the `match` statement (Python 3.10+)is_mps = latent_model_input.device.type == "mps"if isinstance(current_timestep, float):dtype = torch.float32 if is_mps else torch.float64else:dtype = torch.int32 if is_mps else torch.int64current_timestep = torch.tensor([current_timestep], dtype=dtype, device=latent_model_input.device)elif len(current_timestep.shape) == 0:current_timestep = current_timestep[None].to(latent_model_input.device)# broadcast to batch dimension in a way that's compatible with ONNX/Core MLcurrent_timestep = current_timestep.expand(latent_model_input.shape[0])# predict noise model_outputnoise_pred = self.transformer(latent_model_input,encoder_hidden_states=prompt_embeds,encoder_attention_mask=prompt_attention_mask,timestep=current_timestep,added_cond_kwargs=added_cond_kwargs,return_dict=False,)[0]# perform guidanceif do_classifier_free_guidance:noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)# learned sigmaif self.transformer.config.out_channels // 2 == latent_channels:noise_pred = noise_pred.chunk(2, dim=1)[0]else:noise_pred = noise_pred# compute previous image: x_t -> x_t-1latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):progress_bar.update()if callback is not None and i % callback_steps == 0:step_idx = i // getattr(self.scheduler, "order", 1)callback(step_idx, t, latents)if comfyui_progressbar:pbar.update(1)if self.enable_autocast_float8_transformer_flag:self.transformer = self.transformer.to("cpu", origin_weight_dtype)# Post-processingvideo = self.decode_latents(latents)1 unmodified lineif output_type == "latent":video = torch.from_numpy(video)if not return_dict:return videoreturn EasyAnimatePipelineOutput(videos=video)12347 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231244 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501514 unmodified lines1561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672681 unmodified line2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143152 unmodified lines3183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155163 unmodified lines52052152252352452552652752818 unmodified lines5475485495505515525535545555565575585595605615625635645655665675685695705715 unmodified lines5775785795805815825835845855865875885895905915925935941 unmodified line5965975985996006016026036046056066076081 unmodified line6106116126136146156166176186196206216226236246256266276286296306316326336347 unmodified lines6426436446456466476486496506516526539 unmodified lines6636646656666676686696706716726736746756766776786796 unmodified lines6866876886896906916926936946956966976986997007017027037047057067077087097107117127131 unmodified line7157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448452 unmodified lines848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701 unmodified line1072107310741075107610771078107910801081# Copyright 2024 EasyAnimate Authors 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.7 unmodified lines# See the License for the specific language governing permissions and# limitations under the License.import inspectfrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional, Tuple, Unionimport numpy as npimport torchimport torch.nn.functional as Ffrom diffusers import DiffusionPipelinefrom diffusers.callbacks import MultiPipelineCallbacks, PipelineCallbackfrom diffusers.image_processor import VaeImageProcessorfrom diffusers.models import AutoencoderKL, HunyuanDiT2DModelfrom diffusers.models.embeddings import (get_2d_rotary_pos_embed,get_3d_rotary_pos_embed)from diffusers.pipelines.pipeline_utils import DiffusionPipelinefrom diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutputfrom diffusers.pipelines.stable_diffusion.safety_checker import \StableDiffusionSafetyCheckerfrom diffusers.schedulers import DDIMScheduler, FlowMatchEulerDiscreteSchedulerfrom diffusers.utils import (BACKENDS_MAPPING, BaseOutput, deprecate,is_bs4_available, is_ftfy_available,is_torch_xla_available, logging,replace_example_docstring)from diffusers.utils.torch_utils import randn_tensorfrom einops import rearrangefrom PIL import Imagefrom tqdm import tqdmfrom transformers import (BertModel, BertTokenizer, CLIPImageProcessor,Qwen2Tokenizer, Qwen2VLForConditionalGeneration,T5EncoderModel, T5Tokenizer)from ..models import AutoencoderKLMagvit, EasyAnimateTransformer3DModelfrom .pipeline_easyanimate_inpaint import EasyAnimatePipelineOutputif is_torch_xla_available():import torch_xla.core.xla_model as xmXLA_AVAILABLE = Trueelse:XLA_AVAILABLE = Falselogger = logging.get_logger(__name__) # pylint: disable=invalid-nameEXAMPLE_DOC_STRING = """Examples:```python>>> import torch>>> from diffusers import EasyAnimatePipeline>>> from diffusers.utils import export_to_video>>> # Models: "alibaba-pai/EasyAnimateV5.1-12b-zh" or "alibaba-pai/EasyAnimateV5.1-7b-zh">>> pipe = EasyAnimatePipeline.from_pretrained("alibaba-pai/EasyAnimateV5.1-7b-zh", torch_dtype=torch.float16).to("cuda")>>> prompt = (... "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "... "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "... "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "... "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "... "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "... "atmosphere of this unique musical performance."... )>>> video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).sample[0]>>> export_to_video(video, "output.mp4", fps=8)```"""# Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_griddef get_resize_crop_region_for_grid(src, tgt_width, tgt_height):tw = tgt_widthth = tgt_heighth, w = srcr = h / wif r > (th / tw):resize_height = thresize_width = int(round(th / h * w))else:resize_width = twresize_height = int(round(tw / w * h))crop_top = int(round((th - resize_height) / 2.0))crop_left = int(round((tw - resize_width) / 2.0))return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfgdef rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):"""Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules andSample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4"""std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)# rescale the results from guidance (fixes overexposure)noise_pred_rescaled = noise_cfg * (std_text / std_cfg)# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" imagesnoise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfgreturn noise_cfg# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timestepsdef retrieve_timesteps(scheduler,num_inference_steps: Optional[int] = None,device: Optional[Union[str, torch.device]] = None,timesteps: Optional[List[int]] = None,sigmas: Optional[List[float]] = None,**kwargs,):"""4 unmodified linesscheduler (`SchedulerMixin`):The scheduler to get timesteps from.num_inference_steps (`int`):The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`must be `None`.device (`str` or `torch.device`, *optional*):The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.timesteps (`List[int]`, *optional*):Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,`num_inference_steps` and `sigmas` must be `None`.sigmas (`List[float]`, *optional*):Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,`num_inference_steps` and `timesteps` must be `None`.Returns:`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and thesecond element is the number of inference steps."""if timesteps is not None and sigmas is not None:raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")if timesteps is not None:accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())if not accepts_timesteps:4 unmodified linesscheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)timesteps = scheduler.timestepsnum_inference_steps = len(timesteps)elif sigmas is not None:accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())if not accept_sigmas:raise ValueError(f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"f" sigmas schedules. Please check whether you are using the correct scheduler.")scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)timesteps = scheduler.timestepsnum_inference_steps = len(timesteps)else:scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)timesteps = scheduler.timestepsreturn timesteps, num_inference_stepsclass EasyAnimatePipeline(DiffusionPipeline):r"""Pipeline for text-to-video generation using EasyAnimate.This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods thelibrary implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)EasyAnimate uses one text encoder [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) in V5.1.EasyAnimate uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned byHunyuanDiT team) in V5.Args:vae ([`AutoencoderKLMagvit`]):Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations.text_encoder (Optional[`~transformers.Qwen2VLForConditionalGeneration`, `~transformers.BertModel`]):EasyAnimate uses [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) in V5.1.EasyAnimate uses [bilingual CLIP](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers) in V5.tokenizer (Optional[`~transformers.Qwen2Tokenizer`, `~transformers.BertTokenizer`]):A `Qwen2Tokenizer` or `BertTokenizer` to tokenize text.transformer ([`EasyAnimateTransformer3DModel`]):The EasyAnimate model designed by EasyAnimate Team.text_encoder_2 (`T5EncoderModel`):EasyAnimate does not use text_encoder_2 in V5.1.EasyAnimate uses [mT5](https://huggingface.co/google/mt5-base) embedder in V5.tokenizer_2 (`T5Tokenizer`):The tokenizer for the mT5 embedder.scheduler ([`FlowMatchEulerDiscreteScheduler`]):A scheduler to be used in combination with EasyAnimate to denoise the encoded image latents."""model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"_optional_components = ["text_encoder_2","tokenizer_2","text_encoder","tokenizer",]_callback_tensor_inputs = ["latents","prompt_embeds","negative_prompt_embeds","prompt_embeds_2","negative_prompt_embeds_2",]def __init__(self,vae: AutoencoderKLMagvit,text_encoder: Union[Qwen2VLForConditionalGeneration, BertModel],tokenizer: Union[Qwen2Tokenizer, BertTokenizer],text_encoder_2: Optional[Union[T5EncoderModel, Qwen2VLForConditionalGeneration]],tokenizer_2: Optional[Union[T5Tokenizer, Qwen2Tokenizer]],transformer: EasyAnimateTransformer3DModel,scheduler: FlowMatchEulerDiscreteScheduler,):super().__init__()self.register_modules(vae=vae,text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,tokenizer_2=tokenizer_2,transformer=transformer,scheduler=scheduler,)self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)def enable_sequential_cpu_offload(self, *args, **kwargs):super().enable_sequential_cpu_offload(*args, **kwargs)if hasattr(self.transformer, "clip_projection") and self.transformer.clip_projection is not None:import accelerateaccelerate.hooks.remove_hook_from_module(self.transformer.clip_projection, recurse=True)self.transformer.clip_projection = self.transformer.clip_projection.to("cuda")def encode_prompt(self,prompt: str,device: torch.device,dtype: torch.dtype,num_images_per_prompt: int = 1,do_classifier_free_guidance: bool = True,negative_prompt: Optional[str] = None,prompt_embeds: Optional[torch.Tensor] = None,negative_prompt_embeds: Optional[torch.Tensor] = None,prompt_attention_mask: Optional[torch.Tensor] = None,negative_prompt_attention_mask: Optional[torch.Tensor] = None,max_sequence_length: Optional[int] = None,text_encoder_index: int = 0,actual_max_sequence_length: int = 256):r"""Encodes the prompt into text encoder hidden states.1 unmodified lineArgs:prompt (`str` or `List[str]`, *optional*):prompt to be encodeddevice: (`torch.device`):torch devicedtype (`torch.dtype`):torch dtypenum_images_per_prompt (`int`):number of images that should be generated per promptdo_classifier_free_guidance (`bool`):whether to use classifier free guidance or notnegative_prompt (`str` or `List[str]`, *optional*):The prompt or prompts not to guide the image generation. If not defined, one has to pass`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` isless than `1`).prompt_embeds (`torch.Tensor`, *optional*):Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If notprovided, text embeddings will be generated from `prompt` input argument.negative_prompt_embeds (`torch.Tensor`, *optional*):Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* promptweighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` inputargument.prompt_attention_mask (`torch.Tensor`, *optional*):Attention mask for the prompt. Required when `prompt_embeds` is passed directly.negative_prompt_attention_mask (`torch.Tensor`, *optional*):Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.max_sequence_length (`int`, *optional*): maximum sequence length to use for the prompt.text_encoder_index (`int`, *optional*):Index of the text encoder to use. `0` for clip and `1` for T5."""tokenizers = [self.tokenizer, self.tokenizer_2]text_encoders = [self.text_encoder, self.text_encoder_2]tokenizer = tokenizers[text_encoder_index]text_encoder = text_encoders[text_encoder_index]if max_sequence_length is None:if text_encoder_index == 0:max_length = min(self.tokenizer.model_max_length, actual_max_sequence_length)if text_encoder_index == 1:max_length = min(self.tokenizer_2.model_max_length, actual_max_sequence_length)else:max_length = max_sequence_lengthif prompt is not None and isinstance(prompt, str):batch_size = 12 unmodified lineselse:batch_size = prompt_embeds.shape[0]if prompt_embeds is None:if type(tokenizer) in [BertTokenizer, T5Tokenizer]:text_inputs = tokenizer(prompt,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,return_tensors="pt",)text_input_ids = text_inputs.input_idsif text_input_ids.shape[-1] > actual_max_sequence_length:reprompt = tokenizer.batch_decode(text_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True)text_inputs = tokenizer(reprompt,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,return_tensors="pt",)text_input_ids = text_inputs.input_idsuntruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_idsif untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):_actual_max_sequence_length = min(tokenizer.model_max_length, actual_max_sequence_length)removed_text = tokenizer.batch_decode(untruncated_ids[:, _actual_max_sequence_length - 1 : -1])logger.warning("The following part of your input was truncated because CLIP can only handle sequences up to"f" {_actual_max_sequence_length} tokens: {removed_text}")prompt_attention_mask = text_inputs.attention_mask.to(device)if self.transformer.config.enable_text_attention_mask:prompt_embeds = text_encoder(text_input_ids.to(device),attention_mask=prompt_attention_mask,)else:prompt_embeds = text_encoder(text_input_ids.to(device))prompt_embeds = prompt_embeds[0]prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)else:if prompt is not None and isinstance(prompt, str):messages = [{"role": "user","content": [{"type": "text", "text": prompt}],}]else:messages = [{"role": "user","content": [{"type": "text", "text": _prompt}],} for _prompt in prompt]text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)text_inputs = tokenizer(text=[text],padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,padding_side="right",return_tensors="pt",)text_inputs = text_inputs.to(text_encoder.device)text_input_ids = text_inputs.input_idsprompt_attention_mask = text_inputs.attention_maskif self.transformer.config.enable_text_attention_mask:# Inference: Generation of the outputprompt_embeds = text_encoder(input_ids=text_input_ids,attention_mask=prompt_attention_mask,output_hidden_states=True).hidden_states[-2]else:raise ValueError("LLM needs attention_mask")prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)bs_embed, seq_len, _ = prompt_embeds.shape# duplicate text embeddings for each generation per prompt, using mps friendly methodprompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)prompt_attention_mask = prompt_attention_mask.to(device=device)# get unconditional embeddings for classifier free guidanceif do_classifier_free_guidance and negative_prompt_embeds is None:if type(tokenizer) in [BertTokenizer, T5Tokenizer]:uncond_tokens: List[str]if negative_prompt is None:uncond_tokens = [""] * batch_sizeelif prompt is not None and type(prompt) is not type(negative_prompt):raise TypeError(f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="f" {type(prompt)}.")elif isinstance(negative_prompt, str):uncond_tokens = [negative_prompt]elif batch_size != len(negative_prompt):raise ValueError(f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"" the batch size of `prompt`.")else:uncond_tokens = negative_promptmax_length = prompt_embeds.shape[1]uncond_input = tokenizer(uncond_tokens,padding="max_length",max_length=max_length,truncation=True,return_tensors="pt",)uncond_input_ids = uncond_input.input_idsif uncond_input_ids.shape[-1] > actual_max_sequence_length:reuncond_tokens = tokenizer.batch_decode(uncond_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True)uncond_input = tokenizer(reuncond_tokens,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,return_tensors="pt",)uncond_input_ids = uncond_input.input_idsnegative_prompt_attention_mask = uncond_input.attention_mask.to(device)if self.transformer.config.enable_text_attention_mask:negative_prompt_embeds = text_encoder(uncond_input.input_ids.to(device),attention_mask=negative_prompt_attention_mask,)else:negative_prompt_embeds = text_encoder(uncond_input.input_ids.to(device))negative_prompt_embeds = negative_prompt_embeds[0]negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)else:if negative_prompt is not None and isinstance(negative_prompt, str):messages = [{"role": "user","content": [{"type": "text", "text": negative_prompt}],}]else:messages = [{"role": "user","content": [{"type": "text", "text": _negative_prompt}],} for _negative_prompt in negative_prompt]text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)text_inputs = tokenizer(text=[text],padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,padding_side="right",return_tensors="pt",)text_inputs = text_inputs.to(text_encoder.device)text_input_ids = text_inputs.input_idsnegative_prompt_attention_mask = text_inputs.attention_maskif self.transformer.config.enable_text_attention_mask:# Inference: Generation of the outputnegative_prompt_embeds = text_encoder(input_ids=text_input_ids,attention_mask=negative_prompt_attention_mask,output_hidden_states=True).hidden_states[-2]else:raise ValueError("LLM needs attention_mask")negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)if do_classifier_free_guidance:# duplicate unconditional embeddings for each generation per prompt, using mps friendly method3 unmodified linesnegative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)negative_prompt_attention_mask = negative_prompt_attention_mask.to(device=device)return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargsdef prepare_extra_step_kwargs(self, generator, eta):18 unmodified linesprompt,height,width,negative_prompt=None,prompt_embeds=None,negative_prompt_embeds=None,prompt_attention_mask=None,negative_prompt_attention_mask=None,prompt_embeds_2=None,negative_prompt_embeds_2=None,prompt_attention_mask_2=None,negative_prompt_attention_mask_2=None,callback_on_step_end_tensor_inputs=None,):if height % 16 != 0 or width % 16 != 0:raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")if callback_on_step_end_tensor_inputs is not None and not all(k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs):raise ValueError(f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}")if prompt is not None and prompt_embeds is not None:5 unmodified linesraise ValueError("Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.")elif prompt is None and prompt_embeds_2 is None:raise ValueError("Provide either `prompt` or `prompt_embeds_2`. Cannot leave both `prompt` and `prompt_embeds_2` undefined.")elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")if prompt_embeds is not None and prompt_attention_mask is None:raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")if prompt_embeds_2 is not None and prompt_attention_mask_2 is None:raise ValueError("Must provide `prompt_attention_mask_2` when specifying `prompt_embeds_2`.")if negative_prompt is not None and negative_prompt_embeds is not None:raise ValueError(1 unmodified linef" {negative_prompt_embeds}. Please make sure to only forward one of the two.")if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")if negative_prompt_embeds_2 is not None and negative_prompt_attention_mask_2 is None:raise ValueError("Must provide `negative_prompt_attention_mask_2` when specifying `negative_prompt_embeds_2`.")if prompt_embeds is not None and negative_prompt_embeds is not None:if prompt_embeds.shape != negative_prompt_embeds.shape:raise ValueError(1 unmodified linef" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"f" {negative_prompt_embeds.shape}.")if prompt_embeds_2 is not None and negative_prompt_embeds_2 is not None:if prompt_embeds_2.shape != negative_prompt_embeds_2.shape:raise ValueError("`prompt_embeds_2` and `negative_prompt_embeds_2` must have the same shape when passed directly, but"f" got: `prompt_embeds_2` {prompt_embeds_2.shape} != `negative_prompt_embeds_2`"f" {negative_prompt_embeds_2.shape}.")# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latentsdef prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None):if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5:if self.vae.cache_mag_vae:mini_batch_encoder = self.vae.mini_batch_encodermini_batch_decoder = self.vae.mini_batch_decodershape = (batch_size, num_channels_latents, int((video_length - 1) // mini_batch_encoder * mini_batch_decoder + 1) if video_length != 1 else 1, height // self.vae_scale_factor, width // self.vae_scale_factor)else:mini_batch_encoder = self.vae.mini_batch_encodermini_batch_decoder = self.vae.mini_batch_decodershape = (batch_size, num_channels_latents, int(video_length // mini_batch_encoder * mini_batch_decoder) if video_length != 1 else 1, height // self.vae_scale_factor, width // self.vae_scale_factor)else:shape = (batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor)7 unmodified lineslatents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)else:latents = latents.to(device)# scale the initial noise by the standard deviation required by the schedulerif hasattr(self.scheduler, "init_noise_sigma"):latents = latents * self.scheduler.init_noise_sigmareturn latentsdef smooth_output(self, video, mini_batch_encoder, mini_batch_decoder):if video.size()[2] <= mini_batch_encoder:return video9 unmodified linesvideo[:, :, prefix_index_before:-prefix_index_after] = (video[:, :, prefix_index_before:-prefix_index_after] + middle_video) / 2return videodef decode_latents(self, latents):video_length = latents.shape[2]latents = 1 / self.vae.config.scaling_factor * latentsif self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5:mini_batch_encoder = self.vae.mini_batch_encodermini_batch_decoder = self.vae.mini_batch_decodervideo = self.vae.decode(latents)[0]video = video.clamp(-1, 1)if not self.vae.cache_compression_vae and not self.vae.cache_mag_vae:video = self.smooth_output(video, mini_batch_encoder, mini_batch_decoder).cpu().clamp(-1, 1)else:latents = rearrange(latents, "b c f h w -> (b f) c h w")video = []6 unmodified linesvideo = video.cpu().float().numpy()return video@propertydef guidance_scale(self):return self._guidance_scale@propertydef guidance_rescale(self):return self._guidance_rescale# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`# corresponds to doing no classifier free guidance.@propertydef do_classifier_free_guidance(self):return self._guidance_scale > 1@propertydef num_timesteps(self):return self._num_timesteps@propertydef interrupt(self):return self._interrupt@torch.no_grad()@replace_example_docstring(EXAMPLE_DOC_STRING)1 unmodified lineself,prompt: Union[str, List[str]] = None,video_length: Optional[int] = None,height: Optional[int] = None,width: Optional[int] = None,num_inference_steps: Optional[int] = 50,guidance_scale: Optional[float] = 5.0,negative_prompt: Optional[Union[str, List[str]]] = None,num_images_per_prompt: Optional[int] = 1,eta: Optional[float] = 0.0,generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,latents: Optional[torch.Tensor] = None,prompt_embeds: Optional[torch.Tensor] = None,prompt_embeds_2: Optional[torch.Tensor] = None,negative_prompt_embeds: Optional[torch.Tensor] = None,negative_prompt_embeds_2: Optional[torch.Tensor] = None,prompt_attention_mask: Optional[torch.Tensor] = None,prompt_attention_mask_2: Optional[torch.Tensor] = None,negative_prompt_attention_mask: Optional[torch.Tensor] = None,negative_prompt_attention_mask_2: Optional[torch.Tensor] = None,output_type: Optional[str] = "latent",return_dict: bool = True,callback_on_step_end: Optional[Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]] = None,callback_on_step_end_tensor_inputs: List[str] = ["latents"],guidance_rescale: float = 0.0,original_size: Optional[Tuple[int, int]] = (1024, 1024),target_size: Optional[Tuple[int, int]] = None,crops_coords_top_left: Tuple[int, int] = (0, 0),comfyui_progressbar: bool = False,timesteps: Optional[List[int]] = None,):r"""Generates images or video using the EasyAnimate pipeline based on the provided prompts.Examples:prompt (`str` or `List[str]`, *optional*):Text prompts to guide the image or video generation. If not provided, use `prompt_embeds` instead.video_length (`int`, *optional*):Length of the generated video (in frames).height (`int`, *optional*):Height of the generated image in pixels.width (`int`, *optional*):Width of the generated image in pixels.num_inference_steps (`int`, *optional*, defaults to 50):Number of denoising steps during generation. More steps generally yield higher quality images but slow down inference.guidance_scale (`float`, *optional*, defaults to 5.0):Encourages the model to align outputs with prompts. A higher value may decrease image quality.negative_prompt (`str` or `List[str]`, *optional*):Prompts indicating what to exclude in generation. If not specified, use `negative_prompt_embeds`.num_images_per_prompt (`int`, *optional*, defaults to 1):Number of images to generate for each prompt.eta (`float`, *optional*, defaults to 0.0):Applies to DDIM scheduling. Controlled by the eta parameter from the related literature.generator (`torch.Generator` or `List[torch.Generator]`, *optional*):A generator to ensure reproducibility in image generation.latents (`torch.Tensor`, *optional*):Predefined latent tensors to condition generation.prompt_embeds (`torch.Tensor`, *optional*):Text embeddings for the prompts. Overrides prompt string inputs for more flexibility.prompt_embeds_2 (`torch.Tensor`, *optional*):Secondary text embeddings to supplement or replace the initial prompt embeddings.negative_prompt_embeds (`torch.Tensor`, *optional*):Embeddings for negative prompts. Overrides string inputs if defined.negative_prompt_embeds_2 (`torch.Tensor`, *optional*):Secondary embeddings for negative prompts, similar to `negative_prompt_embeds`.prompt_attention_mask (`torch.Tensor`, *optional*):Attention mask for the primary prompt embeddings.prompt_attention_mask_2 (`torch.Tensor`, *optional*):Attention mask for the secondary prompt embeddings.negative_prompt_attention_mask (`torch.Tensor`, *optional*):Attention mask for negative prompt embeddings.negative_prompt_attention_mask_2 (`torch.Tensor`, *optional*):Attention mask for secondary negative prompt embeddings.output_type (`str`, *optional*, defaults to "latent"):Format of the generated output, either as a PIL image or as a NumPy array.return_dict (`bool`, *optional*, defaults to `True`):If `True`, returns a structured output. Otherwise returns a simple tuple.callback_on_step_end (`Callable`, *optional*):Functions called at the end of each denoising step.callback_on_step_end_tensor_inputs (`List[str]`, *optional*):Tensor names to be included in callback function calls.guidance_rescale (`float`, *optional*, defaults to 0.0):Adjusts noise levels based on guidance scale.original_size (`Tuple[int, int]`, *optional*, defaults to `(1024, 1024)`):Original dimensions of the output.target_size (`Tuple[int, int]`, *optional*):Desired output dimensions for calculations.crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to `(0, 0)`):Coordinates for cropping.Returns:[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,otherwise a `tuple` is returned where the first element is a list with the generated images and thesecond element is a list of `bool`s indicating whether the corresponding generated image contains"not-safe-for-work" (nsfw) content."""if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs# 0. default height and widthheight = int((height // 16) * 16)width = int((width // 16) * 16)# 1. Check inputs. Raise error if not correctself.check_inputs(prompt,height,width,negative_prompt,prompt_embeds,negative_prompt_embeds,prompt_attention_mask,negative_prompt_attention_mask,prompt_embeds_2,negative_prompt_embeds_2,prompt_attention_mask_2,negative_prompt_attention_mask_2,callback_on_step_end_tensor_inputs,)self._guidance_scale = guidance_scaleself._guidance_rescale = guidance_rescaleself._interrupt = False# 2. Define call parametersif prompt is not None and isinstance(prompt, str):batch_size = 1elif prompt is not None and isinstance(prompt, list):2 unmodified linesbatch_size = prompt_embeds.shape[0]device = self._execution_deviceif self.text_encoder is not None:dtype = self.text_encoder.dtypeelif self.text_encoder_2 is not None:dtype = self.text_encoder_2.dtypeelse:dtype = self.transformer.dtype# 3. Encode input prompt(prompt_embeds,negative_prompt_embeds,prompt_attention_mask,negative_prompt_attention_mask,) = self.encode_prompt(prompt=prompt,device=device,dtype=dtype,num_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=self.do_classifier_free_guidance,negative_prompt=negative_prompt,prompt_embeds=prompt_embeds,negative_prompt_embeds=negative_prompt_embeds,prompt_attention_mask=prompt_attention_mask,negative_prompt_attention_mask=negative_prompt_attention_mask,text_encoder_index=0,)if self.tokenizer_2 is not None:(prompt_embeds_2,negative_prompt_embeds_2,prompt_attention_mask_2,negative_prompt_attention_mask_2,) = self.encode_prompt(prompt=prompt,device=device,dtype=dtype,num_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=self.do_classifier_free_guidance,negative_prompt=negative_prompt,prompt_embeds=prompt_embeds_2,negative_prompt_embeds=negative_prompt_embeds_2,prompt_attention_mask=prompt_attention_mask_2,negative_prompt_attention_mask=negative_prompt_attention_mask_2,text_encoder_index=1,)else:prompt_embeds_2 = Nonenegative_prompt_embeds_2 = Noneprompt_attention_mask_2 = Nonenegative_prompt_attention_mask_2 = None# 4. Prepare timestepsif isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps, mu=1)else:timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)if comfyui_progressbar:from comfy.utils import ProgressBarpbar = ProgressBar(num_inference_steps + 1)# 5. Prepare latent variablesnum_channels_latents = self.transformer.config.in_channelslatents = self.prepare_latents(batch_size * num_images_per_prompt,num_channels_latents,video_length,height,width,dtype,device,generator,latents,)if comfyui_progressbar:pbar.update(1)# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipelineextra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)# 7 create image_rotary_emb, style embedding & time idsgrid_height = height // 8 // self.transformer.config.patch_sizegrid_width = width // 8 // self.transformer.config.patch_sizeif self.transformer.config.get("time_position_encoding_type", "2d_rope") == "3d_rope":base_size_width = 720 // 8 // self.transformer.config.patch_sizebase_size_height = 480 // 8 // self.transformer.config.patch_sizegrid_crops_coords = get_resize_crop_region_for_grid((grid_height, grid_width), base_size_width, base_size_height)image_rotary_emb = get_3d_rotary_pos_embed(self.transformer.config.attention_head_dim, grid_crops_coords, grid_size=(grid_height, grid_width),temporal_size=latents.size(2), use_real=True,)else:base_size = 512 // 8 // self.transformer.config.patch_sizegrid_crops_coords = get_resize_crop_region_for_grid((grid_height, grid_width), base_size, base_size)image_rotary_emb = get_2d_rotary_pos_embed(self.transformer.config.attention_head_dim, grid_crops_coords, (grid_height, grid_width))# Get other hunyuan paramstarget_size = target_size or (height, width)add_time_ids = list(original_size + target_size + crops_coords_top_left)add_time_ids = torch.tensor([add_time_ids], dtype=dtype)style = torch.tensor([0], device=device)if self.do_classifier_free_guidance:add_time_ids = torch.cat([add_time_ids] * 2, dim=0)style = torch.cat([style] * 2, dim=0)# To latents.deviceadd_time_ids = add_time_ids.to(dtype=dtype, device=device).repeat(batch_size * num_images_per_prompt, 1)style = style.to(device=device).repeat(batch_size * num_images_per_prompt)# Get other pixart paramsadded_cond_kwargs = {"resolution": None, "aspect_ratio": None}if self.transformer.config.get("sample_size", 64) == 128:resolution = torch.tensor([height, width]).repeat(batch_size * num_images_per_prompt, 1)aspect_ratio = torch.tensor([float(height / width)]).repeat(batch_size * num_images_per_prompt, 1)resolution = resolution.to(dtype=dtype, device=device)aspect_ratio = aspect_ratio.to(dtype=dtype, device=device)if self.do_classifier_free_guidance:resolution = torch.cat([resolution, resolution], dim=0)aspect_ratio = torch.cat([aspect_ratio, aspect_ratio], dim=0)added_cond_kwargs = {"resolution": resolution, "aspect_ratio": aspect_ratio}if self.do_classifier_free_guidance:prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])if prompt_embeds_2 is not None:prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2])# To latents.deviceprompt_embeds = prompt_embeds.to(device=device)prompt_attention_mask = prompt_attention_mask.to(device=device)if prompt_embeds_2 is not None:prompt_embeds_2 = prompt_embeds_2.to(device=device)prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device)# 8. Denoising loopnum_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.orderself._num_timesteps = len(timesteps)with self.progress_bar(total=num_inference_steps) as progress_bar:for i, t in enumerate(timesteps):if self.interrupt:continue# expand the latents if we are doing classifier free guidancelatent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latentsif hasattr(self.scheduler, "scale_model_input"):latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)# expand scalar t to 1-D tensor to match the 1st dim of latent_model_inputt_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to(dtype=latent_model_input.dtype)# predict the noise residualnoise_pred = self.transformer(latent_model_input,t_expand,encoder_hidden_states=prompt_embeds,text_embedding_mask=prompt_attention_mask,encoder_hidden_states_t5=prompt_embeds_2,text_embedding_mask_t5=prompt_attention_mask_2,image_meta_size=add_time_ids,style=style,image_rotary_emb=image_rotary_emb,added_cond_kwargs=added_cond_kwargs,return_dict=False,)[0]if noise_pred.size()[1] != self.vae.config.latent_channels:noise_pred, _ = noise_pred.chunk(2, dim=1)# perform guidanceif self.do_classifier_free_guidance:noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)if self.do_classifier_free_guidance and guidance_rescale > 0.0:# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdfnoise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)# compute the previous noisy sample x_t -> x_t-1latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]if callback_on_step_end is not None:callback_kwargs = {}for k in callback_on_step_end_tensor_inputs:callback_kwargs[k] = locals()[k]callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)latents = callback_outputs.pop("latents", latents)prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)prompt_embeds_2 = callback_outputs.pop("prompt_embeds_2", prompt_embeds_2)negative_prompt_embeds_2 = callback_outputs.pop("negative_prompt_embeds_2", negative_prompt_embeds_2)if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):progress_bar.update()if XLA_AVAILABLE:xm.mark_step()if comfyui_progressbar:pbar.update(1)# Post-processingvideo = self.decode_latents(latents)1 unmodified lineif output_type == "latent":video = torch.from_numpy(video)# Offload all modelsself.maybe_free_model_hooks()if not return_dict:return videoreturn EasyAnimatePipelineOutput(frames=video)
30 unmodified lines313233343536373 unmodified lines414243444546474849505112 unmodified lines64656667686927 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391405 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719873 unmodified lines2722732742752762772782792802812822832842852862872882892901 unmodified line2922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823 unmodified lines38638738838939039139239339439539639739839940040140240340440540640740840928 unmodified lines43843944044144244344444578 unmodified lines52452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656 unmodified lines6236246256266276286296306313 unmodified lines63563663763863964020 unmodified lines66166266366466566698 unmodified lines7657667677687697704 unmodified lines7757767777787797807813 unmodified lines7857867877887897907917927937947957967977987998008018028038048058068078088098108118127 unmodified lines8208218228238248258261 unmodified line82882983083183283383483583683783883984084184284384484584684784884985085185285385425 unmodified lines8808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129134 unmodified lines91891992092192292392410 unmodified lines93593693793893994094194233 unmodified lines9769779789799809819829839849857 unmodified lines99399499599630 unmodified linesfrom diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutputfrom diffusers.pipelines.stable_diffusion.safety_checker import \StableDiffusionSafetyCheckerfrom diffusers.schedulers import DDIMScheduler, DPMSolverMultistepSchedulerfrom diffusers.utils import (BACKENDS_MAPPING, BaseOutput, deprecate,is_bs4_available, is_ftfy_available,is_torch_xla_available, logging,3 unmodified linesfrom PIL import Imagefrom tqdm import tqdmfrom transformers import (BertModel, BertTokenizer, CLIPImageProcessor,CLIPVisionModelWithProjection,T5EncoderModel, T5Tokenizer)from ..models import AutoencoderKLMagvit, EasyAnimateTransformer3DModelfrom .pipeline_easyanimate import EasyAnimatePipelineOutputif is_torch_xla_available():import torch_xla.core.xla_model as xm12 unmodified lines```"""def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):tw = tgt_widthth = tgt_height27 unmodified linesreturn noise_cfgclass EasyAnimatePipeline_Multi_Text_Encoder_Control(DiffusionPipeline):r"""Pipeline for text-to-video generation using EasyAnimate.This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods thelibrary implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)EasyAnimate uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned byHunyuanDiT team)Args:vae ([`AutoencoderKLMagvit`]):Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations.text_encoder (Optional[`~transformers.BertModel`, `~transformers.CLIPTextModel`]):Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).EasyAnimate uses a fine-tuned [bilingual CLIP].tokenizer (Optional[`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer`]):A `BertTokenizer` or `CLIPTokenizer` to tokenize text.transformer ([`EasyAnimateTransformer3DModel`]):The EasyAnimate model designed by Tencent Hunyuan.text_encoder_2 (`T5EncoderModel`):The mT5 embedder.tokenizer_2 (`T5Tokenizer`):The tokenizer for the mT5 embedder.scheduler ([`DDIMScheduler`]):A scheduler to be used in combination with EasyAnimate to denoise the encoded image latents."""model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"_optional_components = ["safety_checker","feature_extractor","text_encoder_2","tokenizer_2","text_encoder","tokenizer",]_exclude_from_cpu_offload = ["safety_checker"]_callback_tensor_inputs = ["latents","prompt_embeds",5 unmodified linesdef __init__(self,vae: AutoencoderKLMagvit,text_encoder: BertModel,tokenizer: BertTokenizer,text_encoder_2: T5EncoderModel,tokenizer_2: T5Tokenizer,transformer: EasyAnimateTransformer3DModel,scheduler: DDIMScheduler,safety_checker: StableDiffusionSafetyChecker,feature_extractor: CLIPImageProcessor,requires_safety_checker: bool = True):super().__init__()self.register_modules(vae=vae,text_encoder=text_encoder,tokenizer=tokenizer,tokenizer_2=tokenizer_2,transformer=transformer,scheduler=scheduler,safety_checker=safety_checker,feature_extractor=feature_extractor,text_encoder_2=text_encoder_2)if safety_checker is None and requires_safety_checker:logger.warning(f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"" results in services or applications open to the public. Both the diffusers team and Hugging Face"" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"" it only for use-cases that involve analyzing network behavior or auditing its results. For more"" information, please have a look at https://github.com/huggingface/diffusers/pull/254 .")if safety_checker is not None and feature_extractor is None:raise ValueError("Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead.")self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)self.mask_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True)self.enable_autocast_float8_transformer_flag = Falseself.register_to_config(requires_safety_checker=requires_safety_checker)def enable_sequential_cpu_offload(self, *args, **kwargs):super().enable_sequential_cpu_offload(*args, **kwargs)73 unmodified linesbatch_size = prompt_embeds.shape[0]if prompt_embeds is None:text_inputs = tokenizer(prompt,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,return_tensors="pt",)text_input_ids = text_inputs.input_idsif text_input_ids.shape[-1] > actual_max_sequence_length:reprompt = tokenizer.batch_decode(text_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True)text_inputs = tokenizer(reprompt,padding="max_length",max_length=max_length,truncation=True,1 unmodified linereturn_tensors="pt",)text_input_ids = text_inputs.input_idsuntruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_idsif untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):_actual_max_sequence_length = min(tokenizer.model_max_length, actual_max_sequence_length)removed_text = tokenizer.batch_decode(untruncated_ids[:, _actual_max_sequence_length - 1 : -1])logger.warning("The following part of your input was truncated because CLIP can only handle sequences up to"f" {_actual_max_sequence_length} tokens: {removed_text}")prompt_attention_mask = text_inputs.attention_mask.to(device)if self.transformer.config.enable_text_attention_mask:prompt_embeds = text_encoder(text_input_ids.to(device),attention_mask=prompt_attention_mask,)else:prompt_embeds = text_encoder(text_input_ids.to(device))prompt_embeds = prompt_embeds[0]prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)bs_embed, seq_len, _ = prompt_embeds.shape# duplicate text embeddings for each generation per prompt, using mps friendly methodprompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)# get unconditional embeddings for classifier free guidanceif do_classifier_free_guidance and negative_prompt_embeds is None:uncond_tokens: List[str]if negative_prompt is None:uncond_tokens = [""] * batch_sizeelif prompt is not None and type(prompt) is not type(negative_prompt):raise TypeError(f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="f" {type(prompt)}.")elif isinstance(negative_prompt, str):uncond_tokens = [negative_prompt]elif batch_size != len(negative_prompt):raise ValueError(f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"" the batch size of `prompt`.")else:uncond_tokens = negative_promptmax_length = prompt_embeds.shape[1]uncond_input = tokenizer(uncond_tokens,padding="max_length",max_length=max_length,truncation=True,return_tensors="pt",)uncond_input_ids = uncond_input.input_idsif uncond_input_ids.shape[-1] > actual_max_sequence_length:reuncond_tokens = tokenizer.batch_decode(uncond_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True)uncond_input = tokenizer(reuncond_tokens,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,return_tensors="pt",)uncond_input_ids = uncond_input.input_idsnegative_prompt_attention_mask = uncond_input.attention_mask.to(device)if self.transformer.config.enable_text_attention_mask:negative_prompt_embeds = text_encoder(uncond_input.input_ids.to(device),attention_mask=negative_prompt_attention_mask,)else:negative_prompt_embeds = text_encoder(uncond_input.input_ids.to(device))negative_prompt_embeds = negative_prompt_embeds[0]negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)if do_classifier_free_guidance:# duplicate unconditional embeddings for each generation per prompt, using mps friendly method3 unmodified linesnegative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checkerdef run_safety_checker(self, image, device, dtype):if self.safety_checker is None:has_nsfw_concept = Noneelse:if torch.is_tensor(image):feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")else:feature_extractor_input = self.image_processor.numpy_to_pil(image)safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_checker_input.pixel_values.to(dtype))return image, has_nsfw_concept# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargsdef prepare_extra_step_kwargs(self, generator, eta):# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature28 unmodified linesnegative_prompt_attention_mask_2=None,callback_on_step_end_tensor_inputs=None,):if height % 8 != 0 or width % 8 != 0:raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")if callback_on_step_end_tensor_inputs is not None and not all(k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs78 unmodified lineslatents = latents.to(device)# scale the initial noise by the standard deviation required by the schedulerlatents = latents * self.scheduler.init_noise_sigmareturn latentsdef prepare_control_latents(self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance):# resize the mask to latents shape as we concatenate the mask to the latents# we do that before converting to dtype to avoid breaking in case we're using cpu_offload# and half precisionif mask is not None:mask = mask.to(device=device, dtype=self.vae.dtype)bs = 1new_mask = []for i in range(0, mask.shape[0], bs):mask_bs = mask[i : i + bs]mask_bs = self.vae.encode(mask_bs)[0]mask_bs = mask_bs.mode()new_mask.append(mask_bs)mask = torch.cat(new_mask, dim = 0)mask = mask * self.vae.config.scaling_factorif masked_image is not None:masked_image = masked_image.to(device=device, dtype=self.vae.dtype)bs = 1new_mask_pixel_values = []for i in range(0, masked_image.shape[0], bs):mask_pixel_values_bs = masked_image[i : i + bs]mask_pixel_values_bs = self.vae.encode(mask_pixel_values_bs)[0]mask_pixel_values_bs = mask_pixel_values_bs.mode()new_mask_pixel_values.append(mask_pixel_values_bs)masked_image_latents = torch.cat(new_mask_pixel_values, dim = 0)masked_image_latents = masked_image_latents * self.vae.config.scaling_factorelse:masked_image_latents = Nonereturn mask, masked_image_latentsdef smooth_output(self, video, mini_batch_encoder, mini_batch_decoder):if video.size()[2] <= mini_batch_encoder:56 unmodified linesdef interrupt(self):return self._interruptdef enable_autocast_float8_transformer(self):self.enable_autocast_float8_transformer_flag = True@torch.no_grad()@replace_example_docstring(EXAMPLE_DOC_STRING)def __call__(3 unmodified linesheight: Optional[int] = None,width: Optional[int] = None,control_video: Union[torch.FloatTensor] = None,num_inference_steps: Optional[int] = 50,guidance_scale: Optional[float] = 5.0,negative_prompt: Optional[Union[str, List[str]]] = None,20 unmodified linestarget_size: Optional[Tuple[int, int]] = None,crops_coords_top_left: Tuple[int, int] = (0, 0),comfyui_progressbar: bool = False,):r"""Generates images or video using the EasyAnimate pipeline based on the provided prompts.98 unmodified linesbatch_size = prompt_embeds.shape[0]device = self._execution_device# 3. Encode input prompt(4 unmodified lines) = self.encode_prompt(prompt=prompt,device=device,dtype=self.transformer.dtype,num_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=self.do_classifier_free_guidance,negative_prompt=negative_prompt,3 unmodified linesnegative_prompt_attention_mask=negative_prompt_attention_mask,text_encoder_index=0,)(prompt_embeds_2,negative_prompt_embeds_2,prompt_attention_mask_2,negative_prompt_attention_mask_2,) = self.encode_prompt(prompt=prompt,device=device,dtype=self.transformer.dtype,num_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=self.do_classifier_free_guidance,negative_prompt=negative_prompt,prompt_embeds=prompt_embeds_2,negative_prompt_embeds=negative_prompt_embeds_2,prompt_attention_mask=prompt_attention_mask_2,negative_prompt_attention_mask=negative_prompt_attention_mask_2,text_encoder_index=1,)torch.cuda.empty_cache()# 4. Prepare timestepsself.scheduler.set_timesteps(num_inference_steps, device=device)timesteps = self.scheduler.timestepsif comfyui_progressbar:from comfy.utils import ProgressBar7 unmodified linesvideo_length,height,width,prompt_embeds.dtype,device,generator,latents,1 unmodified lineif comfyui_progressbar:pbar.update(1)if control_video is not None:video_length = control_video.shape[2]control_video = self.image_processor.preprocess(rearrange(control_video, "b c f h w -> (b f) c h w"), height=height, width=width)control_video = control_video.to(dtype=torch.float32)control_video = rearrange(control_video, "(b f) c h w -> b c f h w", f=video_length)else:control_video = Nonecontrol_video_latents = self.prepare_control_latents(None,control_video,batch_size,height,width,prompt_embeds.dtype,device,generator,self.do_classifier_free_guidance)[1]control_latents = (torch.cat([control_video_latents] * 2) if self.do_classifier_free_guidance else control_video_latents)if comfyui_progressbar:pbar.update(1)25 unmodified lines)# Get other hunyuan paramsstyle = torch.tensor([0], device=device)target_size = target_size or (height, width)add_time_ids = list(original_size + target_size + crops_coords_top_left)add_time_ids = torch.tensor([add_time_ids], dtype=prompt_embeds.dtype)if self.do_classifier_free_guidance:prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2])add_time_ids = torch.cat([add_time_ids] * 2, dim=0)style = torch.cat([style] * 2, dim=0)# To latents.deviceprompt_embeds = prompt_embeds.to(device=device)prompt_attention_mask = prompt_attention_mask.to(device=device)prompt_embeds_2 = prompt_embeds_2.to(device=device)prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device)add_time_ids = add_time_ids.to(dtype=prompt_embeds.dtype, device=device).repeat(batch_size * num_images_per_prompt, 1)style = style.to(device=device).repeat(batch_size * num_images_per_prompt)torch.cuda.empty_cache()if self.enable_autocast_float8_transformer_flag:origin_weight_dtype = self.transformer.dtypeself.transformer = self.transformer.to(torch.float8_e4m3fn)# 8. Denoising loopnum_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.orderself._num_timesteps = len(timesteps)4 unmodified lines# expand the latents if we are doing classifier free guidancelatent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latentslatent_model_input = self.scheduler.scale_model_input(latent_model_input, t)# expand scalar t to 1-D tensor to match the 1st dim of latent_model_inputt_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to(10 unmodified linesimage_meta_size=add_time_ids,style=style,image_rotary_emb=image_rotary_emb,return_dict=False,control_latents=control_latents,)[0]if noise_pred.size()[1] != self.vae.config.latent_channels:noise_pred, _ = noise_pred.chunk(2, dim=1)33 unmodified linesif comfyui_progressbar:pbar.update(1)if self.enable_autocast_float8_transformer_flag:self.transformer = self.transformer.to("cpu", origin_weight_dtype)torch.cuda.empty_cache()# Post-processingvideo = self.decode_latents(latents)7 unmodified linesif not return_dict:return videoreturn EasyAnimatePipelineOutput(videos=video)30 unmodified lines31323334353637383 unmodified lines42434445464748495051525312 unmodified lines6667686970717227 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382395 unmodified lines24524624724824925025125225325425525625725825926026126226326426526626726826927027127227327473 unmodified lines3483493503513523533543553561 unmodified line3583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445453 unmodified lines54955055155255355455555655755828 unmodified lines58758858959059159259359478 unmodified lines67367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571656 unmodified lines7737747757767777783 unmodified lines78278378478578678778878920 unmodified lines81081181281381481581698 unmodified lines9159169179189199209219229239249259264 unmodified lines9319329339349359369373 unmodified lines9419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759767 unmodified lines9849859869879889899901 unmodified line992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106025 unmodified lines10861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311344 unmodified lines1139114011411142114311441145114610 unmodified lines11571158115911601161116211631164116533 unmodified lines1199120012011202120312047 unmodified lines121212131214121530 unmodified linesfrom diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutputfrom diffusers.pipelines.stable_diffusion.safety_checker import \StableDiffusionSafetyCheckerfrom diffusers.schedulers import (DDIMScheduler, DPMSolverMultistepScheduler,FlowMatchEulerDiscreteScheduler)from diffusers.utils import (BACKENDS_MAPPING, BaseOutput, deprecate,is_bs4_available, is_ftfy_available,is_torch_xla_available, logging,3 unmodified linesfrom PIL import Imagefrom tqdm import tqdmfrom transformers import (BertModel, BertTokenizer, CLIPImageProcessor,CLIPVisionModelWithProjection, Qwen2Tokenizer,Qwen2VLForConditionalGeneration, T5EncoderModel,T5Tokenizer)from ..models import AutoencoderKLMagvit, EasyAnimateTransformer3DModelfrom .pipeline_easyanimate_inpaint import EasyAnimatePipelineOutputif is_torch_xla_available():import torch_xla.core.xla_model as xm12 unmodified lines```"""# Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_griddef get_resize_crop_region_for_grid(src, tgt_width, tgt_height):tw = tgt_widthth = tgt_height27 unmodified linesreturn noise_cfg# Resize mask information in magvitdef resize_mask(mask, latent, process_first_frame_only=True):latent_size = latent.size()if process_first_frame_only:target_size = list(latent_size[2:])target_size[0] = 1first_frame_resized = F.interpolate(mask[:, :, 0:1, :, :],size=target_size,mode='trilinear',align_corners=False)target_size = list(latent_size[2:])target_size[0] = target_size[0] - 1if target_size[0] != 0:remaining_frames_resized = F.interpolate(mask[:, :, 1:, :, :],size=target_size,mode='trilinear',align_corners=False)resized_mask = torch.cat([first_frame_resized, remaining_frames_resized], dim=2)else:resized_mask = first_frame_resizedelse:target_size = list(latent_size[2:])resized_mask = F.interpolate(mask,size=target_size,mode='trilinear',align_corners=False)return resized_mask# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timestepsdef retrieve_timesteps(scheduler,num_inference_steps: Optional[int] = None,device: Optional[Union[str, torch.device]] = None,timesteps: Optional[List[int]] = None,sigmas: Optional[List[float]] = None,**kwargs,):"""Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handlescustom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.Args:scheduler (`SchedulerMixin`):The scheduler to get timesteps from.num_inference_steps (`int`):The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`must be `None`.device (`str` or `torch.device`, *optional*):The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.timesteps (`List[int]`, *optional*):Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,`num_inference_steps` and `sigmas` must be `None`.sigmas (`List[float]`, *optional*):Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,`num_inference_steps` and `timesteps` must be `None`.Returns:`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and thesecond element is the number of inference steps."""if timesteps is not None and sigmas is not None:raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")if timesteps is not None:accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())if not accepts_timesteps:raise ValueError(f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"f" timestep schedules. Please check whether you are using the correct scheduler.")scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)timesteps = scheduler.timestepsnum_inference_steps = len(timesteps)elif sigmas is not None:accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())if not accept_sigmas:raise ValueError(f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"f" sigmas schedules. Please check whether you are using the correct scheduler.")scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)timesteps = scheduler.timestepsnum_inference_steps = len(timesteps)else:scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)timesteps = scheduler.timestepsreturn timesteps, num_inference_stepsclass EasyAnimateControlPipeline(DiffusionPipeline):r"""Pipeline for text-to-video generation using EasyAnimate.This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods thelibrary implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)EasyAnimate uses one text encoder [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) in V5.1.EasyAnimate uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned byHunyuanDiT team) in V5.Args:vae ([`AutoencoderKLMagvit`]):Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations.text_encoder (Optional[`~transformers.Qwen2VLForConditionalGeneration`, `~transformers.BertModel`]):EasyAnimate uses [qwen2 vl](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct) in V5.1.EasyAnimate uses [bilingual CLIP](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers) in V5.tokenizer (Optional[`~transformers.Qwen2Tokenizer`, `~transformers.BertTokenizer`]):A `Qwen2Tokenizer` or `BertTokenizer` to tokenize text.transformer ([`EasyAnimateTransformer3DModel`]):The EasyAnimate model designed by EasyAnimate Team.text_encoder_2 (`T5EncoderModel`):EasyAnimate does not use text_encoder_2 in V5.1.EasyAnimate uses [mT5](https://huggingface.co/google/mt5-base) embedder in V5.tokenizer_2 (`T5Tokenizer`):The tokenizer for the mT5 embedder.scheduler ([`FlowMatchEulerDiscreteScheduler`]):A scheduler to be used in combination with EasyAnimate to denoise the encoded image latents."""model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"_optional_components = ["text_encoder_2","tokenizer_2","text_encoder","tokenizer",]_callback_tensor_inputs = ["latents","prompt_embeds",5 unmodified linesdef __init__(self,vae: AutoencoderKLMagvit,text_encoder: Union[Qwen2VLForConditionalGeneration, BertModel],tokenizer: Union[Qwen2Tokenizer, BertTokenizer],text_encoder_2: Optional[Union[T5EncoderModel, Qwen2VLForConditionalGeneration]],tokenizer_2: Optional[Union[T5Tokenizer, Qwen2Tokenizer]],transformer: EasyAnimateTransformer3DModel,scheduler: FlowMatchEulerDiscreteScheduler,):super().__init__()self.register_modules(vae=vae,text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,tokenizer_2=tokenizer_2,transformer=transformer,scheduler=scheduler,)self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)self.mask_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True)def enable_sequential_cpu_offload(self, *args, **kwargs):super().enable_sequential_cpu_offload(*args, **kwargs)73 unmodified linesbatch_size = prompt_embeds.shape[0]if prompt_embeds is None:if type(tokenizer) in [BertTokenizer, T5Tokenizer]:text_inputs = tokenizer(prompt,padding="max_length",max_length=max_length,truncation=True,1 unmodified linereturn_tensors="pt",)text_input_ids = text_inputs.input_idsif text_input_ids.shape[-1] > actual_max_sequence_length:reprompt = tokenizer.batch_decode(text_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True)text_inputs = tokenizer(reprompt,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,return_tensors="pt",)text_input_ids = text_inputs.input_idsuntruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_idsif untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):_actual_max_sequence_length = min(tokenizer.model_max_length, actual_max_sequence_length)removed_text = tokenizer.batch_decode(untruncated_ids[:, _actual_max_sequence_length - 1 : -1])logger.warning("The following part of your input was truncated because CLIP can only handle sequences up to"f" {_actual_max_sequence_length} tokens: {removed_text}")prompt_attention_mask = text_inputs.attention_mask.to(device)if self.transformer.config.enable_text_attention_mask:prompt_embeds = text_encoder(text_input_ids.to(device),attention_mask=prompt_attention_mask,)else:prompt_embeds = text_encoder(text_input_ids.to(device))prompt_embeds = prompt_embeds[0]prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)else:if prompt is not None and isinstance(prompt, str):messages = [{"role": "user","content": [{"type": "text", "text": prompt}],}]else:messages = [{"role": "user","content": [{"type": "text", "text": _prompt}],} for _prompt in prompt]text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)text_inputs = tokenizer(text=[text],padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,padding_side="right",return_tensors="pt",)text_inputs = text_inputs.to(text_encoder.device)text_input_ids = text_inputs.input_idsprompt_attention_mask = text_inputs.attention_maskif self.transformer.config.enable_text_attention_mask:# Inference: Generation of the outputprompt_embeds = text_encoder(input_ids=text_input_ids,attention_mask=prompt_attention_mask,output_hidden_states=True).hidden_states[-2]else:raise ValueError("LLM needs attention_mask")prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)bs_embed, seq_len, _ = prompt_embeds.shape# duplicate text embeddings for each generation per prompt, using mps friendly methodprompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)prompt_attention_mask = prompt_attention_mask.to(device=device)# get unconditional embeddings for classifier free guidanceif do_classifier_free_guidance and negative_prompt_embeds is None:if type(tokenizer) in [BertTokenizer, T5Tokenizer]:uncond_tokens: List[str]if negative_prompt is None:uncond_tokens = [""] * batch_sizeelif prompt is not None and type(prompt) is not type(negative_prompt):raise TypeError(f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="f" {type(prompt)}.")elif isinstance(negative_prompt, str):uncond_tokens = [negative_prompt]elif batch_size != len(negative_prompt):raise ValueError(f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"" the batch size of `prompt`.")else:uncond_tokens = negative_promptmax_length = prompt_embeds.shape[1]uncond_input = tokenizer(uncond_tokens,padding="max_length",max_length=max_length,truncation=True,return_tensors="pt",)uncond_input_ids = uncond_input.input_idsif uncond_input_ids.shape[-1] > actual_max_sequence_length:reuncond_tokens = tokenizer.batch_decode(uncond_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True)uncond_input = tokenizer(reuncond_tokens,padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,return_tensors="pt",)uncond_input_ids = uncond_input.input_idsnegative_prompt_attention_mask = uncond_input.attention_mask.to(device)if self.transformer.config.enable_text_attention_mask:negative_prompt_embeds = text_encoder(uncond_input.input_ids.to(device),attention_mask=negative_prompt_attention_mask,)else:negative_prompt_embeds = text_encoder(uncond_input.input_ids.to(device))negative_prompt_embeds = negative_prompt_embeds[0]negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)else:if negative_prompt is not None and isinstance(negative_prompt, str):messages = [{"role": "user","content": [{"type": "text", "text": negative_prompt}],}]else:messages = [{"role": "user","content": [{"type": "text", "text": _negative_prompt}],} for _negative_prompt in negative_prompt]text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)text_inputs = tokenizer(text=[text],padding="max_length",max_length=max_length,truncation=True,return_attention_mask=True,padding_side="right",return_tensors="pt",)text_inputs = text_inputs.to(text_encoder.device)text_input_ids = text_inputs.input_idsnegative_prompt_attention_mask = text_inputs.attention_maskif self.transformer.config.enable_text_attention_mask:# Inference: Generation of the outputnegative_prompt_embeds = text_encoder(input_ids=text_input_ids,attention_mask=negative_prompt_attention_mask,output_hidden_states=True).hidden_states[-2]else:raise ValueError("LLM needs attention_mask")negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)if do_classifier_free_guidance:# duplicate unconditional embeddings for each generation per prompt, using mps friendly method3 unmodified linesnegative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)negative_prompt_attention_mask = negative_prompt_attention_mask.to(device=device)return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargsdef prepare_extra_step_kwargs(self, generator, eta):# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature28 unmodified linesnegative_prompt_attention_mask_2=None,callback_on_step_end_tensor_inputs=None,):if height % 16 != 0 or width % 16 != 0:raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")if callback_on_step_end_tensor_inputs is not None and not all(k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs78 unmodified lineslatents = latents.to(device)# scale the initial noise by the standard deviation required by the schedulerif hasattr(self.scheduler, "init_noise_sigma"):latents = latents * self.scheduler.init_noise_sigmareturn latentsdef prepare_control_latents(self, control, control_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance):# resize the control to latents shape as we concatenate the control to the latents# we do that before converting to dtype to avoid breaking in case we're using cpu_offload# and half precisionif control is not None:control = control.to(device=device, dtype=dtype)bs = 1new_control = []for i in range(0, control.shape[0], bs):control_bs = control[i : i + bs]control_bs = self.vae.encode(control_bs)[0]control_bs = control_bs.mode()new_control.append(control_bs)control = torch.cat(new_control, dim = 0)control = control * self.vae.config.scaling_factorif control_image is not None:control_image = control_image.to(device=device, dtype=dtype)bs = 1new_control_pixel_values = []for i in range(0, control_image.shape[0], bs):control_pixel_values_bs = control_image[i : i + bs]control_pixel_values_bs = self.vae.encode(control_pixel_values_bs)[0]control_pixel_values_bs = control_pixel_values_bs.mode()new_control_pixel_values.append(control_pixel_values_bs)control_image_latents = torch.cat(new_control_pixel_values, dim = 0)control_image_latents = control_image_latents * self.vae.config.scaling_factorelse:control_image_latents = Nonereturn control, control_image_latentsdef smooth_output(self, video, mini_batch_encoder, mini_batch_decoder):if video.size()[2] <= mini_batch_encoder:56 unmodified linesdef interrupt(self):return self._interrupt@torch.no_grad()@replace_example_docstring(EXAMPLE_DOC_STRING)def __call__(3 unmodified linesheight: Optional[int] = None,width: Optional[int] = None,control_video: Union[torch.FloatTensor] = None,control_camera_video: Union[torch.FloatTensor] = None,ref_image: Union[torch.FloatTensor] = None,num_inference_steps: Optional[int] = 50,guidance_scale: Optional[float] = 5.0,negative_prompt: Optional[Union[str, List[str]]] = None,20 unmodified linestarget_size: Optional[Tuple[int, int]] = None,crops_coords_top_left: Tuple[int, int] = (0, 0),comfyui_progressbar: bool = False,timesteps: Optional[List[int]] = None,):r"""Generates images or video using the EasyAnimate pipeline based on the provided prompts.98 unmodified linesbatch_size = prompt_embeds.shape[0]device = self._execution_deviceif self.text_encoder is not None:dtype = self.text_encoder.dtypeelif self.text_encoder_2 is not None:dtype = self.text_encoder_2.dtypeelse:dtype = self.transformer.dtype# 3. Encode input prompt(4 unmodified lines) = self.encode_prompt(prompt=prompt,device=device,dtype=dtype,num_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=self.do_classifier_free_guidance,negative_prompt=negative_prompt,3 unmodified linesnegative_prompt_attention_mask=negative_prompt_attention_mask,text_encoder_index=0,)if self.tokenizer_2 is not None:(prompt_embeds_2,negative_prompt_embeds_2,prompt_attention_mask_2,negative_prompt_attention_mask_2,) = self.encode_prompt(prompt=prompt,device=device,dtype=dtype,num_images_per_prompt=num_images_per_prompt,do_classifier_free_guidance=self.do_classifier_free_guidance,negative_prompt=negative_prompt,prompt_embeds=prompt_embeds_2,negative_prompt_embeds=negative_prompt_embeds_2,prompt_attention_mask=prompt_attention_mask_2,negative_prompt_attention_mask=negative_prompt_attention_mask_2,text_encoder_index=1,)else:prompt_embeds_2 = Nonenegative_prompt_embeds_2 = Noneprompt_attention_mask_2 = Nonenegative_prompt_attention_mask_2 = None# 4. Prepare timestepsif isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps, mu=1)else:timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)timesteps = self.scheduler.timestepsif comfyui_progressbar:from comfy.utils import ProgressBar7 unmodified linesvideo_length,height,width,dtype,device,generator,latents,1 unmodified lineif comfyui_progressbar:pbar.update(1)if control_camera_video is not None:control_video_latents = resize_mask(control_camera_video, latents, process_first_frame_only=True)control_video_latents = control_video_latents * 6control_latents = (torch.cat([control_video_latents] * 2) if self.do_classifier_free_guidance else control_video_latents).to(device, dtype)elif control_video is not None:video_length = control_video.shape[2]control_video = self.image_processor.preprocess(rearrange(control_video, "b c f h w -> (b f) c h w"), height=height, width=width)control_video = control_video.to(dtype=torch.float32)control_video = rearrange(control_video, "(b f) c h w -> b c f h w", f=video_length)control_video_latents = self.prepare_control_latents(None,control_video,batch_size,height,width,dtype,device,generator,self.do_classifier_free_guidance)[1]control_latents = (torch.cat([control_video_latents] * 2) if self.do_classifier_free_guidance else control_video_latents).to(device, dtype)else:control_video_latents = torch.zeros_like(latents).to(device, dtype)control_latents = (torch.cat([control_video_latents] * 2) if self.do_classifier_free_guidance else control_video_latents).to(device, dtype)if ref_image is not None:video_length = ref_image.shape[2]ref_image = self.image_processor.preprocess(rearrange(ref_image, "b c f h w -> (b f) c h w"), height=height, width=width)ref_image = ref_image.to(dtype=torch.float32)ref_image = rearrange(ref_image, "(b f) c h w -> b c f h w", f=video_length)ref_image_latentes = self.prepare_control_latents(None,ref_image,batch_size,height,width,prompt_embeds.dtype,device,generator,self.do_classifier_free_guidance)[1]ref_image_latentes_conv_in = torch.zeros_like(latents)if latents.size()[2] != 1:ref_image_latentes_conv_in[:, :, :1] = ref_image_latentesref_image_latentes_conv_in = (torch.cat([ref_image_latentes_conv_in] * 2) if self.do_classifier_free_guidance else ref_image_latentes_conv_in).to(device, dtype)control_latents = torch.cat([control_latents, ref_image_latentes_conv_in], dim = 1)else:if self.transformer.config.get("add_ref_latent_in_control_model", False):ref_image_latentes_conv_in = torch.zeros_like(latents)ref_image_latentes_conv_in = (torch.cat([ref_image_latentes_conv_in] * 2) if self.do_classifier_free_guidance else ref_image_latentes_conv_in).to(device, dtype)control_latents = torch.cat([control_latents, ref_image_latentes_conv_in], dim = 1)if comfyui_progressbar:pbar.update(1)25 unmodified lines)# Get other hunyuan paramstarget_size = target_size or (height, width)add_time_ids = list(original_size + target_size + crops_coords_top_left)add_time_ids = torch.tensor([add_time_ids], dtype=dtype)style = torch.tensor([0], device=device)if self.do_classifier_free_guidance:add_time_ids = torch.cat([add_time_ids] * 2, dim=0)style = torch.cat([style] * 2, dim=0)# To latents.deviceadd_time_ids = add_time_ids.to(dtype=dtype, device=device).repeat(batch_size * num_images_per_prompt, 1)style = style.to(device=device).repeat(batch_size * num_images_per_prompt)# Get other pixart paramsadded_cond_kwargs = {"resolution": None, "aspect_ratio": None}if self.transformer.config.get("sample_size", 64) == 128:resolution = torch.tensor([height, width]).repeat(batch_size * num_images_per_prompt, 1)aspect_ratio = torch.tensor([float(height / width)]).repeat(batch_size * num_images_per_prompt, 1)resolution = resolution.to(dtype=dtype, device=device)aspect_ratio = aspect_ratio.to(dtype=dtype, device=device)if self.do_classifier_free_guidance:resolution = torch.cat([resolution, resolution], dim=0)aspect_ratio = torch.cat([aspect_ratio, aspect_ratio], dim=0)added_cond_kwargs = {"resolution": resolution, "aspect_ratio": aspect_ratio}if self.do_classifier_free_guidance:prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])if prompt_embeds_2 is not None:prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2])# To latents.deviceprompt_embeds = prompt_embeds.to(device=device)prompt_attention_mask = prompt_attention_mask.to(device=device)if prompt_embeds_2 is not None:prompt_embeds_2 = prompt_embeds_2.to(device=device)prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device)# 8. Denoising loopnum_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.orderself._num_timesteps = len(timesteps)4 unmodified lines# expand the latents if we are doing classifier free guidancelatent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latentsif hasattr(self.scheduler, "scale_model_input"):latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)# expand scalar t to 1-D tensor to match the 1st dim of latent_model_inputt_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to(10 unmodified linesimage_meta_size=add_time_ids,style=style,image_rotary_emb=image_rotary_emb,added_cond_kwargs=added_cond_kwargs,control_latents=control_latents,return_dict=False,)[0]if noise_pred.size()[1] != self.vae.config.latent_channels:noise_pred, _ = noise_pred.chunk(2, dim=1)33 unmodified linesif comfyui_progressbar:pbar.update(1)# Post-processingvideo = self.decode_latents(latents)7 unmodified linesif not return_dict:return videoreturn EasyAnimatePipelineOutput(frames=video)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925# Copyright 2024 EasyAnimate Authors 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 inspectfrom typing import Callable, Dict, List, Optional, Tuple, Union
import numpy as npimport torchfrom diffusers.callbacks import MultiPipelineCallbacks, PipelineCallbackfrom diffusers.image_processor import VaeImageProcessorfrom diffusers.models.embeddings import (get_2d_rotary_pos_embed, get_3d_rotary_pos_embed)from diffusers.pipelines.pipeline_utils import DiffusionPipelinefrom diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutputfrom diffusers.pipelines.stable_diffusion.safety_checker import \ StableDiffusionSafetyCheckerfrom diffusers.schedulers import DDIMSchedulerfrom diffusers.utils import (is_torch_xla_available, logging, replace_example_docstring)from diffusers.utils.torch_utils import randn_tensorfrom einops import rearrangefrom tqdm import tqdmfrom transformers import (BertModel, BertTokenizer, CLIPImageProcessor, T5Tokenizer, T5EncoderModel)
from .pipeline_easyanimate import EasyAnimatePipelineOutputfrom ..models import AutoencoderKLMagvit, EasyAnimateTransformer3DModel
if is_torch_xla_available(): import torch_xla.core.xla_model as xm
XLA_AVAILABLE = Trueelse: XLA_AVAILABLE = False
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
EXAMPLE_DOC_STRING = """ Examples: ```py >>> pass ```"""
def get_resize_crop_region_for_grid(src, tgt_width, tgt_height): tw = tgt_width th = tgt_height h, w = src r = h / w if r > (th / tw): resize_height = th resize_width = int(round(th / h * w)) else: resize_width = tw resize_height = int(round(tw / w * h))
crop_top = int(round((th - resize_height) / 2.0)) crop_left = int(round((tw - resize_width) / 2.0))
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfgdef rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0): """ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4 """ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True) std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True) # rescale the results from guidance (fixes overexposure) noise_pred_rescaled = noise_cfg * (std_text / std_cfg) # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg return noise_cfg
class EasyAnimatePipeline_Multi_Text_Encoder(DiffusionPipeline): r""" Pipeline for text-to-video generation using EasyAnimate.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
EasyAnimate uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned by HunyuanDiT team)
Args: vae ([`AutoencoderKLMagvit`]): Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations. text_encoder (Optional[`~transformers.BertModel`, `~transformers.CLIPTextModel`]): Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). EasyAnimate uses a fine-tuned [bilingual CLIP]. tokenizer (Optional[`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer`]): A `BertTokenizer` or `CLIPTokenizer` to tokenize text. transformer ([`EasyAnimateTransformer3DModel`]): The EasyAnimate model designed by Tencent Hunyuan. text_encoder_2 (`T5EncoderModel`): The mT5 embedder. tokenizer_2 (`T5Tokenizer`): The tokenizer for the mT5 embedder. scheduler ([`DDIMScheduler`]): A scheduler to be used in combination with EasyAnimate to denoise the encoded image latents. """
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae" _optional_components = [ "safety_checker", "feature_extractor", "text_encoder_2", "tokenizer_2", "text_encoder", "tokenizer", ] _exclude_from_cpu_offload = ["safety_checker"] _callback_tensor_inputs = [ "latents", "prompt_embeds", "negative_prompt_embeds", "prompt_embeds_2", "negative_prompt_embeds_2", ]
def __init__( self, vae: AutoencoderKLMagvit, text_encoder: BertModel, tokenizer: BertTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: EasyAnimateTransformer3DModel, scheduler: DDIMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessor, requires_safety_checker: bool = True, ): super().__init__()
self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, tokenizer_2=tokenizer_2, transformer=transformer, scheduler=scheduler, safety_checker=safety_checker, feature_extractor=feature_extractor, text_encoder_2=text_encoder_2, )
if safety_checker is None and requires_safety_checker: logger.warning( f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." )
if safety_checker is not None and feature_extractor is None: raise ValueError( "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." )
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) self.enable_autocast_float8_transformer_flag = False self.register_to_config(requires_safety_checker=requires_safety_checker)
def enable_sequential_cpu_offload(self, *args, **kwargs): super().enable_sequential_cpu_offload(*args, **kwargs) if hasattr(self.transformer, "clip_projection") and self.transformer.clip_projection is not None: import accelerate accelerate.hooks.remove_hook_from_module(self.transformer.clip_projection, recurse=True) self.transformer.clip_projection = self.transformer.clip_projection.to("cuda")
def encode_prompt( self, prompt: str, device: torch.device, dtype: torch.dtype, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: Optional[str] = None, prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, prompt_attention_mask: Optional[torch.Tensor] = None, negative_prompt_attention_mask: Optional[torch.Tensor] = None, max_sequence_length: Optional[int] = None, text_encoder_index: int = 0, actual_max_sequence_length: int = 256 ): r""" Encodes the prompt into text encoder hidden states.
Args: prompt (`str` or `List[str]`, *optional*): prompt to be encoded device: (`torch.device`): torch device dtype (`torch.dtype`): torch dtype num_images_per_prompt (`int`): number of images that should be generated per prompt do_classifier_free_guidance (`bool`): whether to use classifier free guidance or not negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). prompt_embeds (`torch.Tensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. negative_prompt_embeds (`torch.Tensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask for the prompt. Required when `prompt_embeds` is passed directly. negative_prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly. max_sequence_length (`int`, *optional*): maximum sequence length to use for the prompt. text_encoder_index (`int`, *optional*): Index of the text encoder to use. `0` for clip and `1` for T5. """ tokenizers = [self.tokenizer, self.tokenizer_2] text_encoders = [self.text_encoder, self.text_encoder_2]
tokenizer = tokenizers[text_encoder_index] text_encoder = text_encoders[text_encoder_index]
if max_sequence_length is None: if text_encoder_index == 0: max_length = min(self.tokenizer.model_max_length, actual_max_sequence_length) if text_encoder_index == 1: max_length = min(self.tokenizer_2.model_max_length, actual_max_sequence_length) else: max_length = max_sequence_length
if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0]
if prompt_embeds is None: text_inputs = tokenizer( prompt, padding="max_length", max_length=max_length, truncation=True, return_attention_mask=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids if text_input_ids.shape[-1] > actual_max_sequence_length: reprompt = tokenizer.batch_decode(text_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True) text_inputs = tokenizer( reprompt, padding="max_length", max_length=max_length, truncation=True, return_attention_mask=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( text_input_ids, untruncated_ids ): _actual_max_sequence_length = min(tokenizer.model_max_length, actual_max_sequence_length) removed_text = tokenizer.batch_decode(untruncated_ids[:, _actual_max_sequence_length - 1 : -1]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f" {_actual_max_sequence_length} tokens: {removed_text}" ) prompt_attention_mask = text_inputs.attention_mask.to(device)
if self.transformer.config.enable_text_attention_mask: prompt_embeds = text_encoder( text_input_ids.to(device), attention_mask=prompt_attention_mask, ) else: prompt_embeds = text_encoder( text_input_ids.to(device) ) prompt_embeds = prompt_embeds[0] prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
bs_embed, seq_len, _ = prompt_embeds.shape # duplicate text embeddings for each generation per prompt, using mps friendly method prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
# get unconditional embeddings for classifier free guidance if do_classifier_free_guidance and negative_prompt_embeds is None: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif prompt is not None and type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" f" {type(prompt)}." ) elif isinstance(negative_prompt, str): uncond_tokens = [negative_prompt] elif batch_size != len(negative_prompt): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: uncond_tokens = negative_prompt
max_length = prompt_embeds.shape[1] uncond_input = tokenizer( uncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt", ) uncond_input_ids = uncond_input.input_ids if uncond_input_ids.shape[-1] > actual_max_sequence_length: reuncond_tokens = tokenizer.batch_decode(uncond_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True) uncond_input = tokenizer( reuncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_attention_mask=True, return_tensors="pt", ) uncond_input_ids = uncond_input.input_ids
negative_prompt_attention_mask = uncond_input.attention_mask.to(device) if self.transformer.config.enable_text_attention_mask: negative_prompt_embeds = text_encoder( uncond_input.input_ids.to(device), attention_mask=negative_prompt_attention_mask, ) else: negative_prompt_embeds = text_encoder( uncond_input.input_ids.to(device) ) negative_prompt_embeds = negative_prompt_embeds[0] negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
if do_classifier_free_guidance: # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = negative_prompt_embeds.shape[1]
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker def run_safety_checker(self, image, device, dtype): if self.safety_checker is None: has_nsfw_concept = None else: if torch.is_tensor(image): feature_extractor_input = self.image_processor.postprocess(image, output_type="pil") else: feature_extractor_input = self.image_processor.numpy_to_pil(image) safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device) image, has_nsfw_concept = self.safety_checker( images=image, clip_input=safety_checker_input.pixel_values.to(dtype) ) return image, has_nsfw_concept
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1]
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) extra_step_kwargs = {} if accepts_eta: extra_step_kwargs["eta"] = eta
# check if the scheduler accepts generator accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: extra_step_kwargs["generator"] = generator return extra_step_kwargs
def check_inputs( self, prompt, height, width, negative_prompt=None, prompt_embeds=None, negative_prompt_embeds=None, prompt_attention_mask=None, negative_prompt_attention_mask=None, prompt_embeds_2=None, negative_prompt_embeds_2=None, prompt_attention_mask_2=None, negative_prompt_attention_mask_2=None, callback_on_step_end_tensor_inputs=None, ): if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
if callback_on_step_end_tensor_inputs is not None and not all( k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs ): raise ValueError( f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" )
if prompt is not None and prompt_embeds is not None: raise ValueError( f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" " only forward one of the two." ) elif prompt is None and prompt_embeds is None: raise ValueError( "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." ) elif prompt is None and prompt_embeds_2 is None: raise ValueError( "Provide either `prompt` or `prompt_embeds_2`. Cannot leave both `prompt` and `prompt_embeds_2` undefined." ) elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
if prompt_embeds is not None and prompt_attention_mask is None: raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
if prompt_embeds_2 is not None and prompt_attention_mask_2 is None: raise ValueError("Must provide `prompt_attention_mask_2` when specifying `prompt_embeds_2`.")
if negative_prompt is not None and negative_prompt_embeds is not None: raise ValueError( f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" f" {negative_prompt_embeds}. Please make sure to only forward one of the two." )
if negative_prompt_embeds is not None and negative_prompt_attention_mask is None: raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
if negative_prompt_embeds_2 is not None and negative_prompt_attention_mask_2 is None: raise ValueError( "Must provide `negative_prompt_attention_mask_2` when specifying `negative_prompt_embeds_2`." ) if prompt_embeds is not None and negative_prompt_embeds is not None: if prompt_embeds.shape != negative_prompt_embeds.shape: raise ValueError( "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" f" {negative_prompt_embeds.shape}." ) if prompt_embeds_2 is not None and negative_prompt_embeds_2 is not None: if prompt_embeds_2.shape != negative_prompt_embeds_2.shape: raise ValueError( "`prompt_embeds_2` and `negative_prompt_embeds_2` must have the same shape when passed directly, but" f" got: `prompt_embeds_2` {prompt_embeds_2.shape} != `negative_prompt_embeds_2`" f" {negative_prompt_embeds_2.shape}." )
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None): if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5: if self.vae.cache_mag_vae: mini_batch_encoder = self.vae.mini_batch_encoder mini_batch_decoder = self.vae.mini_batch_decoder shape = (batch_size, num_channels_latents, int((video_length - 1) // mini_batch_encoder * mini_batch_decoder + 1) if video_length != 1 else 1, height // self.vae_scale_factor, width // self.vae_scale_factor) else: mini_batch_encoder = self.vae.mini_batch_encoder mini_batch_decoder = self.vae.mini_batch_decoder shape = (batch_size, num_channels_latents, int(video_length // mini_batch_encoder * mini_batch_decoder) if video_length != 1 else 1, height // self.vae_scale_factor, width // self.vae_scale_factor) else: shape = (batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor)
if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." )
if latents is None: latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) else: latents = latents.to(device) # scale the initial noise by the standard deviation required by the scheduler latents = latents * self.scheduler.init_noise_sigma return latents
def smooth_output(self, video, mini_batch_encoder, mini_batch_decoder): if video.size()[2] <= mini_batch_encoder: return video prefix_index_before = mini_batch_encoder // 2 prefix_index_after = mini_batch_encoder - prefix_index_before pixel_values = video[:, :, prefix_index_before:-prefix_index_after]
# Encode middle videos latents = self.vae.encode(pixel_values)[0] latents = latents.mode() # Decode middle videos middle_video = self.vae.decode(latents)[0]
video[:, :, prefix_index_before:-prefix_index_after] = (video[:, :, prefix_index_before:-prefix_index_after] + middle_video) / 2 return video
def decode_latents(self, latents): video_length = latents.shape[2] latents = 1 / self.vae.config.scaling_factor * latents if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5: mini_batch_encoder = self.vae.mini_batch_encoder mini_batch_decoder = self.vae.mini_batch_decoder video = self.vae.decode(latents)[0] video = video.clamp(-1, 1) if not self.vae.cache_compression_vae and not self.vae.cache_mag_vae: video = self.smooth_output(video, mini_batch_encoder, mini_batch_decoder).cpu().clamp(-1, 1) else: latents = rearrange(latents, "b c f h w -> (b f) c h w") video = [] for frame_idx in tqdm(range(latents.shape[0])): video.append(self.vae.decode(latents[frame_idx:frame_idx+1]).sample) video = torch.cat(video) video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length) video = (video / 2 + 0.5).clamp(0, 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 video = video.cpu().float().numpy() return video
@property def guidance_scale(self): return self._guidance_scale
@property def guidance_rescale(self): return self._guidance_rescale
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. @property def do_classifier_free_guidance(self): return self._guidance_scale > 1
@property def num_timesteps(self): return self._num_timesteps
@property def interrupt(self): return self._interrupt
def enable_autocast_float8_transformer(self): self.enable_autocast_float8_transformer_flag = True
@torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Union[str, List[str]] = None, video_length: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: Optional[int] = 50, guidance_scale: Optional[float] = 5.0, negative_prompt: Optional[Union[str, List[str]]] = None, num_images_per_prompt: Optional[int] = 1, eta: Optional[float] = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.Tensor] = None, prompt_embeds: Optional[torch.Tensor] = None, prompt_embeds_2: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds_2: Optional[torch.Tensor] = None, prompt_attention_mask: Optional[torch.Tensor] = None, prompt_attention_mask_2: Optional[torch.Tensor] = None, negative_prompt_attention_mask: Optional[torch.Tensor] = None, negative_prompt_attention_mask_2: Optional[torch.Tensor] = None, output_type: Optional[str] = "latent", return_dict: bool = True, callback_on_step_end: Optional[ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks] ] = None, callback_on_step_end_tensor_inputs: List[str] = ["latents"], guidance_rescale: float = 0.0, original_size: Optional[Tuple[int, int]] = (1024, 1024), target_size: Optional[Tuple[int, int]] = None, crops_coords_top_left: Tuple[int, int] = (0, 0), comfyui_progressbar: bool = False, ): r""" Generates images or video using the EasyAnimate pipeline based on the provided prompts.
Examples: prompt (`str` or `List[str]`, *optional*): Text prompts to guide the image or video generation. If not provided, use `prompt_embeds` instead. video_length (`int`, *optional*): Length of the generated video (in frames). height (`int`, *optional*): Height of the generated image in pixels. width (`int`, *optional*): Width of the generated image in pixels. num_inference_steps (`int`, *optional*, defaults to 50): Number of denoising steps during generation. More steps generally yield higher quality images but slow down inference. guidance_scale (`float`, *optional*, defaults to 5.0): Encourages the model to align outputs with prompts. A higher value may decrease image quality. negative_prompt (`str` or `List[str]`, *optional*): Prompts indicating what to exclude in generation. If not specified, use `negative_prompt_embeds`. num_images_per_prompt (`int`, *optional*, defaults to 1): Number of images to generate for each prompt. eta (`float`, *optional*, defaults to 0.0): Applies to DDIM scheduling. Controlled by the eta parameter from the related literature. generator (`torch.Generator` or `List[torch.Generator]`, *optional*): A generator to ensure reproducibility in image generation. latents (`torch.Tensor`, *optional*): Predefined latent tensors to condition generation. prompt_embeds (`torch.Tensor`, *optional*): Text embeddings for the prompts. Overrides prompt string inputs for more flexibility. prompt_embeds_2 (`torch.Tensor`, *optional*): Secondary text embeddings to supplement or replace the initial prompt embeddings. negative_prompt_embeds (`torch.Tensor`, *optional*): Embeddings for negative prompts. Overrides string inputs if defined. negative_prompt_embeds_2 (`torch.Tensor`, *optional*): Secondary embeddings for negative prompts, similar to `negative_prompt_embeds`. prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask for the primary prompt embeddings. prompt_attention_mask_2 (`torch.Tensor`, *optional*): Attention mask for the secondary prompt embeddings. negative_prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask for negative prompt embeddings. negative_prompt_attention_mask_2 (`torch.Tensor`, *optional*): Attention mask for secondary negative prompt embeddings. output_type (`str`, *optional*, defaults to "latent"): Format of the generated output, either as a PIL image or as a NumPy array. return_dict (`bool`, *optional*, defaults to `True`): If `True`, returns a structured output. Otherwise returns a simple tuple. callback_on_step_end (`Callable`, *optional*): Functions called at the end of each denoising step. callback_on_step_end_tensor_inputs (`List[str]`, *optional*): Tensor names to be included in callback function calls. guidance_rescale (`float`, *optional*, defaults to 0.0): Adjusts noise levels based on guidance scale. original_size (`Tuple[int, int]`, *optional*, defaults to `(1024, 1024)`): Original dimensions of the output. target_size (`Tuple[int, int]`, *optional*): Desired output dimensions for calculations. crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to `(0, 0)`): Coordinates for cropping.
Returns: [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content. """
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
# 0. default height and width height = int((height // 16) * 16) width = int((width // 16) * 16)
# 1. Check inputs. Raise error if not correct self.check_inputs( prompt, height, width, negative_prompt, prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask, prompt_embeds_2, negative_prompt_embeds_2, prompt_attention_mask_2, negative_prompt_attention_mask_2, callback_on_step_end_tensor_inputs, ) self._guidance_scale = guidance_scale self._guidance_rescale = guidance_rescale self._interrupt = False
# 2. Define call parameters if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0]
device = self._execution_device
# 3. Encode input prompt ( prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask, ) = self.encode_prompt( prompt=prompt, device=device, dtype=self.transformer.dtype, num_images_per_prompt=num_images_per_prompt, do_classifier_free_guidance=self.do_classifier_free_guidance, negative_prompt=negative_prompt, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, prompt_attention_mask=prompt_attention_mask, negative_prompt_attention_mask=negative_prompt_attention_mask, text_encoder_index=0, ) ( prompt_embeds_2, negative_prompt_embeds_2, prompt_attention_mask_2, negative_prompt_attention_mask_2, ) = self.encode_prompt( prompt=prompt, device=device, dtype=self.transformer.dtype, num_images_per_prompt=num_images_per_prompt, do_classifier_free_guidance=self.do_classifier_free_guidance, negative_prompt=negative_prompt, prompt_embeds=prompt_embeds_2, negative_prompt_embeds=negative_prompt_embeds_2, prompt_attention_mask=prompt_attention_mask_2, negative_prompt_attention_mask=negative_prompt_attention_mask_2, text_encoder_index=1, ) torch.cuda.empty_cache()
# 4. Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps if comfyui_progressbar: from comfy.utils import ProgressBar pbar = ProgressBar(num_inference_steps + 1)
# 5. Prepare latent variables num_channels_latents = self.transformer.config.in_channels latents = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, video_length, height, width, prompt_embeds.dtype, device, generator, latents, ) if comfyui_progressbar: pbar.update(1)
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
# 7 create image_rotary_emb, style embedding & time ids grid_height = height // 8 // self.transformer.config.patch_size grid_width = width // 8 // self.transformer.config.patch_size if self.transformer.config.get("time_position_encoding_type", "2d_rope") == "3d_rope": base_size_width = 720 // 8 // self.transformer.config.patch_size base_size_height = 480 // 8 // self.transformer.config.patch_size
grid_crops_coords = get_resize_crop_region_for_grid( (grid_height, grid_width), base_size_width, base_size_height ) image_rotary_emb = get_3d_rotary_pos_embed( self.transformer.config.attention_head_dim, grid_crops_coords, grid_size=(grid_height, grid_width), temporal_size=latents.size(2), use_real=True, ) else: base_size = 512 // 8 // self.transformer.config.patch_size grid_crops_coords = get_resize_crop_region_for_grid( (grid_height, grid_width), base_size, base_size ) image_rotary_emb = get_2d_rotary_pos_embed( self.transformer.config.attention_head_dim, grid_crops_coords, (grid_height, grid_width) )
# Get other hunyuan params style = torch.tensor([0], device=device)
target_size = target_size or (height, width) add_time_ids = list(original_size + target_size + crops_coords_top_left) add_time_ids = torch.tensor([add_time_ids], dtype=prompt_embeds.dtype)
if self.do_classifier_free_guidance: prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask]) prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2]) prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2]) add_time_ids = torch.cat([add_time_ids] * 2, dim=0) style = torch.cat([style] * 2, dim=0)
# To latents.device prompt_embeds = prompt_embeds.to(device=device) prompt_attention_mask = prompt_attention_mask.to(device=device) prompt_embeds_2 = prompt_embeds_2.to(device=device) prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device) add_time_ids = add_time_ids.to(dtype=prompt_embeds.dtype, device=device).repeat( batch_size * num_images_per_prompt, 1 ) style = style.to(device=device).repeat(batch_size * num_images_per_prompt)
torch.cuda.empty_cache() if self.enable_autocast_float8_transformer_flag: origin_weight_dtype = self.transformer.dtype self.transformer = self.transformer.to(torch.float8_e4m3fn) # 8. Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order self._num_timesteps = len(timesteps) with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): if self.interrupt: continue
# expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
# expand scalar t to 1-D tensor to match the 1st dim of latent_model_input t_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to( dtype=latent_model_input.dtype )
# predict the noise residual noise_pred = self.transformer( latent_model_input, t_expand, encoder_hidden_states=prompt_embeds, text_embedding_mask=prompt_attention_mask, encoder_hidden_states_t5=prompt_embeds_2, text_embedding_mask_t5=prompt_attention_mask_2, image_meta_size=add_time_ids, style=style, image_rotary_emb=image_rotary_emb, return_dict=False, )[0] if noise_pred.size()[1] != self.vae.config.latent_channels: noise_pred, _ = noise_pred.chunk(2, dim=1)
# perform guidance if self.do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
if self.do_classifier_free_guidance and guidance_rescale > 0.0: # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
# compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
if callback_on_step_end is not None: callback_kwargs = {} for k in callback_on_step_end_tensor_inputs: callback_kwargs[k] = locals()[k] callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
latents = callback_outputs.pop("latents", latents) prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) prompt_embeds_2 = callback_outputs.pop("prompt_embeds_2", prompt_embeds_2) negative_prompt_embeds_2 = callback_outputs.pop( "negative_prompt_embeds_2", negative_prompt_embeds_2 )
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update()
if XLA_AVAILABLE: xm.mark_step()
if comfyui_progressbar: pbar.update(1)
if self.enable_autocast_float8_transformer_flag: self.transformer = self.transformer.to("cpu", origin_weight_dtype)
torch.cuda.empty_cache() # Post-processing video = self.decode_latents(latents)
# Convert to tensor if output_type == "latent": video = torch.from_numpy(video)
# Offload all models self.maybe_free_model_hooks()
if not return_dict: return video
return EasyAnimatePipelineOutput(videos=video)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334# Copyright 2024 EasyAnimate Authors 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 inspectfrom typing import Callable, Dict, List, Optional, Tuple, Union
import torchimport torch.nn.functional as Ffrom diffusers import DiffusionPipelinefrom diffusers.callbacks import MultiPipelineCallbacks, PipelineCallbackfrom diffusers.image_processor import VaeImageProcessorfrom diffusers.models import AutoencoderKL, HunyuanDiT2DModelfrom diffusers.models.embeddings import (get_2d_rotary_pos_embed, get_3d_rotary_pos_embed)from diffusers.pipelines.pipeline_utils import DiffusionPipelinefrom diffusers.pipelines.stable_diffusion.safety_checker import \ StableDiffusionSafetyCheckerfrom diffusers.schedulers import DDIMSchedulerfrom diffusers.utils import (is_torch_xla_available, logging, replace_example_docstring)from diffusers.utils.torch_utils import randn_tensorfrom einops import rearrangefrom PIL import Imagefrom tqdm import tqdmfrom transformers import (BertModel, BertTokenizer, CLIPImageProcessor, CLIPVisionModelWithProjection, T5Tokenizer, T5EncoderModel)
from .pipeline_easyanimate import EasyAnimatePipelineOutputfrom ..models import AutoencoderKLMagvit, EasyAnimateTransformer3DModel
if is_torch_xla_available(): import torch_xla.core.xla_model as xm
XLA_AVAILABLE = Trueelse: XLA_AVAILABLE = False
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
EXAMPLE_DOC_STRING = """ Examples: ```py >>> pass ```"""
def get_resize_crop_region_for_grid(src, tgt_width, tgt_height): tw = tgt_width th = tgt_height h, w = src r = h / w if r > (th / tw): resize_height = th resize_width = int(round(th / h * w)) else: resize_width = tw resize_height = int(round(tw / w * h))
crop_top = int(round((th - resize_height) / 2.0)) crop_left = int(round((tw - resize_width) / 2.0))
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfgdef rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0): """ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4 """ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True) std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True) # rescale the results from guidance (fixes overexposure) noise_pred_rescaled = noise_cfg * (std_text / std_cfg) # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg return noise_cfg
def resize_mask(mask, latent, process_first_frame_only=True): latent_size = latent.size()
if process_first_frame_only: target_size = list(latent_size[2:]) target_size[0] = 1 first_frame_resized = F.interpolate( mask[:, :, 0:1, :, :], size=target_size, mode='trilinear', align_corners=False ) target_size = list(latent_size[2:]) target_size[0] = target_size[0] - 1 if target_size[0] != 0: remaining_frames_resized = F.interpolate( mask[:, :, 1:, :, :], size=target_size, mode='trilinear', align_corners=False ) resized_mask = torch.cat([first_frame_resized, remaining_frames_resized], dim=2) else: resized_mask = first_frame_resized else: target_size = list(latent_size[2:]) resized_mask = F.interpolate( mask, size=target_size, mode='trilinear', align_corners=False ) return resized_mask
def add_noise_to_reference_video(image, ratio=None): if ratio is None: sigma = torch.normal(mean=-3.0, std=0.5, size=(image.shape[0],)).to(image.device) sigma = torch.exp(sigma).to(image.dtype) else: sigma = torch.ones((image.shape[0],)).to(image.device, image.dtype) * ratio image_noise = torch.randn_like(image) * sigma[:, None, None, None, None] image_noise = torch.where(image==-1, torch.zeros_like(image), image_noise) image = image + image_noise return image
class EasyAnimatePipeline_Multi_Text_Encoder_Inpaint(DiffusionPipeline): r""" Pipeline for text-to-video generation using EasyAnimate.
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
EasyAnimate uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned by HunyuanDiT team)
Args: vae ([`AutoencoderKLMagvit`]): Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations. text_encoder (Optional[`~transformers.BertModel`, `~transformers.CLIPTextModel`]): Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). EasyAnimate uses a fine-tuned [bilingual CLIP]. tokenizer (Optional[`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer`]): A `BertTokenizer` or `CLIPTokenizer` to tokenize text. transformer ([`EasyAnimateTransformer3DModel`]): The EasyAnimate model designed by Tencent Hunyuan. text_encoder_2 (`T5EncoderModel`): The mT5 embedder. tokenizer_2 (`T5Tokenizer`): The tokenizer for the mT5 embedder. scheduler ([`DDIMScheduler`]): A scheduler to be used in combination with EasyAnimate to denoise the encoded image latents. clip_image_processor (`CLIPImageProcessor`): The CLIP image embedder. clip_image_encoder (`CLIPVisionModelWithProjection`): The image processor for the CLIP image embedder. """
model_cpu_offload_seq = "text_encoder->text_encoder_2->clip_image_encoder->transformer->vae" _optional_components = [ "safety_checker", "feature_extractor", "text_encoder_2", "tokenizer_2", "text_encoder", "tokenizer", "clip_image_encoder", ] _exclude_from_cpu_offload = ["safety_checker"] _callback_tensor_inputs = [ "latents", "prompt_embeds", "negative_prompt_embeds", "prompt_embeds_2", "negative_prompt_embeds_2", ]
def __init__( self, vae: AutoencoderKLMagvit, text_encoder: BertModel, tokenizer: BertTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: EasyAnimateTransformer3DModel, scheduler: DDIMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessor, requires_safety_checker: bool = True, clip_image_processor: CLIPImageProcessor = None, clip_image_encoder: CLIPVisionModelWithProjection = None, ): super().__init__()
self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, tokenizer_2=tokenizer_2, transformer=transformer, scheduler=scheduler, safety_checker=safety_checker, feature_extractor=feature_extractor, text_encoder_2=text_encoder_2, clip_image_processor=clip_image_processor, clip_image_encoder=clip_image_encoder, )
if safety_checker is None and requires_safety_checker: logger.warning( f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." )
if safety_checker is not None and feature_extractor is None: raise ValueError( "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." )
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) self.mask_processor = VaeImageProcessor( vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True ) self.enable_autocast_float8_transformer_flag = False self.register_to_config(requires_safety_checker=requires_safety_checker)
def enable_sequential_cpu_offload(self, *args, **kwargs): super().enable_sequential_cpu_offload(*args, **kwargs) if hasattr(self.transformer, "clip_projection") and self.transformer.clip_projection is not None: import accelerate accelerate.hooks.remove_hook_from_module(self.transformer.clip_projection, recurse=True) self.transformer.clip_projection = self.transformer.clip_projection.to("cuda")
def encode_prompt( self, prompt: str, device: torch.device, dtype: torch.dtype, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: Optional[str] = None, prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, prompt_attention_mask: Optional[torch.Tensor] = None, negative_prompt_attention_mask: Optional[torch.Tensor] = None, max_sequence_length: Optional[int] = None, text_encoder_index: int = 0, actual_max_sequence_length: int = 256 ): r""" Encodes the prompt into text encoder hidden states.
Args: prompt (`str` or `List[str]`, *optional*): prompt to be encoded device: (`torch.device`): torch device dtype (`torch.dtype`): torch dtype num_images_per_prompt (`int`): number of images that should be generated per prompt do_classifier_free_guidance (`bool`): whether to use classifier free guidance or not negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). prompt_embeds (`torch.Tensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. negative_prompt_embeds (`torch.Tensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask for the prompt. Required when `prompt_embeds` is passed directly. negative_prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly. max_sequence_length (`int`, *optional*): maximum sequence length to use for the prompt. text_encoder_index (`int`, *optional*): Index of the text encoder to use. `0` for clip and `1` for T5. """ tokenizers = [self.tokenizer, self.tokenizer_2] text_encoders = [self.text_encoder, self.text_encoder_2]
tokenizer = tokenizers[text_encoder_index] text_encoder = text_encoders[text_encoder_index]
if max_sequence_length is None: if text_encoder_index == 0: max_length = min(self.tokenizer.model_max_length, actual_max_sequence_length) if text_encoder_index == 1: max_length = min(self.tokenizer_2.model_max_length, actual_max_sequence_length) else: max_length = max_sequence_length
if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0]
if prompt_embeds is None: text_inputs = tokenizer( prompt, padding="max_length", max_length=max_length, truncation=True, return_attention_mask=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids if text_input_ids.shape[-1] > actual_max_sequence_length: reprompt = tokenizer.batch_decode(text_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True) text_inputs = tokenizer( reprompt, padding="max_length", max_length=max_length, truncation=True, return_attention_mask=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( text_input_ids, untruncated_ids ): _actual_max_sequence_length = min(tokenizer.model_max_length, actual_max_sequence_length) removed_text = tokenizer.batch_decode(untruncated_ids[:, _actual_max_sequence_length - 1 : -1]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f" {_actual_max_sequence_length} tokens: {removed_text}" ) prompt_attention_mask = text_inputs.attention_mask.to(device) if self.transformer.config.enable_text_attention_mask: prompt_embeds = text_encoder( text_input_ids.to(device), attention_mask=prompt_attention_mask, ) else: prompt_embeds = text_encoder( text_input_ids.to(device) ) prompt_embeds = prompt_embeds[0] prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
bs_embed, seq_len, _ = prompt_embeds.shape # duplicate text embeddings for each generation per prompt, using mps friendly method prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
# get unconditional embeddings for classifier free guidance if do_classifier_free_guidance and negative_prompt_embeds is None: uncond_tokens: List[str] if negative_prompt is None: uncond_tokens = [""] * batch_size elif prompt is not None and type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" f" {type(prompt)}." ) elif isinstance(negative_prompt, str): uncond_tokens = [negative_prompt] elif batch_size != len(negative_prompt): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: uncond_tokens = negative_prompt
max_length = prompt_embeds.shape[1] uncond_input = tokenizer( uncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt", ) uncond_input_ids = uncond_input.input_ids if uncond_input_ids.shape[-1] > actual_max_sequence_length: reuncond_tokens = tokenizer.batch_decode(uncond_input_ids[:, :actual_max_sequence_length], skip_special_tokens=True) uncond_input = tokenizer( reuncond_tokens, padding="max_length", max_length=max_length, truncation=True, return_attention_mask=True, return_tensors="pt", ) uncond_input_ids = uncond_input.input_ids
negative_prompt_attention_mask = uncond_input.attention_mask.to(device) if self.transformer.config.enable_text_attention_mask: negative_prompt_embeds = text_encoder( uncond_input.input_ids.to(device), attention_mask=negative_prompt_attention_mask, ) else: negative_prompt_embeds = text_encoder( uncond_input.input_ids.to(device) ) negative_prompt_embeds = negative_prompt_embeds[0] negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
if do_classifier_free_guidance: # duplicate unconditional embeddings for each generation per prompt, using mps friendly method seq_len = negative_prompt_embeds.shape[1]
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker def run_safety_checker(self, image, device, dtype): if self.safety_checker is None: has_nsfw_concept = None else: if torch.is_tensor(image): feature_extractor_input = self.image_processor.postprocess(image, output_type="pil") else: feature_extractor_input = self.image_processor.numpy_to_pil(image) safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device) image, has_nsfw_concept = self.safety_checker( images=image, clip_input=safety_checker_input.pixel_values.to(dtype) ) return image, has_nsfw_concept
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1]
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) extra_step_kwargs = {} if accepts_eta: extra_step_kwargs["eta"] = eta
# check if the scheduler accepts generator accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: extra_step_kwargs["generator"] = generator return extra_step_kwargs
def check_inputs( self, prompt, height, width, negative_prompt=None, prompt_embeds=None, negative_prompt_embeds=None, prompt_attention_mask=None, negative_prompt_attention_mask=None, prompt_embeds_2=None, negative_prompt_embeds_2=None, prompt_attention_mask_2=None, negative_prompt_attention_mask_2=None, callback_on_step_end_tensor_inputs=None, ): if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
if callback_on_step_end_tensor_inputs is not None and not all( k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs ): raise ValueError( f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" )
if prompt is not None and prompt_embeds is not None: raise ValueError( f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" " only forward one of the two." ) elif prompt is None and prompt_embeds is None: raise ValueError( "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." ) elif prompt is None and prompt_embeds_2 is None: raise ValueError( "Provide either `prompt` or `prompt_embeds_2`. Cannot leave both `prompt` and `prompt_embeds_2` undefined." ) elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
if prompt_embeds is not None and prompt_attention_mask is None: raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
if prompt_embeds_2 is not None and prompt_attention_mask_2 is None: raise ValueError("Must provide `prompt_attention_mask_2` when specifying `prompt_embeds_2`.")
if negative_prompt is not None and negative_prompt_embeds is not None: raise ValueError( f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" f" {negative_prompt_embeds}. Please make sure to only forward one of the two." )
if negative_prompt_embeds is not None and negative_prompt_attention_mask is None: raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
if negative_prompt_embeds_2 is not None and negative_prompt_attention_mask_2 is None: raise ValueError( "Must provide `negative_prompt_attention_mask_2` when specifying `negative_prompt_embeds_2`." ) if prompt_embeds is not None and negative_prompt_embeds is not None: if prompt_embeds.shape != negative_prompt_embeds.shape: raise ValueError( "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" f" {negative_prompt_embeds.shape}." ) if prompt_embeds_2 is not None and negative_prompt_embeds_2 is not None: if prompt_embeds_2.shape != negative_prompt_embeds_2.shape: raise ValueError( "`prompt_embeds_2` and `negative_prompt_embeds_2` must have the same shape when passed directly, but" f" got: `prompt_embeds_2` {prompt_embeds_2.shape} != `negative_prompt_embeds_2`" f" {negative_prompt_embeds_2.shape}." )
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps def get_timesteps(self, num_inference_steps, strength, device): # get the original timestep using init_timestep init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
t_start = max(num_inference_steps - init_timestep, 0) timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
return timesteps, num_inference_steps - t_start
def prepare_mask_latents( self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance, noise_aug_strength ): # resize the mask to latents shape as we concatenate the mask to the latents # we do that before converting to dtype to avoid breaking in case we're using cpu_offload # and half precision if mask is not None: mask = mask.to(device=device, dtype=self.vae.dtype) if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5: bs = 1 new_mask = [] for i in range(0, mask.shape[0], bs): mask_bs = mask[i : i + bs] mask_bs = self.vae.encode(mask_bs)[0] mask_bs = mask_bs.mode() new_mask.append(mask_bs) mask = torch.cat(new_mask, dim = 0) mask = mask * self.vae.config.scaling_factor
else: if mask.shape[1] == 4: mask = mask else: video_length = mask.shape[2] mask = rearrange(mask, "b c f h w -> (b f) c h w") mask = self._encode_vae_image(mask, generator=generator) mask = rearrange(mask, "(b f) c h w -> b c f h w", f=video_length)
if masked_image is not None: masked_image = masked_image.to(device=device, dtype=self.vae.dtype) if self.transformer.config.add_noise_in_inpaint_model: masked_image = add_noise_to_reference_video(masked_image, ratio=noise_aug_strength) if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5: bs = 1 new_mask_pixel_values = [] for i in range(0, masked_image.shape[0], bs): mask_pixel_values_bs = masked_image[i : i + bs] mask_pixel_values_bs = self.vae.encode(mask_pixel_values_bs)[0] mask_pixel_values_bs = mask_pixel_values_bs.mode() new_mask_pixel_values.append(mask_pixel_values_bs) masked_image_latents = torch.cat(new_mask_pixel_values, dim = 0) masked_image_latents = masked_image_latents * self.vae.config.scaling_factor
else: if masked_image.shape[1] == 4: masked_image_latents = masked_image else: video_length = masked_image.shape[2] masked_image = rearrange(masked_image, "b c f h w -> (b f) c h w") masked_image_latents = self._encode_vae_image(masked_image, generator=generator) masked_image_latents = rearrange(masked_image_latents, "(b f) c h w -> b c f h w", f=video_length)
# aligning device to prevent device errors when concating it with the latent model input masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) else: masked_image_latents = None
return mask, masked_image_latents
def prepare_latents( self, batch_size, num_channels_latents, height, width, video_length, dtype, device, generator, latents=None, video=None, timestep=None, is_strength_max=True, return_noise=False, return_video_latents=False, ): if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5: if self.vae.cache_mag_vae: mini_batch_encoder = self.vae.mini_batch_encoder mini_batch_decoder = self.vae.mini_batch_decoder shape = (batch_size, num_channels_latents, int((video_length - 1) // mini_batch_encoder * mini_batch_decoder + 1) if video_length != 1 else 1, height // self.vae_scale_factor, width // self.vae_scale_factor) else: mini_batch_encoder = self.vae.mini_batch_encoder mini_batch_decoder = self.vae.mini_batch_decoder shape = (batch_size, num_channels_latents, int(video_length // mini_batch_encoder * mini_batch_decoder) if video_length != 1 else 1, height // self.vae_scale_factor, width // self.vae_scale_factor) else: shape = (batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor)
if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." )
if return_video_latents or (latents is None and not is_strength_max): video = video.to(device=device, dtype=self.vae.dtype) if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5: bs = 1 new_video = [] for i in range(0, video.shape[0], bs): video_bs = video[i : i + bs] video_bs = self.vae.encode(video_bs)[0] video_bs = video_bs.sample() new_video.append(video_bs) video = torch.cat(new_video, dim = 0) video = video * self.vae.config.scaling_factor
else: if video.shape[1] == 4: video = video else: video_length = video.shape[2] video = rearrange(video, "b c f h w -> (b f) c h w") video = self._encode_vae_image(video, generator=generator) video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length) video_latents = video.repeat(batch_size // video.shape[0], 1, 1, 1, 1) video_latents = video_latents.to(device=device, dtype=dtype)
if latents is None: noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) # if strength is 1. then initialise the latents to noise, else initial to image + noise latents = noise if is_strength_max else self.scheduler.add_noise(video_latents, noise, timestep) # if pure noise then scale the initial latents by the Scheduler's init sigma latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents else: noise = latents.to(device) latents = noise * self.scheduler.init_noise_sigma
# scale the initial noise by the standard deviation required by the scheduler outputs = (latents,)
if return_noise: outputs += (noise,)
if return_video_latents: outputs += (video_latents,)
return outputs
def smooth_output(self, video, mini_batch_encoder, mini_batch_decoder): if video.size()[2] <= mini_batch_encoder: return video prefix_index_before = mini_batch_encoder // 2 prefix_index_after = mini_batch_encoder - prefix_index_before pixel_values = video[:, :, prefix_index_before:-prefix_index_after]
# Encode middle videos latents = self.vae.encode(pixel_values)[0] latents = latents.mode() # Decode middle videos middle_video = self.vae.decode(latents)[0]
video[:, :, prefix_index_before:-prefix_index_after] = (video[:, :, prefix_index_before:-prefix_index_after] + middle_video) / 2 return video
def decode_latents(self, latents): video_length = latents.shape[2] latents = 1 / self.vae.config.scaling_factor * latents if self.vae.quant_conv is None or self.vae.quant_conv.weight.ndim==5: mini_batch_encoder = self.vae.mini_batch_encoder mini_batch_decoder = self.vae.mini_batch_decoder video = self.vae.decode(latents)[0] video = video.clamp(-1, 1) if not self.vae.cache_compression_vae and not self.vae.cache_mag_vae: video = self.smooth_output(video, mini_batch_encoder, mini_batch_decoder).cpu().clamp(-1, 1) else: latents = rearrange(latents, "b c f h w -> (b f) c h w") video = [] for frame_idx in tqdm(range(latents.shape[0])): video.append(self.vae.decode(latents[frame_idx:frame_idx+1]).sample) video = torch.cat(video) video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length) video = (video / 2 + 0.5).clamp(0, 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 video = video.cpu().float().numpy() return video
@property def guidance_scale(self): return self._guidance_scale
@property def guidance_rescale(self): return self._guidance_rescale
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. @property def do_classifier_free_guidance(self): return self._guidance_scale > 1
@property def num_timesteps(self): return self._num_timesteps
@property def interrupt(self): return self._interrupt
def enable_autocast_float8_transformer(self): self.enable_autocast_float8_transformer_flag = True
@torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Union[str, List[str]] = None, video_length: Optional[int] = None, video: Union[torch.FloatTensor] = None, mask_video: Union[torch.FloatTensor] = None, masked_video_latents: Union[torch.FloatTensor] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: Optional[int] = 50, guidance_scale: Optional[float] = 5.0, negative_prompt: Optional[Union[str, List[str]]] = None, num_images_per_prompt: Optional[int] = 1, eta: Optional[float] = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.Tensor] = None, prompt_embeds: Optional[torch.Tensor] = None, prompt_embeds_2: Optional[torch.Tensor] = None, negative_prompt_embeds: Optional[torch.Tensor] = None, negative_prompt_embeds_2: Optional[torch.Tensor] = None, prompt_attention_mask: Optional[torch.Tensor] = None, prompt_attention_mask_2: Optional[torch.Tensor] = None, negative_prompt_attention_mask: Optional[torch.Tensor] = None, negative_prompt_attention_mask_2: Optional[torch.Tensor] = None, output_type: Optional[str] = "latent", return_dict: bool = True, callback_on_step_end: Optional[ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks] ] = None, callback_on_step_end_tensor_inputs: List[str] = ["latents"], guidance_rescale: float = 0.0, original_size: Optional[Tuple[int, int]] = (1024, 1024), target_size: Optional[Tuple[int, int]] = None, crops_coords_top_left: Tuple[int, int] = (0, 0), clip_image: Image = None, clip_apply_ratio: float = 0.40, strength: float = 1.0, noise_aug_strength: float = 0.0563, comfyui_progressbar: bool = False, ): r""" The call function to the pipeline for generation with HunyuanDiT.
Examples: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. video_length (`int`, *optional*): Length of the video to be generated in seconds. This parameter influences the number of frames and continuity of generated content. video (`torch.FloatTensor`, *optional*): A tensor representing an input video, which can be modified depending on the prompts provided. mask_video (`torch.FloatTensor`, *optional*): A tensor to specify areas of the video to be masked (omitted from generation). masked_video_latents (`torch.FloatTensor`, *optional*): Latents from masked portions of the video, utilized during image generation. height (`int`, *optional*): The height in pixels of the generated image or video frames. width (`int`, *optional*): The width in pixels of the generated image or video frames. num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image but slower inference time. This parameter is modulated by `strength`. guidance_scale (`float`, *optional*, defaults to 5.0): A higher guidance scale value encourages the model to generate images closely linked to the text `prompt` at the expense of lower image quality. Guidance scale is effective when `guidance_scale > 1`. negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide what to exclude in image generation. If not defined, you need to provide `negative_prompt_embeds`. This parameter is ignored when not using guidance (`guidance_scale < 1`). num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. eta (`float`, *optional*, defaults to 0.0): A parameter defined in the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies to the [`~schedulers.DDIMScheduler`] and is ignored in other schedulers. It adjusts noise level during the inference process. generator (`torch.Generator` or `List[torch.Generator]`, *optional*): A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) for setting random seeds which helps in making generation deterministic. latents (`torch.Tensor`, *optional*): A pre-computed latent representation which can be used to guide the generation process. prompt_embeds (`torch.Tensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, embeddings are generated from the `prompt` input argument. prompt_embeds_2 (`torch.Tensor`, *optional*): Secondary set of pre-generated text embeddings, useful for advanced prompt weighting. negative_prompt_embeds (`torch.Tensor`, *optional*): Pre-generated negative text embeddings, aiding in fine-tuning what should not be represented in the outputs. If not provided, embeddings are generated from the `negative_prompt` argument. negative_prompt_embeds_2 (`torch.Tensor`, *optional*): Secondary set of pre-generated negative text embeddings for further control. prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask guiding the focus of the model on specific parts of the prompt text. Required when using `prompt_embeds`. prompt_attention_mask_2 (`torch.Tensor`, *optional*): Attention mask for the secondary prompt embedding. negative_prompt_attention_mask (`torch.Tensor`, *optional*): Attention mask for the negative prompt, needed when `negative_prompt_embeds` are used. negative_prompt_attention_mask_2 (`torch.Tensor`, *optional*): Attention mask for the secondary negative prompt embedding. output_type (`str`, *optional*, defaults to `"latent"`): The output format of the generated image. Choose between `PIL.Image` and `np.array` to define how you want the results to be formatted. return_dict (`bool`, *optional*, defaults to `True`): If set to `True`, a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] will be returned; otherwise, a tuple containing the generated images and safety flags will be returned. callback_on_step_end (`Callable[[int, int, Dict], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*): A callback function (or a list of them) that will be executed at the end of each denoising step, allowing for custom processing during generation. callback_on_step_end_tensor_inputs (`List[str]`, *optional*): Specifies which tensor inputs should be included in the callback function. If not defined, all tensor inputs will be passed, facilitating enhanced logging or monitoring of the generation process. guidance_rescale (`float`, *optional*, defaults to 0.0): Rescale parameter for adjusting noise configuration based on guidance rescale. Based on findings from [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). original_size (`Tuple[int, int]`, *optional*, defaults to `(1024, 1024)`): The original dimensions of the image. Used to compute time ids during the generation process. target_size (`Tuple[int, int]`, *optional*): The targeted dimensions of the generated image, also utilized in the time id calculations. crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to `(0, 0)`): Coordinates defining the top left corner of any cropping, utilized while calculating the time ids. clip_image (`Image`, *optional*): An optional image to assist in the generation process. It may be used as an additional visual cue. clip_apply_ratio (`float`, *optional*, defaults to 0.40): Ratio indicating how much influence the clip image should exert over the generated content. strength (`float`, *optional*, defaults to 1.0): Affects the overall styling or quality of the generated output. Values closer to 1 usually provide direct adherence to prompts. comfyui_progressbar (`bool`, *optional*, defaults to `False`): Enables a progress bar in ComfyUI, providing visual feedback during the generation process.
Examples: # Example usage of the function for generating images based on prompts. Returns: [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: Returns either a structured output containing generated images and their metadata when `return_dict` is `True`, or a simpler tuple, where the first element is a list of generated images and the second element indicates if any of them contain "not-safe-for-work" (NSFW) content. """
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
# 0. default height and width height = int(height // 16 * 16) width = int(width // 16 * 16)
# 1. Check inputs. Raise error if not correct self.check_inputs( prompt, height, width, negative_prompt, prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask, prompt_embeds_2, negative_prompt_embeds_2, prompt_attention_mask_2, negative_prompt_attention_mask_2, callback_on_step_end_tensor_inputs, ) self._guidance_scale = guidance_scale self._guidance_rescale = guidance_rescale self._interrupt = False
# 2. Define call parameters if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0]
device = self._execution_device # 3. Encode input prompt ( prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask, ) = self.encode_prompt( prompt=prompt, device=device, dtype=self.transformer.dtype, num_images_per_prompt=num_images_per_prompt, do_classifier_free_guidance=self.do_classifier_free_guidance, negative_prompt=negative_prompt, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, prompt_attention_mask=prompt_attention_mask, negative_prompt_attention_mask=negative_prompt_attention_mask, text_encoder_index=0, ) ( prompt_embeds_2, negative_prompt_embeds_2, prompt_attention_mask_2, negative_prompt_attention_mask_2, ) = self.encode_prompt( prompt=prompt, device=device, dtype=self.transformer.dtype, num_images_per_prompt=num_images_per_prompt, do_classifier_free_guidance=self.do_classifier_free_guidance, negative_prompt=negative_prompt, prompt_embeds=prompt_embeds_2, negative_prompt_embeds=negative_prompt_embeds_2, prompt_attention_mask=prompt_attention_mask_2, negative_prompt_attention_mask=negative_prompt_attention_mask_2, text_encoder_index=1, ) torch.cuda.empty_cache()
# 4. set timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps, num_inference_steps = self.get_timesteps( num_inference_steps=num_inference_steps, strength=strength, device=device ) if comfyui_progressbar: from comfy.utils import ProgressBar pbar = ProgressBar(num_inference_steps + 3) # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise is_strength_max = strength == 1.0
if video is not None: video_length = video.shape[2] init_video = self.image_processor.preprocess(rearrange(video, "b c f h w -> (b f) c h w"), height=height, width=width) init_video = init_video.to(dtype=torch.float32) init_video = rearrange(init_video, "(b f) c h w -> b c f h w", f=video_length) else: init_video = None
# Prepare latent variables num_channels_latents = self.vae.config.latent_channels num_channels_transformer = self.transformer.config.in_channels return_image_latents = num_channels_transformer == num_channels_latents
# 5. Prepare latents. latents_outputs = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, video_length, prompt_embeds.dtype, device, generator, latents, video=init_video, timestep=latent_timestep, is_strength_max=is_strength_max, return_noise=True, return_video_latents=return_image_latents, ) if return_image_latents: latents, noise, image_latents = latents_outputs else: latents, noise = latents_outputs
if comfyui_progressbar: pbar.update(1)
# 6. Prepare clip latents if it needs. if clip_image is not None and self.transformer.enable_clip_in_inpaint: inputs = self.clip_image_processor(images=clip_image, return_tensors="pt") inputs["pixel_values"] = inputs["pixel_values"].to(latents.device, dtype=latents.dtype) clip_encoder_hidden_states = self.clip_image_encoder(**inputs).last_hidden_state[:, 1:] clip_encoder_hidden_states_neg = torch.zeros( [ batch_size, int(self.clip_image_encoder.config.image_size / self.clip_image_encoder.config.patch_size) ** 2, int(self.clip_image_encoder.config.hidden_size) ] ).to(latents.device, dtype=latents.dtype)
clip_attention_mask = torch.ones([batch_size, self.transformer.n_query]).to(latents.device, dtype=latents.dtype) clip_attention_mask_neg = torch.zeros([batch_size, self.transformer.n_query]).to(latents.device, dtype=latents.dtype)
clip_encoder_hidden_states_input = torch.cat([clip_encoder_hidden_states_neg, clip_encoder_hidden_states]) if self.do_classifier_free_guidance else clip_encoder_hidden_states clip_attention_mask_input = torch.cat([clip_attention_mask_neg, clip_attention_mask]) if self.do_classifier_free_guidance else clip_attention_mask
elif clip_image is None and num_channels_transformer != num_channels_latents and self.transformer.enable_clip_in_inpaint: clip_encoder_hidden_states = torch.zeros( [ batch_size, int(self.clip_image_encoder.config.image_size / self.clip_image_encoder.config.patch_size) ** 2, int(self.clip_image_encoder.config.hidden_size) ] ).to(latents.device, dtype=latents.dtype)
clip_attention_mask = torch.zeros([batch_size, self.transformer.n_query]) clip_attention_mask = clip_attention_mask.to(latents.device, dtype=latents.dtype)
clip_encoder_hidden_states_input = torch.cat([clip_encoder_hidden_states] * 2) if self.do_classifier_free_guidance else clip_encoder_hidden_states clip_attention_mask_input = torch.cat([clip_attention_mask] * 2) if self.do_classifier_free_guidance else clip_attention_mask
else: clip_encoder_hidden_states_input = None clip_attention_mask_input = None if comfyui_progressbar: pbar.update(1)
# 7. Prepare inpaint latents if it needs. if mask_video is not None: if (mask_video == 255).all(): # Use zero latents if we want to t2v. if self.transformer.resize_inpaint_mask_directly: mask_latents = torch.zeros_like(latents)[:, :1].to(latents.device, latents.dtype) else: mask_latents = torch.zeros_like(latents).to(latents.device, latents.dtype) masked_video_latents = torch.zeros_like(latents).to(latents.device, latents.dtype)
mask_input = torch.cat([mask_latents] * 2) if self.do_classifier_free_guidance else mask_latents masked_video_latents_input = ( torch.cat([masked_video_latents] * 2) if self.do_classifier_free_guidance else masked_video_latents ) inpaint_latents = torch.cat([mask_input, masked_video_latents_input], dim=1).to(latents.dtype) else: # Prepare mask latent variables video_length = video.shape[2] mask_condition = self.mask_processor.preprocess(rearrange(mask_video, "b c f h w -> (b f) c h w"), height=height, width=width) mask_condition = mask_condition.to(dtype=torch.float32) mask_condition = rearrange(mask_condition, "(b f) c h w -> b c f h w", f=video_length)
if num_channels_transformer != num_channels_latents: mask_condition_tile = torch.tile(mask_condition, [1, 3, 1, 1, 1]) if masked_video_latents is None: masked_video = init_video * (mask_condition_tile < 0.5) + torch.ones_like(init_video) * (mask_condition_tile > 0.5) * -1 else: masked_video = masked_video_latents if self.transformer.resize_inpaint_mask_directly: _, masked_video_latents = self.prepare_mask_latents( None, masked_video, batch_size, height, width, prompt_embeds.dtype, device, generator, self.do_classifier_free_guidance, noise_aug_strength=noise_aug_strength, ) mask_latents = resize_mask(1 - mask_condition, masked_video_latents, self.vae.cache_mag_vae) mask_latents = mask_latents.to(masked_video_latents.device) * self.vae.config.scaling_factor else: mask_latents, masked_video_latents = self.prepare_mask_latents( mask_condition_tile, masked_video, batch_size, height, width, prompt_embeds.dtype, device, generator, self.do_classifier_free_guidance, noise_aug_strength=noise_aug_strength, ) mask_input = torch.cat([mask_latents] * 2) if self.do_classifier_free_guidance else mask_latents masked_video_latents_input = ( torch.cat([masked_video_latents] * 2) if self.do_classifier_free_guidance else masked_video_latents ) inpaint_latents = torch.cat([mask_input, masked_video_latents_input], dim=1).to(latents.dtype) else: inpaint_latents = None
mask = torch.tile(mask_condition, [1, num_channels_latents, 1, 1, 1]) mask = F.interpolate(mask, size=latents.size()[-3:], mode='trilinear', align_corners=True).to(latents.device, latents.dtype) else: if num_channels_transformer != num_channels_latents: mask = torch.zeros_like(latents).to(latents.device, latents.dtype) masked_video_latents = torch.zeros_like(latents).to(latents.device, latents.dtype)
mask_input = torch.cat([mask] * 2) if self.do_classifier_free_guidance else mask masked_video_latents_input = ( torch.cat([masked_video_latents] * 2) if self.do_classifier_free_guidance else masked_video_latents ) inpaint_latents = torch.cat([mask_input, masked_video_latents_input], dim=1).to(latents.dtype) else: mask = torch.zeros_like(init_video[:, :1]) mask = torch.tile(mask, [1, num_channels_latents, 1, 1, 1]) mask = F.interpolate(mask, size=latents.size()[-3:], mode='trilinear', align_corners=True).to(latents.device, latents.dtype)
inpaint_latents = None if comfyui_progressbar: pbar.update(1)
# Check that sizes of mask, masked image and latents match if num_channels_transformer != num_channels_latents: num_channels_mask = mask_latents.shape[1] num_channels_masked_image = masked_video_latents.shape[1] if num_channels_latents + num_channels_mask + num_channels_masked_image != self.transformer.config.in_channels: raise ValueError( f"Incorrect configuration settings! The config of `pipeline.transformer`: {self.transformer.config} expects" f" {self.transformer.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of" " `pipeline.transformer` or your `mask_image` or `image` input." )
# 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
# 9 create image_rotary_emb, style embedding & time ids grid_height = height // 8 // self.transformer.config.patch_size grid_width = width // 8 // self.transformer.config.patch_size if self.transformer.config.get("time_position_encoding_type", "2d_rope") == "3d_rope": base_size_width = 720 // 8 // self.transformer.config.patch_size base_size_height = 480 // 8 // self.transformer.config.patch_size
grid_crops_coords = get_resize_crop_region_for_grid( (grid_height, grid_width), base_size_width, base_size_height ) image_rotary_emb = get_3d_rotary_pos_embed( self.transformer.config.attention_head_dim, grid_crops_coords, grid_size=(grid_height, grid_width), temporal_size=latents.size(2), use_real=True, ) else: base_size = 512 // 8 // self.transformer.config.patch_size grid_crops_coords = get_resize_crop_region_for_grid( (grid_height, grid_width), base_size, base_size ) image_rotary_emb = get_2d_rotary_pos_embed( self.transformer.config.attention_head_dim, grid_crops_coords, (grid_height, grid_width) )
# Get other hunyuan params style = torch.tensor([0], device=device)
target_size = target_size or (height, width) add_time_ids = list(original_size + target_size + crops_coords_top_left) add_time_ids = torch.tensor([add_time_ids], dtype=prompt_embeds.dtype)
if self.do_classifier_free_guidance: prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask]) prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2]) prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2]) add_time_ids = torch.cat([add_time_ids] * 2, dim=0) style = torch.cat([style] * 2, dim=0)
prompt_embeds = prompt_embeds.to(device=device) prompt_attention_mask = prompt_attention_mask.to(device=device) prompt_embeds_2 = prompt_embeds_2.to(device=device) prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device) add_time_ids = add_time_ids.to(dtype=prompt_embeds.dtype, device=device).repeat( batch_size * num_images_per_prompt, 1 ) style = style.to(device=device).repeat(batch_size * num_images_per_prompt)
torch.cuda.empty_cache() if self.enable_autocast_float8_transformer_flag: origin_weight_dtype = self.transformer.dtype self.transformer = self.transformer.to(torch.float8_e4m3fn) # 10. Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order self._num_timesteps = len(timesteps) with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): if self.interrupt: continue
# expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
if i < len(timesteps) * (1 - clip_apply_ratio) and clip_encoder_hidden_states_input is not None: clip_encoder_hidden_states_actual_input = torch.zeros_like(clip_encoder_hidden_states_input) clip_attention_mask_actual_input = torch.zeros_like(clip_attention_mask_input) else: clip_encoder_hidden_states_actual_input = clip_encoder_hidden_states_input clip_attention_mask_actual_input = clip_attention_mask_input # expand scalar t to 1-D tensor to match the 1st dim of latent_model_input t_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to( dtype=latent_model_input.dtype )
# predict the noise residual noise_pred = self.transformer( latent_model_input, t_expand, encoder_hidden_states=prompt_embeds, text_embedding_mask=prompt_attention_mask, encoder_hidden_states_t5=prompt_embeds_2, text_embedding_mask_t5=prompt_attention_mask_2, image_meta_size=add_time_ids, style=style, image_rotary_emb=image_rotary_emb, inpaint_latents=inpaint_latents, clip_encoder_hidden_states=clip_encoder_hidden_states_actual_input, clip_attention_mask=clip_attention_mask_actual_input, return_dict=False, )[0] if noise_pred.size()[1] != self.vae.config.latent_channels: noise_pred, _ = noise_pred.chunk(2, dim=1)
# perform guidance if self.do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
if self.do_classifier_free_guidance and guidance_rescale > 0.0: # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
# compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
if num_channels_transformer == 4: init_latents_proper = image_latents init_mask = mask if i < len(timesteps) - 1: noise_timestep = timesteps[i + 1] init_latents_proper = self.scheduler.add_noise( init_latents_proper, noise, torch.tensor([noise_timestep]) ) latents = (1 - init_mask) * init_latents_proper + init_mask * latents
if callback_on_step_end is not None: callback_kwargs = {} for k in callback_on_step_end_tensor_inputs: callback_kwargs[k] = locals()[k] callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
latents = callback_outputs.pop("latents", latents) prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) prompt_embeds_2 = callback_outputs.pop("prompt_embeds_2", prompt_embeds_2) negative_prompt_embeds_2 = callback_outputs.pop( "negative_prompt_embeds_2", negative_prompt_embeds_2 )
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update()
if XLA_AVAILABLE: xm.mark_step()
if comfyui_progressbar: pbar.update(1)
if self.enable_autocast_float8_transformer_flag: self.transformer = self.transformer.to("cpu", origin_weight_dtype)
torch.cuda.empty_cache() # Post-processing video = self.decode_latents(latents)
# Convert to tensor if output_type == "latent": video = torch.from_numpy(video)
# Offload all models self.maybe_free_model_hooks()
if not return_dict: return video
return EasyAnimatePipelineOutput(videos=video)16 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565740 unmodified lines989910010110210310410515 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514623 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012029 unmodified lines2122132142152162172182192202212222232242252262272282292302312322332341 unmodified line2362372382392402412422432442452462472481 unmodified line25025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828984 unmodified lines37437537637737837938038144 unmodified lines42642742842943043143243343443543643743843944044144244344435 unmodified lines48048148248348448548644 unmodified lines5315325335345355365379 unmodified lines54754854955055155255312 unmodified lines566567568569570571572103 unmodified lines67667767867968068168268367 unmodified lines75175275375475575675775875976076176276330 unmodified lines79479579679779879980080180280380433 unmodified lines83883984084184284383 unmodified lines92792892993093193270 unmodified lines1003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410359 unmodified lines104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671 unmodified line10691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111994 unmodified lines1214121512161217121812191220122112221223122412251226122712281229123023 unmodified lines12541255125612571258125912604 unmodified lines126512661267126812691270127113 unmodified lines1285128612871288128912901291114 unmodified lines140614071408140914101411141214131414141514161417141847 unmodified lines1466146714681469147014711472147314741475147633 unmodified lines151015111512151315141515304 unmodified lines182018211822182318241825182618271828182918301831183242 unmodified lines1875187618771878187918801881188218831884188516 unmodified linesfrom diffusers import (AutoencoderKL, DDIMScheduler,DPMSolverMultistepScheduler,EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,PNDMScheduler)from diffusers.utils.import_utils import is_xformers_availablefrom omegaconf import OmegaConffrom PIL import Imagefrom safetensors import safe_openfrom transformers import (BertModel, BertTokenizer, CLIPImageProcessor,CLIPVisionModelWithProjection, T5Tokenizer,T5EncoderModel, T5Tokenizer)from easyanimate.data.bucket_sampler import ASPECT_RATIO_512, get_closest_ratiofrom easyanimate.models import (name_to_autoencoder_magvit,name_to_transformer3d)from easyanimate.models.autoencoder_magvit import AutoencoderKLMagvitfrom easyanimate.models.transformer3d import (HunyuanTransformer3DModel,Transformer3DModel)from easyanimate.pipeline.pipeline_easyanimate import EasyAnimatePipelinefrom easyanimate.pipeline.pipeline_easyanimate_inpaint import \EasyAnimateInpaintPipelinefrom easyanimate.pipeline.pipeline_easyanimate_multi_text_encoder import \EasyAnimatePipeline_Multi_Text_Encoderfrom easyanimate.pipeline.pipeline_easyanimate_multi_text_encoder_inpaint import \EasyAnimatePipeline_Multi_Text_Encoder_Inpaintfrom easyanimate.utils.lora_utils import merge_lora, unmerge_lorafrom easyanimate.utils.utils import (get_image_to_video_latent, get_video_to_video_latent,get_width_and_height_from_image_and_base_resolution, save_videos_grid)from easyanimate.utils.fp8_optimization import convert_weight_dtype_wrapperscheduler_dict = {"Euler": EulerDiscreteScheduler,"Euler A": EulerAncestralDiscreteScheduler,"DPM++": DPMSolverMultistepScheduler,"PNDM": PNDMScheduler,"DDIM": DDIMScheduler,}gradio_version = pkg_resources.get_distribution("gradio").versiongradio_version_is_above_4 = True if int(gradio_version.split('.')[0]) >= 4 else False40 unmodified linesself.GPU_memory_mode = GPU_memory_modeself.weight_dtype = weight_dtypeself.edition = "v5"self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v5_magvit_multi_text_encoder.yaml"))def refresh_diffusion_transformer(self):self.diffusion_transformer_list = sorted(glob(os.path.join(self.diffusion_transformer_dir, "*/")))15 unmodified linesif edition == "v1":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v1_motion_module.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=True), gr.update(visible=True), \gr.update(value=512, minimum=384, maximum=704, step=32), \gr.update(value=512, minimum=384, maximum=704, step=32), gr.update(value=80, minimum=40, maximum=80, step=1)elif edition == "v2":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v2_magvit_motion_module.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=144, minimum=9, maximum=144, step=9)elif edition == "v3":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v3_slicevae_motion_module.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=144, minimum=8, maximum=144, step=8)elif edition == "v4":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v4_slicevae_multi_text_encoder.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=144, minimum=8, maximum=144, step=8)elif edition == "v5":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v5_magvit_multi_text_encoder.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=49, minimum=1, maximum=49, step=4)23 unmodified linesself.transformer = Choosen_Transformer3DModel.from_pretrained_2d(diffusion_transformer_dropdown,subfolder="transformer",transformer_additional_kwargs=transformer_additional_kwargs).to(self.weight_dtype)if self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):tokenizer = BertTokenizer.from_pretrained(diffusion_transformer_dropdown, subfolder="tokenizer")tokenizer_2 = T5Tokenizer.from_pretrained(diffusion_transformer_dropdown, subfolder="tokenizer_2")else:tokenizer = T5Tokenizer.from_pretrained(diffusion_transformer_dropdown, subfolder="tokenizer")tokenizer_2 = Noneif self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):text_encoder = BertModel.from_pretrained(diffusion_transformer_dropdown, subfolder="text_encoder", torch_dtype=self.weight_dtype)text_encoder_2 = T5EncoderModel.from_pretrained(diffusion_transformer_dropdown, subfolder="text_encoder_2", torch_dtype=self.weight_dtype)else:text_encoder = T5EncoderModel.from_pretrained(diffusion_transformer_dropdown, subfolder="text_encoder", torch_dtype=self.weight_dtype)text_encoder_2 = None# Get pipeline9 unmodified linesclip_image_processor = None# Get SchedulerChoosen_Scheduler = scheduler_dict = {"Euler": EulerDiscreteScheduler,"Euler A": EulerAncestralDiscreteScheduler,"DPM++": DPMSolverMultistepScheduler,"PNDM": PNDMScheduler,"DDIM": DDIMScheduler,}["Euler"]scheduler = Choosen_Scheduler.from_pretrained(diffusion_transformer_dropdown,subfolder="scheduler")if self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):if self.transformer.config.in_channels != self.vae.config.latent_channels:self.pipeline = EasyAnimatePipeline_Multi_Text_Encoder_Inpaint.from_pretrained(diffusion_transformer_dropdown,text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,1 unmodified linevae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype,clip_image_encoder=clip_image_encoder,clip_image_processor=clip_image_processor,)else:self.pipeline = EasyAnimatePipeline_Multi_Text_Encoder.from_pretrained(diffusion_transformer_dropdown,text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,1 unmodified linevae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype)else:if self.transformer.config.in_channels != self.vae.config.latent_channels:self.pipeline = EasyAnimateInpaintPipeline(diffusion_transformer_dropdown,text_encoder=text_encoder,tokenizer=tokenizer,vae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype,clip_image_encoder=clip_image_encoder,clip_image_processor=clip_image_processor,)else:self.pipeline = EasyAnimatePipeline(diffusion_transformer_dropdown,text_encoder=text_encoder,tokenizer=tokenizer,vae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype)if self.GPU_memory_mode == "sequential_cpu_offload":self.pipeline.enable_sequential_cpu_offload()elif self.GPU_memory_mode == "model_cpu_offload_and_qfloat8":self.pipeline.enable_model_cpu_offload()self.pipeline.enable_autocast_float8_transformer()convert_weight_dtype_wrapper(self.pipeline.transformer, self.weight_dtype)else:self.GPU_memory_mode.enable_model_cpu_offload()print("Update diffusion transformer done")return gr.update()84 unmodified linesif self.base_model_path != base_model_dropdown:self.update_base_model(base_model_dropdown)if self.lora_model_path != lora_model_dropdown:print("Update lora model")self.update_lora_model(lora_model_dropdown)if control_video is not None and self.model_type == "Inpaint":44 unmodified lineselse:raise gr.Error(f"If specifying the ending image of the video, please specify a starting image of the video.")fps = {"v1": 12, "v2": 24, "v3": 24, "v4": 24, "v5": 8}[self.edition]is_image = True if generation_method == "Image Generation" else Falseif is_xformers_available() and not self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False): self.transformer.enable_xformers_memory_efficient_attention()self.pipeline.scheduler = scheduler_dict[sampler_dropdown].from_config(self.pipeline.scheduler.config)if self.lora_model_path != "none":# lora partself.pipeline = merge_lora(self.pipeline, self.lora_model_path, multiplier=lora_alpha_slider)if int(seed_textbox) != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox))else: seed_textbox = np.random.randint(0, 1e10)generator = torch.Generator(device="cuda").manual_seed(int(seed_textbox))try:if self.model_type == "Inpaint":35 unmodified linesvideo = input_video,mask_video = input_video_mask,strength = 1,).videosif init_frames != 0:mix_ratio = torch.from_numpy(44 unmodified linesvideo = input_video,mask_video = input_video_mask,strength = strength,).videoselse:if self.vae.cache_mag_vae:length_slider = int((length_slider - 1) // self.vae.mini_batch_encoder * self.vae.mini_batch_encoder) + 19 unmodified linesheight = height_slider,video_length = length_slider if not is_image else 1,generator = generator).videoselse:if self.vae.cache_mag_vae:length_slider = int((length_slider - 1) // self.vae.mini_batch_encoder * self.vae.mini_batch_encoder) + 112 unmodified linesgenerator = generator,control_video = input_video,).videosexcept Exception as e:gc.collect()torch.cuda.empty_cache()103 unmodified lineswith gr.Row():easyanimate_edition_dropdown = gr.Dropdown(label="The config of EasyAnimate Edition (EasyAnimate版本配置)",choices=["v1", "v2", "v3", "v4", "v5"],value="v5",interactive=True,)gr.Markdown(67 unmodified lines""")prompt_textbox = gr.Textbox(label="Prompt (正向提示词)", lines=2, value="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.")negative_prompt_textbox = gr.Textbox(label="Negative prompt (负向提示词)", lines=2, value="Blurring, mutation, deformation, distortion, dark and solid, comics." )with gr.Row():with gr.Column():with gr.Row():sampler_dropdown = gr.Dropdown(label="Sampling method (采样器种类)", choices=list(scheduler_dict.keys()), value=list(scheduler_dict.keys())[0])sample_step_slider = gr.Slider(label="Sampling steps (生成步数)", value=50, minimum=10, maximum=100, step=1)resize_method = gr.Radio(30 unmodified linestemplate_gallery_path = ["asset/1.png", "asset/2.png", "asset/3.png", "asset/4.png", "asset/5.png"]def select_template(evt: gr.SelectData):text = {"asset/1.png": "The dog is shaking head. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/2.png": "a sailboat sailing in rough seas with a dramatic sunset. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/3.png": "a beautiful woman with long hair and a dress blowing in the wind. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/4.png": "a man in an astronaut suit playing a guitar. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/5.png": "fireworks display over night city. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",}[template_gallery_path[evt.index]]return template_gallery_path[evt.index], text33 unmodified linesgr.Markdown("""Demo pose control video can be downloaded here [URL](https://pai-aigc-photog.oss-cn-hangzhou.aliyuncs.com/cogvideox_fun/asset/v1.1/pose.mp4).""")control_video = gr.Video(83 unmodified linesdiffusion_transformer_dropdown,motion_module_dropdown,motion_module_refresh_button,width_slider,height_slider,length_slider,70 unmodified linesself.transformer = Choosen_Transformer3DModel.from_pretrained_2d(model_name,subfolder="transformer",transformer_additional_kwargs=transformer_additional_kwargs).to(self.weight_dtype)if self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):tokenizer = BertTokenizer.from_pretrained(model_name, subfolder="tokenizer")tokenizer_2 = T5Tokenizer.from_pretrained(model_name, subfolder="tokenizer_2")else:tokenizer = T5Tokenizer.from_pretrained(model_name, subfolder="tokenizer")tokenizer_2 = Noneif self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):text_encoder = BertModel.from_pretrained(model_name, subfolder="text_encoder", torch_dtype=self.weight_dtype)text_encoder_2 = T5EncoderModel.from_pretrained(model_name, subfolder="text_encoder_2", torch_dtype=self.weight_dtype)else:text_encoder = T5EncoderModel.from_pretrained(model_name, subfolder="text_encoder", torch_dtype=self.weight_dtype)text_encoder_2 = None# Get pipeline9 unmodified linesclip_image_processor = None# Get SchedulerChoosen_Scheduler = scheduler_dict = {"Euler": EulerDiscreteScheduler,"Euler A": EulerAncestralDiscreteScheduler,"DPM++": DPMSolverMultistepScheduler,"PNDM": PNDMScheduler,"DDIM": DDIMScheduler,}["Euler"]scheduler = Choosen_Scheduler.from_pretrained(model_name,subfolder="scheduler")if self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):if self.transformer.config.in_channels != self.vae.config.latent_channels:self.pipeline = EasyAnimatePipeline_Multi_Text_Encoder_Inpaint.from_pretrained(model_name,text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,1 unmodified linevae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype,clip_image_encoder=clip_image_encoder,clip_image_processor=clip_image_processor,)else:self.pipeline = EasyAnimatePipeline_Multi_Text_Encoder.from_pretrained(model_name,text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,tokenizer_2=tokenizer_2,vae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype)else:if self.transformer.config.in_channels != self.vae.config.latent_channels:self.pipeline = EasyAnimateInpaintPipeline(model_name,text_encoder=text_encoder,tokenizer=tokenizer,vae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype,clip_image_encoder=clip_image_encoder,clip_image_processor=clip_image_processor,)else:self.pipeline = EasyAnimatePipeline(model_name,text_encoder=text_encoder,tokenizer=tokenizer,vae=self.vae,transformer=self.transformer,scheduler=scheduler,torch_dtype=self.weight_dtype)if GPU_memory_mode == "sequential_cpu_offload":self.pipeline.enable_sequential_cpu_offload()elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":self.pipeline.enable_model_cpu_offload()self.pipeline.enable_autocast_float8_transformer()convert_weight_dtype_wrapper(self.pipeline.transformer, weight_dtype)else:GPU_memory_mode.enable_model_cpu_offload()94 unmodified lineselse:raise gr.Error(f"If specifying the ending image of the video, please specify a starting image of the video.")fps = {"v1": 12, "v2": 24, "v3": 24, "v4": 24, "v5": 8}[self.edition]is_image = True if generation_method == "Image Generation" else Falseself.pipeline.scheduler = scheduler_dict[sampler_dropdown].from_config(self.pipeline.scheduler.config)if self.lora_model_path != "none":# lora partself.pipeline = merge_lora(self.pipeline, self.lora_model_path, multiplier=lora_alpha_slider)if int(seed_textbox) != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox))else: seed_textbox = np.random.randint(0, 1e10)generator = torch.Generator(device="cuda").manual_seed(int(seed_textbox))try:if self.model_type == "Inpaint":23 unmodified linesvideo = input_video,mask_video = input_video_mask,strength = strength,).videoselse:sample = self.pipeline(prompt_textbox,4 unmodified linesheight = height_slider,video_length = length_slider if not is_image else 1,generator = generator).videoselse:if self.vae.cache_mag_vae:length_slider = int((length_slider - 1) // self.vae.mini_batch_encoder * self.vae.mini_batch_encoder) + 113 unmodified linesgenerator = generator,control_video = input_video,).videosexcept Exception as e:gc.collect()torch.cuda.empty_cache()114 unmodified lines""")prompt_textbox = gr.Textbox(label="Prompt (正向提示词)", lines=2, value="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.")negative_prompt_textbox = gr.Textbox(label="Negative prompt (负向提示词)", lines=2, value="Blurring, mutation, deformation, distortion, dark and solid, comics." )with gr.Row():with gr.Column():with gr.Row():sampler_dropdown = gr.Dropdown(label="Sampling method (采样器种类)", choices=list(scheduler_dict.keys()), value=list(scheduler_dict.keys())[0])sample_step_slider = gr.Slider(label="Sampling steps (生成步数)", value=50, minimum=10, maximum=50, step=1, interactive=False)if edition == "v1":47 unmodified linestemplate_gallery_path = ["asset/1.png", "asset/2.png", "asset/3.png", "asset/4.png", "asset/5.png"]def select_template(evt: gr.SelectData):text = {"asset/1.png": "The dog is shaking head. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/2.png": "a sailboat sailing in rough seas with a dramatic sunset. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/3.png": "a beautiful woman with long hair and a dress blowing in the wind. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/4.png": "a man in an astronaut suit playing a guitar. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/5.png": "fireworks display over night city. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",}[template_gallery_path[evt.index]]return template_gallery_path[evt.index], text33 unmodified linesgr.Markdown("""Demo pose control video can be downloaded here [URL](https://pai-aigc-photog.oss-cn-hangzhou.aliyuncs.com/cogvideox_fun/asset/v1.1/pose.mp4).""")control_video = gr.Video(304 unmodified lines""")prompt_textbox = gr.Textbox(label="Prompt", lines=2, value="A young woman with beautiful and clear eyes and blonde hair standing and white dress in a forest wearing a crown. She seems to be lost in thought, and the camera focuses on her face. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.")negative_prompt_textbox = gr.Textbox(label="Negative prompt", lines=2, value="Blurring, mutation, deformation, distortion, dark and solid, comics." )with gr.Row():with gr.Column():with gr.Row():sampler_dropdown = gr.Dropdown(label="Sampling method", choices=list(scheduler_dict.keys()), value=list(scheduler_dict.keys())[0])sample_step_slider = gr.Slider(label="Sampling steps", value=40, minimum=10, maximum=40, step=1, interactive=False)if edition == "v1":42 unmodified linestemplate_gallery_path = ["asset/1.png", "asset/2.png", "asset/3.png", "asset/4.png", "asset/5.png"]def select_template(evt: gr.SelectData):text = {"asset/1.png": "The dog is shaking head. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/2.png": "a sailboat sailing in rough seas with a dramatic sunset. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/3.png": "a beautiful woman with long hair and a dress blowing in the wind. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/4.png": "a man in an astronaut suit playing a guitar. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.","asset/5.png": "fireworks display over night city. The video is of high quality, and the view is very clear. High quality, masterpiece, best quality, highres, ultra-detailed, fantastic.",}[template_gallery_path[evt.index]]return template_gallery_path[evt.index], text16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575840 unmodified lines9910010110210310410510615 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715823 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352369 unmodified lines2462472482492502512522532542552562572582592602612622631 unmodified line2652662672682692702712722732742751 unmodified line27727827928028128228328428528628728828929029129229329429529629729829930030184 unmodified lines38638738838939039139239339439544 unmodified lines44044144244344444544644744844945045145245345445545645745845946035 unmodified lines49649749849950050150244 unmodified lines5475485495505515525539 unmodified lines56356456556656756856912 unmodified lines582583584585586587588103 unmodified lines69269369469569669769869967 unmodified lines76776876977077177277377477577677777877978078178278378478578678778830 unmodified lines81982082182282382482582682782882933 unmodified lines86386486586686786886983 unmodified lines95395495595695795895970 unmodified lines10301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310849 unmodified lines1094109510961097109810991100110111021103110411051106110711081109111011111 unmodified line111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114694 unmodified lines1241124212431244124512461247124812491250125112521253125412551256125723 unmodified lines12811282128312841285128612874 unmodified lines129212931294129512961297129813 unmodified lines1312131313141315131613171318114 unmodified lines143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146047 unmodified lines1508150915101511151215131514151515161517151833 unmodified lines1552155315541555155615571558304 unmodified lines186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189042 unmodified lines1933193419351936193719381939194019411942194316 unmodified linesfrom diffusers import (AutoencoderKL, DDIMScheduler,DPMSolverMultistepScheduler,EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,FlowMatchEulerDiscreteScheduler, PNDMScheduler)from diffusers.utils.import_utils import is_xformers_availablefrom omegaconf import OmegaConffrom PIL import Imagefrom safetensors import safe_openfrom transformers import (BertModel, BertTokenizer, CLIPImageProcessor,CLIPVisionModelWithProjection, Qwen2Tokenizer,Qwen2VLForConditionalGeneration, T5EncoderModel,T5Tokenizer)from ..data.bucket_sampler import ASPECT_RATIO_512, get_closest_ratiofrom ..models import (name_to_autoencoder_magvit,name_to_transformer3d)from ..pipeline.pipeline_easyanimate import \EasyAnimatePipelinefrom ..pipeline.pipeline_easyanimate_control import \EasyAnimateControlPipelinefrom ..pipeline.pipeline_easyanimate_inpaint import \EasyAnimateInpaintPipelinefrom ..utils.fp8_optimization import convert_weight_dtype_wrapperfrom ..utils.lora_utils import merge_lora, unmerge_lorafrom ..utils.utils import (get_image_to_video_latent, get_video_to_video_latent,get_width_and_height_from_image_and_base_resolution, save_videos_grid)ddpm_scheduler_dict = {"Euler": EulerDiscreteScheduler,"Euler A": EulerAncestralDiscreteScheduler,"DPM++": DPMSolverMultistepScheduler,"PNDM": PNDMScheduler,"DDIM": DDIMScheduler,}flow_scheduler_dict = {"Flow": FlowMatchEulerDiscreteScheduler,}all_cheduler_dict = {**ddpm_scheduler_dict, **flow_scheduler_dict}gradio_version = pkg_resources.get_distribution("gradio").versiongradio_version_is_above_4 = True if int(gradio_version.split('.')[0]) >= 4 else False40 unmodified linesself.GPU_memory_mode = GPU_memory_modeself.weight_dtype = weight_dtypeself.edition = "v5.1"self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v5.1_magvit_qwen.yaml"))def refresh_diffusion_transformer(self):self.diffusion_transformer_list = sorted(glob(os.path.join(self.diffusion_transformer_dir, "*/")))15 unmodified linesif edition == "v1":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v1_motion_module.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=True), gr.update(visible=True), \gr.update(choices=list(ddpm_scheduler_dict.keys()), value=list(ddpm_scheduler_dict.keys())[0]), \gr.update(value=512, minimum=384, maximum=704, step=32), \gr.update(value=512, minimum=384, maximum=704, step=32), gr.update(value=80, minimum=40, maximum=80, step=1)elif edition == "v2":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v2_magvit_motion_module.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(choices=list(ddpm_scheduler_dict.keys()), value=list(ddpm_scheduler_dict.keys())[0]), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=144, minimum=9, maximum=144, step=9)elif edition == "v3":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v3_slicevae_motion_module.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(choices=list(ddpm_scheduler_dict.keys()), value=list(ddpm_scheduler_dict.keys())[0]), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=144, minimum=8, maximum=144, step=8)elif edition == "v4":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v4_slicevae_multi_text_encoder.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(choices=list(ddpm_scheduler_dict.keys()), value=list(ddpm_scheduler_dict.keys())[0]), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=144, minimum=8, maximum=144, step=8)elif edition == "v5":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v5_magvit_multi_text_encoder.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(choices=list(ddpm_scheduler_dict.keys()), value=list(ddpm_scheduler_dict.keys())[0]), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=49, minimum=1, maximum=49, step=4)elif edition == "v5.1":self.inference_config = OmegaConf.load(os.path.join(self.config_dir, "easyanimate_video_v5.1_magvit_qwen.yaml"))return gr.update(), gr.update(value="none"), gr.update(visible=False), gr.update(visible=False), \gr.update(choices=list(flow_scheduler_dict.keys()), value=list(flow_scheduler_dict.keys())[0]), \gr.update(value=672, minimum=128, maximum=1344, step=16), \gr.update(value=384, minimum=128, maximum=1344, step=16), gr.update(value=49, minimum=1, maximum=49, step=4)23 unmodified linesself.transformer = Choosen_Transformer3DModel.from_pretrained_2d(diffusion_transformer_dropdown,subfolder="transformer",transformer_additional_kwargs=transformer_additional_kwargs,torch_dtype=torch.float8_e4m3fn if self.GPU_memory_mode == "model_cpu_offload_and_qfloat8" else self.weight_dtype,low_cpu_mem_usage=True,)if self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):tokenizer = BertTokenizer.from_pretrained(diffusion_transformer_dropdown, subfolder="tokenizer")if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):tokenizer_2 = Qwen2Tokenizer.from_pretrained(os.path.join(diffusion_transformer_dropdown, "tokenizer_2"))else:tokenizer_2 = T5Tokenizer.from_pretrained(diffusion_transformer_dropdown, subfolder="tokenizer_2")else:if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):tokenizer = Qwen2Tokenizer.from_pretrained(os.path.join(diffusion_transformer_dropdown, "tokenizer"))else:tokenizer = T5Tokenizer.from_pretrained(diffusion_transformer_dropdown, subfolder="tokenizer")tokenizer_2 = Noneif self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):text_encoder = BertModel.from_pretrained(diffusion_transformer_dropdown, subfolder="text_encoder", torch_dtype=self.weight_dtype)if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):text_encoder_2 = Qwen2VLForConditionalGeneration.from_pretrained(os.path.join(diffusion_transformer_dropdown, "text_encoder_2"))else:text_encoder_2 = T5EncoderModel.from_pretrained(diffusion_transformer_dropdown, subfolder="text_encoder_2", torch_dtype=self.weight_dtype)else:if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):text_encoder = Qwen2VLForConditionalGeneration.from_pretrained(os.path.join(diffusion_transformer_dropdown, "text_encoder"))else:text_encoder = T5EncoderModel.from_pretrained(diffusion_transformer_dropdown, subfolder="text_encoder", torch_dtype=self.weight_dtype)text_encoder_2 = None# Get pipeline9 unmodified linesclip_image_processor = None# Get Schedulerif self.edition in ["v5.1"]:Choosen_Scheduler = all_cheduler_dict["Flow"]else:Choosen_Scheduler = all_cheduler_dict["Euler"]scheduler = Choosen_Scheduler.from_pretrained(diffusion_transformer_dropdown,subfolder="scheduler")if self.model_type == "Inpaint":if self.transformer.config.in_channels != self.vae.config.latent_channels:self.pipeline = EasyAnimateInpaintPipeline(text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,1 unmodified linevae=self.vae,transformer=self.transformer,scheduler=scheduler,clip_image_encoder=clip_image_encoder,clip_image_processor=clip_image_processor,).to(self.weight_dtype)else:self.pipeline = EasyAnimatePipeline(text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,1 unmodified linevae=self.vae,transformer=self.transformer,scheduler=scheduler,).to(self.weight_dtype)else:self.pipeline = EasyAnimateControlPipeline(text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,tokenizer_2=tokenizer_2,vae=self.vae,transformer=self.transformer,scheduler=scheduler,).to(self.weight_dtype)if self.GPU_memory_mode == "sequential_cpu_offload":self.pipeline.enable_sequential_cpu_offload()elif self.GPU_memory_mode == "model_cpu_offload_and_qfloat8":self.pipeline.enable_model_cpu_offload()convert_weight_dtype_wrapper(self.pipeline.transformer, self.weight_dtype)else:self.pipeline.enable_model_cpu_offload()print("Update diffusion transformer done")return gr.update()84 unmodified linesif self.base_model_path != base_model_dropdown:self.update_base_model(base_model_dropdown)if self.motion_module_path != motion_module_dropdown:self.update_motion_module(motion_module_dropdown)if self.lora_model_path != lora_model_dropdown:self.update_lora_model(lora_model_dropdown)if control_video is not None and self.model_type == "Inpaint":44 unmodified lineselse:raise gr.Error(f"If specifying the ending image of the video, please specify a starting image of the video.")fps = {"v1": 12, "v2": 24, "v3": 24, "v4": 24, "v5": 8, "v5.1": 8}[self.edition]is_image = True if generation_method == "Image Generation" else Falseif int(seed_textbox) != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox))else: seed_textbox = np.random.randint(0, 1e10)generator = torch.Generator(device="cuda").manual_seed(int(seed_textbox))if is_xformers_available() \and self.inference_config['transformer_additional_kwargs'].get('transformer_type', 'Transformer3DModel') == 'Transformer3DModel':self.transformer.enable_xformers_memory_efficient_attention()self.pipeline.scheduler = all_cheduler_dict[sampler_dropdown].from_config(self.pipeline.scheduler.config)if self.lora_model_path != "none":# lora partself.pipeline = merge_lora(self.pipeline, self.lora_model_path, multiplier=lora_alpha_slider)try:if self.model_type == "Inpaint":35 unmodified linesvideo = input_video,mask_video = input_video_mask,strength = 1,).framesif init_frames != 0:mix_ratio = torch.from_numpy(44 unmodified linesvideo = input_video,mask_video = input_video_mask,strength = strength,).frameselse:if self.vae.cache_mag_vae:length_slider = int((length_slider - 1) // self.vae.mini_batch_encoder * self.vae.mini_batch_encoder) + 19 unmodified linesheight = height_slider,video_length = length_slider if not is_image else 1,generator = generator).frameselse:if self.vae.cache_mag_vae:length_slider = int((length_slider - 1) // self.vae.mini_batch_encoder * self.vae.mini_batch_encoder) + 112 unmodified linesgenerator = generator,control_video = input_video,).framesexcept Exception as e:gc.collect()torch.cuda.empty_cache()103 unmodified lineswith gr.Row():easyanimate_edition_dropdown = gr.Dropdown(label="The config of EasyAnimate Edition (EasyAnimate版本配置)",choices=["v1", "v2", "v3", "v4", "v5", "v5.1"],value="v5.1",interactive=True,)gr.Markdown(67 unmodified lines""")prompt_textbox = gr.Textbox(label="Prompt (正向提示词)", lines=2, value="A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical.")gr.Markdown("""Using longer neg prompt such as "Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art." can increase stability. Adding words such as "quiet, solid" to the neg prompt can increase dynamism.使用更长的neg prompt如"模糊,突变,变形,失真,画面暗,文本字幕,画面固定,连环画,漫画,线稿,没有主体。",可以增加稳定性。在neg prompt中添加"安静,固定"等词语可以增加动态性。""")negative_prompt_textbox = gr.Textbox(label="Negative prompt (负向提示词)", lines=2, value="Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code." )with gr.Row():with gr.Column():with gr.Row():sampler_dropdown = gr.Dropdown(label="Sampling method (采样器种类)",choices=list(flow_scheduler_dict.keys()), value=list(flow_scheduler_dict.keys())[0])sample_step_slider = gr.Slider(label="Sampling steps (生成步数)", value=50, minimum=10, maximum=100, step=1)resize_method = gr.Radio(30 unmodified linestemplate_gallery_path = ["asset/1.png", "asset/2.png", "asset/3.png", "asset/4.png", "asset/5.png"]def select_template(evt: gr.SelectData):text = {"asset/1.png": "A brown dog is shaking its head and sitting on a light colored sofa in a comfortable room. Behind the dog, there is a framed painting on the shelf surrounded by pink flowers. The soft and warm lighting in the room creates a comfortable atmosphere.","asset/2.png": "A sailboat navigates through moderately rough seas, with waves and ocean spray visible. The sailboat features a white hull and sails, accompanied by an orange sail catching the wind. The sky above shows dramatic, cloudy formations with a sunset or sunrise backdrop, casting warm colors across the scene. The water reflects the golden light, enhancing the visual contrast between the dark ocean and the bright horizon. The camera captures the scene with a dynamic and immersive angle, showcasing the movement of the boat and the energy of the ocean.","asset/3.png": "A stunningly beautiful woman with flowing long hair stands gracefully, her elegant dress rippling and billowing in the gentle wind. Petals falling off. Her serene expression and the natural movement of her attire create an enchanting and captivating scene, full of ethereal charm.","asset/4.png": "An astronaut, clad in a full space suit with a helmet, plays an electric guitar while floating in a cosmic environment filled with glowing particles and rocky textures. The scene is illuminated by a warm light source, creating dramatic shadows and contrasts. The background features a complex geometry, similar to a space station or an alien landscape, indicating a futuristic or otherworldly setting.","asset/5.png": "Fireworks light up the evening sky over a sprawling cityscape with gothic-style buildings featuring pointed towers and clock faces. The city is lit by both artificial lights from the buildings and the colorful bursts of the fireworks. The scene is viewed from an elevated angle, showcasing a vibrant urban environment set against a backdrop of a dramatic, partially cloudy sky at dusk.",}[template_gallery_path[evt.index]]return template_gallery_path[evt.index], text33 unmodified linesgr.Markdown("""Demo pose control video can be downloaded here [URL](https://pai-aigc-photog.oss-cn-hangzhou.aliyuncs.com/cogvideox_fun/asset/v1.1/pose.mp4).Only normal controls are supported in app.py; trajectory control and camera control need ComfyUI, as shown in https://github.com/aigc-apps/EasyAnimate/tree/main/comfyui.""")control_video = gr.Video(83 unmodified linesdiffusion_transformer_dropdown,motion_module_dropdown,motion_module_refresh_button,sampler_dropdown,width_slider,height_slider,length_slider,70 unmodified linesself.transformer = Choosen_Transformer3DModel.from_pretrained_2d(model_name,subfolder="transformer",transformer_additional_kwargs=transformer_additional_kwargs,torch_dtype=torch.float8_e4m3fn if GPU_memory_mode == "model_cpu_offload_and_qfloat8" else weight_dtype,low_cpu_mem_usage=True,)if self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):tokenizer = BertTokenizer.from_pretrained(model_name, subfolder="tokenizer")if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):tokenizer_2 = Qwen2Tokenizer.from_pretrained(os.path.join(model_name, "tokenizer_2"))else:tokenizer_2 = T5Tokenizer.from_pretrained(model_name, subfolder="tokenizer_2")else:if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):tokenizer = Qwen2Tokenizer.from_pretrained(os.path.join(model_name, "tokenizer"))else:tokenizer = T5Tokenizer.from_pretrained(model_name, subfolder="tokenizer")tokenizer_2 = Noneif self.inference_config['text_encoder_kwargs'].get('enable_multi_text_encoder', False):text_encoder = BertModel.from_pretrained(model_name, subfolder="text_encoder", torch_dtype=self.weight_dtype)if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):text_encoder_2 = Qwen2VLForConditionalGeneration.from_pretrained(os.path.join(model_name, "text_encoder_2"), torch_dtype=self.weight_dtype)else:text_encoder_2 = T5EncoderModel.from_pretrained(model_name, subfolder="text_encoder_2", torch_dtype=self.weight_dtype)else:if self.inference_config['text_encoder_kwargs'].get('replace_t5_to_llm', False):text_encoder = Qwen2VLForConditionalGeneration.from_pretrained(os.path.join(model_name, "text_encoder"), torch_dtype=self.weight_dtype)else:text_encoder = T5EncoderModel.from_pretrained(model_name, subfolder="text_encoder", torch_dtype=self.weight_dtype)text_encoder_2 = None# Get pipeline9 unmodified linesclip_image_processor = None# Get Schedulerif self.edition in ["v5.1"]:Choosen_Scheduler = all_cheduler_dict["Flow"]else:Choosen_Scheduler = all_cheduler_dict["Euler"]scheduler = Choosen_Scheduler.from_pretrained(model_name,subfolder="scheduler")if model_type == "Inpaint":if self.transformer.config.in_channels != self.vae.config.latent_channels:self.pipeline = EasyAnimateInpaintPipeline(text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,1 unmodified linevae=self.vae,transformer=self.transformer,scheduler=scheduler,clip_image_encoder=clip_image_encoder,clip_image_processor=clip_image_processor,).to(weight_dtype)else:self.pipeline = EasyAnimatePipeline(text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,tokenizer_2=tokenizer_2,vae=self.vae,transformer=self.transformer,scheduler=scheduler).to(weight_dtype)else:self.pipeline = EasyAnimateControlPipeline(text_encoder=text_encoder,text_encoder_2=text_encoder_2,tokenizer=tokenizer,tokenizer_2=tokenizer_2,vae=self.vae,transformer=self.transformer,scheduler=scheduler,).to(weight_dtype)if GPU_memory_mode == "sequential_cpu_offload":self.pipeline.enable_sequential_cpu_offload()elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":self.pipeline.enable_model_cpu_offload()convert_weight_dtype_wrapper(self.pipeline.transformer, weight_dtype)else:GPU_memory_mode.enable_model_cpu_offload()94 unmodified lineselse:raise gr.Error(f"If specifying the ending image of the video, please specify a starting image of the video.")fps = {"v1": 12, "v2": 24, "v3": 24, "v4": 24, "v5": 8, "v5.1": 8}[self.edition]is_image = True if generation_method == "Image Generation" else Falseif int(seed_textbox) != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox))else: seed_textbox = np.random.randint(0, 1e10)generator = torch.Generator(device="cuda").manual_seed(int(seed_textbox))self.pipeline.scheduler = all_cheduler_dict[sampler_dropdown].from_config(self.pipeline.scheduler.config)if self.lora_model_path != "none":# lora partself.pipeline = merge_lora(self.pipeline, self.lora_model_path, multiplier=lora_alpha_slider)try:if self.model_type == "Inpaint":23 unmodified linesvideo = input_video,mask_video = input_video_mask,strength = strength,).frameselse:sample = self.pipeline(prompt_textbox,4 unmodified linesheight = height_slider,video_length = length_slider if not is_image else 1,generator = generator).frameselse:if self.vae.cache_mag_vae:length_slider = int((length_slider - 1) // self.vae.mini_batch_encoder * self.vae.mini_batch_encoder) + 113 unmodified linesgenerator = generator,control_video = input_video,).framesexcept Exception as e:gc.collect()torch.cuda.empty_cache()114 unmodified lines""")prompt_textbox = gr.Textbox(label="Prompt (正向提示词)", lines=2, value="A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical.")gr.Markdown("""Using longer neg prompt such as "Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art." can increase stability. Adding words such as "quiet, solid" to the neg prompt can increase dynamism.使用更长的neg prompt如"模糊,突变,变形,失真,画面暗,文本字幕,画面固定,连环画,漫画,线稿,没有主体。",可以增加稳定性。在neg prompt中添加"安静,固定"等词语可以增加动态性。""")negative_prompt_textbox = gr.Textbox(label="Negative prompt (负向提示词)", lines=2, value="Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code." )with gr.Row():with gr.Column():with gr.Row():if edition in ["v5.1"]:sampler_dropdown = gr.Dropdown(label="Sampling method (采样器种类)",choices=list(flow_scheduler_dict.keys()), value=list(flow_scheduler_dict.keys())[0])else:sampler_dropdown = gr.Dropdown(label="Sampling method (采样器种类)",choices=list(ddpm_scheduler_dict.keys()), value=list(ddpm_scheduler_dict.keys())[0])sample_step_slider = gr.Slider(label="Sampling steps (生成步数)", value=50, minimum=10, maximum=50, step=1, interactive=False)if edition == "v1":47 unmodified linestemplate_gallery_path = ["asset/1.png", "asset/2.png", "asset/3.png", "asset/4.png", "asset/5.png"]def select_template(evt: gr.SelectData):text = {"asset/1.png": "A brown dog is shaking its head and sitting on a light colored sofa in a comfortable room. Behind the dog, there is a framed painting on the shelf surrounded by pink flowers. The soft and warm lighting in the room creates a comfortable atmosphere.","asset/2.png": "A sailboat navigates through moderately rough seas, with waves and ocean spray visible. The sailboat features a white hull and sails, accompanied by an orange sail catching the wind. The sky above shows dramatic, cloudy formations with a sunset or sunrise backdrop, casting warm colors across the scene. The water reflects the golden light, enhancing the visual contrast between the dark ocean and the bright horizon. The camera captures the scene with a dynamic and immersive angle, showcasing the movement of the boat and the energy of the ocean.","asset/3.png": "A stunningly beautiful woman with flowing long hair stands gracefully, her elegant dress rippling and billowing in the gentle wind. Petals falling off. Her serene expression and the natural movement of her attire create an enchanting and captivating scene, full of ethereal charm.","asset/4.png": "An astronaut, clad in a full space suit with a helmet, plays an electric guitar while floating in a cosmic environment filled with glowing particles and rocky textures. The scene is illuminated by a warm light source, creating dramatic shadows and contrasts. The background features a complex geometry, similar to a space station or an alien landscape, indicating a futuristic or otherworldly setting.","asset/5.png": "Fireworks light up the evening sky over a sprawling cityscape with gothic-style buildings featuring pointed towers and clock faces. The city is lit by both artificial lights from the buildings and the colorful bursts of the fireworks. The scene is viewed from an elevated angle, showcasing a vibrant urban environment set against a backdrop of a dramatic, partially cloudy sky at dusk.",}[template_gallery_path[evt.index]]return template_gallery_path[evt.index], text33 unmodified linesgr.Markdown("""Demo pose control video can be downloaded here [URL](https://pai-aigc-photog.oss-cn-hangzhou.aliyuncs.com/cogvideox_fun/asset/v1.1/pose.mp4).Only normal controls are supported in app.py; trajectory control and camera control need ComfyUI, as shown in https://github.com/aigc-apps/EasyAnimate/tree/main/comfyui.""")control_video = gr.Video(304 unmodified lines""")prompt_textbox = gr.Textbox(label="Prompt", lines=2, value="A young woman with beautiful, clear eyes and blonde hair stands in the forest, wearing a white dress and a crown. Her expression is serene, reminiscent of a movie star, with fair and youthful skin. Her brown long hair flows in the wind. The video quality is very high, with a clear view. High quality, masterpiece, best quality, high resolution, ultra-fine, fantastical.")gr.Markdown("""Using longer neg prompt such as "Blurring, mutation, deformation, distortion, dark and solid, comics, text subtitles, line art." can increase stability. Adding words such as "quiet, solid" to the neg prompt can increase dynamism.使用更长的neg prompt如"模糊,突变,变形,失真,画面暗,文本字幕,画面固定,连环画,漫画,线稿,没有主体。",可以增加稳定性。在neg prompt中添加"安静,固定"等词语可以增加动态性。""")negative_prompt_textbox = gr.Textbox(label="Negative prompt", lines=2, value="Twisted body, limb deformities, text captions, comic, static, ugly, error, messy code." )with gr.Row():with gr.Column():with gr.Row():if edition in ["v5.1"]:sampler_dropdown = gr.Dropdown(label="Sampling method (采样器种类)",choices=list(flow_scheduler_dict.keys()), value=list(flow_scheduler_dict.keys())[0])else:sampler_dropdown = gr.Dropdown(label="Sampling method (采样器种类)",choices=list(ddpm_scheduler_dict.keys()), value=list(ddpm_scheduler_dict.keys())[0])sample_step_slider = gr.Slider(label="Sampling steps", value=40, minimum=10, maximum=40, step=1, interactive=False)if edition == "v1":42 unmodified linestemplate_gallery_path = ["asset/1.png", "asset/2.png", "asset/3.png", "asset/4.png", "asset/5.png"]def select_template(evt: gr.SelectData):text = {"asset/1.png": "A brown dog is shaking its head and sitting on a light colored sofa in a comfortable room. Behind the dog, there is a framed painting on the shelf surrounded by pink flowers. The soft and warm lighting in the room creates a comfortable atmosphere.","asset/2.png": "A sailboat navigates through moderately rough seas, with waves and ocean spray visible. The sailboat features a white hull and sails, accompanied by an orange sail catching the wind. The sky above shows dramatic, cloudy formations with a sunset or sunrise backdrop, casting warm colors across the scene. The water reflects the golden light, enhancing the visual contrast between the dark ocean and the bright horizon. The camera captures the scene with a dynamic and immersive angle, showcasing the movement of the boat and the energy of the ocean.","asset/3.png": "A stunningly beautiful woman with flowing long hair stands gracefully, her elegant dress rippling and billowing in the gentle wind. Petals falling off. Her serene expression and the natural movement of her attire create an enchanting and captivating scene, full of ethereal charm.","asset/4.png": "An astronaut, clad in a full space suit with a helmet, plays an electric guitar while floating in a cosmic environment filled with glowing particles and rocky textures. The scene is illuminated by a warm light source, creating dramatic shadows and contrasts. The background features a complex geometry, similar to a space station or an alien landscape, indicating a futuristic or otherworldly setting.","asset/5.png": "Fireworks light up the evening sky over a sprawling cityscape with gothic-style buildings featuring pointed towers and clock faces. The city is lit by both artificial lights from the buildings and the colorful bursts of the fireworks. The scene is viewed from an elevated angle, showcasing a vibrant urban environment set against a backdrop of a dramatic, partially cloudy sky at dusk.",}[template_gallery_path[evt.index]]return template_gallery_path[evt.index], text
368 unmodified lines36937037137237337437534 unmodified lines41041141241341441541641741841942042142242342442542642742842918 unmodified lines448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482368 unmodified linesdef merge_lora(pipeline, lora_path, multiplier, device='cpu', dtype=torch.float32, state_dict=None, transformer_only=False):LORA_PREFIX_TRANSFORMER = "lora_unet"LORA_PREFIX_TEXT_ENCODER = "lora_te"SPECIAL_LAYER_NAME = ["text_proj_t5"]if state_dict is None:state_dict = load_file(lora_path, device=device)else:34 unmodified lineselse:temp_name = layer_infos.pop(0)weight_up = elems['lora_up.weight'].to(dtype)weight_down = elems['lora_down.weight'].to(dtype)if 'alpha' in elems.keys():alpha = elems['alpha'].item() / weight_up.shape[1]else:alpha = 1.0curr_layer.weight.data = curr_layer.weight.data.to(device)if len(weight_up.shape) == 4:curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up.squeeze(3).squeeze(2),weight_down.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)else:curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up, weight_down)return pipeline18 unmodified lineslayer_infos = layer.split(LORA_PREFIX_UNET + "_")[-1].split("_")curr_layer = pipeline.transformertemp_name = layer_infos.pop(0)print(layer, curr_layer)while len(layer_infos) > -1:try:curr_layer = curr_layer.__getattr__(temp_name)if len(layer_infos) > 0:temp_name = layer_infos.pop(0)elif len(layer_infos) == 0:breakexcept Exception:if len(layer_infos) == 0:print('Error loading layer')if len(temp_name) > 0:temp_name += "_" + layer_infos.pop(0)else:temp_name = layer_infos.pop(0)weight_up = elems['lora_up.weight'].to(dtype)weight_down = elems['lora_down.weight'].to(dtype)if 'alpha' in elems.keys():alpha = elems['alpha'].item() / weight_up.shape[1]else:alpha = 1.0curr_layer.weight.data = curr_layer.weight.data.to(device)if len(weight_up.shape) == 4:curr_layer.weight.data -= multiplier * alpha * torch.mm(weight_up.squeeze(3).squeeze(2),weight_down.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)else:curr_layer.weight.data -= multiplier * alpha * torch.mm(weight_up, weight_down)return pipeline368 unmodified lines36937037137237337434 unmodified lines40941041141241341441541641741841942042142242342442542642742842943043143243318 unmodified lines452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494368 unmodified linesdef merge_lora(pipeline, lora_path, multiplier, device='cpu', dtype=torch.float32, state_dict=None, transformer_only=False):LORA_PREFIX_TRANSFORMER = "lora_unet"LORA_PREFIX_TEXT_ENCODER = "lora_te"if state_dict is None:state_dict = load_file(lora_path, device=device)else:34 unmodified lineselse:temp_name = layer_infos.pop(0)origin_dtype = curr_layer.weight.data.dtypeorigin_device = curr_layer.weight.data.devicecurr_layer = curr_layer.to(device, dtype)weight_up = elems['lora_up.weight'].to(device, dtype)weight_down = elems['lora_down.weight'].to(device, dtype)if 'alpha' in elems.keys():alpha = elems['alpha'].item() / weight_up.shape[1]else:alpha = 1.0if len(weight_up.shape) == 4:curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up.squeeze(3).squeeze(2), weight_down.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)else:curr_layer.weight.data += multiplier * alpha * torch.mm(weight_up, weight_down)curr_layer = curr_layer.to(origin_device, origin_dtype)return pipeline18 unmodified lineslayer_infos = layer.split(LORA_PREFIX_UNET + "_")[-1].split("_")curr_layer = pipeline.transformertry:curr_layer = curr_layer.__getattr__("_".join(layer_infos[1:]))except Exception:temp_name = layer_infos.pop(0)while len(layer_infos) > -1:try:curr_layer = curr_layer.__getattr__(temp_name)if len(layer_infos) > 0:temp_name = layer_infos.pop(0)elif len(layer_infos) == 0:breakexcept Exception:if len(layer_infos) == 0:print('Error loading layer')if len(temp_name) > 0:temp_name += "_" + layer_infos.pop(0)else:temp_name = layer_infos.pop(0)origin_dtype = curr_layer.weight.data.dtypeorigin_device = curr_layer.weight.data.devicecurr_layer = curr_layer.to(device, dtype)weight_up = elems['lora_up.weight'].to(device, dtype)weight_down = elems['lora_down.weight'].to(device, dtype)if 'alpha' in elems.keys():alpha = elems['alpha'].item() / weight_up.shape[1]else:alpha = 1.0if len(weight_up.shape) == 4:curr_layer.weight.data -= multiplier * alpha * torch.mm(weight_up.squeeze(3).squeeze(2), weight_down.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)else:curr_layer.weight.data -= multiplier * alpha * torch.mm(weight_up, weight_down)curr_layer = curr_layer.to(origin_device, origin_dtype)return pipeline
168 unmodified lines169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215168 unmodified linesreturn input_video, input_video_mask, clip_imagedef get_video_to_video_latent(input_video_path, video_length, sample_size, fps=None, validation_video_mask=None, ref_image=None):if isinstance(input_video_path, str):cap = cv2.VideoCapture(input_video_path)input_video = []original_fps = cap.get(cv2.CAP_PROP_FPS)frame_skip = 1 if fps is None else int(original_fps // fps)frame_count = 0while True:ret, frame = cap.read()if not ret:breakif frame_count % frame_skip == 0:frame = cv2.resize(frame, (sample_size[1], sample_size[0]))input_video.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))frame_count += 1cap.release()else:input_video = input_video_pathinput_video = torch.from_numpy(np.array(input_video))[:video_length]input_video = input_video.permute([3, 0, 1, 2]).unsqueeze(0) / 255if ref_image is not None:ref_image = Image.open(ref_image)ref_image = torch.from_numpy(np.array(ref_image))ref_image = ref_image.unsqueeze(0).permute([3, 0, 1, 2]).unsqueeze(0) / 255if validation_video_mask is not None:validation_video_mask = Image.open(validation_video_mask).convert('L').resize((sample_size[1], sample_size[0]))input_video_mask = np.where(np.array(validation_video_mask) < 240, 0, 255)input_video_mask = torch.from_numpy(np.array(input_video_mask)).unsqueeze(0).unsqueeze(-1).permute([3, 0, 1, 2]).unsqueeze(0)input_video_mask = torch.tile(input_video_mask, [1, 1, input_video.size()[2], 1, 1])input_video_mask = input_video_mask.to(input_video.device, input_video.dtype)else:input_video_mask = torch.zeros_like(input_video[:, :1])input_video_mask[:, :, :] = 255return input_video, input_video_mask, ref_image168 unmodified lines169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235168 unmodified linesreturn input_video, input_video_mask, clip_imagedef get_video_to_video_latent(input_video_path, video_length, sample_size, fps=None, validation_video_mask=None, ref_image=None):if input_video_path is not None:if isinstance(input_video_path, str):cap = cv2.VideoCapture(input_video_path)input_video = []original_fps = cap.get(cv2.CAP_PROP_FPS)frame_skip = 1 if fps is None else int(original_fps // fps)frame_count = 0while True:ret, frame = cap.read()if not ret:breakif frame_count % frame_skip == 0:frame = cv2.resize(frame, (sample_size[1], sample_size[0]))input_video.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))frame_count += 1cap.release()else:input_video = input_video_pathinput_video = torch.from_numpy(np.array(input_video))[:video_length]input_video = input_video.permute([3, 0, 1, 2]).unsqueeze(0) / 255if validation_video_mask is not None:validation_video_mask = Image.open(validation_video_mask).convert('L').resize((sample_size[1], sample_size[0]))input_video_mask = np.where(np.array(validation_video_mask) < 240, 0, 255)input_video_mask = torch.from_numpy(np.array(input_video_mask)).unsqueeze(0).unsqueeze(-1).permute([3, 0, 1, 2]).unsqueeze(0)input_video_mask = torch.tile(input_video_mask, [1, 1, input_video.size()[2], 1, 1])input_video_mask = input_video_mask.to(input_video.device, input_video.dtype)else:input_video_mask = torch.zeros_like(input_video[:, :1])input_video_mask[:, :, :] = 255else:input_video, input_video_mask = None, Noneif ref_image is not None:if isinstance(ref_image, str):ref_image = Image.open(ref_image).convert("RGB")ref_image = ref_image.resize((sample_size[1], sample_size[0]))ref_image = torch.from_numpy(np.array(ref_image))ref_image = ref_image.unsqueeze(0).permute([3, 0, 1, 2]).unsqueeze(0) / 255else:ref_image = torch.from_numpy(np.array(ref_image))ref_image = ref_image.unsqueeze(0).permute([3, 0, 1, 2]).unsqueeze(0) / 255return input_video, input_video_mask, ref_imagedef get_image_latent(ref_image=None, sample_size=None):if ref_image is not None:if isinstance(ref_image, str):ref_image = Image.open(ref_image).convert("RGB")ref_image = ref_image.resize((sample_size[1], sample_size[0]))ref_image = torch.from_numpy(np.array(ref_image))ref_image = ref_image.unsqueeze(0).permute([3, 0, 1, 2]).unsqueeze(0) / 255else:ref_image = torch.from_numpy(np.array(ref_image))ref_image = ref_image.unsqueeze(0).permute([3, 0, 1, 2]).unsqueeze(0) / 255return ref_image
125 unmodified lines126127128129130131132133134135136137138125 unmodified linesdef configure_optimizers(self):lr = self.learning_rateopt_ae = torch.optim.Adam(list(self.encoder.parameters())+list(self.decoder.parameters())+list(self.quant_conv.parameters())+list(self.post_quant_conv.parameters()),lr=lr, betas=(0.5, 0.9))opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),lr=lr, betas=(0.5, 0.9))return [opt_ae, opt_disc], []def get_last_layer(self):125 unmodified lines126127128129130131132133134135136137138125 unmodified linesdef configure_optimizers(self):lr = self.learning_rateopt_ae = torch.optim.AdamW(list(self.encoder.parameters())+list(self.decoder.parameters())+list(self.quant_conv.parameters())+list(self.post_quant_conv.parameters()),lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)opt_disc = torch.optim.AdamW(self.loss.discriminator.parameters(),lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)return [opt_ae, opt_disc], []def get_last_layer(self):
278 unmodified lines279280281282283284285286287288289290291278 unmodified linesdef configure_optimizers(self):lr = self.learning_rateopt_ae = torch.optim.Adam(list(self.encoder.parameters())+list(self.decoder.parameters())+list(self.quant_conv.parameters())+list(self.post_quant_conv.parameters()),lr=lr, betas=(0.5, 0.9))opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),lr=lr, betas=(0.5, 0.9))return [opt_ae, opt_disc], []def get_last_layer(self):278 unmodified lines279280281282283284285286287288289290291278 unmodified linesdef configure_optimizers(self):lr = self.learning_rateopt_ae = torch.optim.AdamW(list(self.encoder.parameters())+list(self.decoder.parameters())+list(self.quant_conv.parameters())+list(self.post_quant_conv.parameters()), \lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)opt_disc = torch.optim.AdamW(self.loss.discriminator.parameters(),lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)return [opt_ae, opt_disc], []def get_last_layer(self):
276 unmodified lines277278279280281282283284285286287288289290291292293294295296297298299276 unmodified linestraining_list = list(self.decoder.parameters()) + list(self.post_quant_conv.parameters())else:training_list = list(self.decoder.parameters())opt_ae = torch.optim.Adam(training_list, lr=lr, betas=(0.5, 0.9))elif self.train_encoder_only:if self.quant_conv is not None:training_list = list(self.encoder.parameters()) + list(self.quant_conv.parameters())else:training_list = list(self.encoder.parameters())opt_ae = torch.optim.Adam(training_list, lr=lr, betas=(0.5, 0.9))else:training_list = list(self.encoder.parameters()) + list(self.decoder.parameters())if self.quant_conv is not None:training_list = training_list + list(self.quant_conv.parameters())if self.post_quant_conv is not None:training_list = training_list + list(self.post_quant_conv.parameters())opt_ae = torch.optim.Adam(training_list, lr=lr, betas=(0.5, 0.9))opt_disc = torch.optim.Adam(list(self.loss.discriminator3d.parameters()) + list(self.loss.discriminator.parameters()),lr=lr, betas=(0.5, 0.9))return [opt_ae, opt_disc], []276 unmodified lines277278279280281282283284285286287288289290291292293294295296297298299276 unmodified linestraining_list = list(self.decoder.parameters()) + list(self.post_quant_conv.parameters())else:training_list = list(self.decoder.parameters())opt_ae = torch.optim.AdamW(training_list, lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)elif self.train_encoder_only:if self.quant_conv is not None:training_list = list(self.encoder.parameters()) + list(self.quant_conv.parameters())else:training_list = list(self.encoder.parameters())opt_ae = torch.optim.AdamW(training_list, lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)else:training_list = list(self.encoder.parameters()) + list(self.decoder.parameters())if self.quant_conv is not None:training_list = training_list + list(self.quant_conv.parameters())if self.post_quant_conv is not None:training_list = training_list + list(self.post_quant_conv.parameters())opt_ae = torch.optim.AdamW(training_list, lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)opt_disc = torch.optim.AdamW(list(self.loss.discriminator3d.parameters()) + list(self.loss.discriminator.parameters()),lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)return [opt_ae, opt_disc], []
94 unmodified lines959697989910028 unmodified lines1291301311321331341351367 unmodified lines1441451461471481492 unmodified lines152153154155156157158159132 unmodified lines29229329429529629729829930030130230330430530630730830931031131231331494 unmodified linesout_channels: int = 3,ch = 128,ch_mult = [ 1,2,4,4 ],use_gc_blocks = None,down_block_types: tuple = None,up_block_types: tuple = None,28 unmodified linesin_channels=in_channels,out_channels=latent_channels,down_block_types=down_block_types,ch = ch,ch_mult = ch_mult,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,7 unmodified linesslice_mag_vae=slice_mag_vae,slice_compression_vae=slice_compression_vae,cache_compression_vae=cache_compression_vae,spatial_group_norm=spatial_group_norm,mini_batch_encoder=mini_batch_encoder,)2 unmodified linesin_channels=latent_channels,out_channels=out_channels,up_block_types=up_block_types,ch = ch,ch_mult = ch_mult,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,132 unmodified linestraining_list = list(self.decoder.parameters()) + list(self.post_quant_conv.parameters())else:training_list = list(self.decoder.parameters())opt_ae = torch.optim.Adam(training_list, lr=lr, betas=(0.5, 0.9))elif self.train_encoder_only:if self.quant_conv is not None:training_list = list(self.encoder.parameters()) + list(self.quant_conv.parameters())else:training_list = list(self.encoder.parameters())opt_ae = torch.optim.Adam(training_list, lr=lr, betas=(0.5, 0.9))else:training_list = list(self.encoder.parameters()) + list(self.decoder.parameters())if self.quant_conv is not None:training_list = training_list + list(self.quant_conv.parameters())if self.post_quant_conv is not None:training_list = training_list + list(self.post_quant_conv.parameters())opt_ae = torch.optim.Adam(training_list, lr=lr, betas=(0.5, 0.9))opt_disc = torch.optim.Adam(list(self.loss.discriminator3d.parameters()) + list(self.loss.discriminator.parameters()),lr=lr, betas=(0.5, 0.9))return [opt_ae, opt_disc], []94 unmodified lines959697989910010128 unmodified lines1301311321331341351361371387 unmodified lines1461471481491501511522 unmodified lines155156157158159160161162163132 unmodified lines29629729829930030130230330430530630730830931031131231331431531631731894 unmodified linesout_channels: int = 3,ch = 128,ch_mult = [ 1,2,4,4 ],block_out_channels = [128, 256, 512, 512],use_gc_blocks = None,down_block_types: tuple = None,up_block_types: tuple = None,28 unmodified linesin_channels=in_channels,out_channels=latent_channels,down_block_types=down_block_types,ch=ch,ch_mult=ch_mult,block_out_channels=block_out_channels,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,7 unmodified linesslice_mag_vae=slice_mag_vae,slice_compression_vae=slice_compression_vae,cache_compression_vae=cache_compression_vae,cache_mag_vae=cache_mag_vae,spatial_group_norm=spatial_group_norm,mini_batch_encoder=mini_batch_encoder,)2 unmodified linesin_channels=latent_channels,out_channels=out_channels,up_block_types=up_block_types,ch=ch,ch_mult=ch_mult,block_out_channels=block_out_channels,use_gc_blocks=use_gc_blocks,mid_block_type=mid_block_type,mid_block_use_attention=mid_block_use_attention,132 unmodified linestraining_list = list(self.decoder.parameters()) + list(self.post_quant_conv.parameters())else:training_list = list(self.decoder.parameters())opt_ae = torch.optim.AdamW(training_list, lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)elif self.train_encoder_only:if self.quant_conv is not None:training_list = list(self.encoder.parameters()) + list(self.quant_conv.parameters())else:training_list = list(self.encoder.parameters())opt_ae = torch.optim.AdamW(training_list, lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)else:training_list = list(self.encoder.parameters()) + list(self.decoder.parameters())if self.quant_conv is not None:training_list = training_list + list(self.quant_conv.parameters())if self.post_quant_conv is not None:training_list = training_list + list(self.post_quant_conv.parameters())opt_ae = torch.optim.AdamW(training_list, lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)opt_disc = torch.optim.AdamW(list(self.loss.discriminator3d.parameters()) + list(self.loss.discriminator.parameters()),lr=lr, betas=(0.9, 0.999), weight_decay=5e-2)return [opt_ae, opt_disc], []
57 unmodified lines58596061626313 unmodified lines77787980818283280 unmodified lines36436536636736836912 unmodified lines38238338438538638738857 unmodified linesdown_block_types = ("SpatialDownBlock3D",),ch = 128,ch_mult = [1,2,4,4,],use_gc_blocks = None,mid_block_type: str = "MidBlock3D",mid_block_use_attention: bool = True,13 unmodified linesverbose = False,):super().__init__()block_out_channels = [ch * i for i in ch_mult]assert len(down_block_types) == len(block_out_channels), ("Number of down block types must match number of block output channels.")280 unmodified linesup_block_types = ("SpatialUpBlock3D",),ch = 128,ch_mult = [1,2,4,4,],use_gc_blocks = None,mid_block_type: str = "MidBlock3D",mid_block_use_attention: bool = True,12 unmodified linesverbose = False,):super().__init__()block_out_channels = [ch * i for i in ch_mult]assert len(up_block_types) == len(block_out_channels), ("Number of up block types must match number of block output channels.")57 unmodified lines5859606162636413 unmodified lines7879808182838485280 unmodified lines36636736836937037137212 unmodified lines38538638738838939039139257 unmodified linesdown_block_types = ("SpatialDownBlock3D",),ch = 128,ch_mult = [1,2,4,4,],block_out_channels = [128, 256, 512, 512],use_gc_blocks = None,mid_block_type: str = "MidBlock3D",mid_block_use_attention: bool = True,13 unmodified linesverbose = False,):super().__init__()if block_out_channels is None:block_out_channels = [ch * i for i in ch_mult]assert len(down_block_types) == len(block_out_channels), ("Number of down block types must match number of block output channels.")280 unmodified linesup_block_types = ("SpatialUpBlock3D",),ch = 128,ch_mult = [1,2,4,4,],block_out_channels = [128, 256, 512, 512],use_gc_blocks = None,mid_block_type: str = "MidBlock3D",mid_block_use_attention: bool = True,12 unmodified linesverbose = False,):super().__init__()if block_out_channels is None:block_out_channels = [ch * i for i in ch_mult]assert len(up_block_types) == len(block_out_channels), ("Number of up block types must match number of block output channels.")
8 unmodified lines910111213141518 unmodified lines34353637383910 unmodified lines50515253545530 unmodified lines86878889909110 unmodified lines1021031041051061071081091101111121131148 unmodified linesclass LPIPSWithDiscriminator(nn.Module):def __init__(self, disc_start, logvar_init=0.0, kl_weight=1.0, pixelloss_weight=1.0,disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0,perceptual_weight=1.0, use_actnorm=False, disc_conditional=False,disc_loss="hinge", l2_loss_weight=0.0, l1_loss_weight=1.0):super().__init__()18 unmodified linesself.disc_factor = disc_factorself.discriminator_weight = disc_weightself.disc_conditional = disc_conditionalself.l1_loss_weight = l1_loss_weightself.l2_loss_weight = l2_loss_weight10 unmodified linesd_weight = d_weight * self.discriminator_weightreturn d_weightdef forward(self, inputs, reconstructions, posteriors, optimizer_idx,global_step, last_layer=None, cond=None, split="train",weights=None):30 unmodified lineskl_loss = posteriors.kl()kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]# now the GAN partif optimizer_idx == 0:# generator update10 unmodified linestry:d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer=last_layer)except RuntimeError:assert not self.trainingd_weight = torch.tensor(0.0)else:d_weight = torch.tensor(0.0)disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)loss = weighted_nll_loss + self.kl_weight * kl_loss + d_weight * disc_factor * g_losslog = {"{}/total_loss".format(split): loss.clone().detach().mean(), "{}/logvar".format(split): self.logvar.detach(),"{}/kl_loss".format(split): kl_loss.detach().mean(), "{}/nll_loss".format(split): nll_loss.detach().mean(),8 unmodified lines91011121314151618 unmodified lines353637383940414210 unmodified lines53545556575859606162636465666768697030 unmodified lines10110210310410510610710810 unmodified lines1191201211221231241251261271281291301318 unmodified linesclass LPIPSWithDiscriminator(nn.Module):def __init__(self, disc_start, logvar_init=0.0, kl_weight=1.0, pixelloss_weight=1.0,disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0,perceptual_weight=1.0, use_actnorm=False, disc_conditional=False,outlier_penalty_loss_r=3.0, outlier_penalty_loss_weight=1e5,disc_loss="hinge", l2_loss_weight=0.0, l1_loss_weight=1.0):super().__init__()18 unmodified linesself.disc_factor = disc_factorself.discriminator_weight = disc_weightself.disc_conditional = disc_conditionalself.outlier_penalty_loss_r = outlier_penalty_loss_rself.outlier_penalty_loss_weight = outlier_penalty_loss_weightself.l1_loss_weight = l1_loss_weightself.l2_loss_weight = l2_loss_weight10 unmodified linesd_weight = d_weight * self.discriminator_weightreturn d_weightdef outlier_penalty_loss(self, posteriors, r):batch_size, channels, frames, height, width = posteriors.shapemean_X = posteriors.mean(dim=(3, 4), keepdim=True)std_X = posteriors.std(dim=(3, 4), keepdim=True)diff = torch.abs(posteriors - mean_X)penalty = torch.maximum(diff - r * std_X, torch.zeros_like(diff))opl = penalty.sum(dim=(3, 4)) / (height * width)opl_final = opl.mean(dim=(0, 1, 2))return opl_finaldef forward(self, inputs, reconstructions, posteriors, optimizer_idx,global_step, last_layer=None, cond=None, split="train",weights=None):30 unmodified lineskl_loss = posteriors.kl()kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]outlier_penalty_loss = self.outlier_penalty_loss(posteriors.mode(), self.outlier_penalty_loss_r) * self.outlier_penalty_loss_weight# now the GAN partif optimizer_idx == 0:# generator update10 unmodified linestry:d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer=last_layer)except RuntimeError:# assert not self.trainingd_weight = torch.tensor(0.0)else:d_weight = torch.tensor(0.0)disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)loss = weighted_nll_loss + self.kl_weight * kl_loss + d_weight * disc_factor * g_loss + outlier_penalty_losslog = {"{}/total_loss".format(split): loss.clone().detach().mean(), "{}/logvar".format(split): self.logvar.detach(),"{}/kl_loss".format(split): kl_loss.detach().mean(), "{}/nll_loss".format(split): nll_loss.detach().mean(),
7 unmodified lines891011121352 unmodified lines666768697071727374759 unmodified lines8586878889909113 unmodified lines10510610710810911011110 unmodified lines1221231241251261271284 unmodified lines1331341351361371381397 unmodified linesfrom .activations import get_activationdef cast_tuple(t, length = 1):return t if isinstance(t, tuple) else ((t,) * length)52 unmodified lines**kwargs,)def forward(self, x: torch.Tensor) -> torch.Tensor:# x: (B, C, T, H, W)dtype = x.dtypex = x.float()if self.padding_flag == 0:x = F.pad(x,9 unmodified linesmode="replicate", # TODO: check if this is necessary)x = x.to(dtype=dtype)self.prev_features = x[:, :, -self.temporal_padding:]b, c, f, h, w = x.size()outputs = []13 unmodified lines[self.prev_features, x], dim = 2)x = x.to(dtype=dtype)self.prev_features = x[:, :, -self.temporal_padding:]b, c, f, h, w = x.size()outputs = []10 unmodified linesmode="replicate", # TODO: check if this is necessary)x = x.to(dtype=dtype)self.prev_features = x[:, :, -self.temporal_padding:]return super().forward(x)elif self.padding_flag == 6:if self.t_stride == 2:4 unmodified linesx = torch.concat([self.prev_features, x], dim = 2)self.prev_features = x[:, :, -self.temporal_padding:]x = x.to(dtype=dtype)return super().forward(x)else:7 unmodified lines8910111213141516171819202122232452 unmodified lines7778798081828384858687888990919 unmodified lines10110210310410510610710810911011113 unmodified lines12512612712812913013113213313413510 unmodified lines1461471481491501511521531541551561574 unmodified lines1621631641651661671681691701711721737 unmodified linesfrom .activations import get_activationtry:current_version = torch.__version__version_numbers = [int(x) for x in current_version.split('.')[:2]]if version_numbers[0] < 2 or (version_numbers[0] == 2 and version_numbers[1] < 2):need_to_float = Trueelse:need_to_float = Falseexcept Exception as e:print("Encountered an error with Torch version. Set the data type to float in the VAE. ")need_to_float = Falsedef cast_tuple(t, length = 1):return t if isinstance(t, tuple) else ((t,) * length)52 unmodified lines**kwargs,)def _clear_conv_cache(self):del self.prev_featuresself.prev_features = Nonedef forward(self, x: torch.Tensor) -> torch.Tensor:# x: (B, C, T, H, W)dtype = x.dtypeif need_to_float:x = x.float()if self.padding_flag == 0:x = F.pad(x,9 unmodified linesmode="replicate", # TODO: check if this is necessary)x = x.to(dtype=dtype)# Clear cache beforeself._clear_conv_cache()# We could move these to the cpu for a lower VRAMself.prev_features = x[:, :, -self.temporal_padding:].clone()b, c, f, h, w = x.size()outputs = []13 unmodified lines[self.prev_features, x], dim = 2)x = x.to(dtype=dtype)# Clear cache beforeself._clear_conv_cache()# We could move these to the cpu for a lower VRAMself.prev_features = x[:, :, -self.temporal_padding:].clone()b, c, f, h, w = x.size()outputs = []10 unmodified linesmode="replicate", # TODO: check if this is necessary)x = x.to(dtype=dtype)# Clear cache beforeself._clear_conv_cache()# We could move these to the cpu for a lower VRAMself.prev_features = x[:, :, -self.temporal_padding:].clone()return super().forward(x)elif self.padding_flag == 6:if self.t_stride == 2:4 unmodified linesx = torch.concat([self.prev_features, x], dim = 2)# Clear cache beforeself._clear_conv_cache()# We could move these to the cpu for a lower VRAMself.prev_features = x[:, :, -self.temporal_padding:].clone()x = x.to(dtype=dtype)return super().forward(x)else:
5 unmodified lines67891011128 unmodified lines21222324252627285 unmodified linestorch>=2.1.2torchdiffeqtorchsdexformersdecorddatasetsnumpy8 unmodified linesbeautifulsoup4ftfyfunc_timeoutdeepspeedaccelerate>=0.25.0gradio>=3.41.2diffusers>=0.30.1transformers>=4.37.25 unmodified lines678910118 unmodified lines2021222324255 unmodified linestorch>=2.1.2torchdiffeqtorchsdedecorddatasetsnumpy8 unmodified linesbeautifulsoup4ftfyfunc_timeoutaccelerate>=0.25.0diffusers==0.30.1transformers==4.46.2
app.py+9-18
config/easyanimate_video_v5.1_magvit_qwen.yamlAdded+21
easyanimate/api/api.py+1-1
easyanimate/api/post_infer.py+2-2
easyanimate/data/dataset_image_video.py+220-32
easyanimate/models/__init__.py+3-4
easyanimate/models/attention.py+60-31
easyanimate/models/autoencoder_magvit.py+15-117
easyanimate/models/embeddings.py+3-2
easyanimate/models/norm.py+16
easyanimate/models/processor.py+146
easyanimate/models/transformer3d.py+280-43
easyanimate/pipeline/pipeline_easyanimate.py+730-486
easyanimate/pipeline/pipeline_easyanimate_multi_text_encoder_control.py → easyanimate/pipeline/pipeline_easyanimate_control.pyRenamed+448-229
easyanimate/pipeline/pipeline_easyanimate_inpaint.py
easyanimate/pipeline/pipeline_easyanimate_multi_text_encoder.pyDeleted-925
easyanimate/pipeline/pipeline_easyanimate_multi_text_encoder_inpaint.pyDeleted-1334
easyanimate/ui/ui.py+237-179
easyanimate/utils/lora_utils.py+42-30
easyanimate/utils/utils.py+53-33
easyanimate/vae/ldm/models/autoencoder.py+4-4
easyanimate/vae/ldm/models/casual3dcnn.py+5-5
easyanimate/vae/ldm/models/cogvideox_casual3dcnn.py+5-5
easyanimate/vae/ldm/models/omnigen_casual3dcnn.py+13-9
easyanimate/vae/ldm/models/omnigen_enc_dec.py+6-2
easyanimate/vae/ldm/modules/losses/contperceptual.py+20-3
easyanimate/vae/ldm/modules/vaemodules/__init__.py
easyanimate/vae/ldm/modules/vaemodules/activations.py
easyanimate/vae/ldm/modules/vaemodules/common.py+39-5
easyanimate/vae/ldm/modules/vaemodules/down_blocks.py
easyanimate/vae/ldm/modules/vaemodules/mid_blocks.py
easyanimate/vae/ldm/modules/vaemodules/up_blocks.py
requirements.txt+2-5