diff --git a/Helios-main/example/toy_data/toy_filter.json b/Helios-main/example/toy_data/toy_filter.json new file mode 100644 index 0000000000000000000000000000000000000000..610c8a1edecae7502af491cacedd7aaeeca39319 --- /dev/null +++ b/Helios-main/example/toy_data/toy_filter.json @@ -0,0 +1,46 @@ +[ + { + "cut": [ + 0, + 81 + ], + "crop": [ + 0, + 832, + 0, + 480 + ], + "fps": 24.0, + "num_frames": 81, + "resolution": { + "height": 480, + "width": 832 + }, + "cap": [ + "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity." + ], + "path": "videos/2_240_ori81.mp4" + }, + { + "cut": [ + 0, + 129 + ], + "crop": [ + 0, + 832, + 0, + 480 + ], + "fps": 24.0, + "num_frames": 129, + "resolution": { + "height": 480, + "width": 832 + }, + "cap": [ + "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man." + ], + "path": "videos/239_120_ori129.mp4" + } +] \ No newline at end of file diff --git a/Helios-main/helios/dataset/__init__.py b/Helios-main/helios/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios-main/helios/dataset/dataloader_dmd.py b/Helios-main/helios/dataset/dataloader_dmd.py new file mode 100644 index 0000000000000000000000000000000000000000..bf66562003089c5a676f49e019ca0188be12ebff --- /dev/null +++ b/Helios-main/helios/dataset/dataloader_dmd.py @@ -0,0 +1,531 @@ +import os +import pickle +import random +from collections import defaultdict + +import torch +from einops import rearrange +from torch.utils.data import Dataset, Sampler + + +class BucketedFeatureDataset(Dataset): + def __init__( + self, + gan_folders=None, + ode_folders=None, + text_folders=None, + is_use_gt_history=False, + return_secondary=False, + force_rebuild=False, + single_res=True, + single_length=True, + single_num_frame=81, + single_height=384, + single_width=640, + seed=42, + ): + self.is_use_gt_history = is_use_gt_history + self.return_secondary = return_secondary + self.force_rebuild = force_rebuild + self.base_seed = seed + self._epoch = 0 + + self.single_res = single_res + self.single_length = single_length + self.single_num_frame = single_num_frame + self.single_height = single_height + self.single_width = single_width + + self.gan_samples = self._init_samples(gan_folders, "gan") + self.ode_samples = self._init_samples(ode_folders, "ode") + self.text_samples = self._init_samples(text_folders, "text") + + self._align_sample_counts() + + def _init_samples(self, folders, data_type): + if folders is None: + return [] + + folders = [folders] if isinstance(folders, str) else folders + samples = [] + + for folder in folders: + cache_file = os.path.join(folder, f"{data_type}_dataset_cache.pkl") + folder_samples = self._process_folder(folder, cache_file, data_type) + samples.extend(folder_samples) + + return samples + + def _align_sample_counts(self, is_log=True): + lengths = {"gan": len(self.gan_samples), "ode": len(self.ode_samples), "text": len(self.text_samples)} + + non_empty_lengths = {k: v for k, v in lengths.items() if v > 0} + if not non_empty_lengths: + return + max_length = max(non_empty_lengths.values()) + + if is_log: + print(f"\nAligning sample counts to max: {max_length}") + print(f"Original counts - GAN: {lengths['gan']}, ODE: {lengths['ode']}, TEXT: {lengths['text']}") + + random.seed(self.base_seed) + + if self.gan_samples and len(self.gan_samples) < max_length: + self.gan_samples = self._expand_samples(self.gan_samples, max_length, "GAN") + + if self.ode_samples and len(self.ode_samples) < max_length: + self.ode_samples = self._expand_samples(self.ode_samples, max_length, "ODE") + + if self.text_samples and len(self.text_samples) < max_length: + self.text_samples = self._expand_samples(self.text_samples, max_length, "TEXT") + + if is_log: + print( + f"Aligned counts - GAN: {len(self.gan_samples)}, ODE: {len(self.ode_samples)}, TEXT: {len(self.text_samples)}\n" + ) + + def _expand_samples(self, samples, target_length, data_type): + original_length = len(samples) + expanded_samples = samples.copy() + + while len(expanded_samples) < target_length: + random_sample = random.choice(samples) + expanded_samples.append(random_sample) + + print(f"{data_type}: Expanded from {original_length} to {len(expanded_samples)} samples") + return expanded_samples + + def _process_folder(self, folder, cache_file, data_type): + if self.force_rebuild or not os.path.exists(cache_file): + # if os.path.exists(cache_file): + # os.remove(cache_file) + print(f"{data_type.upper()}: Building metadata cache for folder: {folder}") + folder_samples = self._build_folder_metadata(folder, data_type) + + if not self.force_rebuild: + print(f"{data_type.upper()}: Saving metadata cache for folder: {folder}") + with open(cache_file, "wb") as f: + pickle.dump({"samples": folder_samples}, f) + + print(f"{data_type.upper()}: Cached {len(folder_samples)} samples from {folder}") + else: + print(f"{data_type.upper()}: Loading cached metadata from: {folder}") + with open(cache_file, "rb") as f: + folder_samples = pickle.load(f)["samples"] + print(f"{data_type.upper()}: Loaded {len(folder_samples)} samples from cache: {folder}") + + return folder_samples + + def _build_folder_metadata(self, folder, data_type): + feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")] + samples = [] + + print(f"{data_type.upper()}: Processing {len(feature_files)} files in {folder}...") + for i, feature_file in enumerate(feature_files): + if i % 10000 == 0: + print(f" {data_type.upper()}: Processed {i}/{len(feature_files)} files") + + feature_path = os.path.join(folder, feature_file) + + # TODO hard code here now + if data_type == "gan": + parts = feature_file.split("_") + num_frame = int(parts[-3]) + height = int(parts[-2]) + width = int(parts[-1].replace(".pt", "")) + + if self.is_use_gt_history: + if (height, width) not in [(self.single_height, self.single_width)]: + continue + else: + if (num_frame, height, width) not in [ + (self.single_num_frame, self.single_height, self.single_width) + ]: + continue + + samples.append( + { + "uttid": os.path.splitext(os.path.basename(feature_file))[0], + "dataset_name": folder.rstrip("/"), + "file_path": feature_path, + } + ) + + return samples + + def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None, return_secondary=False): + self.is_keep_x0 = (True,) + self.history_sizes = [16, 2, 1] + self.num_rollout_sections = 9 + + source_latent = base_vae_latent if base_vae_latent is not None else vae_latent + + x0_latent = None + if self.is_keep_x0: + x0_latent = source_latent[0, :, :1, :, :].clone() + total_sections = source_latent.shape[0] + latent_window_size = source_latent.shape[2] + history_window_size = sum(self.history_sizes) + section_size = history_window_size + latent_window_size + + temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w") + zero_padding_source = torch.zeros( + temp_source_latent.shape[0], + history_window_size, + temp_source_latent.shape[2], + temp_source_latent.shape[3], + device=temp_source_latent.device, + dtype=temp_source_latent.dtype, + ) + continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1) + + temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w") + zero_padding_vae = torch.zeros( + temp_vae_latent.shape[0], + history_window_size, + temp_vae_latent.shape[2], + temp_vae_latent.shape[3], + device=temp_vae_latent.device, + dtype=temp_vae_latent.dtype, + ) + continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1) + + sample_seed = self.base_seed + self._epoch * 1000000 + idx + choice_idx = torch.randint( + 0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed) + ).item() + if choice_idx == 0 and x0_latent is not None: + x0_latent = torch.zeros_like(x0_latent) + + start_indice = choice_idx * latent_window_size + end_indice = start_indice + section_size + + history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :] + target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :] + + x0_latent_2 = None + history_latent_2 = None + target_latent_2 = None + if return_secondary: + sample_seed_2 = self.base_seed + self._epoch * 1000000 + idx + 999999 + choice_idx_2 = torch.randint( + 0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed_2) + ).item() + + x0_latent_2 = None + if self.is_keep_x0: + x0_latent_2 = source_latent[0, :, :1, :, :].clone() + if choice_idx_2 == 0: + x0_latent_2 = torch.zeros_like(x0_latent_2) + + start_indice_2 = choice_idx_2 * latent_window_size + end_indice_2 = start_indice_2 + section_size + + history_latent_2 = continue_source_latent[:, start_indice_2 : start_indice_2 + history_window_size, :, :] + target_latent_2 = continue_vae_latent[:, start_indice_2 + history_window_size : end_indice_2, :, :] + + return (x0_latent, history_latent, target_latent), (x0_latent_2, history_latent_2, target_latent_2) + + def set_epoch(self, epoch): + self._epoch = epoch + random.seed(self.base_seed + epoch) + self._align_sample_counts(is_log=False) + + def __len__(self): + return max(len(self.gan_samples), len(self.ode_samples), len(self.text_samples)) + + def __getitem__(self, idx): + while True: + try: + output_dict = {} + + if self.gan_samples: + gan_sample = self.gan_samples[idx] + gan_feature = torch.load(gan_sample["file_path"], map_location="cpu", weights_only=False) + if self.is_use_gt_history: + ( + (x0_latent, history_latent, target_latent), + (x0_latent_2, history_latent_2, target_latent_2), + ) = self.prepare_stage1_latent( + gan_feature["vae_latent"], + idx, + return_secondary=self.return_secondary, + ) + output_dict.update( + { + "gan_uttid": gan_sample["uttid"], + "gan_dataset_name": gan_sample["dataset_name"], + "gan_vae_latents": target_latent, + "gan_x0_latents": x0_latent, + "gan_history_latents": history_latent, + "gan_vae_latents_2": target_latent_2, + "gan_x0_latents_2": x0_latent_2, + "gan_history_latents_2": history_latent_2, + "gan_prompt_raws": gan_feature["prompt_raw"], + "gan_prompt_embeds": gan_feature["prompt_embed"], + } + ) + else: + output_dict.update( + { + "gan_uttid": gan_sample["uttid"], + "gan_dataset_name": gan_sample["dataset_name"], + "gan_vae_latents": gan_feature["vae_latent"], + "gan_prompt_raws": gan_feature["prompt_raw"], + "gan_prompt_embeds": gan_feature["prompt_embed"], + } + ) + gan_sample = None + gan_feature = None + del gan_sample + del gan_feature + + if self.ode_samples: + ode_sample = self.ode_samples[idx] + ode_feature = torch.load(ode_sample["file_path"], map_location="cpu", weights_only=False) + output_dict.update( + { + "ode_uttid": ode_sample["uttid"], + "ode_dataset_name": ode_sample["dataset_name"], + "ode_latent_window_size": ode_feature["latent_window_size"], + "ode_latents": ode_feature["ode_latents"], + "ode_prompt_raws": ode_feature["prompt_raw"], + "ode_prompt_embeds": ode_feature["prompt_embed"][0], + } + ) + ode_sample = None + ode_feature = None + del ode_sample + del ode_feature + + if self.text_samples: + text_sample = self.text_samples[idx] + text_feature = torch.load(text_sample["file_path"], map_location="cpu", weights_only=False) + output_dict.update( + { + "text_uttid": text_sample["uttid"], + "text_dataset_name": text_sample["dataset_name"], + "text_prompt_raws": text_feature["prompt_raw"], + "text_prompt_embeds": text_feature["prompt_embed"], + } + ) + text_sample = None + text_feature = None + del text_sample + del text_feature + + return output_dict + + except Exception as e: + idx = random.randint(0, len(self) - 1) + print(f"Error loading sample at idx {idx}, retrying... Error: {e}") + + +class BucketedSampler(Sampler): + def __init__( + self, + dataset, + batch_size, + dataset_sampling_ratios={}, + drop_last=False, + shuffle=True, + seed=42, + num_sp_groups=1, + sp_world_size=1, + global_rank=0, + ): + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.shuffle = shuffle + self.seed = seed + self.generator = torch.Generator() + self._epoch = 0 + + # Distributed parameters + self.num_sp_groups = num_sp_groups + self.sp_world_size = sp_world_size + self.global_rank = global_rank + self.ith_sp_group = self.global_rank // self.sp_world_size + + def set_epoch(self, epoch): + self._epoch = epoch + + def _shard_indices_for_sp_group(self, indices): + """ + Shard indices across SP groups. + Each SP group gets a disjoint subset of the data. + """ + if self.num_sp_groups == 1: + return indices + + # Convert to tensor if it's a list + if isinstance(indices, list): + indices_tensor = torch.tensor(indices, dtype=torch.long) + else: + indices_tensor = indices + + # Pad indices if necessary to make it divisible by num_sp_groups + total_size = len(indices_tensor) + if total_size % self.num_sp_groups != 0: + if not self.drop_last: + padding_size = self.num_sp_groups - (total_size % self.num_sp_groups) + indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]]) + else: + # If drop_last, truncate to be divisible + if self.drop_last: + truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups + indices_tensor = indices_tensor[:truncate_size] + + # Shard: each SP group gets every num_sp_groups-th element + sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups] + + return sp_group_indices.tolist() + + def __iter__(self): + # Use epoch-level seed for reproducibility + epoch_seed = self.seed + self._epoch + self.generator.manual_seed(epoch_seed) + + # Get all indices + all_indices = list(range(len(self.dataset))) + + # Global shuffle before sharding (important for distributed consistency) + if self.shuffle: + perm = torch.randperm(len(all_indices), generator=self.generator).tolist() + all_indices = [all_indices[i] for i in perm] + + # Shard indices for this SP group + sp_group_indices = self._shard_indices_for_sp_group(all_indices) + + # Create batches + for i in range(0, len(sp_group_indices), self.batch_size): + batch = sp_group_indices[i : i + self.batch_size] + if len(batch) == self.batch_size or not self.drop_last: + yield batch + + def __len__(self): + # Total samples in dataset + total_samples = len(self.dataset) + + # Account for SP group sharding + sp_group_samples = total_samples // self.num_sp_groups + if not self.drop_last and total_samples % self.num_sp_groups != 0: + sp_group_samples += 1 + + # Calculate number of batches + total_batches = sp_group_samples // self.batch_size + if not self.drop_last and sp_group_samples % self.batch_size != 0: + total_batches += 1 + + return total_batches + + +def collate_fn(batch): + return { + key: torch.stack([d[key] for d in batch]) + if isinstance(batch[0][key], torch.Tensor) + else [d[key] for d in batch] + for key in batch[0] + } + + +if __name__ == "__main__": + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + dataloader_num_workers = 8 + batch_size = 2 + num_train_epochs = 2 + seed = 0 + + gan_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_long_960", + "/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_short_960", + ] + ode_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/ode_pairs/vidprom_filtered_extended", + ] + text_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/mixkit_filter", + "/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/vidprom_filtered_extended", + ] + + accelerator = Accelerator() + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + gan_folders=gan_folder, + ode_folders=ode_folder, + text_folders=text_folder, + is_use_gt_history=True, + force_rebuild=True, + seed=seed, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=True, + shuffle=True, + seed=seed, + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + dataloader = StatefulDataLoader( + dataset, + batch_sampler=sampler, + collate_fn=collate_fn, + num_workers=dataloader_num_workers, + prefetch_factor=2 if dataloader_num_workers > 0 else None, + ) + print(len(dataset), len(dataloader)) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + + step = 0 + global_step = 0 + first_epoch = 0 + print("Testing dataloader...") + dataset_counts = defaultdict(int) + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + for i, batch in enumerate(dataloader): + # Get metadata + gan_uttid = batch["gan_uttid"] + ode_uttid = batch["ode_uttid"] + text_uttid = batch["text_uttid"] + + # Get feature + # For GAN + gan_vae_latents = batch["gan_vae_latents"] + gan_prompt_raws = batch["gan_prompt_raws"] + gan_prompt_embeds = batch["gan_prompt_embeds"] + print(gan_vae_latents.shape, gan_prompt_embeds.shape, gan_prompt_raws) + + # For ODE + ode_prompt_raws = batch["ode_prompt_raws"] + ode_prompt_embeds = batch["ode_prompt_embeds"] + print(ode_prompt_embeds.shape, ode_prompt_raws) + + # For Text + text_prompt_raws = batch["text_prompt_raws"] + text_prompt_embeds = batch["text_prompt_embeds"] + print(text_prompt_embeds.shape, text_prompt_raws) + + if accelerator.process_index == 0: + # print info + print(f" Step {step}:") + print(f" Batch {i}:") + print(f" Batch size: {len(gan_uttid)}") + print(f" Uttids: {gan_uttid}, {ode_uttid}, {text_uttid}") + print( + f" Data Name: {batch['gan_dataset_name']}, {batch['ode_dataset_name']}, {batch['text_dataset_name']}" + ) + + for dataset_name in batch["gan_dataset_name"]: + dataset_counts[dataset_name] += 1 + + step += 1 + + print("实际采样统计:", dict(dataset_counts)) diff --git a/Helios-main/helios/dataset/dataloader_history_latents_dist.py b/Helios-main/helios/dataset/dataloader_history_latents_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..f53ca5ee7a429c899ca48fc9baa0df0f24e0e72c --- /dev/null +++ b/Helios-main/helios/dataset/dataloader_history_latents_dist.py @@ -0,0 +1,685 @@ +import os +import pickle +import random +from collections import defaultdict + +import torch +from einops import rearrange +from torch.utils.data import Dataset, Sampler + + +class BucketedFeatureDataset(Dataset): + def __init__( + self, + feature_folders, + history_sizes=[16, 2, 1], + is_keep_x0=True, + force_rebuild=False, + return_all_vae_latent=False, + return_prompt_raw=False, + num_rollout_sections=3, + single_res=False, + single_height=384, + single_width=640, + seed=42, + ): + self.history_sizes = history_sizes + self.is_keep_x0 = is_keep_x0 + self.force_rebuild = force_rebuild + self.return_all_vae_latent = return_all_vae_latent + self.return_prompt_raw = return_prompt_raw + self.num_rollout_sections = num_rollout_sections + self.single_res = single_res + self.single_height = single_height + self.single_width = single_width + assert self.is_keep_x0, "is_keep_x0 need to be True now!" + + self.base_seed = seed + self._epoch = 0 + + if isinstance(feature_folders, str): + self.feature_folders = [feature_folders] + else: + self.feature_folders = feature_folders + + self.samples = [] + self.buckets = defaultdict(list) + + for folder in self.feature_folders: + cache_file = os.path.join(folder, "dataset_cache.pkl") + self._process_folder(folder, cache_file) + + def _process_folder(self, folder, cache_file): + if self.force_rebuild or not os.path.exists(cache_file): + print(f"Building metadata cache for folder: {folder}") + folder_samples, folder_buckets = self._build_folder_metadata(folder) + + print(f"Saving metadata cache for folder: {folder}") + cached_data = {"samples": folder_samples, "buckets": folder_buckets} + if not self.force_rebuild: + with open(cache_file, "wb") as f: + pickle.dump(cached_data, f) + print(f"Cached {len(folder_samples)} samples from {folder}\n") + else: + print(f"Loading cached metadata from: {folder}") + with open(cache_file, "rb") as f: + cached_data = pickle.load(f) + folder_samples = cached_data["samples"] + folder_buckets = cached_data["buckets"] + print(f"Loaded {len(folder_samples)} samples from cache: {folder}\n") + + sample_idx_offset = len(self.samples) + self.samples.extend(folder_samples) + + for bucket_key, indices in folder_buckets.items(): + adjusted_indices = [idx + sample_idx_offset for idx in indices] + self.buckets[bucket_key].extend(adjusted_indices) + + def _build_folder_metadata(self, folder): + feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")] + samples = [] + buckets = defaultdict(list) + sample_idx = 0 + + print(f"Processing {len(feature_files)} files in {folder}...") + + for i, feature_file in enumerate(feature_files): + if i % 10000 == 0: + print(f" Processed {i}/{len(feature_files)} files") + + feature_path = os.path.join(folder, feature_file) + + # Parse filename + parts = feature_file.split("_") + uttid = "_".join(parts[:-3]) + num_frame = int(parts[-3]) + height = int(parts[-2]) + width = int(parts[-1].replace(".pt", "")) + + # keep length >= 121 + if num_frame < 121: + continue + + # keep resolution + allowed_resolutions = [ + (self.single_height, self.single_width), + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ] + if self.single_res and (height, width) not in allowed_resolutions: + continue + + bucket_key = (num_frame, height, width) + + sample_info = { + "uttid": uttid, + "dataset_name": folder.rstrip("/"), + "file_path": feature_path, + "bucket_key": bucket_key, + "num_frame": num_frame, + "height": height, + "width": width, + } + + samples.append(sample_info) + buckets[bucket_key].append(sample_idx) + sample_idx += 1 + + return samples, buckets + + def set_epoch(self, epoch): + self._epoch = epoch + + def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None): + source_latent = base_vae_latent if base_vae_latent is not None else vae_latent + + x0_latent = None + if self.is_keep_x0: + x0_latent = source_latent[0, :, :1, :, :].clone() + total_sections = source_latent.shape[0] + latent_window_size = source_latent.shape[2] + history_window_size = sum(self.history_sizes) + section_size = history_window_size + latent_window_size + + temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w") + zero_padding_source = torch.zeros( + temp_source_latent.shape[0], + history_window_size, + temp_source_latent.shape[2], + temp_source_latent.shape[3], + device=temp_source_latent.device, + dtype=temp_source_latent.dtype, + ) + continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1) + + temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w") + zero_padding_vae = torch.zeros( + temp_vae_latent.shape[0], + history_window_size, + temp_vae_latent.shape[2], + temp_vae_latent.shape[3], + device=temp_vae_latent.device, + dtype=temp_vae_latent.dtype, + ) + continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1) + + sample_seed = self.base_seed + self._epoch * 1000000 + idx + choice_idx = torch.randint( + 0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed) + ).item() + if choice_idx == 0 and x0_latent is not None: + x0_latent = torch.zeros_like(x0_latent) + + clean_all_vae_latent = None + if self.return_all_vae_latent: + max_start_idx = total_sections - self.num_rollout_sections + if max_start_idx < 0: + raise ValueError( + f"Not enough sections: total_sections={total_sections}, num_rollout_sections={self.num_rollout_sections}" + ) + start_section_idx = random.randint(0, max_start_idx) + start_indice = start_section_idx * latent_window_size + end_indice = start_indice + history_window_size + self.num_rollout_sections * latent_window_size + clean_all_vae_latent = continue_source_latent[:, start_indice:end_indice, :, :] + + start_indice = choice_idx * latent_window_size + end_indice = start_indice + section_size + + history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :] + target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :] + + return x0_latent, history_latent, target_latent, clean_all_vae_latent + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + anchor_f = self.samples[idx]["num_frame"] + anchor_h = self.samples[idx]["height"] + anchor_w = self.samples[idx]["width"] + while True: + sample_info = self.samples[idx] + + if ( + anchor_f != sample_info["num_frame"] + or anchor_h != sample_info["height"] + or anchor_w != sample_info["width"] + ): + idx = random.randint(0, len(self.samples) - 1) + print("Try to find a same dim sample, retrying...") + continue + + try: + base_vae_latent = None + if (anchor_h, anchor_w) in [ + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ]: + base_file_path = ( + sample_info["file_path"] + .replace("/mid", "") + .replace("/low", "") + .replace( + f"{self.single_height // 2}_{self.single_width // 2}", + f"{self.single_height}_{self.single_width}", + ) + .replace( + f"{self.single_height // 4}_{self.single_width // 4}", + f"{self.single_height}_{self.single_width}", + ) + ) + base_vae_latent = torch.load(base_file_path, map_location="cpu", weights_only=False)["vae_latent"] + + feature_data = torch.load(sample_info["file_path"], map_location="cpu", weights_only=False) + x0_latent, history_latent, target_latent, clean_all_vae_latent = self.prepare_stage1_latent( + feature_data["vae_latent"], idx, base_vae_latent + ) + if self.return_prompt_raw: + prompt_raws = feature_data["prompt_raw"] + break + except Exception: + idx = random.randint(0, len(self.samples) - 1) + print(f"Error loading {sample_info['file_path']}, retrying...") + file_name = os.path.basename(sample_info["file_path"]) + txt_name = f"{file_name}.txt" + with open(txt_name, "w") as f: + f.write(sample_info["file_path"] + "\n") + + output_dict = { + "uttid": sample_info["uttid"], + "bucket_key": sample_info["bucket_key"], + "dataset_name": sample_info["dataset_name"], + "num_frame": sample_info["num_frame"], + "height": sample_info["height"], + "width": sample_info["width"], + "x0_latents": x0_latent, + "history_latents": history_latent, + "target_latents": target_latent, + "clean_all_latents": clean_all_vae_latent, + "prompt_embeds": feature_data["prompt_embed"], + "prompt_attention_masks": feature_data.get("prompt_attention_mask", None), + } + + if self.return_prompt_raw: + output_dict["prompt_raws"] = prompt_raws + + return output_dict + + +class BucketedSampler(Sampler): + def __init__( + self, + dataset, + batch_size, + drop_last=False, + shuffle=True, + seed=42, + dataset_sampling_ratios=None, + num_sp_groups=1, + sp_world_size=1, + global_rank=0, + ): + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.shuffle = shuffle + self.seed = seed + self.generator = torch.Generator() + self.buckets = dataset.buckets + self._epoch = 0 + + # Distributed parameters + self.num_sp_groups = num_sp_groups + self.sp_world_size = sp_world_size + self.global_rank = global_rank + self.ith_sp_group = self.global_rank // self.sp_world_size + + self.dataset_sampling_ratios = ( + {key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()} + if dataset_sampling_ratios is not None + else {} + ) + self._prepare_dataset_buckets() + + def _prepare_dataset_buckets(self): + self.dataset_buckets = {} + + for bucket_key, sample_indices in self.buckets.items(): + dataset_groups = {} + for idx in sample_indices: + dataset_name = self.dataset.samples[idx]["dataset_name"] + if dataset_name not in dataset_groups: + dataset_groups[dataset_name] = [] + dataset_groups[dataset_name].append(idx) + self.dataset_buckets[bucket_key] = dataset_groups + + def set_epoch(self, epoch): + self._epoch = epoch + + def _shard_indices_for_sp_group(self, indices): + """ + Shard indices across SP groups, similar to DP_SP_BatchSampler. + Each SP group gets a disjoint subset of the data. + """ + if self.num_sp_groups == 1: + return indices + + # Convert to tensor if it's a list + if isinstance(indices, list): + indices_tensor = torch.tensor(indices, dtype=torch.long) + else: + indices_tensor = indices + + # Pad indices if necessary to make it divisible by num_sp_groups + total_size = len(indices_tensor) + if total_size % self.num_sp_groups != 0: + if not self.drop_last: + padding_size = self.num_sp_groups - (total_size % self.num_sp_groups) + indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]]) + else: + # If drop_last, truncate to be divisible + if self.drop_last: + truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups + indices_tensor = indices_tensor[:truncate_size] + + # Shard: each SP group gets every num_sp_groups-th element + sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups] + + return sp_group_indices.tolist() + + def _apply_global_ratio_sampling(self): + if not self.dataset_sampling_ratios: + return + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = {"indices": [], "buckets": []} + dataset_sample_map[dataset_name]["indices"].extend(indices) + dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices)) + + total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_dataset_map = {} + for dataset_name, info in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + + indices = info["indices"] + buckets = info["buckets"] + + if len(indices) >= target_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist() + sampled_indices = [indices[i] for i in selected] + sampled_buckets = [buckets[i] for i in selected] + else: + sampled_indices = [] + sampled_buckets = [] + remaining = target_samples + + while remaining > 0: + repeat_count = min(remaining, len(indices)) + selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist() + sampled_indices.extend([indices[i] for i in selected]) + sampled_buckets.extend([buckets[i] for i in selected]) + remaining -= repeat_count + + sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets} + else: + sampled_dataset_map[dataset_name] = info + + new_dataset_buckets = {} + for bucket_key in self.dataset_buckets.keys(): + new_dataset_buckets[bucket_key] = {} + + for dataset_name, info in sampled_dataset_map.items(): + indices = info["indices"] + buckets = info["buckets"] + + for idx, bucket_key in zip(indices, buckets): + if dataset_name not in new_dataset_buckets[bucket_key]: + new_dataset_buckets[bucket_key][dataset_name] = [] + new_dataset_buckets[bucket_key][dataset_name].append(idx) + + self.dataset_buckets = new_dataset_buckets + + def __iter__(self): + # Use epoch-level seed for reproducibility + epoch_seed = self.seed + self._epoch + self.generator.manual_seed(epoch_seed) + + if self.dataset_sampling_ratios: + self._apply_global_ratio_sampling() + + bucket_iterators = {} + bucket_batches = {} + + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Global shuffle before sharding (important for distributed consistency) + if self.shuffle: + perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist() + balanced_indices = [balanced_indices[i] for i in perm] + + # Shard indices for this SP group + sp_group_indices = self._shard_indices_for_sp_group(balanced_indices) + + batches = [] + for i in range(0, len(sp_group_indices), self.batch_size): + batch = sp_group_indices[i : i + self.batch_size] + if len(batch) == self.batch_size or not self.drop_last: + batches.append(batch) + + if batches: + bucket_batches[bucket_key] = batches + bucket_iterators[bucket_key] = iter(batches) + + remaining_buckets = list(bucket_iterators.keys()) + + while remaining_buckets: + idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item() + bucket_key = remaining_buckets[idx] + bucket_iter = bucket_iterators[bucket_key] + + try: + batch = next(bucket_iter) + yield batch + except StopIteration: + remaining_buckets.remove(bucket_key) + + def _create_balanced_indices(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def _equal_sampling(self, dataset_groups): + all_indices = [] + dataset_names = list(dataset_groups.keys()) + + if len(dataset_names) <= 1: + return sum(dataset_groups.values(), []) + + min_samples = min(len(indices) for indices in dataset_groups.values()) + + for dataset_name, indices in dataset_groups.items(): + if len(indices) > min_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist() + sampled_indices = [indices[i] for i in selected] + else: + sampled_indices = indices + all_indices.extend(sampled_indices) + + return all_indices + + def _ratio_sampling(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def __len__(self): + if self.dataset_sampling_ratios: + temp_generator = torch.Generator() + temp_generator.manual_seed(self.seed) + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = [] + dataset_sample_map[dataset_name].extend(indices) + + total_samples = sum(len(indices) for indices in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_total = 0 + for dataset_name, indices in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + sampled_total += target_samples + else: + sampled_total += len(indices) + + # Account for SP group sharding + sp_group_samples = sampled_total // self.num_sp_groups + if not self.drop_last and sampled_total % self.num_sp_groups != 0: + sp_group_samples += 1 + + total_batches = sp_group_samples // self.batch_size + if not self.drop_last and sp_group_samples % self.batch_size != 0: + total_batches += 1 + return total_batches + else: + total_batches = 0 + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Account for SP group sharding + sp_group_size = len(balanced_indices) // self.num_sp_groups + if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0: + sp_group_size += 1 + + num_batches = sp_group_size // self.batch_size + if not self.drop_last and sp_group_size % self.batch_size != 0: + num_batches += 1 + total_batches += num_batches + return total_batches + + +def collate_fn(batch): + return { + key: torch.stack([d[key] for d in batch]) + if isinstance(batch[0][key], torch.Tensor) + else [d[key] for d in batch] + for key in batch[0] + } + + +if __name__ == "__main__": + import torch.distributed.checkpoint as dcp + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + feature_folder = [ + "demo_data/ultravideo-long", + ] + dataloader_num_workers = 0 + batch_size = 2 + num_train_epochs = 2 + seed = 0 + output_dir = "accelerate_checkpoints" + checkpoint_dirs = ( + [ + d + for d in os.listdir(output_dir) + if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d)) + ] + if os.path.exists(output_dir) + else [] + ) + + dataset_ratios = {} + # dataset_ratios = { + # "demo_data/ultravideo-long": 0.9, + # } + + accelerator = Accelerator() + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + feature_folder, + force_rebuild=True, + return_all_vae_latent=True, + return_prompt_raw=True, + single_res=True, + single_height=384, + single_width=640, + seed=seed, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=True, + shuffle=True, + dataset_sampling_ratios=dataset_ratios, + seed=seed, + # num_sp_groups=get_world_size() // get_sp_world_size(), + # sp_world_size=get_sp_world_size(), + # global_rank=get_world_rank(), + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + dataloader = StatefulDataLoader( + dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=dataloader_num_workers + ) + + print(len(dataset), len(dataloader)) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + + step = 0 + global_step = 0 + first_epoch = 0 + num_update_steps_per_epoch = len(dataloader) + if checkpoint_dirs: + latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1])) + checkpoint_path = os.path.join(output_dir, latest_checkpoint) + print(f"Found checkpoint: {checkpoint_path}") + + accelerator.load_state(checkpoint_path) + global_step = int(latest_checkpoint.split("-")[1]) + first_epoch = global_step // num_update_steps_per_epoch + + states = { + "dataloader": dataloader, + } + dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint") + dcp.load(states, checkpoint_id=dcp_dir) + + print(f"Resuming from step {global_step}, epoch {first_epoch}") + + print("Testing dataloader...") + step = global_step + dataset_counts = defaultdict(int) + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + for i, batch in enumerate(dataloader): + # Get metadata + uttid = batch["uttid"] + num_frame = batch["num_frame"] + height = batch["height"] + width = batch["width"] + bucket_key = batch["bucket_key"] + + # Get feature + x0_latents = batch["x0_latents"] + history_latents = batch["history_latents"] + target_latents = batch["target_latents"] + prompt_embeds = batch["prompt_embeds"] + + if accelerator.process_index == 0: + # print info + print(f" Step {step}:") + print(f" Batch {i}:") + # print(f" Data Name: {batch['dataset_name']}") + print(f" Batch size: {len(uttid)}") + print(f" Uttids: {uttid}") + print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}") + print(f" Bucket key: {bucket_key[0]}") + print(f" X0 latent shape: {x0_latents.shape}") + print(f" History latent shape: {history_latents.shape}") + print(f" Context latent shape: {target_latents.shape}") + print(f" Prompt embed shape: {prompt_embeds.shape}") + # print(f" Prompt attention mask shape: {prompt_attention_masks.shape}") + + # verify + assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch" + assert all(h == height[0] for h in height), "Heights not consistent in batch" + assert all(w == width[0] for w in width), "Widths not consistent in batch" + + print(" ✓ Batch dimensions are consistent") + + for dataset_name in batch["dataset_name"]: + dataset_counts[dataset_name] += 1 + + step += 1 + + # if step == 20: + # checkpoint_dir = f"checkpoint-{step}" + # save_path = os.path.join(output_dir, checkpoint_dir) + # os.makedirs(save_path, exist_ok=True) + + # if accelerator.is_main_process: + # print(f"Saving checkpoint at step {step}") + + # accelerator.save_state(save_path) + + # print(accelerator.process_index, accelerator.num_processes) + # states = { + # "dataloader": dataloader, + # } + # dcp_dir = os.path.join(save_path, "distributed_checkpoint") + # dcp.save(states, checkpoint_id=dcp_dir) + + print("实际采样统计:", dict(dataset_counts)) diff --git a/Helios-main/helios/dataset/dataloader_mp4_dist.py b/Helios-main/helios/dataset/dataloader_mp4_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc7529d39bdde6e8cdb58adeb427fc54c4f013a --- /dev/null +++ b/Helios-main/helios/dataset/dataloader_mp4_dist.py @@ -0,0 +1,854 @@ +import json +import os +import pickle +import random +from collections import defaultdict +from typing import Optional + +import pandas as pd +import torch +import torchvision +from torch.utils.data import Dataset, Sampler +from video_reader import PyVideoReader + +from diffusers.training_utils import free_memory +from diffusers.utils import export_to_video + + +resolution_bucket_options = { + 640: [ + (768, 320), + (768, 384), + (640, 384), + (768, 512), + (576, 448), + (512, 512), + (448, 576), + (512, 768), + (384, 640), + (384, 768), + (320, 768), + ], +} + +length_bucket_options = { + 1: [ + 501, + 481, + 461, + 441, + 421, + 401, + 381, + 361, + 341, + 321, + 301, + 281, + 261, + 241, + 221, + 193, + 181, + 161, + 141, + 121, + 101, + 81, + 61, + 41, + 21, + ], + 2: [193, 177, 161, 156, 145, 133, 129, 121, 113, 109, 97, 85, 81, 73, 65, 61, 49, 37, 25], +} + + +def find_nearest_resolution_bucket(h, w, resolution=640): + min_metric = float("inf") + best_bucket = None + for bucket_h, bucket_w in resolution_bucket_options[resolution]: + metric = abs(h * bucket_w - w * bucket_h) + if metric <= min_metric: + min_metric = metric + best_bucket = (bucket_h, bucket_w) + return best_bucket + + +def find_nearest_length_bucket(length, stride=1): + buckets = length_bucket_options[stride] + min_bucket = min(buckets) + if length < min_bucket: + return length + valid_buckets = [bucket for bucket in buckets if bucket <= length] + return max(valid_buckets) + + +def read_cut_crop_and_resize( + video_path, f_prime, h_prime, w_prime, stride=1, start_frame=None, end_frame=None, crop=None +): + frame_indices = list(range(start_frame, end_frame, stride)) + assert len(frame_indices) == f_prime + + vr = PyVideoReader(video_path, threads=0) # 0 means auto (let ffmpeg pick the optimal number) + frames = torch.from_numpy(vr.get_batch(frame_indices)).float() + + frames = (frames / 127.5) - 1 + video = frames.permute(0, 3, 1, 2) + + s_x, e_x, s_y, e_y = crop + video = video[:, :, s_y:e_y, s_x:e_x] + + frames, channels, h, w = video.shape + aspect_ratio_original = h / w + aspect_ratio_target = h_prime / w_prime + + if aspect_ratio_original >= aspect_ratio_target: + new_h = int(w * aspect_ratio_target) + top = (h - new_h) // 2 + bottom = top + new_h + left = 0 + right = w + else: + new_w = int(h / aspect_ratio_target) + left = (w - new_w) // 2 + right = left + new_w + top = 0 + bottom = h + + # Crop the video + cropped_video = video[:, :, top:bottom, left:right] + # Resize the cropped video + resized_video = torchvision.transforms.functional.resize(cropped_video, (h_prime, w_prime)) + return resized_video + + +def save_frames(frame_raw, fps=24, video_path="1.mp4"): + save_list = [] + for frame in frame_raw: + frame = (frame + 1) / 2 * 255 + frame = torchvision.transforms.transforms.ToPILImage()(frame.to(torch.uint8)).convert("RGB") + save_list.append(frame) + frame = None + del frame + export_to_video(save_list, video_path, fps=fps) + + save_list = None + del save_list + free_memory() + + +class BucketedFeatureDataset(Dataset): + def __init__( + self, + json_files, + video_folders, + stride=1, + base_fps=None, + resolution=640, + force_rebuild=True, + single_res=False, + single_length=False, + single_num_frame=81, + single_height=384, + single_width=640, + multi_res=False, + id_token: Optional[str] = None, + ): + self.stride = stride + self.base_fps = base_fps + self.resolution = resolution + self.force_rebuild = force_rebuild + self.single_res = single_res + self.single_height = single_height + self.single_width = single_width + self.single_length = single_length + self.single_num_frame = single_num_frame + self.multi_res = multi_res + self.id_token = id_token or "" + self._epoch = 0 + + if isinstance(json_files, str): + self.json_files = [json_files] + else: + self.json_files = json_files + + if isinstance(video_folders, str): + self.video_folders = [video_folders] + else: + self.video_folders = video_folders + + assert len(self.json_files) == len(self.video_folders), ( + f"json_files ({len(self.json_files)}) and video_folders ({len(self.video_folders)}) must have the same length" + ) + + self.samples = [] + self.buckets = defaultdict(list) + + for json_file, video_folder in zip(self.json_files, self.video_folders): + cache_file = json_file.replace(".json", "_cache.pkl").replace(".csv", "_cache.pkl") + self._process_json_file(json_file, video_folder, cache_file) + + def _process_json_file(self, json_file, video_folder, cache_file): + if self.force_rebuild or not os.path.exists(cache_file): + if os.path.exists(cache_file): + print(f"Remove {cache_file}") + os.remove(cache_file) + print(f"Building metadata cache for file: {json_file}") + print(f" Video folder: {video_folder}") + file_samples, file_buckets = self._build_file_metadata(json_file, video_folder) + + print(f"Saving metadata cache to: {cache_file}") + cached_data = {"samples": file_samples, "buckets": file_buckets} + with open(cache_file, "wb") as f: + pickle.dump(cached_data, f) + print(f"Cached {len(file_samples)} samples from {json_file}\n") + else: + print(f"Loading cached metadata from: {cache_file}") + with open(cache_file, "rb") as f: + cached_data = pickle.load(f) + file_samples = cached_data["samples"] + file_buckets = cached_data["buckets"] + print(f"Loaded {len(file_samples)} samples from cache: {cache_file}\n") + + sample_idx_offset = len(self.samples) + self.samples.extend(file_samples) + + for bucket_key, indices in file_buckets.items(): + adjusted_indices = [idx + sample_idx_offset for idx in indices] + self.buckets[bucket_key].extend(adjusted_indices) + + def _build_file_metadata(self, json_file, video_folder): + with open(json_file, "r") as f: + data = json.load(f) + + print(f"Scanning video folder: {video_folder}") + existing_videos = set() + for root, dirs, files in os.walk(video_folder): + for file in files: + if file.endswith(".mp4"): + rel_path = os.path.relpath(os.path.join(root, file), video_folder) + existing_videos.add(rel_path) + print(f"Found {len(existing_videos)} video files") + + df = pd.DataFrame( + [ + { + "cut": item["cut"], + "crop": item["crop"], + "path": item["path"], + "num_frames": item["num_frames"], + "width": item["resolution"]["width"], + "height": item["resolution"]["height"], + "fps": item["fps"], + "cap": item["cap"], + } + for item in data + ] + ) + + samples = [] + buckets = defaultdict(list) + sample_idx = 0 + + print(f"Processing {len(df)} records from {json_file} with stride={self.stride}...") + for i, row in df.iterrows(): + if i % 10000 == 0: + print(f" Processed {i}/{len(df)} records") + + video_file = ( + row["path"] + .replace("videos_clip_v1_20241111/", "") + .replace("videos_clip_v2_20241111/", "") + .replace("videos_clip_v4_20241111/", "") + ) + if video_file not in existing_videos: + print("bad video!") + continue + video_path = os.path.join(video_folder, video_file) + + cut_start_frame = row["cut"][0] + cut_end_frame = row["cut"][1] + num_frame = cut_end_frame - cut_start_frame + + if self.single_length: + if num_frame < self.single_num_frame: + continue + else: + if num_frame < 121: + continue + + uttid = os.path.basename(video_file).replace(".mp4", "") + f"_{cut_start_frame}-{cut_end_frame}" + fps = row["fps"] + + crop = row["crop"] + width = crop[1] - crop[0] + height = crop[3] - crop[2] + + prompt = row["cap"][0] + + # TODO need to be checked + effective_num_frame = (num_frame + self.stride - 1) // self.stride + bucket_num_frame = find_nearest_length_bucket(effective_num_frame, stride=self.stride) + bucket_height, bucket_width = find_nearest_resolution_bucket(height, width, resolution=self.resolution) + + if self.single_res or self.multi_res: + allowed_resolutions = [(self.single_height, self.single_width)] + if self.multi_res: + allowed_resolutions.extend( + [ + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ] + ) + if (bucket_height, bucket_width) not in allowed_resolutions: + print("continue res") + continue + bucket_height, bucket_width = random.choice(allowed_resolutions) + + if self.single_length: + bucket_num_frame = self.single_num_frame + + if self.base_fps is not None: + stride = max(int(fps / self.base_fps), 1) + required_frames = bucket_num_frame * stride + if required_frames >= num_frame: + print("continue frame") + continue + else: + stride = self.stride + + bucket_key = (bucket_num_frame, bucket_height, bucket_width) + + sample_info = { + "uttid": uttid, + "dataset_name": json_file.rstrip("/"), + "video_folder": video_folder, + "video_path": video_path, + "bucket_key": bucket_key, + "prompt": self.id_token + prompt, + "fps": fps, + "stride": stride, + "effective_num_frame": effective_num_frame, + "num_frame": num_frame, + "height": height, + "width": width, + "bucket_num_frame": bucket_num_frame, + "bucket_height": bucket_height, + "bucket_width": bucket_width, + "cut_start_frame": cut_start_frame, + "cut_end_frame": cut_end_frame, + "crop": crop, + } + + samples.append(sample_info) + buckets[bucket_key].append(sample_idx) + sample_idx += 1 + + return samples, buckets + + def set_epoch(self, epoch): + self._epoch = epoch + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + anchor_h = self.samples[idx]["bucket_height"] + anchor_w = self.samples[idx]["bucket_width"] + anchor_f = self.samples[idx]["bucket_num_frame"] + + max_retries = 1000 + retry_count = 0 + + while retry_count < max_retries: + sample_info = self.samples[idx] + + if ( + anchor_h != sample_info["bucket_height"] + or anchor_w != sample_info["bucket_width"] + or anchor_f != sample_info["bucket_num_frame"] + ): + idx = random.randint(0, len(self.samples) - 1) + retry_count += 1 + continue + + try: + stride = sample_info["stride"] + cut_start_frame = sample_info["cut_start_frame"] + cut_end_frame = sample_info["cut_end_frame"] + bucket_num_frame = sample_info["bucket_num_frame"] + + max_start_frame = cut_end_frame - bucket_num_frame * stride + if max_start_frame < cut_start_frame: + start_frame = cut_start_frame + else: + start_frame = random.randint(cut_start_frame, max_start_frame) + end_frame = start_frame + bucket_num_frame * stride + + video_data = read_cut_crop_and_resize( + video_path=sample_info["video_path"], + f_prime=sample_info["bucket_num_frame"], + h_prime=sample_info["bucket_height"], + w_prime=sample_info["bucket_width"], + stride=stride, + start_frame=start_frame, + end_frame=end_frame, + crop=sample_info["crop"], + ) + + return { + "uttid": sample_info["uttid"], + "bucket_key": sample_info["bucket_key"], + "dataset_name": sample_info["dataset_name"], + "video_metadata": { + "num_frames": sample_info["bucket_num_frame"], + "height": sample_info["bucket_height"], + "width": sample_info["bucket_width"], + "fps": sample_info["fps"], + "stride": stride, + "effective_num_frame": sample_info["effective_num_frame"], + }, + "videos": video_data, + "prompts": sample_info["prompt"], + "first_frames_images": (video_data[0] + 1) / 2 * 255, + } + except Exception as e: + print(f"Error loading {sample_info['video_path']}: {e}") + idx = random.randint(0, len(self.samples) - 1) + retry_count += 1 + + print(f"Failed to load sample after {max_retries} retries, returning None") + return None + + +class BucketedSampler(Sampler): + def __init__( + self, + dataset, + batch_size, + drop_last=False, + shuffle=True, + seed=42, + dataset_sampling_ratios=None, + num_sp_groups=1, + sp_world_size=1, + global_rank=0, + ): + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.shuffle = shuffle + self.seed = seed + self.generator = torch.Generator() + self.buckets = dataset.buckets + self._epoch = 0 + + # Distributed parameters + self.num_sp_groups = num_sp_groups + self.sp_world_size = sp_world_size + self.global_rank = global_rank + self.ith_sp_group = self.global_rank // self.sp_world_size + + self.dataset_sampling_ratios = ( + {key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()} + if dataset_sampling_ratios is not None + else {} + ) + self._prepare_dataset_buckets() + + def _prepare_dataset_buckets(self): + self.dataset_buckets = {} + + for bucket_key, sample_indices in self.buckets.items(): + dataset_groups = {} + for idx in sample_indices: + dataset_name = self.dataset.samples[idx]["dataset_name"] + if dataset_name not in dataset_groups: + dataset_groups[dataset_name] = [] + dataset_groups[dataset_name].append(idx) + self.dataset_buckets[bucket_key] = dataset_groups + + def set_epoch(self, epoch): + self._epoch = epoch + + def _shard_indices_for_sp_group(self, indices): + """ + Shard indices across SP groups, similar to DP_SP_BatchSampler. + Each SP group gets a disjoint subset of the data. + """ + if self.num_sp_groups == 1: + return indices + + # Convert to tensor if it's a list + if isinstance(indices, list): + indices_tensor = torch.tensor(indices, dtype=torch.long) + else: + indices_tensor = indices + + # Pad indices if necessary to make it divisible by num_sp_groups + total_size = len(indices_tensor) + if total_size % self.num_sp_groups != 0: + if not self.drop_last: + padding_size = self.num_sp_groups - (total_size % self.num_sp_groups) + indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]]) + else: + # If drop_last, truncate to be divisible + if self.drop_last: + truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups + indices_tensor = indices_tensor[:truncate_size] + + # Shard: each SP group gets every num_sp_groups-th element + sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups] + + return sp_group_indices.tolist() + + def _apply_global_ratio_sampling(self): + if not self.dataset_sampling_ratios: + return + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = {"indices": [], "buckets": []} + dataset_sample_map[dataset_name]["indices"].extend(indices) + dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices)) + + total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_dataset_map = {} + for dataset_name, info in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + + indices = info["indices"] + buckets = info["buckets"] + + if len(indices) >= target_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist() + sampled_indices = [indices[i] for i in selected] + sampled_buckets = [buckets[i] for i in selected] + else: + sampled_indices = [] + sampled_buckets = [] + remaining = target_samples + + while remaining > 0: + repeat_count = min(remaining, len(indices)) + selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist() + sampled_indices.extend([indices[i] for i in selected]) + sampled_buckets.extend([buckets[i] for i in selected]) + remaining -= repeat_count + + sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets} + else: + sampled_dataset_map[dataset_name] = info + + new_dataset_buckets = {} + for bucket_key in self.dataset_buckets.keys(): + new_dataset_buckets[bucket_key] = {} + + for dataset_name, info in sampled_dataset_map.items(): + indices = info["indices"] + buckets = info["buckets"] + + for idx, bucket_key in zip(indices, buckets): + if dataset_name not in new_dataset_buckets[bucket_key]: + new_dataset_buckets[bucket_key][dataset_name] = [] + new_dataset_buckets[bucket_key][dataset_name].append(idx) + + self.dataset_buckets = new_dataset_buckets + + def __iter__(self): + # Use epoch-level seed for reproducibility + epoch_seed = self.seed + self._epoch + self.generator.manual_seed(epoch_seed) + + if self.dataset_sampling_ratios: + self._apply_global_ratio_sampling() + + bucket_iterators = {} + bucket_batches = {} + + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Global shuffle before sharding (important for distributed consistency) + if self.shuffle: + perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist() + balanced_indices = [balanced_indices[i] for i in perm] + + # Shard indices for this SP group + sp_group_indices = self._shard_indices_for_sp_group(balanced_indices) + + batches = [] + for i in range(0, len(sp_group_indices), self.batch_size): + batch = sp_group_indices[i : i + self.batch_size] + if len(batch) == self.batch_size or not self.drop_last: + batches.append(batch) + + if batches: + bucket_batches[bucket_key] = batches + bucket_iterators[bucket_key] = iter(batches) + + remaining_buckets = list(bucket_iterators.keys()) + + while remaining_buckets: + idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item() + bucket_key = remaining_buckets[idx] + bucket_iter = bucket_iterators[bucket_key] + + try: + batch = next(bucket_iter) + yield batch + except StopIteration: + remaining_buckets.remove(bucket_key) + + def _create_balanced_indices(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def _equal_sampling(self, dataset_groups): + all_indices = [] + dataset_names = list(dataset_groups.keys()) + + if len(dataset_names) <= 1: + return sum(dataset_groups.values(), []) + + min_samples = min(len(indices) for indices in dataset_groups.values()) + + for dataset_name, indices in dataset_groups.items(): + if len(indices) > min_samples: + selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist() + sampled_indices = [indices[i] for i in selected] + else: + sampled_indices = indices + all_indices.extend(sampled_indices) + + return all_indices + + def _ratio_sampling(self, dataset_groups): + return sum(dataset_groups.values(), []) + + def __len__(self): + if self.dataset_sampling_ratios: + temp_generator = torch.Generator() + temp_generator.manual_seed(self.seed) + + dataset_sample_map = {} + for bucket_key, dataset_groups in self.dataset_buckets.items(): + for dataset_name, indices in dataset_groups.items(): + if dataset_name not in dataset_sample_map: + dataset_sample_map[dataset_name] = [] + dataset_sample_map[dataset_name].extend(indices) + + total_samples = sum(len(indices) for indices in dataset_sample_map.values()) + total_ratio = sum(self.dataset_sampling_ratios.values()) + + sampled_total = 0 + for dataset_name, indices in dataset_sample_map.items(): + if dataset_name in self.dataset_sampling_ratios: + ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio + target_samples = max(1, int(total_samples * ratio)) + sampled_total += target_samples + else: + sampled_total += len(indices) + + # Account for SP group sharding + sp_group_samples = sampled_total // self.num_sp_groups + if not self.drop_last and sampled_total % self.num_sp_groups != 0: + sp_group_samples += 1 + + total_batches = sp_group_samples // self.batch_size + if not self.drop_last and sp_group_samples % self.batch_size != 0: + total_batches += 1 + return total_batches + else: + total_batches = 0 + for bucket_key, dataset_groups in self.dataset_buckets.items(): + balanced_indices = self._create_balanced_indices(dataset_groups) + + # Account for SP group sharding + sp_group_size = len(balanced_indices) // self.num_sp_groups + if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0: + sp_group_size += 1 + + num_batches = sp_group_size // self.batch_size + if not self.drop_last and sp_group_size % self.batch_size != 0: + num_batches += 1 + total_batches += num_batches + return total_batches + + +def collate_fn(batch): + batch = [item for item in batch if item is not None] + + if len(batch) == 0: + return None + + def collate_dict(data_list): + if isinstance(data_list[0], dict): + return {key: collate_dict([d[key] for d in data_list]) for key in data_list[0]} + elif isinstance(data_list[0], torch.Tensor): + return torch.stack(data_list) + else: + return data_list + + return {key: collate_dict([d[key] for d in batch]) for key in batch[0]} + + +if __name__ == "__main__": + import torch.distributed.checkpoint as dcp + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + json_file = [ + "opensoraplan/jsons/video_mixkit_513f_1997.json", + ] + video_folder = [ + "opensoraplan/videos", + ] + stride = 1 + batch_size = 2 + num_train_epochs = 1 + seed = 0 + num_workers = 8 + output_dir = "accelerate_checkpoints" + checkpoint_dirs = ( + [ + d + for d in os.listdir(output_dir) + if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d)) + ] + if os.path.exists(output_dir) + else [] + ) + + dataset_ratios = {} + # dataset_ratios = { + # "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents": 0.9, + # "/mnt/hdfs/data/ysh_new/userful_things_wan/sekai/sekai-real-walking-hq-193/latents_stride1": 0.1 + # } + + accelerator = Accelerator() + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + json_files=json_file, + video_folders=video_folder, + stride=stride, + force_rebuild=False, + resolution=640, + single_res=True, + single_height=384, + single_width=640, + single_length=True, + single_num_frame=81, + multi_res=True, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=True, + shuffle=False, + dataset_sampling_ratios=dataset_ratios, + seed=seed, + # num_sp_groups=get_world_size() // get_sp_world_size(), + # sp_world_size=get_sp_world_size(), + # global_rank=get_world_rank(), + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + dataloader = StatefulDataLoader(dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=num_workers) + + print(len(dataset), len(dataloader)) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + + step = 0 + global_step = 0 + first_epoch = 0 + num_update_steps_per_epoch = len(dataloader) + if checkpoint_dirs: + latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1])) + checkpoint_path = os.path.join(output_dir, latest_checkpoint) + print(f"Found checkpoint: {checkpoint_path}") + + accelerator.load_state(checkpoint_path) + global_step = int(latest_checkpoint.split("-")[1]) + first_epoch = global_step // num_update_steps_per_epoch + + states = { + "dataloader": dataloader, + } + dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint") + dcp.load(states, checkpoint_id=dcp_dir) + + print(f"Resuming from step {global_step}, epoch {first_epoch}") + + print("Testing dataloader...") + step = global_step + dataset_counts = defaultdict(int) + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + for i, batch in enumerate(dataloader): + # Get metadata + uttid = batch["uttid"] + bucket_key = batch["bucket_key"] + num_frame = batch["video_metadata"]["num_frames"] + height = batch["video_metadata"]["height"] + width = batch["video_metadata"]["width"] + + # Get feature + video_data = batch["videos"] + prompt = batch["prompts"] + first_frames_images = batch["first_frames_images"] + first_frames_images = [torchvision.transforms.ToPILImage()(x.to(torch.uint8)) for x in first_frames_images] + + # save_frames(video_data[0].squeeze(0), video_path="1.mp4") + # import pdb;pdb.set_trace() + + if accelerator.process_index == 0: + # print info + print(f" Step {step}:") + print(f" Batch {i}:") + # print(f" Data Name: {batch['dataset_name']}") + print(f" Batch size: {len(uttid)}") + print(f" Uttids: {uttid}") + print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}") + print(f" Bucket key: {bucket_key[0]}") + print(f" Videos shape: {video_data.shape}") + print(f" Cpation: {prompt}") + + # verify + assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch" + assert all(h == height[0] for h in height), "Heights not consistent in batch" + assert all(w == width[0] for w in width), "Widths not consistent in batch" + + print(" ✓ Batch dimensions are consistent") + + for dataset_name in batch["dataset_name"]: + dataset_counts[dataset_name] += 1 + + step += 1 + + # if step == 20: + # checkpoint_dir = f"checkpoint-{step}" + # save_path = os.path.join(output_dir, checkpoint_dir) + # os.makedirs(save_path, exist_ok=True) + + # if accelerator.is_main_process: + # print(f"Saving checkpoint at step {step}") + + # accelerator.save_state(save_path) + + # print(accelerator.process_index, accelerator.num_processes) + # states = { + # "dataloader": dataloader, + # } + # dcp_dir = os.path.join(save_path, "distributed_checkpoint") + # dcp.save(states, checkpoint_id=dcp_dir) + + print("实际采样统计:", dict(dataset_counts)) diff --git a/Helios-main/helios/pipelines/__init__.py b/Helios-main/helios/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios-main/helios/pipelines/pipeline_output.py b/Helios-main/helios/pipelines/pipeline_output.py new file mode 100644 index 0000000000000000000000000000000000000000..08546289ef4c0739916c3106b8d9e6a93120d64a --- /dev/null +++ b/Helios-main/helios/pipelines/pipeline_output.py @@ -0,0 +1,20 @@ +from dataclasses import dataclass + +import torch + +from diffusers.utils import BaseOutput + + +@dataclass +class HeliosPipelineOutput(BaseOutput): + r""" + Output class for Helios pipelines. + + Args: + frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]): + List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing + denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape + `(batch_size, num_frames, channels, height, width)`. + """ + + frames: torch.Tensor diff --git a/Helios-main/helios/scheduler/__init__.py b/Helios-main/helios/scheduler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Helios-main/helios/scheduler/scheduling_helios.py b/Helios-main/helios/scheduler/scheduling_helios.py new file mode 100644 index 0000000000000000000000000000000000000000..b4831b9e9405e9d41d7fdae73eb1640d04d0a373 --- /dev/null +++ b/Helios-main/helios/scheduler/scheduling_helios.py @@ -0,0 +1,1056 @@ +import math +from dataclasses import dataclass +from typing import List, Optional, Tuple, Union + +import numpy as np +import torch + +from diffusers.configuration_utils import ConfigMixin, register_to_config +from diffusers.schedulers.scheduling_utils import SchedulerMixin +from diffusers.utils import BaseOutput, deprecate + + +@dataclass +class HeliosSchedulerOutput(BaseOutput): + """ + Output class for the scheduler's `step` function output. + + Args: + prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): + Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the + denoising loop. + """ + + prev_sample: torch.FloatTensor + model_outputs: torch.FloatTensor + last_sample: torch.FloatTensor + this_order: int + + +class HeliosScheduler(SchedulerMixin, ConfigMixin): + """ + Euler scheduler. + + This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic + methods the library implements for all schedulers such as loading and saving. + + Args: + num_train_timesteps (`int`, defaults to 1000): + The number of diffusion steps to train the model. + timestep_spacing (`str`, defaults to `"linspace"`): + The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and + Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information. + shift (`float`, defaults to 1.0): + The shift value for the timestep schedule. + """ + + _compatibles = [] + order = 1 + + @register_to_config + def __init__( + self, + num_train_timesteps: int = 1000, + shift: float = 1.0, # Following Stable diffusion 3, + stages: int = 3, + stage_range: List = [0, 1 / 3, 2 / 3, 1], + gamma: float = 1 / 3, + # For UniPC + thresholding: bool = False, + prediction_type: str = "flow_prediction", + solver_order: int = 2, + predict_x0: bool = True, + solver_type: str = "bh2", + lower_order_final: bool = True, + disable_corrector: List[int] = [], + solver_p: SchedulerMixin = None, + use_flow_sigmas: bool = True, + version: str = "v1", + ): + self.version = version + self.timestep_ratios = {} # The timestep ratio for each stage + self.timesteps_per_stage = {} # The detailed timesteps per stage (fix max and min per stage) + self.sigmas_per_stage = {} # always uniform [1000, 0] + self.start_sigmas = {} # for start point / upsample renoise + self.end_sigmas = {} # for end point + self.ori_start_sigmas = {} + + # self.init_sigmas() + self.init_sigmas_for_each_stage() + self.sigma_min = self.sigmas[-1].item() + self.sigma_max = self.sigmas[0].item() + self.gamma = gamma + + if solver_type not in ["bh1", "bh2"]: + if solver_type in ["midpoint", "heun", "logrho"]: + self.register_to_config(solver_type="bh2") + else: + raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}") + + self.predict_x0 = predict_x0 + self.model_outputs = [None] * solver_order + self.timestep_list = [None] * solver_order + self.lower_order_nums = 0 + self.disable_corrector = disable_corrector + self.solver_p = solver_p + self.last_sample = None + self._step_index = None + self._begin_index = None + + def init_sigmas(self): + """ + initialize the global timesteps and sigmas + """ + num_train_timesteps = self.config.num_train_timesteps + shift = self.config.shift + + alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps + 1) + sigmas = 1.0 - alphas + sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy() + sigmas = torch.from_numpy(sigmas) + timesteps = (sigmas * num_train_timesteps).clone() + + self._step_index = None + self._begin_index = None + self.timesteps = timesteps + self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication + + def init_sigmas_for_each_stage(self): + """ + Init the timesteps for each stage + """ + self.init_sigmas() + + stage_distance = [] + stages = self.config.stages + training_steps = self.config.num_train_timesteps + stage_range = self.config.stage_range + + # Init the start and end point of each stage + for i_s in range(stages): + # To decide the start and ends point + start_indice = int(stage_range[i_s] * training_steps) + start_indice = max(start_indice, 0) + end_indice = int(stage_range[i_s + 1] * training_steps) + end_indice = min(end_indice, training_steps) + start_sigma = self.sigmas[start_indice].item() + end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0 + self.ori_start_sigmas[i_s] = start_sigma + + if i_s != 0: + ori_sigma = 1 - start_sigma + gamma = self.config.gamma + corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma + # corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma + start_sigma = 1 - corrected_sigma + + stage_distance.append(start_sigma - end_sigma) + self.start_sigmas[i_s] = start_sigma + self.end_sigmas[i_s] = end_sigma + + if self.version == "v2": + new_start_indice = ( + len(self.sigmas) - torch.searchsorted(self.sigmas.flip(0), start_sigma, right=True) + ).item() + self.sigmas_per_stage[i_s] = self.sigmas[new_start_indice:end_indice] + self.timesteps_per_stage[i_s] = self.timesteps[new_start_indice:end_indice] + + if self.version == "v2": + return + + # Determine the ratio of each stage according to flow length + tot_distance = sum(stage_distance) + for i_s in range(stages): + if i_s == 0: + start_ratio = 0.0 + else: + start_ratio = sum(stage_distance[:i_s]) / tot_distance + if i_s == stages - 1: + end_ratio = 0.9999999999999999 + else: + end_ratio = sum(stage_distance[: i_s + 1]) / tot_distance + + self.timestep_ratios[i_s] = (start_ratio, end_ratio) + + # Determine the timesteps and sigmas for each stage + for i_s in range(stages): + timestep_ratio = self.timestep_ratios[i_s] + # timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)] + timestep_max = min(self.timesteps[int(timestep_ratio[0] * training_steps)], 999) + timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)] + timesteps = np.linspace(timestep_max, timestep_min, training_steps + 1) + self.timesteps_per_stage[i_s] = ( + timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1]) + ) + stage_sigmas = np.linspace(0.999, 0, training_steps + 1) + self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1]) + + @property + def step_index(self): + """ + The index counter for current timestep. It will increase 1 after each scheduler step. + """ + return self._step_index + + @property + def begin_index(self): + """ + The index for the first timestep. It should be set from pipeline with `set_begin_index` method. + """ + return self._begin_index + + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index + def set_begin_index(self, begin_index: int = 0): + """ + Sets the begin index for the scheduler. This function should be run from pipeline before the inference. + + Args: + begin_index (`int`): + The begin index for the scheduler. + """ + self._begin_index = begin_index + + def _sigma_to_t(self, sigma): + return sigma * self.config.num_train_timesteps + + def set_timesteps( + self, + num_inference_steps: int, + stage_index: int, + device: Union[str, torch.device] = None, + ): + """ + Setting the timesteps and sigmas for each stage + """ + self.num_inference_steps = num_inference_steps + self.init_sigmas() + + if self.version == "v1": + stage_timesteps = self.timesteps_per_stage[stage_index] + timestep_max = stage_timesteps[0].item() + timestep_min = stage_timesteps[-1].item() + + timesteps = np.linspace( + timestep_max, + timestep_min, + num_inference_steps, + ) + self.timesteps = torch.from_numpy(timesteps).to(device=device) + + stage_sigmas = self.sigmas_per_stage[stage_index] + sigma_max = stage_sigmas[0].item() + sigma_min = stage_sigmas[-1].item() + + ratios = np.linspace(sigma_max, sigma_min, num_inference_steps) + sigmas = torch.from_numpy(ratios).to(device=device) + self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)]) + else: + total_steps = len(self.timesteps_per_stage[stage_index]) + indices = np.linspace(0, total_steps - 1, num_inference_steps, dtype=int) + + self.timesteps = self.timesteps_per_stage[stage_index][indices].to(device=device) + + if stage_index == (self.config.stages - 1): + sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device) + self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)]) + else: + sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device) + self.sigmas = torch.cat( + [sigmas, torch.tensor([self.ori_start_sigmas[stage_index + 1]], device=sigmas.device)] + ) + + self._step_index = None + self.reset_scheduler_history() + + def index_for_timestep(self, timestep, schedule_timesteps=None): + if schedule_timesteps is None: + schedule_timesteps = self.timesteps + + indices = (schedule_timesteps == timestep).nonzero() + + # The sigma index that is taken for the **very** first `step` + # is always the second index (or the last index if there is only 1) + # This way we can ensure we don't accidentally skip a sigma in + # case we start in the middle of the denoising schedule (e.g. for image-to-image) + pos = 1 if len(indices) > 1 else 0 + + return indices[pos].item() + + def _init_step_index(self, timestep): + if self.begin_index is None: + if isinstance(timestep, torch.Tensor): + timestep = timestep.to(self.timesteps.device) + self._step_index = self.index_for_timestep(timestep) + else: + self._step_index = self._begin_index + + def step( + self, + model_output: torch.FloatTensor, + timestep: Union[float, torch.FloatTensor] = None, + sample: torch.FloatTensor = None, + generator: Optional[torch.Generator] = None, + sigma: Optional[torch.FloatTensor] = None, + sigma_next: Optional[torch.FloatTensor] = None, + return_dict: bool = True, + ) -> Union[HeliosSchedulerOutput, Tuple]: + """ + Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion + process from the learned model outputs (most often the predicted noise). + + Args: + model_output (`torch.FloatTensor`): + The direct output from learned diffusion model. + timestep (`float`): + The current discrete timestep in the diffusion chain. + sample (`torch.FloatTensor`): + A current instance of a sample created by the diffusion process. + generator (`torch.Generator`, *optional*): + A random number generator. + return_dict (`bool`): + Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or + tuple. + + Returns: + [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`: + If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is + returned, otherwise a tuple is returned where the first element is the sample tensor. + """ + + assert (sigma is None) == (sigma_next is None), "sigma and sigma_next must both be None or both be not None" + + if sigma is None and sigma_next is None: + if ( + isinstance(timestep, int) + or isinstance(timestep, torch.IntTensor) + or isinstance(timestep, torch.LongTensor) + ): + raise ValueError( + ( + "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to" + " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass" + " one of the `scheduler.timesteps` as a timestep." + ), + ) + + if self.step_index is None: + self._step_index = 0 + + # Upcast to avoid precision issues when computing prev_sample + sample = sample.to(torch.float32) + + if sigma is None and sigma_next is None: + sigma = self.sigmas[self.step_index] + sigma_next = self.sigmas[self.step_index + 1] + + prev_sample = sample + (sigma_next - sigma) * model_output + + # Cast sample back to model compatible dtype + prev_sample = prev_sample.to(model_output.dtype) + + # upon completion increase step index by one + self._step_index += 1 + + if not return_dict: + return (prev_sample,) + + return HeliosSchedulerOutput(prev_sample=prev_sample) + + # ---------------------------------- UniPC ---------------------------------- + # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._sigma_to_alpha_sigma_t + def _sigma_to_alpha_sigma_t(self, sigma): + if self.config.use_flow_sigmas: + alpha_t = 1 - sigma + sigma_t = torch.clamp(sigma, min=1e-8) + else: + alpha_t = 1 / ((sigma**2 + 1) ** 0.5) + sigma_t = sigma * alpha_t + + return alpha_t, sigma_t + + def convert_model_output( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + sigma: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + r""" + Convert the model output to the corresponding type the UniPC algorithm needs. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model. + timestep (`int`): + The current discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + + Returns: + `torch.Tensor`: + The converted model output. + """ + timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyword argument") + if timestep is not None: + deprecate( + "timesteps", + "1.0.0", + "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + flag = False + if sigma is None: + flag = True + sigma = self.sigmas[self.step_index] + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) + + if self.predict_x0: + if self.config.prediction_type == "epsilon": + x0_pred = (sample - sigma_t * model_output) / alpha_t + elif self.config.prediction_type == "sample": + x0_pred = model_output + elif self.config.prediction_type == "v_prediction": + x0_pred = alpha_t * sample - sigma_t * model_output + elif self.config.prediction_type == "flow_prediction": + if flag: + sigma_t = self.sigmas[self.step_index] + else: + sigma_t = sigma + x0_pred = sample - sigma_t * model_output + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, " + "`v_prediction`, or `flow_prediction` for the UniPCMultistepScheduler." + ) + + if self.config.thresholding: + x0_pred = self._threshold_sample(x0_pred) + + return x0_pred + else: + if self.config.prediction_type == "epsilon": + return model_output + elif self.config.prediction_type == "sample": + epsilon = (sample - alpha_t * model_output) / sigma_t + return epsilon + elif self.config.prediction_type == "v_prediction": + epsilon = alpha_t * model_output + sigma_t * sample + return epsilon + else: + raise ValueError( + f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" + " `v_prediction` for the UniPCMultistepScheduler." + ) + + def multistep_uni_p_bh_update( + self, + model_output: torch.Tensor, + *args, + sample: torch.Tensor = None, + order: int = None, + sigma: torch.Tensor = None, + sigma_next: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified. + + Args: + model_output (`torch.Tensor`): + The direct output from the learned diffusion model at the current timestep. + prev_timestep (`int`): + The previous discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + order (`int`): + The order of UniP at this timestep (corresponds to the *p* in UniPC-p). + + Returns: + `torch.Tensor`: + The sample tensor at the previous timestep. + """ + prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None) + if sample is None: + if len(args) > 1: + sample = args[1] + else: + raise ValueError("missing `sample` as a required keyword argument") + if order is None: + if len(args) > 2: + order = args[2] + else: + raise ValueError("missing `order` as a required keyword argument") + if prev_timestep is not None: + deprecate( + "prev_timestep", + "1.0.0", + "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + model_output_list = self.model_outputs + + s0 = self.timestep_list[-1] + m0 = model_output_list[-1] + x = sample + + if self.solver_p: + x_t = self.solver_p.step(model_output, s0, x).prev_sample + return x_t + + if sigma_next is None and sigma is None: + sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] + else: + sigma_t, sigma_s0 = sigma_next, sigma + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - i + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) # (B, K) + # for order 2, we use a simplified version + if order == 2: + rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype) + else: + D1s = None + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) + else: + pred_res = 0 + x_t = x_t_ - alpha_t * B_h * pred_res + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s) + else: + pred_res = 0 + x_t = x_t_ - sigma_t * B_h * pred_res + + x_t = x_t.to(x.dtype) + return x_t + + def multistep_uni_c_bh_update( + self, + this_model_output: torch.Tensor, + *args, + last_sample: torch.Tensor = None, + this_sample: torch.Tensor = None, + order: int = None, + sigma_before: torch.Tensor = None, + sigma: torch.Tensor = None, + **kwargs, + ) -> torch.Tensor: + """ + One step for the UniC (B(h) version). + + Args: + this_model_output (`torch.Tensor`): + The model outputs at `x_t`. + this_timestep (`int`): + The current timestep `t`. + last_sample (`torch.Tensor`): + The generated sample before the last predictor `x_{t-1}`. + this_sample (`torch.Tensor`): + The generated sample after the last predictor `x_{t}`. + order (`int`): + The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`. + + Returns: + `torch.Tensor`: + The corrected sample tensor at the current timestep. + """ + this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None) + if last_sample is None: + if len(args) > 1: + last_sample = args[1] + else: + raise ValueError("missing `last_sample` as a required keyword argument") + if this_sample is None: + if len(args) > 2: + this_sample = args[2] + else: + raise ValueError("missing `this_sample` as a required keyword argument") + if order is None: + if len(args) > 3: + order = args[3] + else: + raise ValueError("missing `order` as a required keyword argument") + if this_timestep is not None: + deprecate( + "this_timestep", + "1.0.0", + "Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", + ) + + model_output_list = self.model_outputs + + m0 = model_output_list[-1] + x = last_sample + x_t = this_sample + model_t = this_model_output + + if sigma_before is None and sigma is None: + sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1] + else: + sigma_t, sigma_s0 = sigma, sigma_before + alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) + alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) + + lambda_t = torch.log(alpha_t) - torch.log(sigma_t) + lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) + + h = lambda_t - lambda_s0 + device = this_sample.device + + rks = [] + D1s = [] + for i in range(1, order): + si = self.step_index - (i + 1) + mi = model_output_list[-(i + 1)] + alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si]) + lambda_si = torch.log(alpha_si) - torch.log(sigma_si) + rk = (lambda_si - lambda_s0) / h + rks.append(rk) + D1s.append((mi - m0) / rk) + + rks.append(1.0) + rks = torch.tensor(rks, device=device) + + R = [] + b = [] + + hh = -h if self.predict_x0 else h + h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 + h_phi_k = h_phi_1 / hh - 1 + + factorial_i = 1 + + if self.config.solver_type == "bh1": + B_h = hh + elif self.config.solver_type == "bh2": + B_h = torch.expm1(hh) + else: + raise NotImplementedError() + + for i in range(1, order + 1): + R.append(torch.pow(rks, i - 1)) + b.append(h_phi_k * factorial_i / B_h) + factorial_i *= i + 1 + h_phi_k = h_phi_k / hh - 1 / factorial_i + + R = torch.stack(R) + b = torch.tensor(b, device=device) + + if len(D1s) > 0: + D1s = torch.stack(D1s, dim=1) + else: + D1s = None + + # for order 1, we use a simplified version + if order == 1: + rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device) + else: + rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype) + + if self.predict_x0: + x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t) + else: + x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0 + if D1s is not None: + corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s) + else: + corr_res = 0 + D1_t = model_t - m0 + x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t) + x_t = x_t.to(x.dtype) + return x_t + + def step_unipc( + self, + model_output: torch.Tensor, + timestep: Union[int, torch.Tensor] = None, + sample: torch.Tensor = None, + return_dict: bool = True, + model_outputs: list = None, + timestep_list: list = None, + sigma_before: torch.Tensor = None, + sigma: torch.Tensor = None, + sigma_next: torch.Tensor = None, + cus_step_index: int = None, + cus_lower_order_num: int = None, + cus_this_order: int = None, + cus_last_sample: torch.Tensor = None, + ) -> Union[HeliosSchedulerOutput, Tuple]: + """ + Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with + the multistep UniPC. + + Args: + model_output (`torch.Tensor`): + The direct output from learned diffusion model. + timestep (`int`): + The current discrete timestep in the diffusion chain. + sample (`torch.Tensor`): + A current instance of a sample created by the diffusion process. + return_dict (`bool`): + Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`. + + Returns: + [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`: + If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a + tuple is returned where the first element is the sample tensor. + + """ + # don't change + # print(len(self.model_outputs), len(self.timestep_list), self.disable_corrector, self.solver_p, self._begin_index) + + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + if cus_step_index is None: + if self.step_index is None: + self._step_index = 0 + else: + self._step_index = cus_step_index + + if cus_lower_order_num is not None: + self.lower_order_nums = cus_lower_order_num + + if cus_this_order is not None: + self.this_order = cus_this_order + + if cus_last_sample is not None: + self.last_sample = cus_last_sample + + use_corrector = ( + self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None + ) + + # Convert model output using the proper conversion method + model_output_convert = self.convert_model_output(model_output, sample=sample, sigma=sigma) + + if model_outputs is not None and timestep_list is not None: + self.model_outputs = model_outputs[:-1] + self.timestep_list = timestep_list[:-1] + + # print("1", self.step_index, self.timestep_list) + + if use_corrector: + sample = self.multistep_uni_c_bh_update( + this_model_output=model_output_convert, + last_sample=self.last_sample, + this_sample=sample, + order=self.this_order, + sigma_before=sigma_before, + sigma=sigma, + ) + + if model_outputs is not None and timestep_list is not None: + model_outputs[-1] = model_output_convert + self.model_outputs = model_outputs[1:] + self.timestep_list = timestep_list[1:] + else: + for i in range(self.config.solver_order - 1): + self.model_outputs[i] = self.model_outputs[i + 1] + self.timestep_list[i] = self.timestep_list[i + 1] + self.model_outputs[-1] = model_output_convert + self.timestep_list[-1] = timestep + + if self.config.lower_order_final: + this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index) + else: + this_order = self.config.solver_order + self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep + assert self.this_order > 0 + + # change + # print("2", self.step_index, self.timestep_list, self.lower_order_nums, self.this_order, "\n") + # print(self._step_index, self.lower_order_nums, use_corrector, self.this_order, self.lower_order_nums) + # 0 1 False 1 1 + # 1 2 True 2 2 + # 2 2 True 2 2 + # 3 2 True 2 2 + # 4 2 True 2 2 + # 5 2 True 2 2 + # 6 2 True 2 2 + # 7 2 True 2 2 + # 8 2 True 2 2 + # 9 2 True 1 2 + + self.last_sample = sample + prev_sample = self.multistep_uni_p_bh_update( + model_output=model_output, # pass the original non-converted model output, in case solver-p is used + sample=sample, + order=self.this_order, + sigma=sigma, + sigma_next=sigma_next, + ) + + if cus_lower_order_num is None: + if self.lower_order_nums < self.config.solver_order: + self.lower_order_nums += 1 + + # upon completion increase step index by one + if cus_step_index is None: + self._step_index += 1 + + if not return_dict: + return (prev_sample, model_outputs, self.last_sample, self.this_order) + + return HeliosSchedulerOutput( + prev_sample=prev_sample, + model_outputs=model_outputs, + last_sample=self.last_sample, + this_order=self.this_order, + ) + + def reset_scheduler_history(self): + self.model_outputs = [None] * self.config.solver_order + self.timestep_list = [None] * self.config.solver_order + self.lower_order_nums = 0 + self.disable_corrector = self.config.disable_corrector + self.solver_p = self.config.solver_p + self.last_sample = None + self._step_index = None + self._begin_index = None + + def __len__(self): + return self.config.num_train_timesteps + + +if __name__ == "__main__": + device = "cuda" + + # ---------------------- For dynamic shifting ---------------------- + from examples.scheduling_unipc_multistep_latest import UniPCMultistepScheduler + + scheduler_official = UniPCMultistepScheduler.from_pretrained("BestWishYsh/Helios-Base", subfolder="scheduler") + scheduler_official.set_timesteps(num_inference_steps=50) + scheduler_official.timesteps + scheduler_official.sigmas + + # # Official + # from scheduling_flow_match_euler_discrete_official import FlowMatchEulerDiscreteScheduler + # scheduler_official = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=3.0) + # scheduler_official.set_timesteps(num_inference_steps=50, sigmas=None) + # scheduler_official.timesteps + # scheduler_official.sigmas + + # import sys + # sys.path.append("../../") + # from helios.utils.utils_helios_base import apply_schedule_shift + + # sigmas = apply_schedule_shift(scheduler_official.sigmas, torch.ones([2, 16, 21, 48, 80]), mu=3) + # timesteps = sigmas[:-1] * 1000.0 + + # import copy + # from diffusers.training_utils import compute_density_for_timestep_sampling + + # def get_sigmas(timesteps, n_dim=4, device="cpu", dtype=torch.float32): + # sigmas = noise_scheduler_copy.sigmas.to(device=device, dtype=dtype) + # schedule_timesteps = noise_scheduler_copy.timesteps.to(device) + # timesteps = timesteps.to(device) + # step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps] + # sigma = sigmas[step_indices].flatten() + # while len(sigma.shape) < n_dim: + # sigma = sigma.unsqueeze(-1) + # return sigma + + # noise_scheduler_copy = copy.deepcopy(scheduler_official) + + # # Sample noise that we'll add to the latents + # model_input = torch.ones([2, 16, 9, 88, 68]) + # noise = torch.randn_like(model_input) + # bsz = model_input.shape[0] + + # # Sample a random timestep for each image + # # for weighting schemes where we sample timesteps non-uniformly + # u = compute_density_for_timestep_sampling( + # weighting_scheme="logit_normal", batch_size=bsz, logit_mean=0.0, logit_std=1.0, mode_scale=1.29 + # ) + # indices = (u * noise_scheduler_copy.config.num_train_timesteps).long() + # timesteps = noise_scheduler_copy.timesteps[indices].to(device=model_input.device) + + # # Add noise according to flow matching. + # # zt = (1 - texp) * x + texp * z1 + # sigmas = get_sigmas(timesteps, n_dim=model_input.ndim, dtype=model_input.dtype) + + # import sys + # sys.path.append("../../") + # from helios.utils.utils_helios_base import apply_schedule_shift + + # sigmas = apply_schedule_shift(sigmas, noise) # torch.Size([2, 1, 1, 1, 1]) + # timesteps = sigmas * 1000.0 # rescale to [0, 1000.0) + # while timesteps.ndim > 1: + # timesteps = timesteps.squeeze(-1) + # ---------------------- For dynamic shifting ---------------------- + + # ---------------------- For timestep shifting ---------------------- + stages = 3 + timestep_shift = 1.0 + stage_range = [0, 1 / 3, 2 / 3, 1] + scheduler_gamma = 1 / 3 + version = "v1" + scheduler = HeliosScheduler( + shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version + ) + print( + f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}" + ) + + i_s = 1 + stage2_num_inference_steps_list = [3, 3, 3] + scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s) + scheduler.timesteps.to(dtype=torch.float32) + scheduler.sigmas.to(dtype=torch.float32) + + # stages = 2 + # timestep_shift = 3.0 + # stage_range = [0, 1 / 2, 1] + # scheduler_gamma = 1 / 3 + # version = "v2" + # scheduler = HeliosScheduler( + # shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version + # ) + # print( + # f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}" + # ) + + # i_s = 1 + # stage2_num_inference_steps_list = [10, 10] + # scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s) + # scheduler.timesteps.to(dtype=torch.float32) + # scheduler.sigmas.to(dtype=torch.float32) + + # scheduler.timesteps_per_stage[0] + # scheduler.sigmas_per_stage[0] + # shift1: (999, 743.5120) -> (743.2563, 385.9723) -> (385.6146, 1.3846) + # shift3: (999, 957.3958) -> (957.3542, 828.9170) -> (828.7885, 3.8198) + + # timesteps_1 = np.linspace(1, 1000 - 1, 1000, dtype=np.float32)[::-1].copy() + # timesteps_1 = torch.from_numpy(timesteps_1).to(dtype=torch.float32) + # sigmas_1 = timesteps_1 / 1000 + # sigmas_1 = apply_schedule_shift(sigmas_1, torch.ones([2, 16, 21, 48, 80]), mu=3) + # timesteps_2 = sigmas_1 * 1000 + + # import pdb;pdb.set_trace() + # temp_sigmas = apply_schedule_shift(scheduler.timesteps / 1000, torch.ones([2, 16, 21, 48, 80]), mu=3) + # temp_timesteps = temp_sigmas * 1000 + # while temp_timesteps.ndim > 1: + # temp_timesteps = temp_timesteps.squeeze(-1) + # temp_timesteps = temp_timesteps[:-1] + + # # very important here! + # timesteps = temp_timesteps + # # self.scheduler.sigmas = temp_sigmas + # scheduler.timesteps = temp_timesteps + + # ---------------------- For timestep shifting ---------------------- + + # ---------------------- For dynamic shifting ---------------------- + + # ---------------------- For per step sigmas & timesteps ---------------------- + # scheduler = HeliosScheduler(shift=3.0, stages=stages, stage_range=stage_range, gamma=scheduler_gamma) + # stage2_num_inference_steps_list = [10, 10, 10] + # i_s = 0 + # scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s) + # scheduler.timesteps_per_stage[0] + # scheduler.sigmas_per_stage[0] + # scheduler.timesteps + # scheduler.sigmas + # ---------------------- For per step sigmas & timesteps ---------------------- + + # ---------------------- For Custom step ---------------------- + # timesteps = scheduler.timesteps + # noise_pred = torch.randn([2, 16, 10, 48, 80], device=device) + # latents = torch.randn([2, 16, 10, 48, 80], device=device) + # for i, t in enumerate(timesteps): + # print(i, t) + # # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0] + # latents = scheduler.step_custom_unipc(noise_pred, t, latents, return_dict=False)[0] + + # def upsample_tensor(tensor, scale_factor=2): + # return torch.nn.functional.interpolate( + # tensor, scale_factor=scale_factor, mode="trilinear", align_corners=False + # ) + + # stage2_num_inference_steps_list = [10, 10, 10] + # noise_pred = torch.randn([2, 16, 10, 12, 20], device=device) + # latents = torch.randn([2, 16, 10, 12, 20], device=device) + # for stage, num_steps in enumerate(stage2_num_inference_steps_list): + # print(f"stage: {stage}, num_steps: {num_steps}") + # if stage > 0: + # latents = upsample_tensor(latents, scale_factor=2) + # noise_pred = upsample_tensor(noise_pred, scale_factor=2) + + # scheduler.set_timesteps(num_steps, stage) + # timesteps = scheduler.timesteps + + # print(f"Timesteps for stage {stage + 1}: {timesteps}") + + # for i, t in enumerate(timesteps): + # # print(i, t, latents.shape) + # # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0] + # latents = scheduler.step_unipc(noise_pred, t, latents, return_dict=False)[0] + # ---------------------- For Custom step ---------------------- diff --git a/Helios-main/scripts/inference/experiment_interactive/README.md b/Helios-main/scripts/inference/experiment_interactive/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3a37f60c20d23e1868398088592a111225b6f70b --- /dev/null +++ b/Helios-main/scripts/inference/experiment_interactive/README.md @@ -0,0 +1,3 @@ +# Interactive Pipeline by *Helios* + +⚠️ This feature is still under development — results may not always meet expectations. \ No newline at end of file diff --git a/Helios-main/scripts/inference/experiment_interactive/helios-base_t2v.sh b/Helios-main/scripts/inference/experiment_interactive/helios-base_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..814049e0603bef10890dc850aa4e8a42822d6009 --- /dev/null +++ b/Helios-main/scripts/inference/experiment_interactive/helios-base_t2v.sh @@ -0,0 +1,27 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Base" \ + --transformer_path "BestWishYsh/Helios-Base" \ + --sample_type "t2v" \ + --num_frames 1452 \ + --fps 24 \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --guidance_scale 5.0 \ + --enable_compile \ + --use_interpolate_prompt \ + --interpolation_steps 3 \ + --interactive_prompt_csv_path "example/prompt_interactive_helios.csv" \ + --interpolate_time 7 \ + --output_folder "./output_helios/helios-base" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --use_cfg_zero_star \ + # --use_zero_init \ + # --zero_steps 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/experiment_interactive/helios-distilled_t2v.sh b/Helios-main/scripts/inference/experiment_interactive/helios-distilled_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..7c0e8b26e26c62bb69838764ce46e4b4e8e53d9d --- /dev/null +++ b/Helios-main/scripts/inference/experiment_interactive/helios-distilled_t2v.sh @@ -0,0 +1,26 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Distilled" \ + --transformer_path "BestWishYsh/Helios-Distilled" \ + --sample_type "t2v" \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --num_frames 1452 \ + --guidance_scale 1.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 2 2 2 \ + --is_amplify_first_chunk \ + --enable_compile \ + --interpolation_steps 3 \ + --interactive_prompt_csv_path "example/prompt_interactive_helios.csv" \ + --interpolate_time 7 \ + --output_folder "./output_helios/helios-distilled" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 1 1 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/experiment_interactive/helios-mid_t2v.sh b/Helios-main/scripts/inference/experiment_interactive/helios-mid_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..15a8fa024a8d5d324bb2a9883cf6a1aa5bcebd6a --- /dev/null +++ b/Helios-main/scripts/inference/experiment_interactive/helios-mid_t2v.sh @@ -0,0 +1,28 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Mid" \ + --transformer_path "BestWishYsh/Helios-Mid" \ + --sample_type "t2v" \ + --num_frames 1452 \ + --fps 24 \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --guidance_scale 5.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 20 20 20 \ + --use_zero_init \ + --zero_steps 1 \ + --enable_compile \ + --interpolation_steps 3 \ + --interactive_prompt_csv_path "example/prompt_interactive_helios.csv" \ + --interpolate_time 7 \ + --output_folder "./output_helios/helios-mid" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 17 17 17 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-base_i2v.sh b/Helios-main/scripts/inference/helios-base_i2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..05dc9af463aad5cf7dc324bc045f0af1a17e55c4 --- /dev/null +++ b/Helios-main/scripts/inference/helios-base_i2v.sh @@ -0,0 +1,26 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Base" \ + --transformer_path "BestWishYsh/Helios-Base" \ + --sample_type "i2v" \ + --num_frames 99 \ + --fps 24 \ + --image_path "example/wave.jpg" \ + --image_noise_sigma_min 0.111 \ + --image_noise_sigma_max 0.135 \ + --prompt "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might." \ + --guidance_scale 5.0 \ + --enable_compile \ + --output_folder "./output_helios/helios-base" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --use_cfg_zero_star \ + # --use_zero_init \ + # --zero_steps 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-base_t2v.sh b/Helios-main/scripts/inference/helios-base_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..525a0328172727306feb878407b132133831561c --- /dev/null +++ b/Helios-main/scripts/inference/helios-base_t2v.sh @@ -0,0 +1,23 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Base" \ + --transformer_path "BestWishYsh/Helios-Base" \ + --sample_type "t2v" \ + --num_frames 99 \ + --fps 24 \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --guidance_scale 5.0 \ + --enable_compile \ + --output_folder "./output_helios/helios-base" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --use_cfg_zero_star \ + # --use_zero_init \ + # --zero_steps 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-base_v2v.sh b/Helios-main/scripts/inference/helios-base_v2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..14219ddc1c91c4bfc7d1ebbd5647e6bbb253c177 --- /dev/null +++ b/Helios-main/scripts/inference/helios-base_v2v.sh @@ -0,0 +1,26 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Base" \ + --transformer_path "BestWishYsh/Helios-Base" \ + --sample_type "v2v" \ + --num_frames 99 \ + --fps 24 \ + --video_path "example/car.mp4" \ + --video_noise_sigma_min 0.111 \ + --video_noise_sigma_max 0.135 \ + --prompt "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery." \ + --guidance_scale 5.0 \ + --enable_compile \ + --output_folder "./output_helios/helios-base" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --use_cfg_zero_star \ + # --use_zero_init \ + # --zero_steps 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-distilled_i2v.sh b/Helios-main/scripts/inference/helios-distilled_i2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..82e76a926468b8a029bd1600ca8f45e6b079d794 --- /dev/null +++ b/Helios-main/scripts/inference/helios-distilled_i2v.sh @@ -0,0 +1,27 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Distilled" \ + --transformer_path "BestWishYsh/Helios-Distilled" \ + --sample_type "i2v" \ + --num_frames 240 \ + --fps 24 \ + --image_path "example/wave.jpg" \ + --image_noise_sigma_min 0.111 \ + --image_noise_sigma_max 0.135 \ + --prompt "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might." \ + --guidance_scale 1.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 2 2 2 \ + --is_amplify_first_chunk \ + --enable_compile \ + --output_folder "./output_helios/helios-distilled" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 1 1 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-distilled_t2v.sh b/Helios-main/scripts/inference/helios-distilled_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..361ce2b84a614965ef92caf117f1487a937b94f6 --- /dev/null +++ b/Helios-main/scripts/inference/helios-distilled_t2v.sh @@ -0,0 +1,24 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Distilled" \ + --transformer_path "BestWishYsh/Helios-Distilled" \ + --sample_type "t2v" \ + --num_frames 240 \ + --fps 24 \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --guidance_scale 1.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 2 2 2 \ + --is_amplify_first_chunk \ + --enable_compile \ + --output_folder "./output_helios/helios-distilled" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 1 1 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-distilled_v2v.sh b/Helios-main/scripts/inference/helios-distilled_v2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..fb39e7f139735735ca23838b6c9f75f49f2bb720 --- /dev/null +++ b/Helios-main/scripts/inference/helios-distilled_v2v.sh @@ -0,0 +1,27 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Distilled" \ + --transformer_path "BestWishYsh/Helios-Distilled" \ + --sample_type "v2v" \ + --num_frames 240 \ + --fps 24 \ + --video_path "example/car.mp4" \ + --video_noise_sigma_min 0.111 \ + --video_noise_sigma_max 0.135 \ + --prompt "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery." \ + --guidance_scale 1.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 2 2 2 \ + --is_amplify_first_chunk \ + --enable_compile \ + --output_folder "./output_helios/helios-distilled" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 1 1 1 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-mid_i2v.sh b/Helios-main/scripts/inference/helios-mid_i2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3b7a6305bd384168cd2f16e5b445c47cb33aa65 --- /dev/null +++ b/Helios-main/scripts/inference/helios-mid_i2v.sh @@ -0,0 +1,28 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Mid" \ + --transformer_path "BestWishYsh/Helios-Mid" \ + --sample_type "i2v" \ + --num_frames 99 \ + --fps 24 \ + --image_path "example/wave.jpg" \ + --image_noise_sigma_min 0.111 \ + --image_noise_sigma_max 0.135 \ + --prompt "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might." \ + --guidance_scale 5.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 20 20 20 \ + --use_zero_init \ + --zero_steps 1 \ + --enable_compile \ + --output_folder "./output_helios/helios-mid" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 17 17 17 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-mid_t2v.sh b/Helios-main/scripts/inference/helios-mid_t2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..5fa8d7b96f368606533198e07b1d790903070274 --- /dev/null +++ b/Helios-main/scripts/inference/helios-mid_t2v.sh @@ -0,0 +1,25 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Mid" \ + --transformer_path "BestWishYsh/Helios-Mid" \ + --sample_type "t2v" \ + --num_frames 99 \ + --fps 24 \ + --prompt "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \ + --guidance_scale 5.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 20 20 20 \ + --use_zero_init \ + --zero_steps 1 \ + --enable_compile \ + --output_folder "./output_helios/helios-mid" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 17 17 17 \ \ No newline at end of file diff --git a/Helios-main/scripts/inference/helios-mid_v2v.sh b/Helios-main/scripts/inference/helios-mid_v2v.sh new file mode 100644 index 0000000000000000000000000000000000000000..d89f8040040728753c7d56ba07b53166c3492775 --- /dev/null +++ b/Helios-main/scripts/inference/helios-mid_v2v.sh @@ -0,0 +1,28 @@ +# Example: Running inference with 2-GPU parallelism +# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \ +# --enable_parallelism \ +# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"] + +CUDA_VISIBLE_DEVICES=0 python infer_helios.py \ + --base_model_path "BestWishYsh/Helios-Mid" \ + --transformer_path "BestWishYsh/Helios-Mid" \ + --sample_type "v2v" \ + --num_frames 99 \ + --fps 24 \ + --video_path "example/car.mp4" \ + --video_noise_sigma_min 0.111 \ + --video_noise_sigma_max 0.135 \ + --prompt "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery." \ + --guidance_scale 5.0 \ + --is_enable_stage2 \ + --pyramid_num_inference_steps_list 20 20 20 \ + --use_zero_init \ + --zero_steps 1 \ + --enable_compile \ + --output_folder "./output_helios/helios-mid" + + + # --enable_low_vram_mode \ + # --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"] + # --num_blocks_per_group + # --pyramid_num_inference_steps_list 17 17 17 \ \ No newline at end of file diff --git a/Helios-main/scripts/training/README.md b/Helios-main/scripts/training/README.md new file mode 100644 index 0000000000000000000000000000000000000000..72f65ea386619d3b7fd99ff07c62ed19e152bb90 --- /dev/null +++ b/Helios-main/scripts/training/README.md @@ -0,0 +1,37 @@ +# Training Details by *Helios* + + +## 🎉 Overview + +We use a three-stage progressive pipeline, all the setting can be found [here](./configs). Stage-1 (Base) performs architectural adaptation: we apply Unified History Injection, Easy Anti-Drifting, and Multi-Term Memory Patchification to convert the bidirectional pretrained model into an autoregressive generator. Stage-2 (Mid) targets token compression by introducing Pyramid Unified Predictor Corrector, which aggressively reduces the number of noisy tokens and thus the overall computation. Stage-3 (Distilled) applies Adversarial Hierarchical Distillation, reducing the sampling steps from 50 to 3 and eliminating the need for classifier-free guidance (CFG). Throughout training, we apply dynamic shifting to all timestep-dependent operations to match the noise schedule to the latent size. For Stages 1 and 2, training is further divided into two phases: a high learning-rate phase for rapid convergence, followed by a low learning-rate phase for refinement. + +
+ +
+ +### Data Preparation + +Please refer to [this guide](../..//tools/offload_data/README.md) for how to obtain the training data required by Helios. And we prepare a toy training data [here](https://huggingface.co/BestWishYsh/HeliosBench-Weights/tree/main/demo_data). + +### Run the model + +```bash +# Use DDP +bash scripts/training/train_ddp.sh + +# or + +# Use DeepSpeed +bash scripts/training/train_deepspeed.sh +``` + +Training configuration can be adjusted in `./configs`. You can use `./compare_yaml.py` to check for configuration completeness or differences between stages. + +### Model Merging + +After training, you can use this [script](../..//tools/merge_lora_for_helios.py) to merge all the checkpoints and obtain the final safetensors file, similar to [this](https://huggingface.co/BestWishYsh/Helios-Distilled/tree/main/transformer). + + +## 💡 Important + +Based on the findings in [issue #38](https://github.com/PKU-YuanGroup/Helios/issues/38), we have identified several areas with potential for further improving Helios's performance. These include fixing the train-inference inconsistency in i2v to address the issue where i2v tends to produce very slow motion at the beginning, as well as fully enabling Easy Anti-Drifting to enhance Helios's resistance to quality degradation over time. For the relevant configuration details, please refer to [correct.yaml](./configs/correct.yaml). diff --git a/Helios-main/scripts/training/compare_yaml.py b/Helios-main/scripts/training/compare_yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..083f0ec638d4a287a6206677e4d4d755ff2c5405 --- /dev/null +++ b/Helios-main/scripts/training/compare_yaml.py @@ -0,0 +1,65 @@ +import yaml + + +def compare_yaml(file1_path, file2_path): + with open(file1_path, "r") as f1: + yaml1 = yaml.safe_load(f1) + + with open(file2_path, "r") as f2: + yaml2 = yaml.safe_load(f2) + + missing_keys = [] + different_values = [] + + compare_dict(yaml1, yaml2, "", missing_keys, different_values) + + print("=" * 60) + print("Missing Keys") + print("=" * 60) + if missing_keys: + for diff in missing_keys: + print(diff) + else: + print("None") + + print("\n" + "=" * 60) + print("Different Values") + print("=" * 60) + if different_values: + for diff in different_values: + print(diff) + else: + print("None") + + print("\n" + "=" * 60) + print(f"Total: {len(missing_keys)} missing keys, {len(different_values)} different values") + print("=" * 60) + + +def compare_dict(dict1, dict2, path, missing_keys, different_values): + all_keys = set(dict1.keys()) | set(dict2.keys()) + + for key in all_keys: + current_path = f"{path}.{key}" if path else key + + if key not in dict2: + missing_keys.append(f"[{current_path}] Only in file1: {dict1[key]}") + elif key not in dict1: + missing_keys.append(f"[{current_path}] Only in file2: {dict2[key]}") + else: + val1, val2 = dict1[key], dict2[key] + + if isinstance(val1, dict) and isinstance(val2, dict): + compare_dict(val1, val2, current_path, missing_keys, different_values) + elif isinstance(val1, list) and isinstance(val2, list): + if val1 != val2: + different_values.append(f"[{current_path}]\n File1: {val1}\n File2: {val2}") + elif val1 != val2: + different_values.append(f"[{current_path}]\n File1: {val1}\n File2: {val2}") + + +if __name__ == "__main__": + compare_yaml( + "configs/stage_1_init.yaml", + "configs/stage_1_post.yaml", + ) diff --git a/Helios-main/scripts/training/configs/correct.yaml b/Helios-main/scripts/training/configs/correct.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce6a2b3bea4825521ee0121f4989a03c975107bb --- /dev/null +++ b/Helios-main/scripts/training/configs/correct.yaml @@ -0,0 +1,27 @@ +validation_config: + # ------------------------------------------------------------------------------------------------------------------------------------ + # ------- During validation/inference, enabling use_dynamic_shifting" yields better results. + use_dynamic_shifting: true + time_shift_type: "exponential" # ["exponential", "linear"] + # ------------------------------------------------------------------------------------------------------------------------------------ + +training_config: + # ------------------------------------------------------------------------------------------------------------------------------------ + # ------- Regarding the issue that I2V tends to produce very slow motion at the beginning: + # ------- During training, we did not construct the corresponding history context format (i.e., first-frame anchor + last-frame), + # ------- which means the current I2V inference relies heavily on the model’s zero-shot capability. + # ------- Incorporating this data format during training should significantly improve performance. + random_drop_i2v_ratio: 0.1 # should be changed according to valiation + # ------------------------------------------------------------------------------------------------------------------------------------ + # + # ------------------------------------------------------------------------------------------------------------------------------------ + # ------- Easy Anit-Drifting (Noise + Blur + Saturation): We actually missed fully turning this on when we trained Helios-Base + # ------- and Helios-Mid. But based on our ablation experiments on Helios-Distilled, it definitely helps mitigate degradation. + corrupt_mode_history: "random" + downsample_min_corrupt_ratio_history: 0.9 # should be changed according to valiation + downsample_max_corrupt_ratio_history: 1.0 # should be changed according to valiation + is_add_saturation: true + saturation_ratio_clean_prob: 0.1 # should be changed according to valiation + saturation_ratio_min: 0.3 # should be changed according to valiation + saturation_ratio_max: 1.7 # should be changed according to valiation + # ------------------------------------------------------------------------------------------------------------------------------------ diff --git a/Helios-main/scripts/training/configs/stage_1_init.yaml b/Helios-main/scripts/training/configs/stage_1_init.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a58860d2aedf06a9ede03cb9fc4dfebf780aa365 --- /dev/null +++ b/Helios-main/scripts/training/configs/stage_1_init.yaml @@ -0,0 +1,182 @@ +output_dir: ablation_stage_1_init +logging_dir: logs +seed: 43 + + +report_to: + tracker_name: Wan-Train + wandb_name: ablation_stage_1_init + report_to: wandb + + +data_config: + # ---- Base ---- + use_shuffle: true + pin_memory: true + persistent_workers: true + force_rebuild: true + single_res: true + single_height: 384 + single_width: 640 + dataloader_num_workers: 8 + prefetch_factor: 2 + caption_dropout_p: 0 + id_token: "" + instance_data_root: + - "demo_data/ultravideo-long" + # ---- Stage 1 ---- + use_stage1_dataset: true + + +model_config: + # ---- Path ---- + pretrained_model_name_or_path: "BestWishYsh/Helios-Base" + transformer_model_name_or_path: "Wan-AI/Wan2.1-T2V-14B-Diffusers" + load_checkpoints_custom: false + # load_model_path: + load_dcp: false + # load_dcp_path: + # ---- Vae ---- + upcast_vae: true + enable_slicing: false + enable_tiling: false + # ---- Lora ---- + lora_rank: 128 + lora_alpha: 128.0 + lora_dropout: 0.0 + lora_layers: "all-linear" + # lora_target_modules: + # - to_k + # - to_q + # - to_v + # - to_out.0 + # - ffn.net.0.proj + # - ffn.net.2 + lora_exclude_modules: + - down + - up + # ---- Other ---- + train_norm_layers: false + + +validation_config: + validation_steps: 500 + validation_height: 384 + validation_width: 640 + validation_max_num_frames: 99 + validation_prompts: + - "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + # - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field." + # - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors." + validation_guidance_scale: 5.0 + validation_latent_window_size: + - 9 + num_validation_videos: 1 + num_inference_steps: 50 + # ---- Dynamic Shifting ---- + use_dynamic_shifting: true + time_shift_type: "exponential" # ["exponential", "linear"] + + +training_config: + # ---- Environment ---- + allow_tf32: false + gradient_checkpointing: true + enable_xformers_memory_efficient_attention: false + enable_npu_flash_attention: false + upcast_before_saving: false + offload: false + mixed_precision: "bf16" + # ---- Training Resource ---- + max_train_steps: 1000000 + train_batch_size: 2 + gradient_accumulation_steps: 1 + checkpointing_steps: 500 + resume_from_checkpoint: "latest" + save_checkpoints_custom: false + # ---- Optimizer ---- + learning_rate: 5e-5 + lr_scheduler: "constant" + lr_warmup_steps: 500 + optimizer: "adamw" + adam_beta1: 0.9 + adam_beta2: 0.999 + adam_weight_decay: 1e-04 + adam_epsilon: 1e-08 + max_grad_norm: 1.0 + weighting_scheme: "logit_normal" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"] + logit_mean: 0.0 + logit_std: 1.0 + mode_scale: 1.29 + # ---- Dynamic Shifting Parameters ---- + use_dynamic_shifting: false + time_shift_type: "exponential" # ["exponential", "linear"] + base_seq_len: 256 + max_seq_len: 4096 + base_shift: 0.5 + max_shift: 1.15 + # ---- VAE Decode Parameters ---- + vae_decode_type: "default" + # ---- EMA Parameters ---- + use_ema: false + use_ema_validation: false + ema_decay: 0.999 + ema_start_step: 250 + ema_zero3_port: 10543 + ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json" + # ---- Stage 1 Parameters ---- + is_enable_stage1: true + history_sizes: + - 16 + - 2 + - 1 + latent_window_size: + # - 12 + # - 10 + - 9 + # - 8 + # - 6 + # - 5 + # - 4 + # - 3 + # - 2 + # - 1 + is_random_drop: true + random_drop_v2v_ratio: 0.4 + random_drop_t2v_ratio: 0.4 + # + corrupt_model_input: false + corrupt_mode_model_input: "noise" + corrupt_mode_prob_model_input: 0.9 + is_frame_independent_corrupt_model_input: true + is_chunk_independent_corrupt_model_input: false + noise_corrupt_ratio_model_input: 0.33333333333333 + noise_corrupt_clean_prob_model_input: 0.1 + downsample_min_corrupt_ratio_model_input: 0.9 + downsample_max_corrupt_ratio_model_input: 1.0 + corrupt_history: true + corrupt_mode_history: "noise" + corrupt_mode_prob_history: 0.9 + is_frame_independent_corrupt_history: true + is_chunk_independent_corrupt_history: false + noise_corrupt_ratio_history_short: 0.33333333333333 + noise_corrupt_ratio_history_mid: 0.33333333333333 + noise_corrupt_ratio_history_long: 0.33333333333333 + noise_corrupt_clean_prob_history: 0.1 + downsample_min_corrupt_ratio_history: 0.9 + downsample_max_corrupt_ratio_history: 1.0 + # + is_amplify_history: false + history_scale_mode: "per_head" + # + is_train_full_patch_embedding: false + is_train_lora_patch_embedding: true + has_multi_term_memory_patch: true + is_train_full_multi_term_memory_patchg: true + is_train_lora_multi_term_memory_patchg: false + zero_history_timestep: true + guidance_cross_attn: true + restrict_self_attn: false + is_train_restrict_lora: false + restrict_lora: false + restrict_lora_rank: 128 diff --git a/Helios-main/scripts/training/configs/stage_1_post.yaml b/Helios-main/scripts/training/configs/stage_1_post.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eea7a8ecffe2cc35b7bdd70f0c4c87a728f56326 --- /dev/null +++ b/Helios-main/scripts/training/configs/stage_1_post.yaml @@ -0,0 +1,183 @@ +output_dir: ablation_stage_1_post +logging_dir: logs +seed: 44 + + +report_to: + tracker_name: Wan-Train + wandb_name: ablation_stage_1_post + report_to: wandb + + +data_config: + # ---- Base ---- + use_shuffle: true + pin_memory: true + persistent_workers: true + force_rebuild: true + single_res: true + single_height: 384 + single_width: 640 + dataloader_num_workers: 8 + prefetch_factor: 2 + caption_dropout_p: 0 + id_token: "" + instance_data_root: + - "demo_data/ultravideo-long" + # ---- Stage 1 ---- + use_stage1_dataset: true + + +model_config: + # ---- Path ---- + pretrained_model_name_or_path: "BestWishYsh/Helios-Base" + transformer_model_name_or_path: "BestWishYsh/Helios-Base" + subfolder: "transformer_init" + load_checkpoints_custom: false + # load_model_path: + load_dcp: false + # load_dcp_path: + # ---- Vae ---- + upcast_vae: true + enable_slicing: false + enable_tiling: false + # ---- Lora ---- + lora_rank: 128 + lora_alpha: 128.0 + lora_dropout: 0.0 + lora_layers: "all-linear" + # lora_target_modules: + # - to_k + # - to_q + # - to_v + # - to_out.0 + # - ffn.net.0.proj + # - ffn.net.2 + lora_exclude_modules: + - down + - up + # ---- Other ---- + train_norm_layers: false + + +validation_config: + validation_steps: 500 + validation_height: 384 + validation_width: 640 + validation_max_num_frames: 99 + validation_prompts: + - "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + # - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field." + # - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors." + validation_guidance_scale: 5.0 + validation_latent_window_size: + - 9 + num_validation_videos: 1 + num_inference_steps: 50 + # ---- Dynamic Shifting ---- + use_dynamic_shifting: true + time_shift_type: "exponential" # ["exponential", "linear"] + + +training_config: + # ---- Environment ---- + allow_tf32: false + gradient_checkpointing: true + enable_xformers_memory_efficient_attention: false + enable_npu_flash_attention: false + upcast_before_saving: false + offload: false + mixed_precision: "bf16" + # ---- Training Resource ---- + max_train_steps: 1000000 + train_batch_size: 2 + gradient_accumulation_steps: 1 + checkpointing_steps: 500 + resume_from_checkpoint: "latest" + save_checkpoints_custom: false + # ---- Optimizer ---- + learning_rate: 3e-5 + lr_scheduler: "constant" + lr_warmup_steps: 500 + optimizer: "adamw" + adam_beta1: 0.9 + adam_beta2: 0.999 + adam_weight_decay: 1e-04 + adam_epsilon: 1e-08 + max_grad_norm: 1.0 + weighting_scheme: "logit_normal" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"] + logit_mean: 0.0 + logit_std: 1.0 + mode_scale: 1.29 + # ---- Dynamic Shifting Parameters ---- + use_dynamic_shifting: false + time_shift_type: "exponential" # ["exponential", "linear"] + base_seq_len: 256 + max_seq_len: 4096 + base_shift: 0.5 + max_shift: 1.15 + # ---- VAE Decode Parameters ---- + vae_decode_type: "default" + # ---- EMA Parameters ---- + use_ema: false + use_ema_validation: false + ema_decay: 0.999 + ema_start_step: 250 + ema_zero3_port: 10543 + ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json" + # ---- Stage 1 Parameters ---- + is_enable_stage1: true + history_sizes: + - 16 + - 2 + - 1 + latent_window_size: + # - 12 + # - 10 + - 9 + # - 8 + # - 6 + # - 5 + # - 4 + # - 3 + # - 2 + # - 1 + is_random_drop: true + random_drop_v2v_ratio: 0.4 + random_drop_t2v_ratio: 0.4 + # + corrupt_model_input: false + corrupt_mode_model_input: "noise" + corrupt_mode_prob_model_input: 0.9 + is_frame_independent_corrupt_model_input: true + is_chunk_independent_corrupt_model_input: false + noise_corrupt_ratio_model_input: 0.33333333333333 + noise_corrupt_clean_prob_model_input: 0.1 + downsample_min_corrupt_ratio_model_input: 0.9 + downsample_max_corrupt_ratio_model_input: 1.0 + corrupt_history: true + corrupt_mode_history: "noise" + corrupt_mode_prob_history: 0.9 + is_frame_independent_corrupt_history: true + is_chunk_independent_corrupt_history: false + noise_corrupt_ratio_history_short: 0.33333333333333 + noise_corrupt_ratio_history_mid: 0.33333333333333 + noise_corrupt_ratio_history_long: 0.33333333333333 + noise_corrupt_clean_prob_history: 0.1 + downsample_min_corrupt_ratio_history: 0.9 + downsample_max_corrupt_ratio_history: 1.0 + # + is_amplify_history: false + history_scale_mode: "per_head" + # + is_train_full_patch_embedding: false + is_train_lora_patch_embedding: true + has_multi_term_memory_patch: true + is_train_full_multi_term_memory_patchg: true + is_train_lora_multi_term_memory_patchg: false + zero_history_timestep: true + guidance_cross_attn: true + restrict_self_attn: false + is_train_restrict_lora: false + restrict_lora: false + restrict_lora_rank: 128 diff --git a/Helios-main/scripts/training/configs/stage_2_init.yaml b/Helios-main/scripts/training/configs/stage_2_init.yaml new file mode 100644 index 0000000000000000000000000000000000000000..06a25f127f7492778a27e117e0d79ad7ba060296 --- /dev/null +++ b/Helios-main/scripts/training/configs/stage_2_init.yaml @@ -0,0 +1,202 @@ +output_dir: ablation_stage_2_init +logging_dir: logs +seed: 45 + + +report_to: + tracker_name: Wan-Train + wandb_name: ablation_stage_2_init + report_to: wandb + + +data_config: + # ---- Base ---- + use_shuffle: true + pin_memory: true + persistent_workers: true + force_rebuild: true + single_res: true + single_height: 384 + single_width: 640 + dataloader_num_workers: 8 + prefetch_factor: 2 + caption_dropout_p: 0 + id_token: "" + instance_data_root: + - "demo_data/ultravideo-long" + # ---- Stage 1 ---- + use_stage1_dataset: true + + +model_config: + # ---- Path ---- + pretrained_model_name_or_path: "BestWishYsh/Helios-Base" + transformer_model_name_or_path: "BestWishYsh/Helios-Base" + load_checkpoints_custom: false + # load_model_path: + load_dcp: false + # load_dcp_path: + # ---- Vae ---- + upcast_vae: true + enable_slicing: false + enable_tiling: false + # ---- Lora ---- + lora_rank: 256 + lora_alpha: 256.0 + lora_dropout: 0.0 + lora_layers: "all-linear" + # lora_target_modules: + # - to_k + # - to_q + # - to_v + # - to_out.0 + # - ffn.net.0.proj + # - ffn.net.2 + lora_exclude_modules: + - down + - up + # ---- Other ---- + train_norm_layers: false + + +validation_config: + validation_steps: 500 + validation_height: 384 + validation_width: 640 + validation_max_num_frames: 99 + validation_prompts: + - "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + # - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field." + # - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors." + validation_guidance_scale: 5.0 + validation_latent_window_size: + - 9 + num_validation_videos: 1 + # ---- Dynamic Shifting ---- + use_dynamic_shifting: true + time_shift_type: "exponential" # ["exponential", "linear"] + # ---- Stage 2 ---- + stage2_simulated_inference_steps: + - 20 + - 20 + - 20 + + +training_config: + # ---- Environment ---- + allow_tf32: false + gradient_checkpointing: true + enable_xformers_memory_efficient_attention: false + enable_npu_flash_attention: false + upcast_before_saving: false + offload: false + mixed_precision: "bf16" + # ---- Training Resource ---- + max_train_steps: 1000000 + train_batch_size: 1 + gradient_accumulation_steps: 1 + checkpointing_steps: 500 + resume_from_checkpoint: "latest" + save_checkpoints_custom: false + # ---- Optimizer ---- + learning_rate: 1e-4 + lr_scheduler: "constant_with_warmup" + lr_warmup_steps: 1000 + optimizer: "adamw" + adam_beta1: 0.9 + adam_beta2: 0.999 + adam_weight_decay: 1e-04 + adam_epsilon: 1e-08 + max_grad_norm: 1.0 + weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"] + logit_mean: 0.0 + logit_std: 1.0 + mode_scale: 1.29 + # ---- Dynamic Shifting Parameters ---- + use_dynamic_shifting: false + time_shift_type: "exponential" # ["exponential", "linear"] + base_seq_len: 256 + max_seq_len: 4096 + base_shift: 0.5 + max_shift: 1.15 + # ---- VAE Decode Parameters ---- + vae_decode_type: "default" + # ---- EMA Parameters ---- + use_ema: false + use_ema_validation: false + ema_decay: 0.999 + ema_start_step: 250 + ema_zero3_port: 10543 + ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json" + # ---- Stage 1 Parameters ---- + is_enable_stage1: true + history_sizes: + - 16 + - 2 + - 1 + latent_window_size: + # - 12 + # - 10 + - 9 + # - 8 + # - 6 + # - 5 + # - 4 + # - 3 + # - 2 + # - 1 + is_random_drop: true + random_drop_v2v_ratio: 0.4 + random_drop_t2v_ratio: 0.4 + # + corrupt_model_input: false + corrupt_mode_model_input: "noise" + corrupt_mode_prob_model_input: 0.9 + is_frame_independent_corrupt_model_input: true + is_chunk_independent_corrupt_model_input: false + noise_corrupt_ratio_model_input: 0.33333333333333 + noise_corrupt_clean_prob_model_input: 0.1 + downsample_min_corrupt_ratio_model_input: 0.9 + downsample_max_corrupt_ratio_model_input: 1.0 + corrupt_history: true + corrupt_mode_history: "noise" + corrupt_mode_prob_history: 0.9 + is_frame_independent_corrupt_history: true + is_chunk_independent_corrupt_history: false + noise_corrupt_ratio_history_short: 0.33333333333333 + noise_corrupt_ratio_history_mid: 0.33333333333333 + noise_corrupt_ratio_history_long: 0.33333333333333 + noise_corrupt_clean_prob_history: 0.1 + downsample_min_corrupt_ratio_history: 0.9 + downsample_max_corrupt_ratio_history: 1.0 + # + is_amplify_history: false + history_scale_mode: "per_head" + # + is_train_full_patch_embedding: false + is_train_lora_patch_embedding: false + has_multi_term_memory_patch: true + is_train_full_multi_term_memory_patchg: false + is_train_lora_multi_term_memory_patchg: false + zero_history_timestep: true + guidance_cross_attn: true + restrict_self_attn: false + is_train_restrict_lora: false + restrict_lora: false + restrict_lora_rank: 128 + # ---- Stage 2 Parameters ---- + is_enable_stage2: true + is_navit_pyramid: true + stage2_num_stages: 3 + stage2_timestep_shift: 1.0 + stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3 + stage2_stage_range: + - 0 + - 0.333333333333333333333333333333333 # Approximate value of 1/3 + - 0.666666666666666666666666666666666 # Approximate value of 2/3 + - 1 + stage2_sample_ratios: + - 1 + - 2 + - 1 + efficient_sample: false diff --git a/Helios-main/scripts/training/configs/stage_2_post.yaml b/Helios-main/scripts/training/configs/stage_2_post.yaml new file mode 100644 index 0000000000000000000000000000000000000000..78afbf1e047232439f9998d8e81fcdd6c6937427 --- /dev/null +++ b/Helios-main/scripts/training/configs/stage_2_post.yaml @@ -0,0 +1,203 @@ +output_dir: ablation_stage_2_post +logging_dir: logs +seed: 46 + + +report_to: + tracker_name: Wan-Train + wandb_name: ablation_stage_2_post + report_to: wandb + + +data_config: + # ---- Base ---- + use_shuffle: true + pin_memory: true + persistent_workers: true + force_rebuild: true + single_res: true + single_height: 384 + single_width: 640 + dataloader_num_workers: 8 + prefetch_factor: 2 + caption_dropout_p: 0 + id_token: "" + instance_data_root: + - "demo_data/ultravideo-long" + # ---- Stage 1 ---- + use_stage1_dataset: true + + +model_config: + # ---- Path ---- + pretrained_model_name_or_path: "BestWishYsh/Helios-Base" + transformer_model_name_or_path: "BestWishYsh/Helios-Mid" + subfolder: "transformer_init" + load_checkpoints_custom: false + # load_model_path: + load_dcp: false + # load_dcp_path: + # ---- Vae ---- + upcast_vae: true + enable_slicing: false + enable_tiling: false + # ---- Lora ---- + lora_rank: 256 + lora_alpha: 256.0 + lora_dropout: 0.0 + lora_layers: "all-linear" + # lora_target_modules: + # - to_k + # - to_q + # - to_v + # - to_out.0 + # - ffn.net.0.proj + # - ffn.net.2 + lora_exclude_modules: + - down + - up + # ---- Other ---- + train_norm_layers: false + + +validation_config: + validation_steps: 500 + validation_height: 384 + validation_width: 640 + validation_max_num_frames: 99 + validation_prompts: + - "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + # - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field." + # - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors." + validation_guidance_scale: 5.0 + validation_latent_window_size: + - 9 + num_validation_videos: 1 + # ---- Dynamic Shifting ---- + use_dynamic_shifting: true + time_shift_type: "exponential" # ["exponential", "linear"] + # ---- Stage 2 ---- + stage2_simulated_inference_steps: + - 20 + - 20 + - 20 + + +training_config: + # ---- Environment ---- + allow_tf32: false + gradient_checkpointing: true + enable_xformers_memory_efficient_attention: false + enable_npu_flash_attention: false + upcast_before_saving: false + offload: false + mixed_precision: "bf16" + # ---- Training Resource ---- + max_train_steps: 1000000 + train_batch_size: 1 + gradient_accumulation_steps: 1 + checkpointing_steps: 500 + resume_from_checkpoint: "latest" + save_checkpoints_custom: false + # ---- Optimizer ---- + learning_rate: 3e-5 + lr_scheduler: "constant_with_warmup" + lr_warmup_steps: 500 + optimizer: "adamw" + adam_beta1: 0.9 + adam_beta2: 0.999 + adam_weight_decay: 1e-04 + adam_epsilon: 1e-08 + max_grad_norm: 1.0 + weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"] + logit_mean: 0.0 + logit_std: 1.0 + mode_scale: 1.29 + # ---- Dynamic Shifting Parameters ---- + use_dynamic_shifting: false + time_shift_type: "exponential" # ["exponential", "linear"] + base_seq_len: 256 + max_seq_len: 4096 + base_shift: 0.5 + max_shift: 1.15 + # ---- VAE Decode Parameters ---- + vae_decode_type: "default" + # ---- EMA Parameters ---- + use_ema: false + use_ema_validation: false + ema_decay: 0.999 + ema_start_step: 250 + ema_zero3_port: 10543 + ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json" + # ---- Stage 1 Parameters ---- + is_enable_stage1: true + history_sizes: + - 16 + - 2 + - 1 + latent_window_size: + # - 12 + # - 10 + - 9 + # - 8 + # - 6 + # - 5 + # - 4 + # - 3 + # - 2 + # - 1 + is_random_drop: true + random_drop_v2v_ratio: 0.4 + random_drop_t2v_ratio: 0.4 + # + corrupt_model_input: false + corrupt_mode_model_input: "noise" + corrupt_mode_prob_model_input: 0.9 + is_frame_independent_corrupt_model_input: true + is_chunk_independent_corrupt_model_input: false + noise_corrupt_ratio_model_input: 0.33333333333333 + noise_corrupt_clean_prob_model_input: 0.1 + downsample_min_corrupt_ratio_model_input: 0.9 + downsample_max_corrupt_ratio_model_input: 1.0 + corrupt_history: true + corrupt_mode_history: "noise" + corrupt_mode_prob_history: 0.9 + is_frame_independent_corrupt_history: true + is_chunk_independent_corrupt_history: false + noise_corrupt_ratio_history_short: 0.33333333333333 + noise_corrupt_ratio_history_mid: 0.33333333333333 + noise_corrupt_ratio_history_long: 0.33333333333333 + noise_corrupt_clean_prob_history: 0.1 + downsample_min_corrupt_ratio_history: 0.9 + downsample_max_corrupt_ratio_history: 1.0 + # + is_amplify_history: false + history_scale_mode: "per_head" + # + is_train_full_patch_embedding: false + is_train_lora_patch_embedding: true + has_multi_term_memory_patch: true + is_train_full_multi_term_memory_patchg: false + is_train_lora_multi_term_memory_patchg: true + zero_history_timestep: true + guidance_cross_attn: true + restrict_self_attn: false + is_train_restrict_lora: false + restrict_lora: false + restrict_lora_rank: 128 + # ---- Stage 2 Parameters ---- + is_enable_stage2: true + is_navit_pyramid: true + stage2_num_stages: 3 + stage2_timestep_shift: 1.0 + stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3 + stage2_stage_range: + - 0 + - 0.333333333333333333333333333333333 # Approximate value of 1/3 + - 0.666666666666666666666666666666666 # Approximate value of 2/3 + - 1 + stage2_sample_ratios: + - 1 + - 1 + - 1 + efficient_sample: false diff --git a/Helios-main/scripts/training/configs/stage_3_ode.yaml b/Helios-main/scripts/training/configs/stage_3_ode.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5fcc67bb60d90a7c9b27c76a7f9c0fa60054adeb --- /dev/null +++ b/Helios-main/scripts/training/configs/stage_3_ode.yaml @@ -0,0 +1,229 @@ +output_dir: ablation_stage_3_ode +logging_dir: logs +seed: 47 + + +report_to: + tracker_name: Wan-Train + wandb_name: ablation_stage_3_ode + report_to: wandb + + +data_config: + # ---- Base ---- + use_shuffle: true + pin_memory: true + persistent_workers: true + force_rebuild: true + single_res: true + single_height: 384 + single_width: 640 + dataloader_num_workers: 8 + prefetch_factor: 1 + caption_dropout_p: 0 + id_token: "" + # ---- Stage 1 ---- + use_stage1_dataset: false + # ---- Stage 3 ---- + use_stage3_dataset: true + ode_data_root: + - "demo_data/vidprom_filtered_extended" + + +model_config: + # ---- Path ---- + pretrained_model_name_or_path: "BestWishYsh/Helios-Base" + transformer_model_name_or_path: "BestWishYsh/Helios-Mid" + load_checkpoints_custom: false + # load_model_path: + load_dcp: false + # load_dcp_path: + # ---- Vae ---- + upcast_vae: true + enable_slicing: false + enable_tiling: false + # ---- Lora ---- + lora_rank: 256 + lora_alpha: 256.0 + lora_dropout: 0.0 + lora_layers: "all-linear" + # lora_target_modules: + # - to_k + # - to_q + # - to_v + # - to_out.0 + # - ffn.net.0.proj + # - ffn.net.2 + lora_exclude_modules: + - down + - up + # ---- Other ---- + train_norm_layers: false + + +validation_config: + validation_steps: 500 + validation_height: 384 + validation_width: 640 + validation_max_num_frames: 99 + validation_prompts: + - "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + # - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field." + # - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors." + validation_guidance_scale: 1.0 + validation_latent_window_size: + - 9 + num_validation_videos: 1 + num_inference_steps: 6 + # ---- Dynamic Shifting ---- + use_dynamic_shifting: true + time_shift_type: "linear" # ["exponential", "linear"] + # ---- Pyramid ---- + stage2_simulated_inference_steps: + - 2 + - 2 + - 2 + + +training_config: + # ---- Environment ---- + allow_tf32: false + gradient_checkpointing: true + enable_xformers_memory_efficient_attention: false + enable_npu_flash_attention: false + upcast_before_saving: false + offload: false + mixed_precision: "bf16" + # ---- Training Resource ---- + max_train_steps: 1000000 + train_batch_size: 1 + gradient_accumulation_steps: 1 + checkpointing_steps: 250 + resume_from_checkpoint: "latest" + save_checkpoints_custom: true + # ---- Optimizer ---- + learning_rate: 2.0e-06 + lr_scheduler: "constant" + lr_warmup_steps: 500 + optimizer: "adamw" + adam_beta1: 0.0 + adam_beta2: 0.999 + adam_weight_decay: 1e-03 + adam_epsilon: 1e-08 + max_grad_norm: 10.0 + weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"] + logit_mean: 0.0 + logit_std: 1.0 + mode_scale: 1.29 + # ---- Dynamic Shifting Parameters ---- + use_dynamic_shifting: true + time_shift_type: "linear" + base_seq_len: 256 + max_seq_len: 4096 + base_shift: 0.5 + max_shift: 1.15 + # ---- VAE Decode Parameters ---- + vae_decode_type: "default" + # ---- EMA Parameters ---- + use_ema: true + use_ema_validation: false + ema_decay: 0.99 + ema_start_step: 250 + ema_zero3_port: 10543 + ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json" + # ---- Stage 1 Parameters ---- + is_enable_stage1: true + history_sizes: + - 16 + - 2 + - 1 + latent_window_size: + # - 12 + # - 10 + - 9 + # - 8 + # - 6 + # - 5 + # - 4 + # - 3 + # - 2 + # - 1 + is_amplify_history: false + history_scale_mode: "per_head" + # + is_train_full_patch_embedding: false + is_train_lora_patch_embedding: false + has_multi_term_memory_patch: true + is_train_full_multi_term_memory_patchg: false + is_train_lora_multi_term_memory_patchg: true + zero_history_timestep: true + guidance_cross_attn: true + restrict_self_attn: false + is_train_restrict_lora: false + restrict_lora: false + restrict_lora_rank: 128 + # ---- Stage 2 Parameters ---- + is_enable_stage2: true + is_navit_pyramid: false + stage2_num_stages: 3 + stage2_timestep_shift: 1.0 + stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3 + stage2_stage_range: + - 0 + - 0.333333333333333333333333333333333 # Approximate value of 1/3 + - 0.666666666666666666666666666666666 # Approximate value of 2/3 + - 1 + stage2_sample_ratios: + - 1 + - 1 + - 1 + efficient_sample: false + # ---- Stage 3 VRAM Parameters ---- + dmd_is_low_vram_mode: true + # ---- Stage 3 Parameters ---- + log_iters: 250 + no_visualize: false + is_train_dmd: false + max_grad_norm_critic: 10.0 + dmd_generator_deepspeed_config: scripts/accelerate_configs/zero2.json + dmd_critic_deepspeed_config: scripts/accelerate_configs/zero2.json + critic_learning_rate: 4.0e-07 + dfake_gen_update_ratio: 5 + dmd_denoising_step_list: + - 1000 + - 750 + - 500 + - 250 + num_critic_input_frames: 9 + dmd_timestep_shift: 5.0 + dmd_last_step_only: false + dmd_last_section_grad_only: false + dmd_teacher_forcing: false + dmd_teacher_forcing_ratio: 0.2 + fake_guidance_scale: 0.0 + real_guidance_scale: 3.0 + # ---- VAE Re-Encode ---- + is_dmd_vae_decode: false + # ---- Multi Stage Backward Simulated ---- + is_multi_pyramid_stage_backward_simulated: false + # ---- ODE Regression Parameters ---- + is_use_ode_regression: true + is_only_ode_regression: true + ode_regression_weight: 80.0 + # ---- Cold Start Parameters ---- + is_enable_cold_start: false + cold_start_step: 2000 + stage_cold_start_step: 2000 + # ---- Dynamic Timestep ---- + generator_is_forcing_low_renoise: false + generator_dynamic_alpha: 4.0 + generator_dynamic_beta: 1.5 + generator_dynamic_sample_type: "uniform" + generator_dynamic_step: 1000 + # ---- Dynamic ODE Section ---- + ode_num_latent_sections_min: 3 + ode_num_latent_sections_max: 3 + ode_dynamic_alpha: 1.5 + ode_dynamic_beta: 4.0 + ode_dynamic_sample_type: "uniform" + ode_dynamic_step: 2000 diff --git a/Helios-main/scripts/training/configs/stage_3_post.yaml b/Helios-main/scripts/training/configs/stage_3_post.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d29b6cce3ef6cac43db4158b285c7c815cd32d1e --- /dev/null +++ b/Helios-main/scripts/training/configs/stage_3_post.yaml @@ -0,0 +1,300 @@ +output_dir: ablation_stage_3_post +logging_dir: logs +seed: 49 + + +report_to: + tracker_name: Wan-Train + wandb_name: ablation_stage_3_post + report_to: wandb + + +data_config: + # ---- Base ---- + use_shuffle: true + pin_memory: true + persistent_workers: true + force_rebuild: true + single_res: true + single_height: 384 + single_width: 640 + dataloader_num_workers: 8 + prefetch_factor: 1 + caption_dropout_p: 0 + id_token: "" + # ---- Stage 1 ---- + use_stage1_dataset: false + # ---- Stage 3 ---- + use_stage3_dataset: true + gan_data_root: + - "demo_data/ultravideo-long" + + +model_config: + # ---- Path ---- + pretrained_model_name_or_path: "BestWishYsh/Helios-Base" + transformer_model_name_or_path: "BestWishYsh/Helios-Distilled" + subfolder: "transformer_ode" + real_score_model_name_or_path: "BestWishYsh/Helios-Base" + load_checkpoints_custom: false + # load_model_path: + load_dcp: false + # load_dcp_path: + # ---- Vae ---- + upcast_vae: true + enable_slicing: false + enable_tiling: false + # ---- Lora ---- + lora_rank: 256 + lora_alpha: 256.0 + lora_dropout: 0.0 + lora_layers: "all-linear" + # lora_target_modules: + # - to_k + # - to_q + # - to_v + # - to_out.0 + # - ffn.net.0.proj + # - ffn.net.2 + lora_exclude_modules: + - down + - up + # ---- Other ---- + train_norm_layers: false + # ---- DMD ---- + critic_lora_rank: 256 + critic_lora_alpha: 256.0 + critic_lora_dropout: 0.0 + # ---- Reward Parameters ---- + reward_model_name_or_path: "/mnt/bn/yufan-dev-my/ysh_new/Ckpts/Videoreward" + + +validation_config: + validation_steps: 500 + validation_height: 384 + validation_width: 640 + validation_max_num_frames: 99 + validation_prompts: + - "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + # - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field." + # - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors." + validation_guidance_scale: 1.0 + validation_latent_window_size: + - 9 + num_validation_videos: 1 + num_inference_steps: 6 + # ---- Dynamic Shifting ---- + use_dynamic_shifting: true + time_shift_type: "linear" # ["exponential", "linear"] + # ---- Pyramid ---- + stage2_simulated_inference_steps: + - 2 + - 2 + - 2 + + +training_config: + # ---- Environment ---- + allow_tf32: false + gradient_checkpointing: true + enable_xformers_memory_efficient_attention: false + enable_npu_flash_attention: false + upcast_before_saving: false + offload: false + mixed_precision: "bf16" + # ---- Training Resource ---- + max_train_steps: 1000000 + train_batch_size: 1 + gradient_accumulation_steps: 1 + checkpointing_steps: 250 + resume_from_checkpoint: "latest" + save_checkpoints_custom: false + # ---- Optimizer ---- + learning_rate: 2.0e-06 + lr_scheduler: "constant" + lr_warmup_steps: 500 + optimizer: "adamw" + adam_beta1: 0.0 + adam_beta2: 0.999 + adam_weight_decay: 1e-03 + adam_epsilon: 1e-08 + max_grad_norm: 10.0 + weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"] + logit_mean: 0.0 + logit_std: 1.0 + mode_scale: 1.29 + # ---- Dynamic Shifting Parameters ---- + use_dynamic_shifting: true + time_shift_type: "linear" + base_seq_len: 256 + max_seq_len: 4096 + base_shift: 0.5 + max_shift: 1.15 + # ---- VAE Decode Parameters ---- + vae_decode_type: "default" + # ---- EMA Parameters ---- + use_ema: true + use_ema_validation: false + ema_decay: 0.99 + ema_start_step: 750 + ema_zero3_port: 10543 + ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json" + # ---- Stage 1 Parameters ---- + is_enable_stage1: true + history_sizes: + - 16 + - 2 + - 1 + latent_window_size: + # - 12 + # - 10 + - 9 + # - 8 + # - 6 + # - 5 + # - 4 + # - 3 + # - 2 + # - 1 + is_random_drop: true + random_drop_v2v_ratio: 0.5 + random_drop_t2v_ratio: 0.4 + # + corrupt_model_input: false + corrupt_mode_model_input: "noise" + corrupt_mode_prob_model_input: 0.9 + is_frame_independent_corrupt_model_input: true + is_chunk_independent_corrupt_model_input: false + noise_corrupt_ratio_model_input: 0.33333333333333 + noise_corrupt_clean_prob_model_input: 0.1 + downsample_min_corrupt_ratio_model_input: 0.9 + downsample_max_corrupt_ratio_model_input: 1.0 + corrupt_history: true + corrupt_mode_history: "noise" + corrupt_mode_prob_history: 0.9 + is_frame_independent_corrupt_history: true + is_chunk_independent_corrupt_history: false + noise_corrupt_ratio_history_short: 0.33333333333333 + noise_corrupt_ratio_history_mid: 0.33333333333333 + noise_corrupt_ratio_history_long: 0.33333333333333 + noise_corrupt_clean_prob_history: 0.1 + downsample_min_corrupt_ratio_history: 0.9 + downsample_max_corrupt_ratio_history: 1.0 + # + is_add_saturation: true + saturation_ratio_clean_prob: 0.1 + saturation_ratio_min: 0.3 + saturation_ratio_max: 1.7 + # + is_amplify_history: false + history_scale_mode: "per_head" + # + is_train_full_patch_embedding: false + is_train_lora_patch_embedding: false + has_multi_term_memory_patch: true + is_train_full_multi_term_memory_patchg: false + is_train_lora_multi_term_memory_patchg: true + zero_history_timestep: true + guidance_cross_attn: true + restrict_self_attn: false + is_train_restrict_lora: false + restrict_lora: false + restrict_lora_rank: 128 + # ---- Stage 2 Parameters ---- + is_enable_stage2: true + is_navit_pyramid: false + stage2_num_stages: 3 + stage2_timestep_shift: 1.0 + stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3 + stage2_stage_range: + - 0 + - 0.333333333333333333333333333333333 # Approximate value of 1/3 + - 0.666666666666666666666666666666666 # Approximate value of 2/3 + - 1 + stage2_sample_ratios: + - 1 + - 1 + - 1 + efficient_sample: false + # ---- Stage 3 VRAM Parameters ---- + dmd_is_low_vram_mode: true + is_gan_low_vram_mode: true + dmd_is_offload_grad: false + # ---- Stage 3 Parameters ---- + log_iters: 125 + no_visualize: false + is_train_dmd: true + max_grad_norm_critic: 10.0 + dmd_generator_deepspeed_config: scripts/accelerate_configs/zero2.json + dmd_critic_deepspeed_config: scripts/accelerate_configs/zero2.json + critic_learning_rate: 4.0e-07 + dfake_gen_update_ratio: 5 + dmd_denoising_step_list: + - 1000 + - 750 + - 500 + - 250 + num_critic_input_frames: 9 + dmd_timestep_shift: 5.0 + dmd_last_step_only: false + dmd_last_section_grad_only: false + dmd_teacher_forcing: false + dmd_teacher_forcing_ratio: 0.2 + fake_guidance_scale: 0.0 + real_guidance_scale: 3.0 + # ---- GT History Parameters ---- + is_use_gt_history: true + use_gt_history_ratio: 1.0 + # ---- VAE Re-Encode ---- + is_dmd_vae_decode: false + # ---- Multi Stage Backward Simulated ---- + is_multi_pyramid_stage_backward_simulated: false + is_amplify_first_chunk: true + # ---- GAN Parameters ---- + is_use_gan: false + gan_start_step: 1000 + is_separate_gan_grad: false + is_use_gan_hooks: true + is_use_gan_final: true + gan_cond_map_dim: 768 + gan_hooks: + - 5 + - 15 + - 25 + - 35 + gan_g_weight: 5e-2 + gan_d_weight: 1e-2 + aprox_r1: true + aprox_r2: true + r1_weight: 100.0 + r2_weight: 0.0 + r1_sigma: 0.1 + r2_sigma: 0.1 + # ---- Cold Start Parameters ---- + is_enable_cold_start: false + cold_start_step: 2000 + stage_cold_start_step: 2000 + # ---- Dynamic Timestep ---- + generator_is_forcing_low_renoise: false + generator_dynamic_alpha: 4.0 + generator_dynamic_beta: 1.5 + generator_dynamic_sample_type: "beta" + generator_dynamic_step: 500 + critic_dynamic_alpha: 4.0 + critic_dynamic_beta: 1.5 + critic_dynamic_sample_type: "uniform" + critic_dynamic_step: 500 + # ---- Dynamic DMD Section ---- + dmd_num_latent_sections_min: 1 + dmd_num_latent_sections_max: 1 + dmd_dynamic_alpha: 1.5 + dmd_dynamic_beta: 4.0 + dmd_dynamic_sample_type: "uniform" + dmd_dynamic_step: 500 + # ---- Dynamic ODE Section ---- + ode_num_latent_sections_min: 3 + ode_num_latent_sections_max: 3 + ode_dynamic_alpha: 1.5 + ode_dynamic_beta: 4.0 + ode_dynamic_sample_type: "uniform" + ode_dynamic_step: 500 diff --git a/Helios-main/scripts/training/configs/stage_3_post_gan_version.yaml b/Helios-main/scripts/training/configs/stage_3_post_gan_version.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f7c53e5d414bec443d7da8d359dc68daa62bf7bc --- /dev/null +++ b/Helios-main/scripts/training/configs/stage_3_post_gan_version.yaml @@ -0,0 +1,300 @@ +output_dir: ablation_stage_3_post_gan_version +logging_dir: logs +seed: 49 + + +report_to: + tracker_name: Wan-Train + wandb_name: ablation_stage_3_post_gan_version + report_to: wandb + + +data_config: + # ---- Base ---- + use_shuffle: true + pin_memory: true + persistent_workers: true + force_rebuild: true + single_res: true + single_height: 384 + single_width: 640 + dataloader_num_workers: 8 + prefetch_factor: 1 + caption_dropout_p: 0 + id_token: "" + # ---- Stage 1 ---- + use_stage1_dataset: false + # ---- Stage 3 ---- + use_stage3_dataset: true + gan_data_root: + - "demo_data/ultravideo-long" + + +model_config: + # ---- Path ---- + pretrained_model_name_or_path: "BestWishYsh/Helios-Base" + transformer_model_name_or_path: "BestWishYsh/Helios-Distilled" + subfolder: "transformer_ode" + real_score_model_name_or_path: "BestWishYsh/Helios-Base" + load_checkpoints_custom: false + # load_model_path: + load_dcp: false + # load_dcp_path: + # ---- Vae ---- + upcast_vae: true + enable_slicing: false + enable_tiling: false + # ---- Lora ---- + lora_rank: 256 + lora_alpha: 256.0 + lora_dropout: 0.0 + lora_layers: "all-linear" + # lora_target_modules: + # - to_k + # - to_q + # - to_v + # - to_out.0 + # - ffn.net.0.proj + # - ffn.net.2 + lora_exclude_modules: + - down + - up + # ---- Other ---- + train_norm_layers: false + # ---- DMD ---- + critic_lora_rank: 256 + critic_lora_alpha: 256.0 + critic_lora_dropout: 0.0 + # ---- Reward Parameters ---- + reward_model_name_or_path: "/mnt/bn/yufan-dev-my/ysh_new/Ckpts/Videoreward" + + +validation_config: + validation_steps: 500 + validation_height: 384 + validation_width: 640 + validation_max_num_frames: 99 + validation_prompts: + - "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + # - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field." + # - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors." + validation_guidance_scale: 1.0 + validation_latent_window_size: + - 9 + num_validation_videos: 1 + num_inference_steps: 6 + # ---- Dynamic Shifting ---- + use_dynamic_shifting: true + time_shift_type: "linear" # ["exponential", "linear"] + # ---- Pyramid ---- + stage2_simulated_inference_steps: + - 2 + - 2 + - 2 + + +training_config: + # ---- Environment ---- + allow_tf32: false + gradient_checkpointing: true + enable_xformers_memory_efficient_attention: false + enable_npu_flash_attention: false + upcast_before_saving: false + offload: false + mixed_precision: "bf16" + # ---- Training Resource ---- + max_train_steps: 1000000 + train_batch_size: 1 + gradient_accumulation_steps: 1 + checkpointing_steps: 250 + resume_from_checkpoint: "latest" + save_checkpoints_custom: false + # ---- Optimizer ---- + learning_rate: 2.0e-06 + lr_scheduler: "constant" + lr_warmup_steps: 500 + optimizer: "adamw" + adam_beta1: 0.0 + adam_beta2: 0.999 + adam_weight_decay: 1e-03 + adam_epsilon: 1e-08 + max_grad_norm: 10.0 + weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"] + logit_mean: 0.0 + logit_std: 1.0 + mode_scale: 1.29 + # ---- Dynamic Shifting Parameters ---- + use_dynamic_shifting: true + time_shift_type: "linear" + base_seq_len: 256 + max_seq_len: 4096 + base_shift: 0.5 + max_shift: 1.15 + # ---- VAE Decode Parameters ---- + vae_decode_type: "default" + # ---- EMA Parameters ---- + use_ema: true + use_ema_validation: false + ema_decay: 0.99 + ema_start_step: 750 + ema_zero3_port: 10543 + ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json" + # ---- Stage 1 Parameters ---- + is_enable_stage1: true + history_sizes: + - 16 + - 2 + - 1 + latent_window_size: + # - 12 + # - 10 + - 9 + # - 8 + # - 6 + # - 5 + # - 4 + # - 3 + # - 2 + # - 1 + is_random_drop: true + random_drop_v2v_ratio: 0.5 + random_drop_t2v_ratio: 0.4 + # + corrupt_model_input: false + corrupt_mode_model_input: "noise" + corrupt_mode_prob_model_input: 0.9 + is_frame_independent_corrupt_model_input: true + is_chunk_independent_corrupt_model_input: false + noise_corrupt_ratio_model_input: 0.33333333333333 + noise_corrupt_clean_prob_model_input: 0.1 + downsample_min_corrupt_ratio_model_input: 0.9 + downsample_max_corrupt_ratio_model_input: 1.0 + corrupt_history: true + corrupt_mode_history: "random" + corrupt_mode_prob_history: 0.9 + is_frame_independent_corrupt_history: true + is_chunk_independent_corrupt_history: false + noise_corrupt_ratio_history_short: 0.33333333333333 + noise_corrupt_ratio_history_mid: 0.33333333333333 + noise_corrupt_ratio_history_long: 0.33333333333333 + noise_corrupt_clean_prob_history: 0.1 + downsample_min_corrupt_ratio_history: 0.9 + downsample_max_corrupt_ratio_history: 1.0 + # + is_add_saturation: true + saturation_ratio_clean_prob: 0.1 + saturation_ratio_min: 0.3 + saturation_ratio_max: 1.7 + # + is_amplify_history: false + history_scale_mode: "per_head" + # + is_train_full_patch_embedding: false + is_train_lora_patch_embedding: false + has_multi_term_memory_patch: true + is_train_full_multi_term_memory_patchg: false + is_train_lora_multi_term_memory_patchg: true + zero_history_timestep: true + guidance_cross_attn: true + restrict_self_attn: false + is_train_restrict_lora: false + restrict_lora: false + restrict_lora_rank: 128 + # ---- Stage 2 Parameters ---- + is_enable_stage2: true + is_navit_pyramid: false + stage2_num_stages: 3 + stage2_timestep_shift: 1.0 + stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3 + stage2_stage_range: + - 0 + - 0.333333333333333333333333333333333 # Approximate value of 1/3 + - 0.666666666666666666666666666666666 # Approximate value of 2/3 + - 1 + stage2_sample_ratios: + - 1 + - 1 + - 1 + efficient_sample: false + # ---- Stage 3 VRAM Parameters ---- + dmd_is_low_vram_mode: true + is_gan_low_vram_mode: true + dmd_is_offload_grad: false + # ---- Stage 3 Parameters ---- + log_iters: 125 + no_visualize: false + is_train_dmd: true + max_grad_norm_critic: 10.0 + dmd_generator_deepspeed_config: scripts/accelerate_configs/zero2.json + dmd_critic_deepspeed_config: scripts/accelerate_configs/zero2.json + critic_learning_rate: 4.0e-07 + dfake_gen_update_ratio: 5 + dmd_denoising_step_list: + - 1000 + - 750 + - 500 + - 250 + num_critic_input_frames: 9 + dmd_timestep_shift: 5.0 + dmd_last_step_only: false + dmd_last_section_grad_only: false + dmd_teacher_forcing: false + dmd_teacher_forcing_ratio: 0.2 + fake_guidance_scale: 0.0 + real_guidance_scale: 3.0 + # ---- GT History Parameters ---- + is_use_gt_history: true + use_gt_history_ratio: 1.0 + # ---- VAE Re-Encode ---- + is_dmd_vae_decode: false + # ---- Multi Stage Backward Simulated ---- + is_multi_pyramid_stage_backward_simulated: false + is_amplify_first_chunk: true + # ---- GAN Parameters ---- + is_use_gan: true + gan_start_step: 1000 + is_separate_gan_grad: false + is_use_gan_hooks: true + is_use_gan_final: true + gan_cond_map_dim: 768 + gan_hooks: + - 5 + - 15 + - 25 + - 35 + gan_g_weight: 5e-2 + gan_d_weight: 1e-2 + aprox_r1: true + aprox_r2: true + r1_weight: 100.0 + r2_weight: 0.0 + r1_sigma: 0.1 + r2_sigma: 0.1 + # ---- Cold Start Parameters ---- + is_enable_cold_start: false + cold_start_step: 2000 + stage_cold_start_step: 2000 + # ---- Dynamic Timestep ---- + generator_is_forcing_low_renoise: false + generator_dynamic_alpha: 4.0 + generator_dynamic_beta: 1.5 + generator_dynamic_sample_type: "beta" + generator_dynamic_step: 500 + critic_dynamic_alpha: 4.0 + critic_dynamic_beta: 1.5 + critic_dynamic_sample_type: "uniform" + critic_dynamic_step: 500 + # ---- Dynamic DMD Section ---- + dmd_num_latent_sections_min: 1 + dmd_num_latent_sections_max: 1 + dmd_dynamic_alpha: 1.5 + dmd_dynamic_beta: 4.0 + dmd_dynamic_sample_type: "uniform" + dmd_dynamic_step: 500 + # ---- Dynamic ODE Section ---- + ode_num_latent_sections_min: 3 + ode_num_latent_sections_max: 3 + ode_dynamic_alpha: 1.5 + ode_dynamic_beta: 4.0 + ode_dynamic_sample_type: "uniform" + ode_dynamic_step: 500 diff --git a/Helios-main/tools/gradio/comparison/gradio_compare_diff-ablation.py b/Helios-main/tools/gradio/comparison/gradio_compare_diff-ablation.py new file mode 100644 index 0000000000000000000000000000000000000000..44c5b0b5d5ee525ba4effe996d6e83f00842b02a --- /dev/null +++ b/Helios-main/tools/gradio/comparison/gradio_compare_diff-ablation.py @@ -0,0 +1,536 @@ +import os +import re + +import gradio as gr + + +def parse_video_name(filename): + """Parse video filename to extract step and index""" + match = re.match(r".*?(\d+)_(\d+)\.mp4$", filename) + if match: + step = int(match.group(1)) + idx = int(match.group(2)) + return step, idx + return None, None + + +def get_video_list(folder_path): + """Get all mp4 videos from the folder""" + if not os.path.exists(folder_path): + return [] + + videos = [] + for file in os.listdir(folder_path): + if file.endswith(".mp4"): + step, idx = parse_video_name(file) + if step is not None: + videos.append({"filename": file, "step": step, "idx": idx, "path": os.path.join(folder_path, file)}) + + # Sort by step and idx + videos.sort(key=lambda x: (x["step"], x["idx"])) + return videos + + +def create_video_mapping(videos): + """Create mapping from (step, idx) to filename""" + mapping = {} + for video in videos: + key = (video["step"], video["idx"]) + mapping[key] = video["filename"] + return mapping + + +def get_step_idx_mapping(common_keys): + """Extract step and idx mapping from common (step, idx) keys""" + step_idx_map = {} # {step: [idx1, idx2, ...]} + all_steps = set() + all_indices = set() + + for step, idx in common_keys: + all_steps.add(step) + all_indices.add(idx) + if step not in step_idx_map: + step_idx_map[step] = [] + step_idx_map[step].append(idx) + + # Sort + for step in step_idx_map: + step_idx_map[step].sort() + + return sorted(all_steps), sorted(all_indices), step_idx_map + + +def load_videos(folder1, folder2): + """Load videos from two folders and match them""" + if not folder1 or not folder2: + return ( + None, + None, + "Please enter two folder paths", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + + videos1 = get_video_list(folder1) + videos2 = get_video_list(folder2) + + if not videos1: + return ( + None, + None, + "No video files found in folder 1", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + if not videos2: + return ( + None, + None, + "No video files found in folder 2", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + + # Create mapping from (step, idx) to filename + video_map1 = create_video_mapping(videos1) + video_map2 = create_video_mapping(videos2) + + # Find common (step, idx) combinations + common_keys = sorted(set(video_map1.keys()) & set(video_map2.keys())) + + if not common_keys: + # Show detailed info for debugging + steps1 = {v["step"] for v in videos1} + steps2 = {v["step"] for v in videos2} + info = "No matching videos found between the two folders\n" + info += f"Folder 1 steps: {sorted(steps1)}\n" + info += f"Folder 2 steps: {sorted(steps2)}\n" + info += f"Common steps: {sorted(steps1 & steps2)}" + return ( + None, + None, + info, + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + + # Get all steps and indices + all_steps, all_indices, step_idx_map = get_step_idx_mapping(common_keys) + + # Load first video + first_key = common_keys[0] + first_step, first_idx = first_key + + filename1 = video_map1[first_key] + filename2 = video_map2[first_key] + + video1_path = os.path.join(folder1, filename1) + video2_path = os.path.join(folder2, filename2) + + info = f"Found {len(common_keys)} matching videos\n" + info += f"Current: Step {first_step}, Index {first_idx}\n" + info += f"Folder 1: {filename1}\n" + info += f"Folder 2: {filename2}" + + # Get available indices for current step + available_indices = step_idx_map.get(first_step, []) + + progress = f"1 / {len(common_keys)}" + + return ( + video1_path, + video2_path, + info, + gr.update(choices=all_steps, value=first_step), + gr.update(choices=available_indices, value=first_idx), + gr.update(interactive=first_step > all_steps[0]), + gr.update(interactive=first_step < all_steps[-1]), + gr.update(interactive=first_idx > available_indices[0] if available_indices else False), + gr.update(interactive=first_idx < available_indices[-1] if available_indices else False), + progress, + video_map1, + video_map2, + step_idx_map, + ) + + +def update_available_indices(selected_step, step_idx_map): + """Update available index list""" + if not step_idx_map or selected_step is None: + return gr.update(choices=[], value=None) + + available_indices = step_idx_map.get(selected_step, []) + first_idx = available_indices[0] if available_indices else None + + return gr.update(choices=available_indices, value=first_idx) + + +def update_videos_from_selectors(folder1, folder2, selected_step, selected_idx, video_map1, video_map2, step_idx_map): + """Update videos based on selected step and idx""" + if selected_step is None or selected_idx is None: + return None, None, "Please select step and index", gr.update(), gr.update(), gr.update(), gr.update(), "" + + key = (selected_step, selected_idx) + + if key not in video_map1 or key not in video_map2: + return ( + None, + None, + f"Video not found for Step {selected_step}, Index {selected_idx}", + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + filename1 = video_map1[key] + filename2 = video_map2[key] + + video1_path = os.path.join(folder1, filename1) + video2_path = os.path.join(folder2, filename2) + + info = f"Current: Step {selected_step}, Index {selected_idx}\n" + info += f"Folder 1: {filename1}\n" + info += f"Folder 2: {filename2}" + + # Get all steps and indices for current step + all_steps = sorted(step_idx_map.keys()) + available_indices = step_idx_map.get(selected_step, []) + + # Update button states + prev_step_interactive = selected_step > all_steps[0] + next_step_interactive = selected_step < all_steps[-1] + prev_idx_interactive = selected_idx > available_indices[0] if available_indices else False + next_idx_interactive = selected_idx < available_indices[-1] if available_indices else False + + # Calculate current video number + all_keys = sorted(set(video_map1.keys()) & set(video_map2.keys())) + current_idx = all_keys.index(key) + 1 + progress = f"{current_idx} / {len(all_keys)}" + + return ( + video1_path, + video2_path, + info, + gr.update(interactive=prev_step_interactive), + gr.update(interactive=next_step_interactive), + gr.update(interactive=prev_idx_interactive), + gr.update(interactive=next_idx_interactive), + progress, + ) + + +def navigate_step(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction): + """Navigate to previous or next step""" + if not step_idx_map or current_step is None: + return ( + None, + None, + "Please load videos first", + current_step, + current_idx, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + all_steps = sorted(step_idx_map.keys()) + current_step_idx = all_steps.index(current_step) + + if direction == "prev": + new_step_idx = max(0, current_step_idx - 1) + else: # next + new_step_idx = min(len(all_steps) - 1, current_step_idx + 1) + + new_step = all_steps[new_step_idx] + + # Get first available index for new step + available_indices = step_idx_map.get(new_step, []) + new_idx = available_indices[0] if available_indices else current_idx + + return update_videos_from_selectors(folder1, folder2, new_step, new_idx, video_map1, video_map2, step_idx_map) + ( + new_step, + new_idx, + ) + + +def navigate_idx(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction): + """Navigate to previous or next index""" + if not step_idx_map or current_step is None or current_idx is None: + return ( + None, + None, + "Please load videos first", + current_step, + current_idx, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + available_indices = step_idx_map.get(current_step, []) + if not available_indices or current_idx not in available_indices: + return ( + None, + None, + "Index not in list", + current_step, + current_idx, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + current_idx_pos = available_indices.index(current_idx) + + if direction == "prev": + new_idx_pos = max(0, current_idx_pos - 1) + else: # next + new_idx_pos = min(len(available_indices) - 1, current_idx_pos + 1) + + new_idx = available_indices[new_idx_pos] + + return update_videos_from_selectors( + folder1, folder2, current_step, new_idx, video_map1, video_map2, step_idx_map + ) + (current_step, new_idx) + + +# Create Gradio interface +with gr.Blocks(title="Video Comparison Tool") as demo: + gr.Markdown("# Video Comparison Tool") + gr.Markdown( + "Enter two folder paths to automatically match and compare videos with the same naming (matched by step and index, ignoring filename prefix)" + ) + + # Store state + video_map1_state = gr.State({}) + video_map2_state = gr.State({}) + step_idx_map_state = gr.State({}) + + with gr.Row(): + folder1_input = gr.Textbox(label="Folder 1 Path", placeholder="/path/to/folder1", scale=2) + folder2_input = gr.Textbox(label="Folder 2 Path", placeholder="/path/to/folder2", scale=2) + + load_btn = gr.Button("Load Videos", variant="primary") + + info_text = gr.Textbox(label="Info", interactive=False, lines=4) + + # Step navigation controls + with gr.Row(): + prev_step_btn = gr.Button("⬅️ Previous Step", interactive=False, scale=1) + step_selector = gr.Dropdown(label="Select Step", choices=[], interactive=True, scale=2) + next_step_btn = gr.Button("Next Step ➡️", interactive=False, scale=1) + + # Index navigation controls + with gr.Row(): + prev_idx_btn = gr.Button("⬅️ Previous Index", interactive=False, scale=1) + idx_selector = gr.Dropdown(label="Select Index", choices=[], interactive=True, scale=2) + next_idx_btn = gr.Button("Next Index ➡️", interactive=False, scale=1) + + progress_text = gr.Textbox(label="Progress", value="0 / 0", interactive=False) + + with gr.Row(): + with gr.Column(): + gr.Markdown("### Folder 1") + video1 = gr.Video(label="Video 1", autoplay=True, loop=True) + + with gr.Column(): + gr.Markdown("### Folder 2") + video2 = gr.Video(label="Video 2", autoplay=True, loop=True) + + # Event bindings + load_btn.click( + fn=load_videos, + inputs=[folder1_input, folder2_input], + outputs=[ + video1, + video2, + info_text, + step_selector, + idx_selector, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + ) + + # When step changes, update available indices + step_selector.change( + fn=update_available_indices, inputs=[step_selector, step_idx_map_state], outputs=[idx_selector] + ).then( + fn=update_videos_from_selectors, + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text], + ) + + # When index changes, update videos + idx_selector.change( + fn=update_videos_from_selectors, + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text], + ) + + # Step navigation buttons + prev_step_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "prev"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + + next_step_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "next"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + + # Index navigation buttons + prev_idx_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "prev"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + + next_idx_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "next"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + +if __name__ == "__main__": + demo.launch(share=True, allowed_paths=["0_ablation_videos"]) diff --git a/Helios-main/tools/gradio/comparison/gradio_compare_diff-ckpt.py b/Helios-main/tools/gradio/comparison/gradio_compare_diff-ckpt.py new file mode 100644 index 0000000000000000000000000000000000000000..942181246d13ca034637e518c013cd982503b519 --- /dev/null +++ b/Helios-main/tools/gradio/comparison/gradio_compare_diff-ckpt.py @@ -0,0 +1,547 @@ +import os +import re + +import gradio as gr + + +def parse_video_name(filename): + """Parse video filename to extract step and index""" + # Match checkpoint-{step}_{idx}.mp4 format + match = re.match(r"checkpoint-(\d+)_(\d+)\.mp4$", filename) + if match: + step = int(match.group(1)) + idx = int(match.group(2)) + return step, idx + return None, None + + +def get_video_list(folder_path): + """Get all mp4 videos from folder""" + if not os.path.exists(folder_path): + return [] + + videos = [] + for file in os.listdir(folder_path): + if file.endswith(".mp4"): + step, idx = parse_video_name(file) + if step is not None: + videos.append({"filename": file, "step": step, "idx": idx, "path": os.path.join(folder_path, file)}) + + # Sort by step and idx + videos.sort(key=lambda x: (x["step"], x["idx"])) + return videos + + +def create_video_mapping(videos): + """Create (step, idx) -> filename mapping""" + mapping = {} + for video in videos: + key = (video["step"], video["idx"]) + mapping[key] = video["filename"] + return mapping + + +def get_step_idx_mapping(common_keys): + """Extract step and idx mapping from common (step, idx) keys""" + step_idx_map = {} # {step: [idx1, idx2, ...]} + all_steps = set() + all_indices = set() + + for step, idx in common_keys: + all_steps.add(step) + all_indices.add(idx) + if step not in step_idx_map: + step_idx_map[step] = [] + step_idx_map[step].append(idx) + + # Sort + for step in step_idx_map: + step_idx_map[step].sort() + + return sorted(all_steps), sorted(all_indices), step_idx_map + + +def load_videos(folder1, folder2): + """Load videos from both folders and match them""" + if not folder1 or not folder2: + return ( + None, + None, + "Please enter both folder paths", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + + videos1 = get_video_list(folder1) + videos2 = get_video_list(folder2) + + if not videos1: + return ( + None, + None, + f"No video files found in folder 1 (total {len(os.listdir(folder1)) if os.path.exists(folder1) else 0} files)", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + if not videos2: + return ( + None, + None, + f"No video files found in folder 2 (total {len(os.listdir(folder2)) if os.path.exists(folder2) else 0} files)", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + + # Create (step, idx) to filename mapping + video_map1 = create_video_mapping(videos1) + video_map2 = create_video_mapping(videos2) + + # Find common (step, idx) combinations + common_keys = sorted(set(video_map1.keys()) & set(video_map2.keys())) + + if not common_keys: + # Show detailed information for debugging + steps1 = {v["step"] for v in videos1} + steps2 = {v["step"] for v in videos2} + info = "No matching videos found in both folders\n" + info += f"Folder 1: {len(videos1)} videos found\n" + info += f"Folder 2: {len(videos2)} videos found\n" + info += f"Folder 1 steps: {sorted(steps1)}\n" + info += f"Folder 2 steps: {sorted(steps2)}\n" + info += f"Common steps: {sorted(steps1 & steps2)}" + return ( + None, + None, + info, + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + {}, + ) + + # Get all steps and indices + all_steps, all_indices, step_idx_map = get_step_idx_mapping(common_keys) + + # Load first video + first_key = common_keys[0] + first_step, first_idx = first_key + + filename1 = video_map1[first_key] + filename2 = video_map2[first_key] + + video1_path = os.path.join(folder1, filename1) + video2_path = os.path.join(folder2, filename2) + + info = f"Found {len(common_keys)} matching video pairs\n" + info += f"Folder 1: {len(videos1)} videos\n" + info += f"Folder 2: {len(videos2)} videos\n" + info += f"Current: Step {first_step}, Index {first_idx}\n" + info += f"File 1: {filename1}\n" + info += f"File 2: {filename2}" + + # Get available indices for current step + available_indices = step_idx_map.get(first_step, []) + + progress = f"1 / {len(common_keys)}" + + return ( + video1_path, + video2_path, + info, + gr.update(choices=all_steps, value=first_step), + gr.update(choices=available_indices, value=first_idx), + gr.update(interactive=first_step > all_steps[0]), + gr.update(interactive=first_step < all_steps[-1]), + gr.update(interactive=first_idx > available_indices[0] if available_indices else False), + gr.update(interactive=first_idx < available_indices[-1] if available_indices else False), + progress, + video_map1, + video_map2, + step_idx_map, + ) + + +def update_available_indices(selected_step, step_idx_map): + """Update available index list""" + if not step_idx_map or selected_step is None: + return gr.update(choices=[], value=None) + + available_indices = step_idx_map.get(selected_step, []) + first_idx = available_indices[0] if available_indices else None + + return gr.update(choices=available_indices, value=first_idx) + + +def update_videos_from_selectors(folder1, folder2, selected_step, selected_idx, video_map1, video_map2, step_idx_map): + """Update videos based on selected step and idx""" + if selected_step is None or selected_idx is None: + return None, None, "Please select step and index", gr.update(), gr.update(), gr.update(), gr.update(), "" + + key = (selected_step, selected_idx) + + if key not in video_map1 or key not in video_map2: + return ( + None, + None, + f"Video not found for Step {selected_step}, Index {selected_idx}", + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + filename1 = video_map1[key] + filename2 = video_map2[key] + + video1_path = os.path.join(folder1, filename1) + video2_path = os.path.join(folder2, filename2) + + info = f"Current: Step {selected_step}, Index {selected_idx}\n" + info += f"File 1: {filename1}\n" + info += f"File 2: {filename2}" + + # Get all steps and indices for current step + all_steps = sorted(step_idx_map.keys()) + available_indices = step_idx_map.get(selected_step, []) + + # Update button states + prev_step_interactive = selected_step > all_steps[0] + next_step_interactive = selected_step < all_steps[-1] + prev_idx_interactive = selected_idx > available_indices[0] if available_indices else False + next_idx_interactive = selected_idx < available_indices[-1] if available_indices else False + + # Calculate current video position + all_keys = sorted(set(video_map1.keys()) & set(video_map2.keys())) + current_idx = all_keys.index(key) + 1 + progress = f"{current_idx} / {len(all_keys)}" + + return ( + video1_path, + video2_path, + info, + gr.update(interactive=prev_step_interactive), + gr.update(interactive=next_step_interactive), + gr.update(interactive=prev_idx_interactive), + gr.update(interactive=next_idx_interactive), + progress, + ) + + +def navigate_step(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction): + """Navigate to previous or next step""" + if not step_idx_map or current_step is None: + return ( + None, + None, + "Please load videos first", + current_step, + current_idx, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + all_steps = sorted(step_idx_map.keys()) + current_step_idx = all_steps.index(current_step) + + if direction == "prev": + new_step_idx = max(0, current_step_idx - 1) + else: # next + new_step_idx = min(len(all_steps) - 1, current_step_idx + 1) + + new_step = all_steps[new_step_idx] + + # Get first available index for new step + available_indices = step_idx_map.get(new_step, []) + new_idx = available_indices[0] if available_indices else current_idx + + return update_videos_from_selectors(folder1, folder2, new_step, new_idx, video_map1, video_map2, step_idx_map) + ( + new_step, + new_idx, + ) + + +def navigate_idx(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction): + """Navigate to previous or next index""" + if not step_idx_map or current_step is None or current_idx is None: + return ( + None, + None, + "Please load videos first", + current_step, + current_idx, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + available_indices = step_idx_map.get(current_step, []) + if not available_indices or current_idx not in available_indices: + return ( + None, + None, + "Index not in list", + current_step, + current_idx, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + current_idx_pos = available_indices.index(current_idx) + + if direction == "prev": + new_idx_pos = max(0, current_idx_pos - 1) + else: # next + new_idx_pos = min(len(available_indices) - 1, current_idx_pos + 1) + + new_idx = available_indices[new_idx_pos] + + return update_videos_from_selectors( + folder1, folder2, current_step, new_idx, video_map1, video_map2, step_idx_map + ) + (current_step, new_idx) + + +# Create Gradio interface +with gr.Blocks(title="Video Comparison Tool") as demo: + gr.Markdown("# Video Comparison Tool") + gr.Markdown( + "Enter two folder paths to automatically match and compare checkpoint-{step}_{idx}.mp4 format video files" + ) + + # Store state + video_map1_state = gr.State({}) + video_map2_state = gr.State({}) + step_idx_map_state = gr.State({}) + + with gr.Row(): + folder1_input = gr.Textbox(label="Folder 1 Path", placeholder="/path/to/folder1", scale=2) + folder2_input = gr.Textbox(label="Folder 2 Path", placeholder="/path/to/folder2", scale=2) + + load_btn = gr.Button("Load Videos", variant="primary") + + info_text = gr.Textbox(label="Information", interactive=False, lines=6) + + # Step navigation controls + with gr.Row(): + prev_step_btn = gr.Button("⬅️ Previous Step", interactive=False, scale=1) + step_selector = gr.Dropdown(label="Select Step", choices=[], interactive=True, scale=2) + next_step_btn = gr.Button("Next Step ➡️", interactive=False, scale=1) + + # Index navigation controls + with gr.Row(): + prev_idx_btn = gr.Button("⬅️ Previous Index", interactive=False, scale=1) + idx_selector = gr.Dropdown(label="Select Index", choices=[], interactive=True, scale=2) + next_idx_btn = gr.Button("Next Index ➡️", interactive=False, scale=1) + + progress_text = gr.Textbox(label="Progress", value="0 / 0", interactive=False) + + with gr.Row(): + with gr.Column(): + gr.Markdown("### Folder 1") + video1 = gr.Video(label="Video 1", autoplay=True, loop=True) + + with gr.Column(): + gr.Markdown("### Folder 2") + video2 = gr.Video(label="Video 2", autoplay=True, loop=True) + + # Event bindings + load_btn.click( + fn=load_videos, + inputs=[folder1_input, folder2_input], + outputs=[ + video1, + video2, + info_text, + step_selector, + idx_selector, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + ) + + # When step changes, update available indices + step_selector.change( + fn=update_available_indices, inputs=[step_selector, step_idx_map_state], outputs=[idx_selector] + ).then( + fn=update_videos_from_selectors, + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text], + ) + + # When index changes, update videos + idx_selector.change( + fn=update_videos_from_selectors, + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text], + ) + + # Step navigation buttons + prev_step_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "prev"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + + next_step_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "next"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + + # Index navigation buttons + prev_idx_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "prev"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + + next_idx_btn.click( + fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "next"), + inputs=[ + folder1_input, + folder2_input, + step_selector, + idx_selector, + video_map1_state, + video_map2_state, + step_idx_map_state, + ], + outputs=[ + video1, + video2, + info_text, + prev_step_btn, + next_step_btn, + prev_idx_btn, + next_idx_btn, + progress_text, + step_selector, + idx_selector, + ], + ) + +if __name__ == "__main__": + demo.launch( + share=True, + allowed_paths=[ + "0_ablation_videos", + "ablation_stage3_1_warmup", + ], + ) diff --git a/Helios-main/tools/gradio/comparison/gradio_compare_diff-video.py b/Helios-main/tools/gradio/comparison/gradio_compare_diff-video.py new file mode 100644 index 0000000000000000000000000000000000000000..94c16f79f54ae9bb7e99d082583f48b04a6e240b --- /dev/null +++ b/Helios-main/tools/gradio/comparison/gradio_compare_diff-video.py @@ -0,0 +1,450 @@ +import os +import re + +import gradio as gr + + +def parse_video_name(filename): + """Parse video filename to extract step and index""" + # Match checkpoint-{step}_{idx}.mp4 format + match = re.match(r"checkpoint-(\d+)_(\d+)\.mp4$", filename) + if match: + step = int(match.group(1)) + idx = int(match.group(2)) + return step, idx + return None, None + + +def get_video_list(folder_path): + """Get all mp4 videos from folder""" + if not os.path.exists(folder_path): + return [] + + videos = [] + for file in os.listdir(folder_path): + if file.endswith(".mp4"): + step, idx = parse_video_name(file) + if step is not None: + videos.append({"filename": file, "step": step, "idx": idx, "path": os.path.join(folder_path, file)}) + + # Sort by step and idx + videos.sort(key=lambda x: (x["step"], x["idx"])) + return videos + + +def create_video_mapping(videos): + """Create (step, idx) -> filename mapping""" + mapping = {} + for video in videos: + key = (video["step"], video["idx"]) + mapping[key] = video["filename"] + return mapping + + +def get_step_idx_info(video_map): + """Extract step and idx information from video mapping""" + all_steps = set() + all_indices = set() + idx_step_map = {} # {idx: [step1, step2, ...]} + + for step, idx in video_map.keys(): + all_steps.add(step) + all_indices.add(idx) + if idx not in idx_step_map: + idx_step_map[idx] = [] + idx_step_map[idx].append(step) + + # Sort + for idx in idx_step_map: + idx_step_map[idx].sort() + + return sorted(all_steps), sorted(all_indices), idx_step_map + + +def load_videos(folder_path): + """Load videos from folder""" + if not folder_path: + return ( + None, + None, + "Please enter folder path", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + ) + + videos = get_video_list(folder_path) + + if not videos: + return ( + None, + None, + f"No video files found in folder ({len(os.listdir(folder_path)) if os.path.exists(folder_path) else 0} files total)", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + ) + + # Create (step, idx) to filename mapping + video_map = create_video_mapping(videos) + + # Get all step and index information + all_steps, all_indices, idx_step_map = get_step_idx_info(video_map) + + # Filter indices with at least 2 steps + valid_indices = [idx for idx in all_indices if len(idx_step_map[idx]) >= 2] + + if not valid_indices: + info = ( + f"Found {len(videos)} videos, but no comparable videos (need at least 2 different steps for same index)\n" + ) + info += f"Steps: {all_steps}\n" + info += f"Indices: {all_indices}" + return ( + None, + None, + info, + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + gr.update(interactive=False), + "0 / 0", + {}, + {}, + ) + + # Select first valid index and its first two steps + first_idx = valid_indices[0] + available_steps = idx_step_map[first_idx] + step1 = available_steps[0] + step2 = available_steps[1] if len(available_steps) > 1 else available_steps[0] + + # Load videos + filename1 = video_map.get((step1, first_idx)) + filename2 = video_map.get((step2, first_idx)) + + video1_path = os.path.join(folder_path, filename1) if filename1 else None + video2_path = os.path.join(folder_path, filename2) if filename2 else None + + info = f"Found {len(videos)} videos, {len(valid_indices)} comparable indices\n" + info += f"Current Index: {first_idx}\n" + info += f"Step1: {step1} - {filename1}\n" + info += f"Step2: {step2} - {filename2}" + + progress = f"1 / {len(valid_indices)}" + + return ( + video1_path, + video2_path, + info, + gr.update(choices=valid_indices, value=first_idx), + gr.update(choices=available_steps, value=step1), + gr.update(choices=available_steps, value=step2), + gr.update(interactive=first_idx > valid_indices[0]), + gr.update(interactive=first_idx < valid_indices[-1]), + gr.update(interactive=True), + gr.update(interactive=True), + progress, + video_map, + idx_step_map, + ) + + +def update_videos(folder_path, selected_idx, selected_step1, selected_step2, video_map, idx_step_map): + """Update videos based on selected idx and two steps""" + if selected_idx is None or selected_step1 is None or selected_step2 is None: + return None, None, "Please select index and steps", gr.update(), gr.update(), gr.update(), gr.update(), "" + + key1 = (selected_step1, selected_idx) + key2 = (selected_step2, selected_idx) + + filename1 = video_map.get(key1) + filename2 = video_map.get(key2) + + if not filename1 or not filename2: + return ( + None, + None, + f"Complete video pair not found: Index {selected_idx}, Step1 {selected_step1}, Step2 {selected_step2}", + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + video1_path = os.path.join(folder_path, filename1) + video2_path = os.path.join(folder_path, filename2) + + info = f"Current Index: {selected_idx}\n" + info += f"Step1: {selected_step1} - {filename1}\n" + info += f"Step2: {selected_step2} - {filename2}" + + # Get all valid indices + all_indices = [idx for idx in idx_step_map.keys() if len(idx_step_map[idx]) >= 2] + all_indices.sort() + + # Update button states + prev_idx_interactive = selected_idx > all_indices[0] if all_indices else False + next_idx_interactive = selected_idx < all_indices[-1] if all_indices else False + + # Calculate progress + current_pos = all_indices.index(selected_idx) + 1 if selected_idx in all_indices else 0 + progress = f"{current_pos} / {len(all_indices)}" + + return ( + video1_path, + video2_path, + info, + gr.update(interactive=prev_idx_interactive), + gr.update(interactive=next_idx_interactive), + gr.update(), + gr.update(), + progress, + ) + + +def update_available_steps(selected_idx, idx_step_map): + """Update available steps list for current index""" + if not idx_step_map or selected_idx is None: + return gr.update(choices=[], value=None), gr.update(choices=[], value=None) + + available_steps = idx_step_map.get(selected_idx, []) + first_step = available_steps[0] if available_steps else None + second_step = available_steps[1] if len(available_steps) > 1 else first_step + + return ( + gr.update(choices=available_steps, value=first_step), + gr.update(choices=available_steps, value=second_step), + ) + + +def navigate_idx(folder_path, current_idx, step1, step2, video_map, idx_step_map, direction): + """Navigate to previous or next index""" + if not idx_step_map or current_idx is None: + return ( + None, + None, + "Please load videos first", + current_idx, + step1, + step2, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + # Get all valid indices + all_indices = [idx for idx in idx_step_map.keys() if len(idx_step_map[idx]) >= 2] + all_indices.sort() + + if current_idx not in all_indices: + return ( + None, + None, + "Current Index invalid", + current_idx, + step1, + step2, + gr.update(), + gr.update(), + gr.update(), + gr.update(), + "", + ) + + current_idx_pos = all_indices.index(current_idx) + + if direction == "prev": + new_idx_pos = max(0, current_idx_pos - 1) + else: # next + new_idx_pos = min(len(all_indices) - 1, current_idx_pos + 1) + + new_idx = all_indices[new_idx_pos] + + # Get available steps for new index + available_steps = idx_step_map.get(new_idx, []) + new_step1 = available_steps[0] if available_steps else step1 + new_step2 = available_steps[1] if len(available_steps) > 1 else available_steps[0] + + result = update_videos(folder_path, new_idx, new_step1, new_step2, video_map, idx_step_map) + return result + (new_idx, new_step1, new_step2) + + +# Create Gradio interface +with gr.Blocks(title="Video Comparison Tool - Different Step Comparison") as demo: + gr.Markdown("# Video Comparison Tool - Different Step Comparison") + gr.Markdown( + "Enter folder path to compare videos of same index at different steps (checkpoint-{step}_{idx}.mp4 format)" + ) + + # Store state + video_map_state = gr.State({}) + idx_step_map_state = gr.State({}) + + folder_input = gr.Textbox(label="Folder Path", placeholder="/path/to/folder", scale=2) + + load_btn = gr.Button("Load Videos", variant="primary") + + info_text = gr.Textbox(label="Information", interactive=False, lines=5) + + # Index navigation controls + with gr.Row(): + prev_idx_btn = gr.Button("⬅️ Previous Index", interactive=False, scale=1) + idx_selector = gr.Dropdown(label="Select Index", choices=[], interactive=True, scale=2) + next_idx_btn = gr.Button("Next Index ➡️", interactive=False, scale=1) + + # Step selectors + with gr.Row(): + step1_selector = gr.Dropdown(label="Select Step1 (Left)", choices=[], interactive=True, scale=1) + step2_selector = gr.Dropdown(label="Select Step2 (Right)", choices=[], interactive=True, scale=1) + + progress_text = gr.Textbox(label="Progress", value="0 / 0", interactive=False) + + with gr.Row(): + with gr.Column(): + gr.Markdown("### Step 1") + video1 = gr.Video(label="Video 1", autoplay=True, loop=True) + + with gr.Column(): + gr.Markdown("### Step 2") + video2 = gr.Video(label="Video 2", autoplay=True, loop=True) + + # Event binding + load_btn.click( + fn=load_videos, + inputs=[folder_input], + outputs=[ + video1, + video2, + info_text, + idx_selector, + step1_selector, + step2_selector, + prev_idx_btn, + next_idx_btn, + gr.State(), + gr.State(), + progress_text, + video_map_state, + idx_step_map_state, + ], + ) + + # When index changes, update available steps and videos + def handle_idx_change(folder_path, selected_idx, video_map, idx_step_map): + """Handle index change - update steps and videos together""" + if not idx_step_map or selected_idx is None: + return ( + None, + None, + "Please select index", + gr.update(choices=[], value=None), + gr.update(choices=[], value=None), + gr.update(), + gr.update(), + "", + ) + + # Get available steps for new index + available_steps = idx_step_map.get(selected_idx, []) + new_step1 = available_steps[0] if available_steps else None + new_step2 = available_steps[1] if len(available_steps) > 1 else available_steps[0] + + # Update videos with new steps + result = update_videos(folder_path, selected_idx, new_step1, new_step2, video_map, idx_step_map) + + return ( + result[0], # video1 + result[1], # video2 + result[2], # info + gr.update(choices=available_steps, value=new_step1), # step1_selector + gr.update(choices=available_steps, value=new_step2), # step2_selector + result[3], # prev_idx_btn + result[4], # next_idx_btn + result[7], # progress + ) + + idx_selector.change( + fn=handle_idx_change, + inputs=[folder_input, idx_selector, video_map_state, idx_step_map_state], + outputs=[video1, video2, info_text, step1_selector, step2_selector, prev_idx_btn, next_idx_btn, progress_text], + ) + + step1_selector.select( + fn=update_videos, + inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state], + outputs=[video1, video2, info_text, prev_idx_btn, next_idx_btn, gr.State(), gr.State(), progress_text], + ) + + step2_selector.select( + fn=update_videos, + inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state], + outputs=[video1, video2, info_text, prev_idx_btn, next_idx_btn, gr.State(), gr.State(), progress_text], + ) + + # Index navigation buttons + prev_idx_btn.click( + fn=lambda f, i, s1, s2, vm, ism: navigate_idx(f, i, s1, s2, vm, ism, "prev"), + inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state], + outputs=[ + video1, + video2, + info_text, + prev_idx_btn, + next_idx_btn, + gr.State(), + gr.State(), + progress_text, + idx_selector, + step1_selector, + step2_selector, + ], + ) + + next_idx_btn.click( + fn=lambda f, i, s1, s2, vm, ism: navigate_idx(f, i, s1, s2, vm, ism, "next"), + inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state], + outputs=[ + video1, + video2, + info_text, + prev_idx_btn, + next_idx_btn, + gr.State(), + gr.State(), + progress_text, + idx_selector, + step1_selector, + step2_selector, + ], + ) + + +if __name__ == "__main__": + demo.launch( + share=True, + allowed_paths=[ + "0_ablation_videos", + "ablation_stage3_1_warmup", + ], + ) diff --git a/Helios-main/tools/offload_data/README.md b/Helios-main/tools/offload_data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8245e5665c47dc1e098957520cc955e894373142 --- /dev/null +++ b/Helios-main/tools/offload_data/README.md @@ -0,0 +1,93 @@ +# Data Preprocessing Pipeline by *Helios* +This repository describes the data preprocessing pipeline used in the [Helios](https://arxiv.org/abs/2603.04379) paper. And we prepare a toy training data [here](https://huggingface.co/BestWishYsh/HeliosBench-Weights/tree/main/demo_data). + + +## ⚙️ Requirements and Installation + + +### Environment + +```bash +# Activate conda environment +conda activate helios +``` + +## 🗝️ Usage + +### Step 1 - Prepare Metadata and Organize Videos + +To train your own video generation model, create JSON files following this [format](./example/toy_data/toy_filter.json): + +``` +[ + { + "cut": [0, 81], + "crop": [0, 832, 0, 480], + "fps": 24.0, + "num_frames": 81, + "resolution": { + "height": 480, + "width": 832 + }, + "cap": [ + "A stunning mid-afternoon ..." + ], + "path": "videos/2_240_ori81.mp4" + }, + { + "cut": [0, 81], + ... + } +... +] +``` + +and arrange video files following this [structure](./example): + +``` +📦 example/ +├── 📂 toy_data/ +│ ├── 📂 videos +│ │ ├── 2_240_ori81.mp4 +│ │ ├── 239_120_ori129.mp4.mp4 +│ │ └── ... +│ └── 📄 toy_data_1.json +│ +├── 📂 toy_data_2/ +│ │ ├── A.mp4 +│ │ ├── B.mp4 +│ │ └── ... +│ └── 📄 toy_data_2.json +... +``` + +### Step 2 - Prepare Autoregressive Real Data + +These data can be used for training Stage-1, Stage-2, and Stage-3. + +```bash +# Remember to modify the input and output paths before running +bash get_short-latents.py +``` + +### Step 3 - Prepare Autoregressive ODE Data + +These data can only be used for training Stage-3. + +```bash +# Remember to modify the input and output paths before running +bash get_ode-pairs.sh +``` + +### (Optional) Step 4 - Prepare Text Data + +If you want to use the [Self-Forcing](https://github.com/guandeh17/Self-Forcing) training approach, prepare text embeddings: + +```bash +# Remember to modify the input and output paths before running +bash get_text-embedding.sh +``` + +## 🔒 Acknowledgement + +* This project wouldn't be possible without the following open-sourced repositories: [OpenSora Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan), [OpenSora](https://github.com/hpcaitech/Open-Sora), [Video-Dataset-Scripts](https://github.com/huggingface/video-dataset-scripts) \ No newline at end of file diff --git a/Helios-main/tools/offload_data/get_long-latents.py b/Helios-main/tools/offload_data/get_long-latents.py new file mode 100644 index 0000000000000000000000000000000000000000..95fa4f6b475025d63d594714652eb0ec84faeac9 --- /dev/null +++ b/Helios-main/tools/offload_data/get_long-latents.py @@ -0,0 +1,329 @@ +import argparse +import os + +import torch +import torch.distributed as dist +import torchvision.transforms as transforms +from accelerate import Accelerator +from helios.dataset.dataloader_mp4_dist import BucketedFeatureDataset, BucketedSampler, collate_fn +from helios.utils.utils_base import encode_prompt +from torch.utils.data import DataLoader +from tqdm import tqdm +from transformers import AutoTokenizer, UMT5EncoderModel + +from diffusers import AutoencoderKLWan +from diffusers.training_utils import free_memory + + +def setup_distributed_env(): + dist.init_process_group(backend="nccl") + torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) + + +def cleanup_distributed_env(): + dist.destroy_process_group() + + +def main( + rank, + world_size, + global_rank, + stride, + batch_size, + dataloader_num_workers, + json_file, + video_folder, + output_latent_folder, + pretrained_model_name_or_path, + resolution=640, +): + weight_dtype = torch.bfloat16 + device = rank + seed = 42 + + # Load the tokenizers + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, + subfolder="tokenizer", + ) + text_encoder = UMT5EncoderModel.from_pretrained( + pretrained_model_name_or_path, + subfolder="text_encoder", + torch_dtype=weight_dtype, + ) + vae = AutoencoderKLWan.from_pretrained( + pretrained_model_name_or_path, + subfolder="vae", + torch_dtype=torch.float32, + ) + + latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(device, weight_dtype) + latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to( + device, weight_dtype + ) + + vae.eval() + vae.requires_grad_(False) + text_encoder.eval() + text_encoder.requires_grad_(False) + + vae = vae.to(device) + text_encoder = text_encoder.to(device) + + # dist.barrier() + dataset = BucketedFeatureDataset( + json_files=json_file, + video_folders=video_folder, + stride=stride, + force_rebuild=False, + resolution=resolution, + single_res=True, + single_height=384, + single_width=640, + single_length=True, + single_num_frame=81, + ) + sampler = BucketedSampler(dataset, batch_size=batch_size, drop_last=False, shuffle=True, seed=seed) + dataloader = DataLoader( + dataset, + batch_sampler=sampler, + collate_fn=collate_fn, + num_workers=dataloader_num_workers, + pin_memory=True, + prefetch_factor=2 if dataloader_num_workers != 0 else None, + # persistent_workers=True if dataloader_num_workers > 0 else False, + ) + + print(len(dataset), len(dataloader)) + accelerator = Accelerator() + dataloader = accelerator.prepare(dataloader) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}") + + sampler.set_epoch(0) + if rank == 0: + pbar = tqdm(total=len(dataloader), desc="Processing") + # dist.barrier() + for idx, batch in enumerate(dataloader): + if batch is None or batch["videos"] is None: + print("None batch, continuing") + continue + free_memory() + + valid_indices = [] + valid_uttids = [] + valid_num_frames = [] + valid_heights = [] + valid_widths = [] + valid_videos = [] + valid_prompts = [] + valid_first_frames_images = [] + + if batch["uttid"] is None: + print("None batch, contiuning") + continue + + for i, (uttid, num_frame, height, width) in enumerate( + zip( + batch["uttid"], + batch["video_metadata"]["num_frames"], + batch["video_metadata"]["height"], + batch["video_metadata"]["width"], + ) + ): + os.makedirs(output_latent_folder, exist_ok=True) + output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt") + if not os.path.exists(output_path): + valid_indices.append(i) + valid_uttids.append(uttid) + valid_num_frames.append(num_frame) + valid_heights.append(height) + valid_widths.append(width) + valid_videos.append(batch["videos"][i]) + valid_prompts.append(batch["prompts"][i]) + valid_first_frames_images.append(batch["first_frames_images"][i]) + else: + print(f"skipping {uttid}") + + if not valid_indices: + print("skipping entire batch!") + if rank == 0: + pbar.update(1) + pbar.set_postfix({"batch": idx}) + continue + + batch = None + del batch + free_memory() + + batch = { + "uttid": valid_uttids, + "video_metadata": {"num_frames": valid_num_frames, "height": valid_heights, "width": valid_widths}, + "videos": torch.stack(valid_videos), + "prompts": valid_prompts, + "first_frames_images": torch.stack(valid_first_frames_images), + } + + if len(batch["uttid"]) == 0: + print("All samples in this batch are already processed, skipping!") + continue + + with torch.no_grad(): + # Get Vae feature + pixel_values = batch["videos"].permute(0, 2, 1, 3, 4).to(dtype=vae.dtype, device=device) + vae_latents = vae.encode(pixel_values).latent_dist.sample() + vae_latents = (vae_latents - latents_mean) * latents_std + + # Encode prompts + prompts = batch["prompts"] + prompt_embeds, prompt_attention_mask = encode_prompt( + tokenizer=tokenizer, + text_encoder=text_encoder, + prompt=prompts, + device=device, + ) + + image_tensor = batch["first_frames_images"] + images = [transforms.ToPILImage()(x.to(torch.uint8)) for x in image_tensor] + + for ( + uttid, + num_frame, + height, + width, + cur_vae_latent, + cur_prompt_embed, + cur_prompt_attention_mask, + cur_first_frames_image, + cur_prompt, + ) in zip( + batch["uttid"], + batch["video_metadata"]["num_frames"], + batch["video_metadata"]["height"], + batch["video_metadata"]["width"], + vae_latents, + prompt_embeds, + prompt_attention_mask, + images, + prompts, + ): + output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt") + temp_to_save = { + "vae_latent": cur_vae_latent.cpu().detach(), + "prompt_embed": cur_prompt_embed.cpu().detach(), + # "prompt_attention_mask": cur_prompt_attention_mask.cpu().detach(), + "first_frames_image": cur_first_frames_image, + "prompt_raw": cur_prompt, + } + try: + torch.save(temp_to_save, output_path) + except Exception: + continue + print(f"save latent to: {output_path}") + + if rank == 0: + pbar.update(1) + pbar.set_postfix({"batch": idx}) + + pixel_values = None + prompts = None + image_tensor = None + images = None + vae_latents = None + vae_latents_2 = None + image_embeds = None + prompt_embeds = None + batch = None + valid_indices = None + valid_uttids = None + valid_num_frames = None + valid_heights = None + valid_widths = None + valid_videos = None + valid_prompts = None + valid_first_frames_images = None + temp_to_save = None + + del pixel_values + del prompts + del image_tensor + del images + del vae_latents + del vae_latents_2 + del image_embeds + del batch + del valid_indices + del valid_uttids + del valid_num_frames + del valid_heights + del valid_widths + del valid_videos + del valid_prompts + del valid_first_frames_images + del temp_to_save + + free_memory() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Script for running model training and data processing.") + parser.add_argument("--dataloader_num_workers", type=int, default=8, help="Number of workers for data loading") + parser.add_argument( + "--pretrained_model_name_or_path", + type=str, + default="BestWishYsh/Helios-Base", + help="Pretrained model path", + ) + args = parser.parse_args() + + setup_distributed_env() + + global_rank = dist.get_rank() + local_rank = int(os.environ["LOCAL_RANK"]) + device = torch.cuda.current_device() + world_size = dist.get_world_size() + + base_video_path = "example" + video_paths = [ + "toy_data", + ] + + base_output_latent_path = "example/toy_data/latents_long" + output_latent_paths = [ + "toy_data", + ] + + base_csv_paths = [ + "example", + ] + csv_paths = [ + "toy_data/toy_filter.json", + ] + + resolutions = [640] + strides = [1] + batch_sizes = [4] + + for stride, batch_size, base_csv_path, csv_path, video_path, output_latent_path, cur_resolution in zip( + strides, batch_sizes, base_csv_paths, csv_paths, video_paths, output_latent_paths, resolutions + ): + json_file = os.path.join(base_csv_path, csv_path) + video_folder = os.path.join(base_video_path, video_path) + output_latent_folder = os.path.join(base_output_latent_path, output_latent_path) + + main( + rank=device, + world_size=world_size, + global_rank=global_rank, + stride=stride, + batch_size=batch_size, + dataloader_num_workers=args.dataloader_num_workers, + json_file=json_file, + video_folder=video_folder, + output_latent_folder=output_latent_folder, + pretrained_model_name_or_path=args.pretrained_model_name_or_path, + resolution=cur_resolution, + ) + + dist.barrier() + dist.destroy_process_group() diff --git a/Helios-main/tools/offload_data/get_long-latents.sh b/Helios-main/tools/offload_data/get_long-latents.sh new file mode 100644 index 0000000000000000000000000000000000000000..9286c25b17a151bf27051322cb422835ed90c08a --- /dev/null +++ b/Helios-main/tools/offload_data/get_long-latents.sh @@ -0,0 +1,64 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +# export CUDA_VISIBLE_DEVICES=1 +# MASTER_PORT=12345 +# GPUS_PER_NODE=1 +# NNODES=1 +# NODE_RANK=0 + +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# +# +torchrun $DISTRIBUTED_ARGS \ + tools/offload_data/get_long-latents.py diff --git a/Helios-main/tools/offload_data/get_ode-pairs.py b/Helios-main/tools/offload_data/get_ode-pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..e51f9aa809adfe4c5073f54512a68d377930010d --- /dev/null +++ b/Helios-main/tools/offload_data/get_ode-pairs.py @@ -0,0 +1,421 @@ +import os + + +os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes" +os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes" + +import argparse +from pathlib import Path + +import torch +import torch.distributed as dist +from accelerate import Accelerator +from helios.modules.helios_kernels import ( + replace_all_norms_with_flash_norms, + replace_rmsnorm_with_fp32, + replace_rope_with_flash_rope, +) +from helios.modules.transformer_helios import HeliosTransformer3DModel +from helios.pipelines.pipeline_helios_ode import HeliosPipeline +from helios.scheduler.scheduling_helios import HeliosScheduler +from helios.utils.utils_base import encode_prompt, load_extra_components +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm + +from diffusers.models import AutoencoderKLWan + + +def setup_distributed_env(): + dist.init_process_group(backend="nccl") + torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) + + +def check_file_exists(args): + basename, idx, line, output_folder = args + uttid = f"{basename}_{idx:05d}" + output_path = os.path.join(output_folder, f"{uttid}.pt") + if os.path.exists(output_path): + return None, None + return line.strip(), uttid + + +def prepare_dataset_on_rank0(txt_file, output_folder, rank): + while True: + try: + if rank == 0: + basename = Path(txt_file).stem + output_dir = Path(output_folder) + + existing_files = set() + if output_dir.exists(): + existing_files = {f.name for f in output_dir.iterdir() if f.is_file()} + + prompts = [] + uttids = [] + + with open(txt_file, "r") as f: + for idx, line in enumerate(f): + if not line.strip(): + continue + + uttid = f"{basename}_{idx:05d}" + filename = f"{uttid}.pt" + + if filename not in existing_files: + prompts.append(line.strip()) + uttids.append(uttid) + + data_to_broadcast = [prompts, uttids] + else: + data_to_broadcast = [None, None] + + dist.broadcast_object_list(data_to_broadcast, src=0) + break + except Exception: + continue + + return data_to_broadcast[0], data_to_broadcast[1] + + +class PromptDataset(Dataset): + def __init__(self, prompts, uttids): + self.prompts = prompts + self.uttids = uttids + + def __len__(self): + return len(self.prompts) + + def __getitem__(self, idx): + return {"prompt": self.prompts[idx], "uttid": self.uttids[idx]} + + +def main(): + args = parse_args() + + # =============== Environment =============== + batch_size = 1 + dataloader_num_workers = 8 + feature_folders = [ + "example/vidprom_first_1k.txt", + ] + output_folders = [ + "example/toy_data/ode_pairs/vidprom_filtered_extended", + ] + + if args.weight_dtype == "fp32": + args.weight_dtype = torch.float32 + elif args.weight_dtype == "fp16": + args.weight_dtype = torch.float16 + else: + args.weight_dtype = torch.bfloat16 + + setup_distributed_env() + + rank = int(os.environ["LOCAL_RANK"]) + device = torch.cuda.current_device() + + accelerator = Accelerator() + + # =============== Prepare Model =============== + transformer = HeliosTransformer3DModel.from_pretrained( + args.transformer_path, + subfolder="transformer", + torch_dtype=args.weight_dtype, + use_default_loader=args.use_default_loader, + ) + transformer = replace_rmsnorm_with_fp32(transformer) + transformer = replace_all_norms_with_flash_norms(transformer) + replace_rope_with_flash_rope() + vae = AutoencoderKLWan.from_pretrained(args.base_model_path, subfolder="vae", torch_dtype=torch.float32) + if args.is_enable_stage2: + scheduler = HeliosScheduler( + shift=args.stage2_timestep_shift, + stages=args.stage2_num_stages, + stage_range=args.stage2_stage_range, + gamma=args.stage2_scheduler_gamma, + ) + pipe = HeliosPipeline.from_pretrained( + args.base_model_path, + transformer=transformer, + vae=vae, + scheduler=scheduler, + torch_dtype=args.weight_dtype, + ) + else: + pipe = HeliosPipeline.from_pretrained( + args.base_model_path, transformer=transformer, vae=vae, torch_dtype=args.weight_dtype + ) + pipe = pipe.to(device) + + if args.lora_path is not None: + pipe.load_lora_weights(args.lora_path, adapter_name="default") + pipe.set_adapters(["default"], adapter_weights=[1.0]) + + if args.partial_path is not None: + if not hasattr(args, "training_config"): + from argparse import Namespace + + args.training_config = Namespace() + args.training_config.is_enable_stage1 = True + args.training_config.restrict_self_attn = True + args.training_config.is_amplify_history = True + args.training_config.is_use_gan = True + load_extra_components(args, transformer, args.partial_path) + + if args.vae_decode_type == "once": + pipe.vae.enable_tiling() + + transformer.eval() + transformer.requires_grad_(False) + vae.eval() + vae.requires_grad_(False) + + transformer.to(device) + vae.to(device) + pipe.to(device) + + for feature_folder, output_folder in zip(feature_folders, output_folders): + print(f"Process {feature_folder} !") + + os.makedirs(output_folder, exist_ok=True) + prompts, uttids = prepare_dataset_on_rank0(feature_folder, output_folder, rank) + dataset = PromptDataset(prompts, uttids) + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=False, + num_workers=dataloader_num_workers, + prefetch_factor=2 if dataloader_num_workers > 0 else None, + pin_memory=True, + drop_last=False, + ) + dataloader = accelerator.prepare(dataloader) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}") + + if len(dataloader) == 0: + continue + + # =============== Main Loop =============== + if rank == 0: + pbar = tqdm(total=len(dataloader), desc="Processing") + + for i, batch in enumerate(dataloader): + assert len(batch["uttid"]) == 1 + uttid = batch["uttid"][0] + prompt_raw = batch["prompt"][0] + + output_path = os.path.join(output_folder, f"{uttid}.pt") + if os.path.exists(output_path): + if rank == 0: + print(f"Skipping existing file: {output_path}") + pbar.update(1) + continue + + with torch.no_grad(): + prompt_embed, _ = encode_prompt( + tokenizer=pipe.tokenizer, + text_encoder=pipe.text_encoder, + prompt=prompt_raw, + device=device, + ) + + all_sections_ode = pipe( + prompt=prompt_raw, + negative_prompt=args.negative_prompt, + height=args.height, + width=args.width, + num_frames=args.num_frames, # 73 109 145 181 215 + num_inference_steps=50, + guidance_scale=args.guidance_scale, + generator=torch.Generator(device="cuda").manual_seed(args.seed), + output_type="latent", + vae_decode_type=args.vae_decode_type, + # stage 1 + history_sizes=[16, 2, 1], + latent_window_size=args.latent_window_size, + is_keep_x0=True, + use_dynamic_shifting=args.use_dynamic_shifting, + time_shift_type=args.time_shift_type, + # stage 2 + is_enable_stage2=args.is_enable_stage2, + stage2_num_stages=args.stage2_num_stages, + stage2_num_inference_steps_list=args.stage2_num_inference_steps_list, + scheduler_type="unipc", + # cfg zero + use_cfg_zero_star=args.use_cfg_zero_star, + use_zero_init=args.use_zero_init, + zero_steps=args.zero_steps, + ) + + # (Pdb) len(all_sections_ode) + # 264 -> % 8 == 0 + # 231 -> % 7 == 0 + # 198 -> % 6 == 0 + # 165 -> % 5 == 0 + # (Pdb) len(all_sections_ode[0]) + # 3 + # (Pdb) all_sections_ode[0][0].keys() + # dict_keys(['latents', 'timesteps', 'noise_pred']) + # (Pdb) all_sections_ode[0][0]["timesteps"].shape + # torch.Size([20] + # (Pdb) all_sections_ode[0][0]["latents"].shape + # torch.Size([20, 1, 16, 9, 12, 20]) + # (Pdb) all_sections_ode[0][0]["noise_pred"].shape + # torch.Size([20, 1, 16, 9, 12, 20]) + + processed_sections_ode = [] + for idx, section in enumerate(all_sections_ode): + processed_section = [] + for iidx, item in enumerate(section): + if idx == 0: + if iidx == 0: + selected_target_timesteps = [998.5342, 902.2183, 833.9636, 783.0660] + elif iidx == 1: + selected_target_timesteps = [742.8216, 640.0038, 547.1926, 462.9951] + elif iidx == 2: + selected_target_timesteps = [385.4137, 328.6249, 253.9905, 151.5308] + else: + if iidx == 0: + selected_target_timesteps = [998.5342, 833.9636] + elif iidx == 1: + selected_target_timesteps = [742.8216, 547.1926] + elif iidx == 2: + selected_target_timesteps = [385.4137, 253.9905] + + indices = [] + actual_timesteps = item["timesteps"] + for target_t in selected_target_timesteps: + diffs = torch.abs(actual_timesteps - target_t) + closest_idx = torch.argmin(diffs).item() + indices.append(closest_idx) + latents_indices = indices + [-1] + + rocessed_item = { + "latents": item["latents"][latents_indices], + "timesteps": item["timesteps"][indices], + } + + processed_section.append(rocessed_item) + processed_sections_ode.append(processed_section) + all_sections_ode = processed_sections_ode + + temp_to_save = { + "latent_window_size": args.latent_window_size, + "prompt_raw": prompt_raw, + "prompt_embed": prompt_embed, + "ode_latents": all_sections_ode, + } + torch.save(temp_to_save, output_path) + print(f"save latent to: {output_path}") + + +def parse_args(): + parser = argparse.ArgumentParser(description="Generate video with model") + + # === Model paths === + parser.add_argument("--base_model_path", type=str, default="BestWishYsh/Helios-Base") + parser.add_argument( + "--transformer_path", + type=str, + default="BestWishYsh/Helios-Mid", + ) + parser.add_argument( + "--lora_path", + type=str, + default=None, + ) + parser.add_argument( + "--partial_path", + type=str, + default=None, + ) + parser.add_argument("--use_default_loader", action="store_true") + + # === Generation parameters === + # environment + parser.add_argument( + "--sample_type", + type=str, + default="t2v", + choices=["t2v", "i2v", "v2v"], + ) + parser.add_argument( + "--weight_dtype", + type=str, + default="bf16", + choices=["bf16", "fp16", "fp32"], + help="Data type for model weights.", + ) + parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.") + # base + parser.add_argument("--height", type=int, default=384) + parser.add_argument("--width", type=int, default=640) + parser.add_argument("--num_frames", type=int, default=165) + parser.add_argument("--num_inference_steps", type=int, default=50) + parser.add_argument("--guidance_scale", type=float, default=5.0) + parser.add_argument("--use_dynamic_shifting", action="store_true") + parser.add_argument( + "--time_shift_type", + type=str, + default="linear", + choices=["exponential", "linear"], + ) + parser.add_argument("--vae_decode_type", type=str, default="default", choices=["default", "once", "default_fast"]) + # stage 1 + parser.add_argument("--latent_window_size", type=int, default=9) + # stage 2 + parser.add_argument("--is_enable_stage2", action="store_true") + parser.add_argument("--stage2_timestep_shift", type=float, default=1.0) + parser.add_argument("--stage2_scheduler_gamma", type=float, default=1 / 3) + parser.add_argument("--stage2_stage_range", type=int, nargs="+", default=[0, 1 / 3, 2 / 3, 1]) + parser.add_argument("--stage2_num_stages", type=int, default=3) + parser.add_argument("--stage2_num_inference_steps_list", type=int, nargs="+", default=[20, 20, 20]) + # cfg zero + parser.add_argument("--use_cfg_zero_star", action="store_true") + parser.add_argument("--use_zero_init", action="store_true") + parser.add_argument("--zero_steps", type=int, default=1) + + # === Prompts === + parser.add_argument( + "--negative_prompt", + type=str, + default="Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards", + ) + parser.add_argument( + "--prompt_txt_path", + type=str, + default=None, + ) + + return parser.parse_args() + + +if __name__ == "__main__": + # from diffusers import AutoencoderKLWan + # from diffusers.video_processor import VideoProcessor + # from diffusers.utils import export_to_video + + # device = "cuda" + # pretrained_model_name_or_path = "BestWishYsh/Helios-Base" + # vae = AutoencoderKLWan.from_pretrained( + # pretrained_model_name_or_path, + # subfolder="vae", + # torch_dtype=torch.float32, + # ).to(device) + # vae.eval() + # vae.requires_grad_(False) + + # vae_scale_factor_spatial = vae.spatial_compression_ratio + # video_processor = VideoProcessor(vae_scale_factor=vae_scale_factor_spatial) + # latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1) + # latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1) + + # x1 = torch.load("/mnt/hdfs/data/ysh_new/userful_things_wan/ode_pairs/vidprom_filtered_extended/vidprom_filtered_extended_00011.pt", map_location="cpu") + # vae_latents = x1["ode_latents"][-1][-1]["latents"][-1] / latents_std + latents_mean + # vae_latents = vae_latents.to(device=device, dtype=vae.dtype) + # video = vae.decode(vae_latents, return_dict=False)[0] + # video = video_processor.postprocess_video(video, output_type="pil") + # export_to_video(video[0], "output_wan.mp4", fps=30) + + main() diff --git a/Helios-main/tools/offload_data/get_ode-pairs.sh b/Helios-main/tools/offload_data/get_ode-pairs.sh new file mode 100644 index 0000000000000000000000000000000000000000..c69ccce9fbfaeada8f37ece865fc5aecca739de6 --- /dev/null +++ b/Helios-main/tools/offload_data/get_ode-pairs.sh @@ -0,0 +1,69 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +# export CUDA_VISIBLE_DEVICES=1 +# MASTER_PORT=12345 +# GPUS_PER_NODE=1 +# NNODES=1 +# NODE_RANK=0 + +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# +# +torchrun $DISTRIBUTED_ARGS \ + tools/offload_data/get_ode-pairs.py \ + --use_dynamic_shifting \ + --time_shift_type "linear" \ + --use_default_loader \ + --is_enable_stage2 \ + --num_frames 165 diff --git a/Helios-main/tools/offload_data/get_short-latents.py b/Helios-main/tools/offload_data/get_short-latents.py new file mode 100644 index 0000000000000000000000000000000000000000..2d042b9ad904a48274b173367711a7bc4dffbb5d --- /dev/null +++ b/Helios-main/tools/offload_data/get_short-latents.py @@ -0,0 +1,341 @@ +import argparse +import os + +import torch +import torch.distributed as dist +import torchvision.transforms as transforms +from accelerate import Accelerator +from helios.dataset.dataloader_mp4_dist import BucketedFeatureDataset, BucketedSampler, collate_fn +from helios.utils.utils_base import encode_prompt +from torch.utils.data import DataLoader +from tqdm import tqdm +from transformers import AutoTokenizer, UMT5EncoderModel + +from diffusers import AutoencoderKLWan +from diffusers.training_utils import free_memory + + +def setup_distributed_env(): + dist.init_process_group(backend="nccl") + torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) + + +def cleanup_distributed_env(): + dist.destroy_process_group() + + +def main( + rank, + world_size, + global_rank, + stride, + batch_size, + dataloader_num_workers, + json_file, + video_folder, + output_latent_folder, + pretrained_model_name_or_path, + resolution=640, +): + weight_dtype = torch.bfloat16 + device = rank + seed = 42 + + # Load the tokenizers + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, + subfolder="tokenizer", + ) + text_encoder = UMT5EncoderModel.from_pretrained( + pretrained_model_name_or_path, + subfolder="text_encoder", + torch_dtype=weight_dtype, + ) + vae = AutoencoderKLWan.from_pretrained( + pretrained_model_name_or_path, + subfolder="vae", + torch_dtype=torch.float32, + ) + + latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(device, weight_dtype) + latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to( + device, weight_dtype + ) + + vae.eval() + vae.requires_grad_(False) + text_encoder.eval() + text_encoder.requires_grad_(False) + + vae = vae.to(device) + text_encoder = text_encoder.to(device) + + # dist.barrier() + dataset = BucketedFeatureDataset( + json_files=json_file, + video_folders=video_folder, + stride=stride, + force_rebuild=False, + resolution=resolution, + single_res=True, + single_height=384, + single_width=640, + ) + sampler = BucketedSampler(dataset, batch_size=batch_size, drop_last=False, shuffle=True, seed=seed) + dataloader = DataLoader( + dataset, + batch_sampler=sampler, + collate_fn=collate_fn, + num_workers=dataloader_num_workers, + pin_memory=True, + prefetch_factor=2 if dataloader_num_workers != 0 else None, + # persistent_workers=True if dataloader_num_workers > 0 else False, + ) + + print(len(dataset), len(dataloader)) + accelerator = Accelerator() + dataloader = accelerator.prepare(dataloader) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}") + + sampler.set_epoch(0) + if rank == 0: + pbar = tqdm(total=len(dataloader), desc="Processing") + # dist.barrier() + for idx, batch in enumerate(dataloader): + if batch is None or batch["videos"] is None: + print("None batch, continuing") + continue + free_memory() + + valid_indices = [] + valid_uttids = [] + valid_num_frames = [] + valid_heights = [] + valid_widths = [] + valid_videos = [] + valid_prompts = [] + valid_first_frames_images = [] + + if batch["uttid"] is None: + print("None batch, contiuning") + continue + + for i, (uttid, num_frame, height, width) in enumerate( + zip( + batch["uttid"], + batch["video_metadata"]["num_frames"], + batch["video_metadata"]["height"], + batch["video_metadata"]["width"], + ) + ): + os.makedirs(output_latent_folder, exist_ok=True) + output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt") + if not os.path.exists(output_path): + valid_indices.append(i) + valid_uttids.append(uttid) + valid_num_frames.append(num_frame) + valid_heights.append(height) + valid_widths.append(width) + valid_videos.append(batch["videos"][i]) + valid_prompts.append(batch["prompts"][i]) + valid_first_frames_images.append(batch["first_frames_images"][i]) + else: + print(f"skipping {uttid}") + + if not valid_indices: + print("skipping entire batch!") + if rank == 0: + pbar.update(1) + pbar.set_postfix({"batch": idx}) + continue + + batch = None + del batch + free_memory() + + batch = { + "uttid": valid_uttids, + "video_metadata": {"num_frames": valid_num_frames, "height": valid_heights, "width": valid_widths}, + "videos": torch.stack(valid_videos), + "prompts": valid_prompts, + "first_frames_images": torch.stack(valid_first_frames_images), + } + + if len(batch["uttid"]) == 0: + print("All samples in this batch are already processed, skipping!") + continue + + with torch.no_grad(): + # Get Vae feature + pixel_values = batch["videos"].permute(0, 2, 1, 3, 4).to(dtype=vae.dtype, device=device) + + latent_window_size = 9 + frame_window_size = (latent_window_size - 1) * 4 + 1 + num_latent_frames = pixel_values.shape[2] + num_chunk_to_encode = num_latent_frames // frame_window_size + + history_latent_list = [] + for i in range(num_chunk_to_encode): + start_idx = i * frame_window_size + end_idx = start_idx + frame_window_size + cur_pixel_values = pixel_values[:, :, start_idx:end_idx, :, :] + with torch.no_grad(): + cur_latent = vae.encode(cur_pixel_values).latent_dist.sample() + cur_latent = (cur_latent - latents_mean) * latents_std + history_latent_list.append(cur_latent) + vae_latents = torch.stack(history_latent_list, dim=1) + + # Encode prompts + prompts = batch["prompts"] + prompt_embeds, prompt_attention_mask = encode_prompt( + tokenizer=tokenizer, + text_encoder=text_encoder, + prompt=prompts, + device=device, + ) + + image_tensor = batch["first_frames_images"] + images = [transforms.ToPILImage()(x.to(torch.uint8)) for x in image_tensor] + + for ( + uttid, + num_frame, + height, + width, + cur_vae_latent, + cur_prompt_embed, + cur_prompt_attention_mask, + cur_first_frames_image, + cur_prompt, + ) in zip( + batch["uttid"], + batch["video_metadata"]["num_frames"], + batch["video_metadata"]["height"], + batch["video_metadata"]["width"], + vae_latents, + prompt_embeds, + prompt_attention_mask, + images, + prompts, + ): + output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt") + temp_to_save = { + "vae_latent": cur_vae_latent.cpu().detach(), + "prompt_embed": cur_prompt_embed.cpu().detach(), + # "prompt_attention_mask": cur_prompt_attention_mask.cpu().detach(), + "first_frames_image": cur_first_frames_image, + "prompt_raw": cur_prompt, + } + try: + torch.save(temp_to_save, output_path) + except Exception: + continue + print(f"save latent to: {output_path}") + + if rank == 0: + pbar.update(1) + pbar.set_postfix({"batch": idx}) + + pixel_values = None + prompts = None + image_tensor = None + images = None + vae_latents = None + vae_latents_2 = None + image_embeds = None + prompt_embeds = None + batch = None + valid_indices = None + valid_uttids = None + valid_num_frames = None + valid_heights = None + valid_widths = None + valid_videos = None + valid_prompts = None + valid_first_frames_images = None + temp_to_save = None + + del pixel_values + del prompts + del image_tensor + del images + del vae_latents + del vae_latents_2 + del image_embeds + del batch + del valid_indices + del valid_uttids + del valid_num_frames + del valid_heights + del valid_widths + del valid_videos + del valid_prompts + del valid_first_frames_images + del temp_to_save + + free_memory() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Script for running model training and data processing.") + parser.add_argument("--dataloader_num_workers", type=int, default=8, help="Number of workers for data loading") + parser.add_argument( + "--pretrained_model_name_or_path", + type=str, + default="BestWishYsh/Helios-Base", + help="Pretrained model path", + ) + args = parser.parse_args() + + setup_distributed_env() + + global_rank = dist.get_rank() + local_rank = int(os.environ["LOCAL_RANK"]) + device = torch.cuda.current_device() + world_size = dist.get_world_size() + + base_video_path = "example" + video_paths = [ + "toy_data", + ] + + base_output_latent_path = "example/toy_data/latents_short" + output_latent_paths = [ + "toy_data", + ] + + base_csv_paths = [ + "example", + ] + csv_paths = [ + "toy_data/toy_filter.json", + ] + + resolutions = [640] + strides = [1] + batch_sizes = [4] + + for stride, batch_size, base_csv_path, csv_path, video_path, output_latent_path, cur_resolution in zip( + strides, batch_sizes, base_csv_paths, csv_paths, video_paths, output_latent_paths, resolutions + ): + json_file = os.path.join(base_csv_path, csv_path) + video_folder = os.path.join(base_video_path, video_path) + output_latent_folder = os.path.join(base_output_latent_path, output_latent_path) + + main( + rank=device, + world_size=world_size, + global_rank=global_rank, + stride=stride, + batch_size=batch_size, + dataloader_num_workers=args.dataloader_num_workers, + json_file=json_file, + video_folder=video_folder, + output_latent_folder=output_latent_folder, + pretrained_model_name_or_path=args.pretrained_model_name_or_path, + resolution=cur_resolution, + ) + + dist.barrier() + dist.destroy_process_group() diff --git a/Helios-main/tools/offload_data/get_short-latents.sh b/Helios-main/tools/offload_data/get_short-latents.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d328f5a506b97c31e2171b99a2a59bc8554f4a0 --- /dev/null +++ b/Helios-main/tools/offload_data/get_short-latents.sh @@ -0,0 +1,64 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +# export CUDA_VISIBLE_DEVICES=1 +# MASTER_PORT=12345 +# GPUS_PER_NODE=1 +# NNODES=1 +# NODE_RANK=0 + +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# +# +torchrun $DISTRIBUTED_ARGS \ + tools/offload_data/get_short-latents.py diff --git a/Helios-main/tools/offload_data/get_text-embedding.py b/Helios-main/tools/offload_data/get_text-embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..fcba014add1e410e0344673bf1589e3ac982a841 --- /dev/null +++ b/Helios-main/tools/offload_data/get_text-embedding.py @@ -0,0 +1,256 @@ +import os + + +os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes" +os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes" + +import argparse +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import torch +import torch.distributed as dist +from accelerate import Accelerator +from helios.utils.utils_base import encode_prompt +from torch.utils.data import DataLoader, Dataset +from tqdm import tqdm +from transformers import AutoTokenizer, UMT5EncoderModel + + +def setup_distributed_env(): + dist.init_process_group(backend="nccl") + torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) + + +def check_file_exists(args): + basename, idx, line, output_folder = args + uttid = f"{basename}_{idx:05d}" + output_path = os.path.join(output_folder, f"{uttid}.pt") + if os.path.exists(output_path): + return None, None + return line.strip(), uttid + + +def prepare_dataset_on_rank0(txt_file, output_folder, rank): + while True: + try: + if rank == 0: + basename = Path(txt_file).stem + output_dir = Path(output_folder) + + existing_files = set() + if output_dir.exists(): + existing_files = {f.name for f in output_dir.iterdir() if f.is_file()} + + prompts = [] + uttids = [] + + with open(txt_file, "r") as f: + for idx, line in enumerate(f): + if not line.strip(): + continue + + uttid = f"{basename}_{idx:05d}" + filename = f"{uttid}.pt" + + if filename not in existing_files: + prompts.append(line.strip()) + uttids.append(uttid) + + data_to_broadcast = [prompts, uttids] + else: + data_to_broadcast = [None, None] + + dist.broadcast_object_list(data_to_broadcast, src=0) + break + except Exception: + continue + + return data_to_broadcast[0], data_to_broadcast[1] + + +class PromptDataset(Dataset): + def __init__(self, prompts, uttids): + self.prompts = prompts + self.uttids = uttids + + def __len__(self): + return len(self.prompts) + + def __getitem__(self, idx): + return {"prompt": self.prompts[idx], "uttid": self.uttids[idx]} + + +def save_single_file(uttid, output_path, prompt_raw, prompt_embed): + temp_to_save = { + "prompt_raw": prompt_raw, + "prompt_embed": prompt_embed, + } + + try: + torch.save(temp_to_save, output_path, pickle_protocol=4) + return f"✓ Saved: {output_path}" + except Exception as e: + return f"✗ Failed to save {uttid}: {str(e)}" + + +def main(): + save_executor = ThreadPoolExecutor(max_workers=8) + save_futures = [] + + args = parse_args() + + # =============== Environment =============== + batch_size = 16 + dataloader_num_workers = 8 + feature_folders = [ + "example/vidprom_first_1k.txt", + ] + output_folders = [ + "example/toy_data/text-embedding/vidprom_filtered_extended", + ] + + if args.weight_dtype == "fp32": + args.weight_dtype = torch.float32 + elif args.weight_dtype == "fp16": + args.weight_dtype = torch.float16 + else: + args.weight_dtype = torch.bfloat16 + + setup_distributed_env() + + rank = int(os.environ["LOCAL_RANK"]) + device = torch.cuda.current_device() + + accelerator = Accelerator() + + # =============== Prepare Model =============== + weight_dtype = torch.bfloat16 + tokenizer = AutoTokenizer.from_pretrained( + args.base_model_path, + subfolder="tokenizer", + ) + text_encoder = UMT5EncoderModel.from_pretrained( + args.base_model_path, + subfolder="text_encoder", + dtype=weight_dtype, + ) + + text_encoder.eval() + text_encoder.requires_grad_(False) + text_encoder = text_encoder.to(device) + + for feature_folder, output_folder in zip(feature_folders, output_folders): + print(f"Process {feature_folder} !") + + os.makedirs(output_folder, exist_ok=True) + prompts, uttids = prepare_dataset_on_rank0(feature_folder, output_folder, rank) + dataset = PromptDataset(prompts, uttids) + dataloader = DataLoader( + dataset, + batch_size=batch_size, + shuffle=False, + num_workers=dataloader_num_workers, + prefetch_factor=2 if dataloader_num_workers > 0 else None, + pin_memory=True, + drop_last=False, + ) + dataloader = accelerator.prepare(dataloader) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}") + + if len(dataloader) == 0: + continue + + # =============== Main Loop =============== + if rank == 0: + pbar = tqdm(total=len(dataloader), desc="Processing") + + for i, batch in enumerate(dataloader): + batch_size = len(batch["uttid"]) + uttids = batch["uttid"] + prompts_raw = batch["prompt"] + + files_to_process = [] + indices_to_process = [] + + for idx, uttid in enumerate(uttids): + output_path = os.path.join(output_folder, f"{uttid}.pt") + if os.path.exists(output_path): + if rank == 0: + print(f"Skipping existing file: {output_path}") + else: + files_to_process.append((uttid, output_path)) + indices_to_process.append(idx) + + if len(files_to_process) == 0: + if rank == 0: + pbar.update(1) + continue + + prompts_to_encode = [prompts_raw[idx] for idx in indices_to_process] + + with torch.no_grad(): + prompt_embeds, _ = encode_prompt( + tokenizer=tokenizer, + text_encoder=text_encoder, + prompt=prompts_to_encode, + device=device, + ) + + for idx, (uttid, output_path) in enumerate(files_to_process): + prompt_embed_cpu = prompt_embeds[idx].cpu().clone() + + future = save_executor.submit( + save_single_file, uttid, output_path, prompts_to_encode[idx], prompt_embed_cpu + ) + save_futures.append(future) + + if len(save_futures) > 100: + completed_futures = [f for f in save_futures if f.done()] + + if rank == 0: + for future in completed_futures: + try: + result = future.result() + print(result) + except Exception as e: + print(f"Save task error: {e}") + + save_futures = [f for f in save_futures if not f.done()] + + if rank == 0: + pbar.update(1) + + if rank == 0: + pbar.close() + + +def parse_args(): + parser = argparse.ArgumentParser(description="Generate video with model") + + # === Model paths === + parser.add_argument("--base_model_path", type=str, default="BestWishYsh/Helios-Base") + + # === Generation parameters === + parser.add_argument( + "--weight_dtype", + type=str, + default="bf16", + choices=["bf16", "fp16", "fp32"], + help="Data type for model weights.", + ) + parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.") + + # === Prompts === + parser.add_argument( + "--negative_prompt", + type=str, + default="Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards", + ) + + return parser.parse_args() + + +if __name__ == "__main__": + main() diff --git a/Helios-main/tools/offload_data/get_text-embedding.sh b/Helios-main/tools/offload_data/get_text-embedding.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b63701c38eadeabd352baa41b67b21f3374c6a9 --- /dev/null +++ b/Helios-main/tools/offload_data/get_text-embedding.sh @@ -0,0 +1,64 @@ +export OMNISTORE_LOAD_STRICT_MODE=0 +export OMNISTORE_LOGGING_LEVEL=ERROR +################################################################# +## Torch +################################################################# +export TOKENIZERS_PARALLELISM=false +export TORCH_LOGS="+dynamo,recompiles,graph_breaks" +export TORCHDYNAMO_VERBOSE=1 +export TORCH_NCCL_ENABLE_MONITORING=1 +export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9" +################################################################# + + +################################################################# +## NCCL +################################################################# +export NCCL_IB_GID_INDEX=3 +export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE +export NCCL_SOCKET_IFNAME=eth0 +export NCCL_SOCKET_TIMEOUT=3600000 + +export NCCL_DEBUG=WARN # disable the verbose NCCL logs +export NCCL_P2P_DISABLE=0 +export NCCL_IB_DISABLE=0 # was 1 +export NCCL_SHM_DISABLE=0 # was 1 +export NCCL_P2P_LEVEL=NVL + +export NCCL_PXN_DISABLE=0 +export NCCL_NET_GDR_LEVEL=2 +export NCCL_IB_QPS_PER_CONNECTION=4 +export NCCL_IB_TC=160 +export NCCL_IB_TIMEOUT=22 +################################################################# + +################################################################# +## DIST +################################################################# +MASTER_ADDR=$ARNOLD_WORKER_0_HOST +ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`) +MASTER_PORT=${ports[0]} +NNODES=$ARNOLD_WORKER_NUM +NODE_RANK=$ARNOLD_ID +GPUS_PER_NODE=$ARNOLD_WORKER_GPU + +# export CUDA_VISIBLE_DEVICES=1 +# MASTER_PORT=12345 +# GPUS_PER_NODE=1 +# NNODES=1 +# NODE_RANK=0 + +WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES)) + +DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT" +if [ ! -z $RDZV_BACKEND ]; then + DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d" + export NCCL_SHM_DISABLE=1 +fi + +echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m" + +################################################################# +# +torchrun $DISTRIBUTED_ARGS \ + tools/offload_data/get_text-embedding.py \ No newline at end of file diff --git a/Helios-main/tools/others/benchmark/benchmark_compile_performance.py b/Helios-main/tools/others/benchmark/benchmark_compile_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..0baee425f8c39b4f66d7d1142b706165ee7ce799 --- /dev/null +++ b/Helios-main/tools/others/benchmark/benchmark_compile_performance.py @@ -0,0 +1,234 @@ +import os +import sys +import time +from datetime import datetime + +import torch + + +os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes" +os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes" + +from helios.modules.kernels import ( + replace_all_norms_with_flash_norms, + replace_rmsnorm_with_fp32, + replace_rope_with_flash_rope, +) +from helios.modules.transformer_helios import HeliosTransformer3DModel +from helios.pipelines.pipeline_wan import WanPipeline + +from diffusers import AutoencoderKLWan + + +class DualLogger: + """同时输出到控制台和文件的日志器""" + + def __init__(self, filename): + self.file = open(filename, "w", encoding="utf-8") + self.stdout = sys.stdout + + def write(self, message): + self.stdout.write(message) # 输出到控制台 + self.file.write(message) # 写入文件 + self.file.flush() # 实时刷新 + + def flush(self): + self.stdout.flush() + self.file.flush() + + def close(self): + self.file.close() + + +def setup_pipeline(model_id, compile_config=None): + """设置pipeline""" + print(f"\n{'=' * 60}") + print(f"设置 Pipeline: {compile_config['name'] if compile_config else 'No Compile'}") + print(f"{'=' * 60}") + + # 加载模型 + transformer = HeliosTransformer3DModel.from_pretrained( + model_id, subfolder="transformer", torch_dtype=torch.bfloat16, use_default_loader=True + ) + transformer = replace_rmsnorm_with_fp32(transformer) + transformer = replace_all_norms_with_flash_norms(transformer) + replace_rope_with_flash_rope() + + vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) + pipe = WanPipeline.from_pretrained(model_id, vae=vae, transformer=transformer, torch_dtype=torch.bfloat16) + + pipe.transformer.set_attention_backend("_flash_3_hub") + pipe.to("cuda") + + # 应用compile配置 + if compile_config: + print(f"应用编译配置: {compile_config['kwargs']}") + pipe.transformer.compile(**compile_config["kwargs"]) + + return pipe + + +def run_benchmark(pipe, prompt, negative_prompt, num_runs=3, warmup=1): + """运行基准测试""" + times = [] + + # Warmup + print(f"\n预热运行 {warmup} 次...") + for i in range(warmup): + print(f" 预热 {i + 1}/{warmup}") + _ = pipe( + prompt=prompt, + negative_prompt=negative_prompt, + height=384, + width=640, + num_frames=45, + guidance_scale=5.0, + num_inference_steps=50, + generator=torch.Generator(device="cuda").manual_seed(42), + ).frames[0] + torch.cuda.empty_cache() + + # 实际测试 + print(f"\n开始基准测试 {num_runs} 次...") + for i in range(num_runs): + print(f" 运行 {i + 1}/{num_runs}") + start = time.time() + torch.cuda.synchronize() + + _ = pipe( + prompt=prompt, + negative_prompt=negative_prompt, + height=384, + width=640, + num_frames=45, + guidance_scale=5.0, + num_inference_steps=50, + generator=torch.Generator(device="cuda").manual_seed(42), + ).frames[0] + + torch.cuda.synchronize() + elapsed = time.time() - start + times.append(elapsed) + print(f" 耗时: {elapsed:.2f}秒") + torch.cuda.empty_cache() + + return times + + +def main(): + # 创建日志文件 + # timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + log_filename = "benchmark_compile_results.txt" + + # 创建双输出日志器 + logger = DualLogger(log_filename) + original_stdout = sys.stdout + sys.stdout = logger + + try: + # 打印测试信息 + print("=" * 80) + print("PyTorch Compile 模式基准测试") + print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + print(f"PyTorch 版本: {torch.__version__}") + print(f"CUDA 版本: {torch.version.cuda}") + print(f"GPU: {torch.cuda.get_device_name(0)}") + print("=" * 80) + + model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers" + + prompt = "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about." + negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" + + # 定义不同的compile配置 + compile_configs = [ + {"name": "No Compile (Baseline)", "kwargs": None}, + {"name": "Default Compile", "kwargs": {}}, + {"name": "Fullgraph Only", "kwargs": {"fullgraph": True}}, + { + "name": "Max-Autotune-No-Cudagraphs + Dynamic", + "kwargs": {"mode": "max-autotune-no-cudagraphs", "dynamic": True}, + }, + {"name": "Max-Autotune + Fullgraph", "kwargs": {"mode": "max-autotune", "fullgraph": True}}, + {"name": "Max-Autotune", "kwargs": {"mode": "max-autotune"}}, + {"name": "Reduce-Overhead", "kwargs": {"mode": "reduce-overhead"}}, + {"name": "Default Mode", "kwargs": {"mode": "default"}}, + ] + + results = {} + + # 测试每个配置 + for config in compile_configs: + try: + # 清理GPU内存 + torch.cuda.empty_cache() + + # 设置pipeline + if config["kwargs"] is None: + pipe = setup_pipeline(model_id, None) + else: + pipe = setup_pipeline(model_id, config) + + # 运行基准测试 + times = run_benchmark(pipe, prompt, negative_prompt, num_runs=3, warmup=1) + results[config["name"]] = times + + # 删除pipeline释放内存 + del pipe + torch.cuda.empty_cache() + + except Exception as e: + print(f"\n❌ 配置 '{config['name']}' 失败: {str(e)}") + results[config["name"]] = None + + # 打印结果摘要 + print("\n" + "=" * 80) + print("基准测试结果摘要") + print("=" * 80) + print(f"{'配置':<45} {'平均时间(秒)':<15} {'最小时间(秒)':<15} {'最大时间(秒)':<15}") + print("-" * 80) + + sorted_results = [] + for name, times in results.items(): + if times: + avg_time = sum(times) / len(times) + min_time = min(times) + max_time = max(times) + sorted_results.append((name, avg_time, min_time, max_time, times)) + print(f"{name:<45} {avg_time:<15.2f} {min_time:<15.2f} {max_time:<15.2f}") + else: + print(f"{name:<45} {'FAILED':<15} {'FAILED':<15} {'FAILED':<15}") + + # 按平均时间排序 + if sorted_results: + sorted_results.sort(key=lambda x: x[1]) + print("\n" + "=" * 80) + print("速度排名 (从快到慢)") + print("=" * 80) + baseline_time = sorted_results[-1][1] + for rank, (name, avg_time, min_time, max_time, times) in enumerate(sorted_results, 1): + speedup = baseline_time / avg_time if avg_time > 0 else 0 + print(f"\n{rank}. {name}") + print(f" 平均时间: {avg_time:.2f}秒") + print(f" 相对最慢提速: {speedup:.2f}x") + print(f" 详细时间: {[f'{t:.2f}s' for t in times]}") + + print("\n" + "=" * 80) + print(f"测试完成! 结果已保存到: {log_filename}") + print("=" * 80) + + except Exception as e: + print(f"\n❌ 测试过程出错: {str(e)}") + import traceback + + traceback.print_exc() + + finally: + # 恢复标准输出并关闭文件 + sys.stdout = original_stdout + logger.close() + print(f"\n✅ 测试完成! 结果已保存到: {log_filename}") + + +if __name__ == "__main__": + main() diff --git a/Helios-main/tools/others/benchmark/benchmark_compile_results.txt b/Helios-main/tools/others/benchmark/benchmark_compile_results.txt new file mode 100644 index 0000000000000000000000000000000000000000..95e3abec058eddad9065e185c941e790a5a90d28 --- /dev/null +++ b/Helios-main/tools/others/benchmark/benchmark_compile_results.txt @@ -0,0 +1,269 @@ +================================================================================ +PyTorch Compile 模式基准测试 +测试时间: 2026-01-25 16:09:44 +PyTorch 版本: 2.7.1+cu126 +CUDA 版本: 12.6 +GPU: NVIDIA H100 80GB HBM3 +================================================================================ + +============================================================ +设置 Pipeline: No Compile +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + + +预热运行 1 次... + 预热 1/1 + +开始基准测试 3 次... + 运行 1/3 + 耗时: 17.15秒 + 运行 2/3 + 耗时: 17.14秒 + 运行 3/3 + 耗时: 17.19秒 + +============================================================ +设置 Pipeline: Default Compile +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + +应用编译配置: {} + +预热运行 1 次... + 预热 1/1 + +开始基准测试 3 次... + 运行 1/3 + 耗时: 12.80秒 + 运行 2/3 + 耗时: 12.79秒 + 运行 3/3 + 耗时: 12.79秒 + +============================================================ +设置 Pipeline: Fullgraph Only +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + +应用编译配置: {'fullgraph': True} + +预热运行 1 次... + 预热 1/1 + +开始基准测试 3 次... + 运行 1/3 + 耗时: 12.79秒 + 运行 2/3 + 耗时: 12.80秒 + 运行 3/3 + 耗时: 12.80秒 + +============================================================ +设置 Pipeline: Max-Autotune-No-Cudagraphs + Dynamic +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + +应用编译配置: {'mode': 'max-autotune-no-cudagraphs', 'dynamic': True} + +预热运行 1 次... + 预热 1/1 + +开始基准测试 3 次... + 运行 1/3 + 耗时: 12.61秒 + 运行 2/3 + 耗时: 12.63秒 + 运行 3/3 + 耗时: 12.63秒 + +============================================================ +设置 Pipeline: Max-Autotune + Fullgraph +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + +应用编译配置: {'mode': 'max-autotune', 'fullgraph': True} + +预热运行 1 次... + 预热 1/1 + +❌ 配置 'Max-Autotune + Fullgraph' 失败: Skip calling `torch.compiler.disable()`d function + Explanation: Skip calling function `` since it was wrapped with `torch.compiler.disable` + Hint: Remove the `torch.compiler.disable` call + + Developer debug context: + + +from user code: + File "transformer_helios.py", line 999, in forward + attn_output = self.attn1( + File "transformer_helios.py", line 737, in forward + return self.processor( + File "transformer_helios.py", line 360, in __call__ + query = attn.norm_q(query) + File "/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py", line 1762, in _call_impl + return forward_call(*args, **kwargs) + File "kernels/triton_norm.py", line 29, in + module.forward = (lambda self, x: flash_rms_layernorm(self, x)).__get__(module, module.__class__) + +Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo" + + +============================================================ +设置 Pipeline: Max-Autotune +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + +应用编译配置: {'mode': 'max-autotune'} + +预热运行 1 次... + 预热 1/1 + +开始基准测试 3 次... + 运行 1/3 + 耗时: 13.02秒 + 运行 2/3 + 耗时: 13.02秒 + 运行 3/3 + 耗时: 13.03秒 + +============================================================ +设置 Pipeline: Reduce-Overhead +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + +应用编译配置: {'mode': 'reduce-overhead'} + +预热运行 1 次... + 预热 1/1 + +开始基准测试 3 次... + 运行 1/3 + 耗时: 13.24秒 + 运行 2/3 + 耗时: 13.24秒 + 运行 3/3 + 耗时: 13.26秒 + +============================================================ +设置 Pipeline: Default Mode +============================================================ +Patched 120 FP32_RMSNorm modules + +Patched 30 Flash_LayerNorm modules + +Patched 120 Flash_RMSNorm modules + +Patched Flash_RoPE globally + +应用编译配置: {'mode': 'default'} + +预热运行 1 次... + 预热 1/1 + +开始基准测试 3 次... + 运行 1/3 + 耗时: 12.74秒 + 运行 2/3 + 耗时: 12.68秒 + 运行 3/3 + 耗时: 12.75秒 + +================================================================================ +基准测试结果摘要 +================================================================================ +配置 平均时间(秒) 最小时间(秒) 最大时间(秒) +-------------------------------------------------------------------------------- +No Compile (Baseline) 17.16 17.14 17.19 +Default Compile 12.79 12.79 12.80 +Fullgraph Only 12.80 12.79 12.80 +Max-Autotune-No-Cudagraphs + Dynamic 12.62 12.61 12.63 +Max-Autotune + Fullgraph FAILED FAILED FAILED +Max-Autotune 13.02 13.02 13.03 +Reduce-Overhead 13.25 13.24 13.26 +Default Mode 12.72 12.68 12.75 + +================================================================================ +速度排名 (从快到慢) +================================================================================ + +1. Max-Autotune-No-Cudagraphs + Dynamic + 平均时间: 12.62秒 + 相对最慢提速: 1.36x + 详细时间: ['12.61s', '12.63s', '12.63s'] + +2. Default Mode + 平均时间: 12.72秒 + 相对最慢提速: 1.35x + 详细时间: ['12.74s', '12.68s', '12.75s'] + +3. Default Compile + 平均时间: 12.79秒 + 相对最慢提速: 1.34x + 详细时间: ['12.80s', '12.79s', '12.79s'] + +4. Fullgraph Only + 平均时间: 12.80秒 + 相对最慢提速: 1.34x + 详细时间: ['12.79s', '12.80s', '12.80s'] + +5. Max-Autotune + 平均时间: 13.02秒 + 相对最慢提速: 1.32x + 详细时间: ['13.02s', '13.02s', '13.03s'] + +6. Reduce-Overhead + 平均时间: 13.25秒 + 相对最慢提速: 1.30x + 详细时间: ['13.24s', '13.24s', '13.26s'] + +7. No Compile (Baseline) + 平均时间: 17.16秒 + 相对最慢提速: 1.00x + 详细时间: ['17.15s', '17.14s', '17.19s'] + +================================================================================ +测试完成! 结果已保存到: compile_benchmark_results_20260125_160944.txt +================================================================================ diff --git a/Helios-main/tools/others/benchmark/benchmark_patchification_performance.py b/Helios-main/tools/others/benchmark/benchmark_patchification_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..e130e872d603f7fabc0183024c033b3e5eddbd0b --- /dev/null +++ b/Helios-main/tools/others/benchmark/benchmark_patchification_performance.py @@ -0,0 +1,381 @@ +import os + + +os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes" + +import json +import time +from datetime import datetime + +import torch + +from diffusers import WanTransformer3DModel + + +# 加载transformer +model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers" +transformer = WanTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.bfloat16) +transformer.enable_gradient_checkpointing() +transformer.set_attention_backend("_flash_3_hub") +transformer.to("cuda") + +noise_per_token = 960 +noise_total_token = noise_per_token * 9 + +his_tokens = [960, 1920, 3840, 5760, 7680, 9600, 11520, 13440, 15360, 17280] +his_tokens_naive = [960, 1920, 2160, 2190, 2220, 2250, 2280, 2310, 2340, 2370] + +benchmark_results = { + "timestamp": datetime.now().isoformat(), + "noise_total_token": noise_total_token, + "experiments": [], +} + + +def create_dummy_inputs(transformer, num_frames, height=384, width=640, requires_grad=False): + """创建transformer的dummy输入""" + batch_size = 1 + device = transformer.device + dtype = transformer.dtype + + # hidden_states: [B, C, F, H, W] + in_channels = transformer.config.in_channels + latent_h = height // 8 + latent_w = width // 8 + latent_f = num_frames + + hidden_states = torch.randn( + batch_size, in_channels, latent_f, latent_h, latent_w, device=device, dtype=dtype, requires_grad=requires_grad + ) + + # timestep + timestep = torch.tensor([999], device=device, dtype=torch.long) + timestep = timestep.expand(batch_size) + + # encoder_hidden_states + seq_len = 512 + hidden_dim = 4096 + encoder_hidden_states = torch.randn(batch_size, seq_len, hidden_dim, device=device, dtype=dtype) + + return hidden_states, timestep, encoder_hidden_states + + +def measure_inference_speed(transformer, hidden_states, timestep, encoder_hidden_states, num_runs=10): + """测量推理速度(单步)""" + try: + # 预热 + for _ in range(3): + with torch.no_grad(): + _ = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=True, + ) + torch.cuda.synchronize() + + # 正式测速 + times = [] + for _ in range(num_runs): + torch.cuda.synchronize() + start_time = time.time() + + with torch.no_grad(): + _ = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=True, + ) + + torch.cuda.synchronize() + end_time = time.time() + times.append(end_time - start_time) + + return { + "avg_time_s": round(sum(times) / len(times), 4), + "min_time_s": round(min(times), 4), + "max_time_s": round(max(times), 4), + "std_time_s": round(torch.std(torch.tensor(times)).item(), 4), + "status": "success", + } + except RuntimeError as e: + if "out of memory" in str(e).lower(): + torch.cuda.empty_cache() + return {"status": "OOM", "error": str(e)} + else: + raise + + +def measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states): + """测量推理显存""" + try: + torch.cuda.reset_peak_memory_stats() + torch.cuda.empty_cache() + torch.cuda.synchronize() + mem_before = torch.cuda.memory_allocated() / 1024**3 + + # Forward (推理模式) + torch.cuda.reset_peak_memory_stats() + with torch.no_grad(): + _ = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=True, + attention_kwargs=None, + ) + torch.cuda.synchronize() + + inference_peak = torch.cuda.max_memory_allocated() / 1024**3 + inference_mem_diff = inference_peak - mem_before + + return { + "mem_before_gb": round(mem_before, 3), + "inference_peak_gb": round(inference_peak, 3), + "inference_mem_diff_gb": round(inference_mem_diff, 3), + "status": "success", + } + except RuntimeError as e: + if "out of memory" in str(e).lower(): + torch.cuda.empty_cache() + return {"status": "OOM", "error": str(e)} + else: + raise + + +def measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states): + """测量训练显存(包含backward)""" + try: + torch.cuda.reset_peak_memory_stats() + torch.cuda.empty_cache() + torch.cuda.synchronize() + mem_before = torch.cuda.memory_allocated() / 1024**3 + + # Forward + Backward (训练模式) + torch.cuda.reset_peak_memory_stats() + + # Forward + output = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=True, + attention_kwargs=None, + ) + + # 创建一个简单的loss并backward + loss = output.sample.sum() + loss.backward() + + torch.cuda.synchronize() + + training_peak = torch.cuda.max_memory_allocated() / 1024**3 + training_mem_diff = training_peak - mem_before + + # 清理梯度 + transformer.zero_grad(set_to_none=True) + + return { + "mem_before_gb": round(mem_before, 3), + "training_peak_gb": round(training_peak, 3), + "training_mem_diff_gb": round(training_mem_diff, 3), + "status": "success", + } + except RuntimeError as e: + if "out of memory" in str(e).lower(): + torch.cuda.empty_cache() + transformer.zero_grad(set_to_none=True) + return {"status": "OOM", "error": str(e)} + else: + raise + + +def warmup(transformer, num_runs=3): + """预热""" + print("🔥 Warming up...") + for i in range(num_runs): + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(transformer, num_frames=5) + with torch.no_grad(): + _ = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=True, + ) + print(f" Warmup {i + 1}/{num_runs} done") + torch.cuda.empty_cache() + print("✅ Warmup completed\n") + + +def run_experiment(his_tokens_list, experiment_name): + """运行完整实验""" + results = [] + + for his_token in his_tokens_list: + torch.cuda.reset_peak_memory_stats() + torch.cuda.empty_cache() + + total_token = his_token + noise_total_token + num_frames = round((total_token / noise_per_token - 1) * 4 + 1) + + print(f"\n{'=' * 60}") + print(f"{experiment_name} | tokens: {his_token} | frames: {int(num_frames)}") + print(f"{'=' * 60}") + + result = { + "his_token": his_token, + "total_token": total_token, + "num_frames": int(num_frames), + } + + # 1. 测推理速度 (不需要梯度) + print("📊 Measuring inference speed...") + try: + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs( + transformer, num_frames, requires_grad=False + ) + speed_stats = measure_inference_speed(transformer, hidden_states, timestep, encoder_hidden_states) + + if speed_stats["status"] == "OOM": + print(" ❌ OOM - Skipping remaining tests for this config") + result.update({"speed_status": "OOM", "inference_status": "SKIPPED", "training_status": "SKIPPED"}) + results.append(result) + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + continue + else: + print( + f" Avg: {speed_stats['avg_time_s']:.4f}s | " + f"Min: {speed_stats['min_time_s']:.4f}s | " + f"Max: {speed_stats['max_time_s']:.4f}s" + ) + result.update(speed_stats) + + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + except Exception as e: + print(f" ❌ Error: {e}") + result["speed_status"] = "ERROR" + torch.cuda.empty_cache() + + # 2. 测推理显存 (不需要梯度) + print("💾 Measuring inference memory...") + try: + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs( + transformer, num_frames, requires_grad=False + ) + inference_mem_stats = measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states) + + if inference_mem_stats["status"] == "OOM": + print(" ❌ OOM - Skipping training test") + result.update(inference_mem_stats) + result["training_status"] = "SKIPPED" + results.append(result) + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + continue + else: + print( + f" Peak: {inference_mem_stats['inference_peak_gb']:.3f} GB | " + f"Diff: {inference_mem_stats['inference_mem_diff_gb']:.3f} GB" + ) + result.update(inference_mem_stats) + + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + except Exception as e: + print(f" ❌ Error: {e}") + result["inference_status"] = "ERROR" + torch.cuda.empty_cache() + + # 3. 测训练显存 (需要梯度) + print("🔥 Measuring training memory...") + try: + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs( + transformer, num_frames, requires_grad=True + ) + training_mem_stats = measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states) + + if training_mem_stats["status"] == "OOM": + print(" ❌ OOM") + result.update(training_mem_stats) + else: + print( + f" Peak: {training_mem_stats['training_peak_gb']:.3f} GB | " + f"Diff: {training_mem_stats['training_mem_diff_gb']:.3f} GB" + ) + result.update(training_mem_stats) + + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + except Exception as e: + print(f" ❌ Error: {e}") + result["training_status"] = "ERROR" + torch.cuda.empty_cache() + + results.append(result) + + return results + + +# 运行实验 +warmup(transformer) + +print("\n" + "=" * 80) +print("STANDARD EXPERIMENT") +print("=" * 80) +results_standard = run_experiment(his_tokens, "Standard") + +print("\n" + "=" * 80) +print("NAIVE EXPERIMENT") +print("=" * 80) +results_naive = run_experiment(his_tokens_naive, "Naive") + +# 保存结果 +benchmark_results["experiments"] = [ + {"name": "standard", "results": results_standard}, + {"name": "naive", "results": results_naive}, +] + +output_file = "benchmark_patchification_results.json" +with open(output_file, "w") as f: + json.dump(benchmark_results, f, indent=2) + +print("\n" + "=" * 80) +print(f"✅ Results saved to {output_file}") +print("=" * 80) + +# 打印汇总表格 +print("\n" + "=" * 80) +print("BENCHMARK SUMMARY") +print("=" * 80) + +for exp in benchmark_results["experiments"]: + print(f"\n=== {exp['name'].upper()} ===") + print(f"{'Tokens':>6} {'Frames':>6} {'Speed(s)':>10} {'Infer(GB)':>11} {'Train(GB)':>11} {'Status':>10}") + print("-" * 72) + for r in exp["results"]: + speed_str = f"{r.get('avg_time_s', 0):.4f}s" if r.get("status") == "success" else "N/A" + infer_str = f"{r.get('inference_mem_diff_gb', 0):.3f}" if r.get("inference_peak_gb") else "N/A" + train_str = f"{r.get('training_mem_diff_gb', 0):.3f}" if r.get("training_peak_gb") else "N/A" + + # 判断整体状态 + if r.get("speed_status") == "OOM": + status = "OOM" + elif r.get("training_status") == "OOM": + status = "OOM(train)" + elif r.get("status") == "success": + status = "OK" + else: + status = "PARTIAL" + + print(f"{r['his_token']:6d} {r['num_frames']:6d} {speed_str:>10} {infer_str:>11} {train_str:>11} {status:>10}") + +print("\n" + "=" * 80) +print("Legend:") +print(" Speed(s) - Average inference time per step") +print(" Infer(GB) - Memory usage during inference (forward only)") +print(" Train(GB) - Memory usage during training (forward + backward)") +print(" Status - OK/OOM/OOM(train)/PARTIAL") +print("=" * 80) diff --git a/Helios-main/tools/others/benchmark/benchmark_patchification_results.json b/Helios-main/tools/others/benchmark/benchmark_patchification_results.json new file mode 100644 index 0000000000000000000000000000000000000000..61e296a750643571ff6e987f02933844602cda0a --- /dev/null +++ b/Helios-main/tools/others/benchmark/benchmark_patchification_results.json @@ -0,0 +1,309 @@ +{ + "timestamp": "2026-02-06T05:34:36.528673", + "noise_total_token": 8640, + "experiments": [ + { + "name": "standard", + "results": [ + { + "his_token": 960, + "total_token": 9600, + "num_frames": 37, + "avg_time_s": 4.1635, + "min_time_s": 4.1583, + "max_time_s": 4.1741, + "std_time_s": 0.0041, + "status": "success", + "mem_before_gb": 26.787, + "inference_peak_gb": 30.565, + "inference_mem_diff_gb": 3.778, + "training_peak_gb": 68.509, + "training_mem_diff_gb": 41.722 + }, + { + "his_token": 1920, + "total_token": 10560, + "num_frames": 41, + "avg_time_s": 4.7998, + "min_time_s": 4.798, + "max_time_s": 4.8031, + "std_time_s": 0.0013, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.001, + "inference_mem_diff_gb": 4.182, + "training_peak_gb": 70.252, + "training_mem_diff_gb": 43.433 + }, + { + "his_token": 3840, + "total_token": 12480, + "num_frames": 49, + "avg_time_s": 6.1835, + "min_time_s": 6.1744, + "max_time_s": 6.1921, + "std_time_s": 0.0049, + "status": "success", + "mem_before_gb": 26.82, + "inference_peak_gb": 31.815, + "inference_mem_diff_gb": 4.995, + "training_peak_gb": 73.733, + "training_mem_diff_gb": 46.913 + }, + { + "his_token": 5760, + "total_token": 14400, + "num_frames": 57, + "avg_time_s": 7.7019, + "min_time_s": 7.6963, + "max_time_s": 7.7083, + "std_time_s": 0.0039, + "status": "OOM", + "mem_before_gb": 26.821, + "inference_peak_gb": 32.628, + "inference_mem_diff_gb": 5.808, + "error": "CUDA out of memory. Tried to allocate 1.04 GiB. GPU 0 has a total capacity of 79.11 GiB of which 196.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 75.12 GiB is allocated by PyTorch, and 3.04 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)" + }, + { + "his_token": 7680, + "total_token": 16320, + "num_frames": 65, + "avg_time_s": 9.3743, + "min_time_s": 9.3587, + "max_time_s": 9.3922, + "std_time_s": 0.0092, + "status": "OOM", + "mem_before_gb": 26.822, + "inference_peak_gb": 33.442, + "inference_mem_diff_gb": 6.621, + "error": "CUDA out of memory. Tried to allocate 1.19 GiB. GPU 0 has a total capacity of 79.11 GiB of which 108.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 77.18 GiB is allocated by PyTorch, and 1.07 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)" + }, + { + "his_token": 9600, + "total_token": 18240, + "num_frames": 73, + "avg_time_s": 11.2228, + "min_time_s": 11.2066, + "max_time_s": 11.2309, + "std_time_s": 0.0076, + "status": "OOM", + "mem_before_gb": 26.823, + "inference_peak_gb": 34.256, + "inference_mem_diff_gb": 7.434, + "error": "CUDA out of memory. Tried to allocate 1.34 GiB. GPU 0 has a total capacity of 79.11 GiB of which 868.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 75.75 GiB is allocated by PyTorch, and 1.76 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)" + }, + { + "his_token": 11520, + "total_token": 20160, + "num_frames": 81, + "avg_time_s": 13.2451, + "min_time_s": 13.2332, + "max_time_s": 13.251, + "std_time_s": 0.0055, + "status": "OOM", + "mem_before_gb": 26.824, + "inference_peak_gb": 35.071, + "inference_mem_diff_gb": 8.248, + "error": "CUDA out of memory. Tried to allocate 1.48 GiB. GPU 0 has a total capacity of 79.11 GiB of which 608.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 75.14 GiB is allocated by PyTorch, and 2.62 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)" + }, + { + "his_token": 13440, + "total_token": 22080, + "num_frames": 89, + "avg_time_s": 15.2558, + "min_time_s": 15.24, + "max_time_s": 15.2622, + "std_time_s": 0.0081, + "status": "OOM", + "mem_before_gb": 26.825, + "inference_peak_gb": 35.885, + "inference_mem_diff_gb": 9.06, + "error": "CUDA out of memory. Tried to allocate 1.63 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.36 GiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 74.19 GiB is allocated by PyTorch, and 2.80 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)" + }, + { + "his_token": 15360, + "total_token": 24000, + "num_frames": 97, + "avg_time_s": 17.5647, + "min_time_s": 17.5502, + "max_time_s": 17.5807, + "std_time_s": 0.0095, + "status": "OOM", + "mem_before_gb": 26.825, + "inference_peak_gb": 36.699, + "inference_mem_diff_gb": 9.873, + "error": "CUDA out of memory. Tried to allocate 1.78 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.39 GiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 74.90 GiB is allocated by PyTorch, and 2.07 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)" + }, + { + "his_token": 17280, + "total_token": 25920, + "num_frames": 105, + "avg_time_s": 20.0106, + "min_time_s": 19.9988, + "max_time_s": 20.0365, + "std_time_s": 0.012, + "status": "OOM", + "mem_before_gb": 26.826, + "inference_peak_gb": 37.512, + "inference_mem_diff_gb": 10.686, + "error": "CUDA out of memory. Tried to allocate 1.92 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.18 GiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 70.20 GiB is allocated by PyTorch, and 6.99 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)" + } + ] + }, + { + "name": "naive", + "results": [ + { + "his_token": 960, + "total_token": 9600, + "num_frames": 37, + "avg_time_s": 4.1671, + "min_time_s": 4.1616, + "max_time_s": 4.171, + "std_time_s": 0.0032, + "status": "success", + "mem_before_gb": 26.818, + "inference_peak_gb": 30.595, + "inference_mem_diff_gb": 3.777, + "training_peak_gb": 68.509, + "training_mem_diff_gb": 41.69 + }, + { + "his_token": 1920, + "total_token": 10560, + "num_frames": 41, + "avg_time_s": 4.8, + "min_time_s": 4.7986, + "max_time_s": 4.8014, + "std_time_s": 0.0009, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.001, + "inference_mem_diff_gb": 4.182, + "training_peak_gb": 70.252, + "training_mem_diff_gb": 43.433 + }, + { + "his_token": 2160, + "total_token": 10800, + "num_frames": 42, + "avg_time_s": 4.9164, + "min_time_s": 4.9075, + "max_time_s": 4.9335, + "std_time_s": 0.0082, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.105, + "inference_mem_diff_gb": 4.286, + "training_peak_gb": 70.689, + "training_mem_diff_gb": 43.87 + }, + { + "his_token": 2190, + "total_token": 10830, + "num_frames": 42, + "avg_time_s": 4.9196, + "min_time_s": 4.9037, + "max_time_s": 4.9359, + "std_time_s": 0.0105, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.105, + "inference_mem_diff_gb": 4.286, + "training_peak_gb": 70.689, + "training_mem_diff_gb": 43.87 + }, + { + "his_token": 2220, + "total_token": 10860, + "num_frames": 42, + "avg_time_s": 4.9201, + "min_time_s": 4.9098, + "max_time_s": 4.9369, + "std_time_s": 0.0086, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.105, + "inference_mem_diff_gb": 4.286, + "training_peak_gb": 70.689, + "training_mem_diff_gb": 43.87 + }, + { + "his_token": 2250, + "total_token": 10890, + "num_frames": 42, + "avg_time_s": 4.9168, + "min_time_s": 4.9079, + "max_time_s": 4.9294, + "std_time_s": 0.0073, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.105, + "inference_mem_diff_gb": 4.286, + "training_peak_gb": 70.689, + "training_mem_diff_gb": 43.87 + }, + { + "his_token": 2280, + "total_token": 10920, + "num_frames": 42, + "avg_time_s": 4.9187, + "min_time_s": 4.9082, + "max_time_s": 4.9277, + "std_time_s": 0.0058, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.105, + "inference_mem_diff_gb": 4.286, + "training_peak_gb": 70.689, + "training_mem_diff_gb": 43.87 + }, + { + "his_token": 2310, + "total_token": 10950, + "num_frames": 43, + "avg_time_s": 5.1375, + "min_time_s": 5.1308, + "max_time_s": 5.1426, + "std_time_s": 0.0039, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.205, + "inference_mem_diff_gb": 4.386, + "training_peak_gb": 71.118, + "training_mem_diff_gb": 44.298 + }, + { + "his_token": 2340, + "total_token": 10980, + "num_frames": 43, + "avg_time_s": 5.1378, + "min_time_s": 5.1338, + "max_time_s": 5.1434, + "std_time_s": 0.0036, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.205, + "inference_mem_diff_gb": 4.386, + "training_peak_gb": 71.118, + "training_mem_diff_gb": 44.298 + }, + { + "his_token": 2370, + "total_token": 11010, + "num_frames": 43, + "avg_time_s": 5.1388, + "min_time_s": 5.1317, + "max_time_s": 5.1453, + "std_time_s": 0.0051, + "status": "success", + "mem_before_gb": 26.819, + "inference_peak_gb": 31.205, + "inference_mem_diff_gb": 4.386, + "training_peak_gb": 71.118, + "training_mem_diff_gb": 44.298 + } + ] + } + ] +} \ No newline at end of file diff --git a/Helios-main/tools/others/benchmark/benchmark_triton_performance.py b/Helios-main/tools/others/benchmark/benchmark_triton_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc4635d0fc2a9207542db87febb677e6f0ce96f --- /dev/null +++ b/Helios-main/tools/others/benchmark/benchmark_triton_performance.py @@ -0,0 +1,659 @@ +import os + + +os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes" +os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes" + +import json +import time +from datetime import datetime + +import torch +from helios.modules.kernels import ( + replace_all_norms_with_flash_norms, + replace_linear_with_tiled_linear, + replace_rope_with_flash_rope, +) +from helios.modules.transformer_helios import HeliosTransformer3DModel + +from diffusers.training_utils import free_memory + + +# ============================================================================ +# 配置参数 +# ============================================================================ +model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers" +TEST_NUM_FRAMES = 21 +NUM_SPEED_RUNS = 10 # 速度测试的运行次数 +HEIGHT = 384 +WIDTH = 640 + +benchmark_results = { + "timestamp": datetime.now().isoformat(), + "test_config": {"num_frames": TEST_NUM_FRAMES, "height": HEIGHT, "width": WIDTH, "num_speed_runs": NUM_SPEED_RUNS}, + "experiments": [], +} + + +# ============================================================================ +# 辅助函数 +# ============================================================================ +def create_dummy_inputs(transformer, num_frames, height=384, width=640, requires_grad=False): + """创建transformer的dummy输入""" + batch_size = 1 + device = transformer.device + dtype = transformer.dtype + + in_channels = transformer.config.in_channels + latent_h = height // 8 + latent_w = width // 8 + latent_f = num_frames + + hidden_states = torch.randn( + batch_size, in_channels, latent_f, latent_h, latent_w, device=device, dtype=dtype, requires_grad=requires_grad + ) + + timestep = torch.tensor([999], device=device, dtype=torch.long) + timestep = timestep.expand(batch_size) + + seq_len = 512 + hidden_dim = 4096 + encoder_hidden_states = torch.randn(batch_size, seq_len, hidden_dim, device=device, dtype=dtype) + + return hidden_states, timestep, encoder_hidden_states + + +def measure_inference_speed(transformer, hidden_states, timestep, encoder_hidden_states, num_runs=10): + """测量推理速度""" + try: + # 预热 + for _ in range(3): + with torch.no_grad(): + _ = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=False, + )[0] + torch.cuda.synchronize() + + # 正式测速 + times = [] + for _ in range(num_runs): + torch.cuda.synchronize() + start_time = time.time() + + with torch.no_grad(): + _ = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=False, + )[0] + + torch.cuda.synchronize() + end_time = time.time() + times.append(end_time - start_time) + + return { + "avg_time_s": round(sum(times) / len(times), 4), + "min_time_s": round(min(times), 4), + "max_time_s": round(max(times), 4), + "std_time_s": round(torch.std(torch.tensor(times)).item(), 4), + "status": "success", + } + except RuntimeError as e: + if "out of memory" in str(e).lower(): + torch.cuda.empty_cache() + free_memory() + return {"status": "OOM", "error": str(e)} + else: + raise + + +def measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states): + """测量推理显存""" + try: + torch.cuda.reset_peak_memory_stats() + torch.cuda.empty_cache() + free_memory() + torch.cuda.synchronize() + mem_before = torch.cuda.memory_allocated() / 1024**3 + + torch.cuda.reset_peak_memory_stats() + with torch.no_grad(): + _ = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=False, + attention_kwargs=None, + )[0] + torch.cuda.synchronize() + + inference_peak = torch.cuda.max_memory_allocated() / 1024**3 + inference_mem_diff = inference_peak - mem_before + + return { + "mem_before_gb": round(mem_before, 3), + "inference_peak_gb": round(inference_peak, 3), + "inference_mem_diff_gb": round(inference_mem_diff, 3), + "status": "success", + } + except RuntimeError as e: + if "out of memory" in str(e).lower(): + torch.cuda.empty_cache() + free_memory() + return {"status": "OOM", "error": str(e)} + else: + raise + + +def measure_training_speed(transformer, hidden_states, timestep, encoder_hidden_states, num_runs=10): + """测量训练速度(forward + backward)""" + try: + # 预热 + for _ in range(3): + output = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=False, + )[0] + loss = output.sum() + loss.backward() + transformer.zero_grad(set_to_none=True) + torch.cuda.synchronize() + + # 正式测速 + times = [] + for _ in range(num_runs): + torch.cuda.synchronize() + start_time = time.time() + + output = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=False, + )[0] + loss = output.sum() + loss.backward() + transformer.zero_grad(set_to_none=True) + + torch.cuda.synchronize() + end_time = time.time() + times.append(end_time - start_time) + + return { + "avg_time_s": round(sum(times) / len(times), 4), + "min_time_s": round(min(times), 4), + "max_time_s": round(max(times), 4), + "std_time_s": round(torch.std(torch.tensor(times)).item(), 4), + "status": "success", + } + except RuntimeError as e: + if "out of memory" in str(e).lower(): + torch.cuda.empty_cache() + free_memory() + transformer.zero_grad(set_to_none=True) + return {"status": "OOM", "error": str(e)} + else: + raise + + +def measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states): + """测量训练显存(forward + backward)""" + try: + torch.cuda.reset_peak_memory_stats() + torch.cuda.empty_cache() + free_memory() + torch.cuda.synchronize() + mem_before = torch.cuda.memory_allocated() / 1024**3 + + torch.cuda.reset_peak_memory_stats() + + output = transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + return_dict=False, + attention_kwargs=None, + )[0] + + loss = output.sum() + loss.backward() + + torch.cuda.synchronize() + + training_peak = torch.cuda.max_memory_allocated() / 1024**3 + training_mem_diff = training_peak - mem_before + + transformer.zero_grad(set_to_none=True) + + return { + "mem_before_gb": round(mem_before, 3), + "training_peak_gb": round(training_peak, 3), + "training_mem_diff_gb": round(training_mem_diff, 3), + "status": "success", + } + except RuntimeError as e: + if "out of memory" in str(e).lower(): + torch.cuda.empty_cache() + free_memory() + transformer.zero_grad(set_to_none=True) + return {"status": "OOM", "error": str(e)} + else: + raise + + +def run_single_config(transformer, config_name, num_frames): + """运行单个配置的完整测试""" + print(f"\n{'=' * 70}") + print(f"Testing: {config_name}") + print(f"{'=' * 70}") + + result = {"config": config_name, "num_frames": num_frames} + + # 1. 测推理速度 + print("📊 Measuring inference speed...") + try: + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs( + transformer, num_frames, HEIGHT, WIDTH, requires_grad=False + ) + speed_stats = measure_inference_speed( + transformer, hidden_states, timestep, encoder_hidden_states, NUM_SPEED_RUNS + ) + + if speed_stats["status"] == "OOM": + print(" ❌ OOM - Skipping remaining tests") + result.update( + { + "inference_speed_status": "OOM", + "inference_memory_status": "SKIPPED", + "training_speed_status": "SKIPPED", + "training_memory_status": "SKIPPED", + } + ) + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + free_memory() + return result + else: + print( + f" ✓ Avg: {speed_stats['avg_time_s']:.4f}s | " + f"Min: {speed_stats['min_time_s']:.4f}s | " + f"Max: {speed_stats['max_time_s']:.4f}s" + ) + result.update( + { + "inference_speed_avg_s": speed_stats["avg_time_s"], + "inference_speed_min_s": speed_stats["min_time_s"], + "inference_speed_max_s": speed_stats["max_time_s"], + "inference_speed_std_s": speed_stats["std_time_s"], + "inference_speed_status": "success", + } + ) + + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + free_memory() + except Exception as e: + print(f" ❌ Error: {e}") + result["inference_speed_status"] = "ERROR" + torch.cuda.empty_cache() + free_memory() + + # 2. 测推理显存 + print("💾 Measuring inference memory...") + try: + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs( + transformer, num_frames, HEIGHT, WIDTH, requires_grad=False + ) + mem_stats = measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states) + + if mem_stats["status"] == "OOM": + print(" ❌ OOM - Skipping training tests") + result.update( + { + "inference_memory_status": "OOM", + "training_speed_status": "SKIPPED", + "training_memory_status": "SKIPPED", + } + ) + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + free_memory() + return result + else: + print( + f" ✓ Peak: {mem_stats['inference_peak_gb']:.3f} GB | " + f"Diff: {mem_stats['inference_mem_diff_gb']:.3f} GB" + ) + result.update( + { + "inference_memory_peak_gb": mem_stats["inference_peak_gb"], + "inference_memory_diff_gb": mem_stats["inference_mem_diff_gb"], + "inference_memory_status": "success", + } + ) + + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + free_memory() + except Exception as e: + print(f" ❌ Error: {e}") + result["inference_memory_status"] = "ERROR" + torch.cuda.empty_cache() + free_memory() + + # 3. 测训练速度 + print("⚡ Measuring training speed...") + try: + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs( + transformer, num_frames, HEIGHT, WIDTH, requires_grad=True + ) + train_speed_stats = measure_training_speed( + transformer, hidden_states, timestep, encoder_hidden_states, NUM_SPEED_RUNS + ) + + if train_speed_stats["status"] == "OOM": + print(" ❌ OOM") + result.update({"training_speed_status": "OOM", "training_memory_status": "SKIPPED"}) + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + free_memory() + return result + else: + print( + f" ✓ Avg: {train_speed_stats['avg_time_s']:.4f}s | " + f"Min: {train_speed_stats['min_time_s']:.4f}s | " + f"Max: {train_speed_stats['max_time_s']:.4f}s" + ) + result.update( + { + "training_speed_avg_s": train_speed_stats["avg_time_s"], + "training_speed_min_s": train_speed_stats["min_time_s"], + "training_speed_max_s": train_speed_stats["max_time_s"], + "training_speed_std_s": train_speed_stats["std_time_s"], + "training_speed_status": "success", + } + ) + + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + free_memory() + except Exception as e: + print(f" ❌ Error: {e}") + result["training_speed_status"] = "ERROR" + torch.cuda.empty_cache() + free_memory() + + # 4. 测训练显存 + print("🔥 Measuring training memory...") + try: + hidden_states, timestep, encoder_hidden_states = create_dummy_inputs( + transformer, num_frames, HEIGHT, WIDTH, requires_grad=True + ) + train_mem_stats = measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states) + + if train_mem_stats["status"] == "OOM": + print(" ❌ OOM") + result["training_memory_status"] = "OOM" + else: + print( + f" ✓ Peak: {train_mem_stats['training_peak_gb']:.3f} GB | " + f"Diff: {train_mem_stats['training_mem_diff_gb']:.3f} GB" + ) + result.update( + { + "training_memory_peak_gb": train_mem_stats["training_peak_gb"], + "training_memory_diff_gb": train_mem_stats["training_mem_diff_gb"], + "training_memory_status": "success", + } + ) + + del hidden_states, timestep, encoder_hidden_states + torch.cuda.empty_cache() + free_memory() + except Exception as e: + print(f" ❌ Error: {e}") + result["training_memory_status"] = "ERROR" + torch.cuda.empty_cache() + free_memory() + + return result + + +# ============================================================================ +# 主测试流程 +# ============================================================================ +print("=" * 70) +print("OPTIMIZATION BENCHMARK - SAME LENGTH COMPARISON") +print("=" * 70) +print(f"Model: {model_id}") +print(f"Test frames: {TEST_NUM_FRAMES}") +print(f"Resolution: {HEIGHT}x{WIDTH}") +print(f"Speed test runs: {NUM_SPEED_RUNS}") +print("=" * 70) + +# ============================================================================ +# 配置1: 原始模型 +# ============================================================================ +print("\n" + "=" * 70) +print("CONFIG 1/5: BASELINE (No optimizations)") +print("=" * 70) + +transformer_baseline = HeliosTransformer3DModel.from_pretrained( + model_id, + subfolder="transformer", + torch_dtype=torch.bfloat16, + use_default_loader=True, +) +transformer_baseline.enable_gradient_checkpointing() +transformer_baseline.set_attention_backend("_flash_3_hub") +transformer_baseline.to("cuda") + +result_baseline = run_single_config(transformer_baseline, "Baseline", TEST_NUM_FRAMES) +benchmark_results["experiments"].append(result_baseline) + +del transformer_baseline +torch.cuda.empty_cache() +free_memory() + +# ============================================================================ +# 配置2: 只替换 TiledLinear +# ============================================================================ +print("\n" + "=" * 70) +print("CONFIG 2/5: TiledLinear only") +print("=" * 70) + +transformer_tiled = HeliosTransformer3DModel.from_pretrained( + model_id, + subfolder="transformer", + torch_dtype=torch.bfloat16, + use_default_loader=True, +) +transformer_tiled.enable_gradient_checkpointing() +transformer_tiled.set_attention_backend("_flash_3_hub") +transformer_tiled = replace_linear_with_tiled_linear(transformer_tiled) +transformer_tiled.to("cuda") + +result_tiled = run_single_config(transformer_tiled, "TiledLinear", TEST_NUM_FRAMES) +benchmark_results["experiments"].append(result_tiled) + +transformer_tiled = None +del transformer_tiled +torch.cuda.empty_cache() +free_memory() + +# ============================================================================ +# 配置3: 只替换 FlashNorm +# ============================================================================ +print("\n" + "=" * 70) +print("CONFIG 3/5: FlashNorm only") +print("=" * 70) + +transformer_flashnorm = HeliosTransformer3DModel.from_pretrained( + model_id, + subfolder="transformer", + torch_dtype=torch.bfloat16, + use_default_loader=True, +) +transformer_flashnorm.enable_gradient_checkpointing() +transformer_flashnorm.set_attention_backend("_flash_3_hub") +transformer_flashnorm = replace_all_norms_with_flash_norms(transformer_flashnorm) +transformer_flashnorm.to("cuda") + +result_flashnorm = run_single_config(transformer_flashnorm, "FlashNorm", TEST_NUM_FRAMES) +benchmark_results["experiments"].append(result_flashnorm) + +transformer_flashnorm = None +del transformer_flashnorm +torch.cuda.empty_cache() +free_memory() + +# ============================================================================ +# 配置4: 只替换 FlashRoPE +# ============================================================================ +print("\n" + "=" * 70) +print("CONFIG 4/5: FlashRoPE only") +print("=" * 70) + +transformer_flashrope = HeliosTransformer3DModel.from_pretrained( + model_id, + subfolder="transformer", + torch_dtype=torch.bfloat16, + use_default_loader=True, +) +transformer_flashrope.enable_gradient_checkpointing() +transformer_flashrope.set_attention_backend("_flash_3_hub") +transformer_flashrope.to("cuda") + +# FlashRoPE 是全局替换,不可逆 +replace_rope_with_flash_rope() + +result_flashrope = run_single_config(transformer_flashrope, "FlashRoPE", TEST_NUM_FRAMES) +benchmark_results["experiments"].append(result_flashrope) + +transformer_flashrope = None +del transformer_flashrope +torch.cuda.empty_cache() +free_memory() + +# ============================================================================ +# 配置5: FlashNorm + FlashRoPE +# ============================================================================ +print("\n" + "=" * 70) +print("CONFIG 5/5: FlashNorm + FlashRoPE") +print("=" * 70) + +transformer_combined = HeliosTransformer3DModel.from_pretrained( + model_id, + subfolder="transformer", + torch_dtype=torch.bfloat16, + use_default_loader=True, +) +transformer_combined.enable_gradient_checkpointing() +transformer_combined.set_attention_backend("_flash_3_hub") +transformer_combined = replace_all_norms_with_flash_norms(transformer_combined) +transformer_combined.to("cuda") + +# FlashRoPE 已经在配置4中全局替换 +replace_rope_with_flash_rope() + +result_combined = run_single_config(transformer_combined, "FlashNorm+FlashRoPE", TEST_NUM_FRAMES) +benchmark_results["experiments"].append(result_combined) + +transformer_combined = None +del transformer_combined +torch.cuda.empty_cache() +free_memory() + +# ============================================================================ +# 保存结果 +# ============================================================================ +output_file = "benchmark_triton_results.json" +with open(output_file, "w") as f: + json.dump(benchmark_results, f, indent=2) + +print("\n" + "=" * 70) +print(f"✅ Results saved to {output_file}") +print("=" * 70) + +# ============================================================================ +# 打印汇总表格 +# ============================================================================ +print("\n" + "=" * 70) +print("BENCHMARK SUMMARY") +print("=" * 70) + +# 表头 +print(f"\n{'Config':<20} {'InfSpeed(s)':>12} {'InfMem(GB)':>12} {'TrainSpeed(s)':>14} {'TrainMem(GB)':>13}") +print("-" * 75) + +# 打印每个配置的结果 +for exp in benchmark_results["experiments"]: + config = exp["config"] + + # 推理速度 + inf_speed = ( + f"{exp.get('inference_speed_avg_s', 0):.4f}" if exp.get("inference_speed_status") == "success" else "N/A" + ) + + # 推理显存 + inf_mem = ( + f"{exp.get('inference_memory_diff_gb', 0):.3f}" if exp.get("inference_memory_status") == "success" else "N/A" + ) + + # 训练速度 + train_speed = ( + f"{exp.get('training_speed_avg_s', 0):.4f}" if exp.get("training_speed_status") == "success" else "N/A" + ) + + # 训练显存 + train_mem = ( + f"{exp.get('training_memory_diff_gb', 0):.3f}" if exp.get("training_memory_status") == "success" else "N/A" + ) + + print(f"{config:<20} {inf_speed:>12} {inf_mem:>12} {train_speed:>14} {train_mem:>13}") + +# 计算加速比(如果baseline成功) +baseline_result = benchmark_results["experiments"][0] +if baseline_result.get("inference_speed_status") == "success": + baseline_inf_speed = baseline_result["inference_speed_avg_s"] + baseline_train_speed = baseline_result.get("training_speed_avg_s", None) + + print("\n" + "=" * 70) + print("SPEEDUP vs BASELINE") + print("=" * 70) + print(f"{'Config':<20} {'InfSpeedup':>12} {'TrainSpeedup':>14}") + print("-" * 50) + + for exp in benchmark_results["experiments"]: + config = exp["config"] + + # 推理加速比 + if exp.get("inference_speed_status") == "success": + speedup_inf = baseline_inf_speed / exp["inference_speed_avg_s"] + speedup_inf_str = f"{speedup_inf:.2f}x" + else: + speedup_inf_str = "N/A" + + # 训练加速比 + if exp.get("training_speed_status") == "success" and baseline_train_speed: + speedup_train = baseline_train_speed / exp["training_speed_avg_s"] + speedup_train_str = f"{speedup_train:.2f}x" + else: + speedup_train_str = "N/A" + + print(f"{config:<20} {speedup_inf_str:>12} {speedup_train_str:>14}") + +print("\n" + "=" * 70) +print("Legend:") +print(" InfSpeed - Inference time (forward only)") +print(" InfMem - Inference memory usage") +print(" TrainSpeed - Training time (forward + backward)") +print(" TrainMem - Training memory usage") +print(" Speedup - Relative to baseline (higher is better)") +print("=" * 70) diff --git a/Helios-main/tools/others/benchmark/benchmark_triton_results_helios.json b/Helios-main/tools/others/benchmark/benchmark_triton_results_helios.json new file mode 100644 index 0000000000000000000000000000000000000000..17892782da579cd364257cd41750b5c2e2d3b7ea --- /dev/null +++ b/Helios-main/tools/others/benchmark/benchmark_triton_results_helios.json @@ -0,0 +1,111 @@ +{ + "timestamp": "2026-02-06T09:14:11.892609", + "test_config": { + "num_frames": 13, + "height": 384, + "width": 640, + "num_speed_runs": 10 + }, + "experiments": [ + { + "config": "Baseline", + "num_frames": 13, + "inference_speed_avg_s": 1.083, + "inference_speed_min_s": 1.0801, + "inference_speed_max_s": 1.088, + "inference_speed_std_s": 0.0027, + "inference_speed_status": "success", + "inference_memory_peak_gb": 29.777, + "inference_memory_diff_gb": 2.993, + "inference_memory_status": "success", + "training_speed_avg_s": 4.302, + "training_speed_min_s": 4.2982, + "training_speed_max_s": 4.3088, + "training_speed_std_s": 0.0031, + "training_speed_status": "success", + "training_memory_peak_gb": 60.792, + "training_memory_diff_gb": 33.978, + "training_memory_status": "success" + }, + { + "config": "TiledLinear", + "num_frames": 13, + "inference_speed_avg_s": 1.1279, + "inference_speed_min_s": 1.1222, + "inference_speed_max_s": 1.1307, + "inference_speed_std_s": 0.0024, + "inference_speed_status": "success", + "inference_memory_peak_gb": 29.807, + "inference_memory_diff_gb": 2.992, + "inference_memory_status": "success", + "training_speed_avg_s": 4.8691, + "training_speed_min_s": 4.8631, + "training_speed_max_s": 4.8769, + "training_speed_std_s": 0.0035, + "training_speed_status": "success", + "training_memory_peak_gb": 60.867, + "training_memory_diff_gb": 34.052, + "training_memory_status": "success" + }, + { + "config": "FlashNorm", + "num_frames": 13, + "inference_speed_avg_s": 0.9742, + "inference_speed_min_s": 0.9724, + "inference_speed_max_s": 0.9762, + "inference_speed_std_s": 0.0011, + "inference_speed_status": "success", + "inference_memory_peak_gb": 29.777, + "inference_memory_diff_gb": 2.993, + "inference_memory_status": "success", + "training_speed_avg_s": 3.8406, + "training_speed_min_s": 3.8371, + "training_speed_max_s": 3.8455, + "training_speed_std_s": 0.0025, + "training_speed_status": "success", + "training_memory_peak_gb": 59.703, + "training_memory_diff_gb": 32.888, + "training_memory_status": "success" + }, + { + "config": "FlashRoPE", + "num_frames": 13, + "inference_speed_avg_s": 1.0208, + "inference_speed_min_s": 1.0183, + "inference_speed_max_s": 1.0252, + "inference_speed_std_s": 0.0021, + "inference_speed_status": "success", + "inference_memory_peak_gb": 29.807, + "inference_memory_diff_gb": 2.992, + "inference_memory_status": "success", + "training_speed_avg_s": 4.0924, + "training_speed_min_s": 4.0881, + "training_speed_max_s": 4.099, + "training_speed_std_s": 0.0044, + "training_speed_status": "success", + "training_memory_peak_gb": 60.817, + "training_memory_diff_gb": 34.002, + "training_memory_status": "success" + }, + { + "config": "FlashNorm+FlashRoPE", + "num_frames": 13, + "inference_speed_avg_s": 0.9093, + "inference_speed_min_s": 0.9073, + "inference_speed_max_s": 0.9115, + "inference_speed_std_s": 0.0016, + "inference_speed_status": "success", + "inference_memory_peak_gb": 29.807, + "inference_memory_diff_gb": 2.992, + "inference_memory_status": "success", + "training_speed_avg_s": 3.5968, + "training_speed_min_s": 3.5889, + "training_speed_max_s": 3.6009, + "training_speed_std_s": 0.004, + "training_speed_status": "success", + "training_memory_peak_gb": 59.728, + "training_memory_diff_gb": 32.913, + "training_memory_status": "success" + } + ] +} \ No newline at end of file diff --git a/Helios-main/tools/others/benchmark/benchmark_triton_results_wan.json b/Helios-main/tools/others/benchmark/benchmark_triton_results_wan.json new file mode 100644 index 0000000000000000000000000000000000000000..2e0903e7cbfc0e11c0711b42a292a8b78a64e60e --- /dev/null +++ b/Helios-main/tools/others/benchmark/benchmark_triton_results_wan.json @@ -0,0 +1,111 @@ +{ + "timestamp": "2026-02-06T12:56:41.488612", + "test_config": { + "num_frames": 21, + "height": 384, + "width": 640, + "num_speed_runs": 10 + }, + "experiments": [ + { + "config": "Baseline", + "num_frames": 21, + "inference_speed_avg_s": 1.9735, + "inference_speed_min_s": 1.97, + "inference_speed_max_s": 1.9756, + "inference_speed_std_s": 0.0016, + "inference_speed_status": "success", + "inference_memory_peak_gb": 31.615, + "inference_memory_diff_gb": 4.831, + "inference_memory_status": "success", + "training_speed_avg_s": 7.9606, + "training_speed_min_s": 7.9545, + "training_speed_max_s": 7.9712, + "training_speed_std_s": 0.0053, + "training_speed_status": "success", + "training_memory_peak_gb": 65.959, + "training_memory_diff_gb": 39.144, + "training_memory_status": "success" + }, + { + "config": "TiledLinear", + "num_frames": 21, + "inference_speed_avg_s": 2.0023, + "inference_speed_min_s": 1.9987, + "inference_speed_max_s": 2.0085, + "inference_speed_std_s": 0.0028, + "inference_speed_status": "success", + "inference_memory_peak_gb": 31.647, + "inference_memory_diff_gb": 4.832, + "inference_memory_status": "success", + "training_speed_avg_s": 8.689, + "training_speed_min_s": 8.6836, + "training_speed_max_s": 8.6957, + "training_speed_std_s": 0.0036, + "training_speed_status": "success", + "training_memory_peak_gb": 65.429, + "training_memory_diff_gb": 38.614, + "training_memory_status": "success" + }, + { + "config": "FlashNorm", + "num_frames": 21, + "inference_speed_avg_s": 1.7982, + "inference_speed_min_s": 1.7923, + "inference_speed_max_s": 1.8029, + "inference_speed_std_s": 0.0035, + "inference_speed_status": "success", + "inference_memory_peak_gb": 31.647, + "inference_memory_diff_gb": 4.832, + "inference_memory_status": "success", + "training_speed_avg_s": 7.2154, + "training_speed_min_s": 7.2076, + "training_speed_max_s": 7.223, + "training_speed_std_s": 0.0045, + "training_speed_status": "success", + "training_memory_peak_gb": 64.213, + "training_memory_diff_gb": 37.397, + "training_memory_status": "success" + }, + { + "config": "FlashRoPE", + "num_frames": 21, + "inference_speed_avg_s": 1.8678, + "inference_speed_min_s": 1.8634, + "inference_speed_max_s": 1.8743, + "inference_speed_std_s": 0.0034, + "inference_speed_status": "success", + "inference_memory_peak_gb": 31.647, + "inference_memory_diff_gb": 4.832, + "inference_memory_status": "success", + "training_speed_avg_s": 7.5754, + "training_speed_min_s": 7.5696, + "training_speed_max_s": 7.5802, + "training_speed_std_s": 0.0038, + "training_speed_status": "success", + "training_memory_peak_gb": 66.0, + "training_memory_diff_gb": 39.185, + "training_memory_status": "success" + }, + { + "config": "FlashNorm+FlashRoPE", + "num_frames": 21, + "inference_speed_avg_s": 1.6882, + "inference_speed_min_s": 1.6835, + "inference_speed_max_s": 1.6913, + "inference_speed_std_s": 0.0029, + "inference_speed_status": "success", + "inference_memory_peak_gb": 31.647, + "inference_memory_diff_gb": 4.832, + "inference_memory_status": "success", + "training_speed_avg_s": 6.8077, + "training_speed_min_s": 6.8014, + "training_speed_max_s": 6.8185, + "training_speed_std_s": 0.0049, + "training_speed_status": "success", + "training_memory_peak_gb": 64.252, + "training_memory_diff_gb": 37.436, + "training_memory_status": "success" + } + ] +} \ No newline at end of file diff --git a/Helios-main/tools/others/change_scheduler.py b/Helios-main/tools/others/change_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd38a1fcfbabd45fce93729f2b7572262568756 --- /dev/null +++ b/Helios-main/tools/others/change_scheduler.py @@ -0,0 +1,28 @@ +import torch + + +# base_lrs: [5e-05] last_epoch: 384000 _step_count: 384001 _get_lr_called_within_step: False _last_lr: [5e-05] lr_lambdas: [None] + +scheduler_path = "ablation_stage2-all_r256_1120_bigbatch_final_3/checkpoint-11500/scheduler.bin" +scheduler_state = torch.load(scheduler_path, map_location="cpu") + +print("Original values:") +print(f" last_epoch: {scheduler_state['last_epoch']}") +print(f" _step_count: {scheduler_state['_step_count']}") +print(f" base_lrs: {scheduler_state['base_lrs']}") +print(f" _last_lr: {scheduler_state['_last_lr']}") + +scheduler_state["last_epoch"] = 736000 +scheduler_state["_step_count"] = 736001 +scheduler_state["base_lrs"] = [4e-05] +scheduler_state["_last_lr"] = [4e-05] + +torch.save(scheduler_state, scheduler_path) + +# 验证修改 +print("\nModified values:") +print(f" last_epoch: {scheduler_state['last_epoch']}") +print(f" _step_count: {scheduler_state['_step_count']}") +print(f" base_lrs: {scheduler_state['base_lrs']}") +print(f" _last_lr: {scheduler_state['_last_lr']}") +print(f"\n✓ Successfully saved to: {scheduler_path}") diff --git a/Helios-main/tools/others/convert_ckpt.py b/Helios-main/tools/others/convert_ckpt.py new file mode 100644 index 0000000000000000000000000000000000000000..39b0855dda9c01c39162c8deadb51054aa21f841 --- /dev/null +++ b/Helios-main/tools/others/convert_ckpt.py @@ -0,0 +1,103 @@ +import json +import os + +from safetensors import safe_open +from safetensors.torch import save_file + + +# RENAME_RULES = [ +# ("clean_patch_embedding.proj_4x", "multi_term_memory_patch.patch_long"), +# ("clean_patch_embedding.proj_2x", "multi_term_memory_patch.patch_mid"), +# ("clean_patch_embedding.proj", "multi_term_memory_patch.patch_short"), +# ] + +# RENAME_RULES = [ +# ("multi_term_memory_patch.proj_4x", "multi_term_memory_patch.patch_long"), +# ("multi_term_memory_patch.proj_2x", "multi_term_memory_patch.patch_mid"), +# ("multi_term_memory_patch.proj", "multi_term_memory_patch.patch_short"), +# ] + +# RENAME_RULES = [ +# ("multi_term_memory_patch.patch_long", "patch_long"), +# ("multi_term_memory_patch.patch_mid", "patch_mid"), +# ("multi_term_memory_patch.patch_short", "patch_short"), +# ] + +# RENAME_RULES = [ +# ("multi_term_memory_patch.patch_long", "patch_long"), +# ("multi_term_memory_patch.patch_mid", "patch_mid"), +# ("multi_term_memory_patch.patch_short", "patch_short"), +# ] + +RENAME_RULES = [ + ("scale_shift_table", "norm_out.scale_shift_table"), +] + + +BASE_DIRS = [ + "Helios-Base/transformer", + "Helios-Base/transformer_init", + "Helios-Base-init/transformer", + "Helios-Mid/transformer", + "Helios-Mid/transformer_init", + "Helios-Mid-init/transformer", + "Helios-Distilled/transformer", + "Helios-Distilled/transformer_ode", + "Helios-Distilled-ODE/transformer", +] + +for BASE_DIR in BASE_DIRS: + index_path = os.path.join(BASE_DIR, "diffusion_pytorch_model.safetensors.index.json") + + def apply_rename(key: str) -> str: + for old_prefix, new_prefix in RENAME_RULES: + if key.startswith(old_prefix): + return new_prefix + key[len(old_prefix) :] + return key + + print(f"[1/3] Reading {index_path} ...") + with open(index_path, "r") as f: + index = json.load(f) + + weight_map = index["weight_map"] + old_keys = [k for k in weight_map if apply_rename(k) != k] + print(f" Found {len(old_keys)} keys to rename") + + for old_key in old_keys: + new_key = apply_rename(old_key) + weight_map[new_key] = weight_map.pop(old_key) + print(f" {old_key} -> {new_key}") + + with open(index_path, "w") as f: + json.dump(index, f, indent=2) + print(" Saved updated index.json") + + with open(index_path, "r") as f: + updated_index = json.load(f) + + affected_shards = set() + for new_key, shard in updated_index["weight_map"].items(): + if any(new_key.startswith(new_prefix) for _, new_prefix in RENAME_RULES): + affected_shards.add(shard) + + print(f"\n[2/3] Affected shard files: {sorted(affected_shards)}") + + for shard_filename in sorted(affected_shards): + shard_path = os.path.join(BASE_DIR, shard_filename) + print(f"\n Processing {shard_filename} ...") + + tensors = {} + metadata = None + + with safe_open(shard_path, framework="pt", device="cpu") as f: + metadata = f.metadata() + for key in f.keys(): + new_key = apply_rename(key) + tensors[new_key] = f.get_tensor(key) + if key != new_key: + print(f" {key} -> {new_key}") + + save_file(tensors, shard_path, metadata=metadata) + print(f" Overwritten {shard_path}") + + print("\n[3/3] Done!") diff --git a/Helios-main/tools/others/get_mean_std_size21.py b/Helios-main/tools/others/get_mean_std_size21.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd9577bf867181881cae2a1bc8f1fc4a33b26b4 --- /dev/null +++ b/Helios-main/tools/others/get_mean_std_size21.py @@ -0,0 +1,165 @@ +from datetime import datetime + +import numpy as np +from helios.dataset.dataloader_dmd import BucketedFeatureDataset, BucketedSampler, collate_fn +from tqdm import tqdm + + +if __name__ == "__main__": + # from diffusers import AutoencoderKLWan + # vae = AutoencoderKLWan.from_pretrained( + # "BestWishYsh/Helios-Base", + # subfolder="vae", + # weight_dtype=torch.bfloat16, + # device_map="cuda", + # ) + # vae.requires_grad_(False) + # vae.eval() + # from diffusers.utils import export_to_video + # from diffusers.video_processor import VideoProcessor + # vae_scale_factor_spatial = vae.spatial_compression_ratio + # video_processor = VideoProcessor(vae_scale_factor=vae_scale_factor_spatial) + # latents_mean = (torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(vae.device, dtype=vae.dtype)) + # latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to(vae.device, dtype=vae.dtype) + + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + dataloader_num_workers = 96 + batch_size = 32 + num_train_epochs = 1 + seed = 0 + + gan_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_long_960", + "/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_short_960", + "/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/osp-sucai", + ] + accelerator = Accelerator() + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + gan_folders=gan_folder, + force_rebuild=True, + seed=seed, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=False, + shuffle=True, + seed=seed, + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + dataloader = StatefulDataLoader( + dataset, + batch_sampler=sampler, + collate_fn=collate_fn, + num_workers=dataloader_num_workers, + prefetch_factor=2 if dataloader_num_workers > 0 else None, + ) + print(len(dataset), len(dataloader)) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + + max_samples = 500000 + output_txt = "latent_statistics_size21.txt" + stats = { + "x0_latents": {"sum": 0.0, "sum_sq": 0.0, "count": 0}, + "target_latents": {"sum": 0.0, "sum_sq": 0.0, "count": 0}, + } + sampled_count = 0 + print(f"Starting to collect statistics from {max_samples} randomly sampled videos...") + + if accelerator.is_main_process: + pbar = tqdm(total=max_samples, desc="Collecting statistics", unit="videos") + + step = 0 + global_step = 0 + first_epoch = 0 + print("Testing dataloader...") + for epoch in range(first_epoch, num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + for i, batch in enumerate(dataloader): + if accelerator.is_main_process: + x0_latents = batch["gan_vae_latents"][:, :, :1].cpu().float() + target_latents = batch["gan_vae_latents"].cpu().float() + + stats["x0_latents"]["sum"] += x0_latents.sum().item() + stats["x0_latents"]["sum_sq"] += (x0_latents**2).sum().item() + stats["x0_latents"]["count"] += x0_latents.numel() + + stats["target_latents"]["sum"] += target_latents.sum().item() + stats["target_latents"]["sum_sq"] += (target_latents**2).sum().item() + stats["target_latents"]["count"] += target_latents.numel() + + sampled_count += x0_latents.shape[0] + + pbar.update(batch_size) + + if sampled_count % 1000 == 0: + print(f"Sampled {sampled_count}/{max_samples} videos...") + + if sampled_count >= max_samples: + break + + if sampled_count >= max_samples: + break + + # 计算并保存统计结果 + if accelerator.is_main_process: + # 准备输出内容 + output_lines = [] + output_lines.append("=" * 80) + output_lines.append("VAE Latent Statistics Report") + output_lines.append("=" * 80) + output_lines.append(f"Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + output_lines.append(f"Total sampled videos: {sampled_count}") + output_lines.append(f"Random seed: {seed}") + output_lines.append("=" * 80) + output_lines.append("") + + # 计算每个latent的统计量 + for latent_name, stat in stats.items(): + if stat["count"] > 0: + mean = stat["sum"] / stat["count"] + variance = (stat["sum_sq"] / stat["count"]) - (mean**2) + std = np.sqrt(variance) + + output_lines.append(f"{latent_name}:") + output_lines.append(f" Total elements: {stat['count']:,}") + output_lines.append(f" Mean (μ): {mean:.8f}") + output_lines.append(f" Variance (σ²): {variance:.8f}") + output_lines.append(f" Std Dev (σ): {std:.8f}") + output_lines.append("") + + output_lines.append("=" * 80) + output_lines.append("Recommended regularization values for training:") + output_lines.append("=" * 80) + + # 计算平均值作为推荐参数 + mean_avg = np.mean([stats[k]["sum"] / stats[k]["count"] for k in stats.keys()]) + var_avg = np.mean( + [ + (stats[k]["sum_sq"] / stats[k]["count"]) - (stats[k]["sum"] / stats[k]["count"]) ** 2 + for k in stats.keys() + ] + ) + + output_lines.append(f"μ_target = {mean_avg:.8f}") + output_lines.append(f"σ²_target = {var_avg:.8f}") + output_lines.append("=" * 80) + + # 保存到文件 + result_text = "\n".join(output_lines) + + with open(output_txt, "w", encoding="utf-8") as f: + f.write(result_text) + + # 同时打印到控制台 + print("\n" + result_text) + print(f"\n✅ Statistics saved to: {output_txt}") + + print("\nStatistics collection completed!") diff --git a/Helios-main/tools/others/get_mean_std_size9.py b/Helios-main/tools/others/get_mean_std_size9.py new file mode 100644 index 0000000000000000000000000000000000000000..5d00a0550e41968cda7b4eb34c88d05915864190 --- /dev/null +++ b/Helios-main/tools/others/get_mean_std_size9.py @@ -0,0 +1,483 @@ +import os +import pickle +import random +from collections import defaultdict +from datetime import datetime + +import numpy as np +import torch +from einops import rearrange +from helios.dataset.dataloader_history_latents_dist import BucketedSampler, collate_fn +from torch.utils.data import Dataset +from tqdm import tqdm + + +class BucketedFeatureDataset(Dataset): + def __init__( + self, + feature_folders, + history_sizes=[16, 2, 1], + is_keep_x0=True, + force_rebuild=False, + return_all_vae_latent=False, + return_prompt_raw=False, + num_rollout_sections=3, + single_res=False, + single_height=384, + single_width=640, + seed=42, + ): + self.history_sizes = history_sizes + self.is_keep_x0 = is_keep_x0 + self.force_rebuild = force_rebuild + self.return_all_vae_latent = return_all_vae_latent + self.return_prompt_raw = return_prompt_raw + self.num_rollout_sections = num_rollout_sections + self.single_res = single_res + self.single_height = single_height + self.single_width = single_width + assert self.is_keep_x0, "is_keep_x0 need to be True now!" + + self.base_seed = seed + self._epoch = 0 + + if isinstance(feature_folders, str): + self.feature_folders = [feature_folders] + else: + self.feature_folders = feature_folders + + self.samples = [] + self.buckets = defaultdict(list) + + for folder in self.feature_folders: + cache_file = os.path.join(folder, "dataset_cache.pkl") + self._process_folder(folder, cache_file) + + def _process_folder(self, folder, cache_file): + if self.force_rebuild or not os.path.exists(cache_file): + if os.path.exists(cache_file): + os.remove(cache_file) + print(f"Building metadata cache for folder: {folder}") + folder_samples, folder_buckets = self._build_folder_metadata(folder) + + if not self.force_rebuild: + print(f"Saving metadata cache for folder: {folder}") + cached_data = {"samples": folder_samples, "buckets": folder_buckets} + with open(cache_file, "wb") as f: + pickle.dump(cached_data, f) + print(f"Cached {len(folder_samples)} samples from {folder}") + else: + print(f"Loading cached metadata from: {folder}") + with open(cache_file, "rb") as f: + cached_data = pickle.load(f) + folder_samples = cached_data["samples"] + folder_buckets = cached_data["buckets"] + print(f"Loaded {len(folder_samples)} samples from cache: {folder}") + + sample_idx_offset = len(self.samples) + self.samples.extend(folder_samples) + + for bucket_key, indices in folder_buckets.items(): + adjusted_indices = [idx + sample_idx_offset for idx in indices] + self.buckets[bucket_key].extend(adjusted_indices) + + def _build_folder_metadata(self, folder): + feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")] + samples = [] + buckets = defaultdict(list) + sample_idx = 0 + + print(f"Processing {len(feature_files)} files in {folder}...") + + for i, feature_file in enumerate(feature_files): + if i % 10000 == 0: + print(f" Processed {i}/{len(feature_files)} files") + + feature_path = os.path.join(folder, feature_file) + + # Parse filename + parts = feature_file.split("_") + uttid = "_".join(parts[:-3]) + num_frame = int(parts[-3]) + height = int(parts[-2]) + width = int(parts[-1].replace(".pt", "")) + + # keep length >= 121 + if num_frame < 121: + continue + + # keep resolution + allowed_resolutions = [ + (self.single_height, self.single_width), + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ] + if self.single_res and (height, width) not in allowed_resolutions: + continue + + bucket_key = (num_frame, height, width) + + sample_info = { + "uttid": uttid, + "dataset_name": folder.rstrip("/"), + "file_path": feature_path, + "bucket_key": bucket_key, + "num_frame": num_frame, + "height": height, + "width": width, + } + + samples.append(sample_info) + buckets[bucket_key].append(sample_idx) + sample_idx += 1 + + return samples, buckets + + def set_epoch(self, epoch): + self._epoch = epoch + + def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None): + source_latent = base_vae_latent if base_vae_latent is not None else vae_latent + + x0_latent = None + if self.is_keep_x0: + x0_latent = source_latent[0, :, :1, :, :].clone() + total_sections = source_latent.shape[0] + latent_window_size = source_latent.shape[2] + history_window_size = sum(self.history_sizes) + section_size = history_window_size + latent_window_size + + temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w") + zero_padding_source = torch.zeros( + temp_source_latent.shape[0], + history_window_size, + temp_source_latent.shape[2], + temp_source_latent.shape[3], + device=temp_source_latent.device, + dtype=temp_source_latent.dtype, + ) + continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1) + + temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w") + zero_padding_vae = torch.zeros( + temp_vae_latent.shape[0], + history_window_size, + temp_vae_latent.shape[2], + temp_vae_latent.shape[3], + device=temp_vae_latent.device, + dtype=temp_vae_latent.dtype, + ) + continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1) + + sample_seed = self.base_seed + self._epoch * 1000000 + idx + choice_idx = torch.randint( + 1, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed) + ).item() + if choice_idx == 0 and x0_latent is not None: + x0_latent = torch.zeros_like(x0_latent) + + clean_all_vae_latent = None + if self.return_all_vae_latent: + max_start_idx = total_sections - self.num_rollout_sections + if max_start_idx < 0: + raise ValueError( + f"Not enough sections: total_sections={total_sections}, num_rollout_sections={self.num_rollout_sections}" + ) + start_section_idx = random.randint(0, max_start_idx) + start_indice = start_section_idx * latent_window_size + end_indice = start_indice + history_window_size + self.num_rollout_sections * latent_window_size + clean_all_vae_latent = continue_source_latent[:, start_indice:end_indice, :, :] + + start_indice = choice_idx * latent_window_size + end_indice = start_indice + section_size + + history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :] + target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :] + + return x0_latent, history_latent, target_latent, clean_all_vae_latent + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + anchor_f = self.samples[idx]["num_frame"] + anchor_h = self.samples[idx]["height"] + anchor_w = self.samples[idx]["width"] + while True: + sample_info = self.samples[idx] + if ( + anchor_f != sample_info["num_frame"] + or anchor_h != sample_info["height"] + or anchor_w != sample_info["width"] + ): + idx = random.randint(0, len(self.samples) - 1) + print("Try to find a same dim sample, retrying...") + continue + try: + base_vae_latent = None + if (anchor_h, anchor_w) in [ + (self.single_height // 2, self.single_width // 2), + (self.single_height // 4, self.single_width // 4), + ]: + base_file_path = ( + sample_info["file_path"] + .replace("/mid", "") + .replace("/low", "") + .replace( + f"{self.single_height // 2}_{self.single_width // 2}", + f"{self.single_height}_{self.single_width}", + ) + .replace( + f"{self.single_height // 4}_{self.single_width // 4}", + f"{self.single_height}_{self.single_width}", + ) + ) + base_vae_latent = torch.load(base_file_path, map_location="cpu", weights_only=False)["vae_latent"] + + feature_data = torch.load(sample_info["file_path"], map_location="cpu", weights_only=False) + x0_latent, history_latent, target_latent, clean_all_vae_latent = self.prepare_stage1_latent( + feature_data["vae_latent"], idx, base_vae_latent + ) + if self.return_prompt_raw: + prompt_raws = feature_data["prompt_raw"] + break + except Exception: + idx = random.randint(0, len(self.samples) - 1) + print(f"Error loading {sample_info['file_path']}, retrying...") + file_name = os.path.basename(sample_info["file_path"]) + txt_name = f"{file_name}.txt" + with open(txt_name, "w") as f: + f.write(sample_info["file_path"] + "\n") + + output_dict = { + "uttid": sample_info["uttid"], + "bucket_key": sample_info["bucket_key"], + "dataset_name": sample_info["dataset_name"], + "num_frame": sample_info["num_frame"], + "height": sample_info["height"], + "width": sample_info["width"], + "x0_latents": x0_latent, + "history_latents": history_latent, + "target_latents": target_latent, + "clean_all_latents": clean_all_vae_latent, + "prompt_embeds": feature_data["prompt_embed"], + "prompt_attention_masks": feature_data.get("prompt_attention_mask", None), + } + + if self.return_prompt_raw: + output_dict["prompt_raws"] = prompt_raws + + return output_dict + + +if __name__ == "__main__": + # from diffusers import AutoencoderKLWan + # vae = AutoencoderKLWan.from_pretrained( + # "BestWishYsh/Helios-Base", + # subfolder="vae", + # weight_dtype=torch.bfloat16, + # device_map="cuda", + # ) + # vae.requires_grad_(False) + # vae.eval() + # from diffusers.utils import export_to_video + # from diffusers.video_processor import VideoProcessor + # vae_scale_factor_spatial = vae.spatial_compression_ratio + # video_processor = VideoProcessor(vae_scale_factor=vae_scale_factor_spatial) + # latents_mean = (torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(vae.device, dtype=vae.dtype)) + # latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to(vae.device, dtype=vae.dtype) + + from accelerate import Accelerator + from torchdata.stateful_dataloader import StatefulDataLoader + + feature_folder = [ + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v1_2/latents-fp9-384_0.01-0.015_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v2/latents-fp9-384_0.01-0.015_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents-fp9-384_0.01-0.015_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v1_2/latents-fp9-384_0.015-0.02_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v2/latents-fp9-384_0.015-0.02_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents-fp9-384_0.015-0.02_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v1_2/latents-fp9-384_0.02_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v2/latents-fp9-384_0.02_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents-fp9-384_0.02_with_prompt", + "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-pexels-45k/latents-fp9-384_with_prompt", + ] + dataloader_num_workers = 96 + batch_size = 8 + num_train_epochs = 1 + seed = 0 + output_dir = "accelerate_checkpoints" + checkpoint_dirs = ( + [ + d + for d in os.listdir(output_dir) + if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d)) + ] + if os.path.exists(output_dir) + else [] + ) + + dataset_ratios = {} + # dataset_ratios = { + # "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents": 0.9, + # "/mnt/hdfs/data/ysh_new/userful_things_wan/sekai/sekai-real-walking-hq-193/latents_stride1": 0.1 + # } + + # maybe_init_distributed_environment_and_model_parallel(1,1) + accelerator = Accelerator() + + # print(get_world_rank(), get_world_size(), get_sp_world_size()) + print(accelerator.process_index, accelerator.num_processes) + + dataset = BucketedFeatureDataset( + feature_folder, + force_rebuild=True, + return_all_vae_latent=False, + return_prompt_raw=False, + single_res=True, + single_height=384, + single_width=640, + seed=seed, + ) + sampler = BucketedSampler( + dataset, + batch_size=batch_size, + drop_last=True, + shuffle=True, + dataset_sampling_ratios=dataset_ratios, + seed=seed, + # num_sp_groups=get_world_size() // get_sp_world_size(), + # sp_world_size=get_sp_world_size(), + # global_rank=get_world_rank(), + num_sp_groups=accelerator.num_processes // 1, + sp_world_size=1, + global_rank=accelerator.process_index, + ) + # dataloader = DataLoader(dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=dataloader_num_workers) + dataloader = StatefulDataLoader( + dataset, + batch_sampler=sampler, + collate_fn=collate_fn, + num_workers=dataloader_num_workers, + pin_memory=True, + prefetch_factor=2, + ) + + print(len(dataset), len(dataloader)) + # dataloader = accelerator.prepare(dataloader) + print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}") + # print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}") + + max_samples = 500000 + output_txt = "latent_statistics.txt" + + # 初始化统计变量 + stats = { + "x0_latents": {"sum": 0.0, "sum_sq": 0.0, "count": 0}, + "history_latents": {"sum": 0.0, "sum_sq": 0.0, "count": 0}, + "target_latents": {"sum": 0.0, "sum_sq": 0.0, "count": 0}, + } + + sampled_count = 0 + + print(f"Starting to collect statistics from {max_samples} randomly sampled videos...") + + if accelerator.is_main_process: + pbar = tqdm(total=max_samples, desc="Collecting statistics", unit="videos") + + for epoch in range(num_train_epochs): + sampler.set_epoch(epoch) + dataset.set_epoch(epoch) + + for i, batch in enumerate(dataloader): + if accelerator.is_main_process: + # 获取latents(已经是shuffle后的随机样本) + x0_latents = batch["x0_latents"].cpu().float() + history_latents = batch["history_latents"].cpu().float() + target_latents = batch["target_latents"].cpu().float() + + # 统计 x0_latents + stats["x0_latents"]["sum"] += x0_latents.sum().item() + stats["x0_latents"]["sum_sq"] += (x0_latents**2).sum().item() + stats["x0_latents"]["count"] += x0_latents.numel() + + # 统计 history_latents + stats["history_latents"]["sum"] += history_latents.sum().item() + stats["history_latents"]["sum_sq"] += (history_latents**2).sum().item() + stats["history_latents"]["count"] += history_latents.numel() + + # 统计 target_latents + stats["target_latents"]["sum"] += target_latents.sum().item() + stats["target_latents"]["sum_sq"] += (target_latents**2).sum().item() + stats["target_latents"]["count"] += target_latents.numel() + + sampled_count += x0_latents.shape[0] + + pbar.update(batch_size) + + if sampled_count % 1000 == 0: + print(f"Sampled {sampled_count}/{max_samples} videos...") + + # 达到1万条就停止 + if sampled_count >= max_samples: + break + + if sampled_count >= max_samples: + break + + # 计算并保存统计结果 + if accelerator.is_main_process: + # 准备输出内容 + output_lines = [] + output_lines.append("=" * 80) + output_lines.append("VAE Latent Statistics Report") + output_lines.append("=" * 80) + output_lines.append(f"Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + output_lines.append(f"Total sampled videos: {sampled_count}") + output_lines.append(f"Dataset: {feature_folder[0]}") + output_lines.append(f"Random seed: {seed}") + output_lines.append("=" * 80) + output_lines.append("") + + # 计算每个latent的统计量 + for latent_name, stat in stats.items(): + if stat["count"] > 0: + mean = stat["sum"] / stat["count"] + variance = (stat["sum_sq"] / stat["count"]) - (mean**2) + std = np.sqrt(variance) + + output_lines.append(f"{latent_name}:") + output_lines.append(f" Total elements: {stat['count']:,}") + output_lines.append(f" Mean (μ): {mean:.8f}") + output_lines.append(f" Variance (σ²): {variance:.8f}") + output_lines.append(f" Std Dev (σ): {std:.8f}") + output_lines.append("") + + output_lines.append("=" * 80) + output_lines.append("Recommended regularization values for training:") + output_lines.append("=" * 80) + + # 计算平均值作为推荐参数 + mean_avg = np.mean([stats[k]["sum"] / stats[k]["count"] for k in stats.keys()]) + var_avg = np.mean( + [ + (stats[k]["sum_sq"] / stats[k]["count"]) - (stats[k]["sum"] / stats[k]["count"]) ** 2 + for k in stats.keys() + ] + ) + + output_lines.append(f"μ_target = {mean_avg:.8f}") + output_lines.append(f"σ²_target = {var_avg:.8f}") + output_lines.append("=" * 80) + + # 保存到文件 + result_text = "\n".join(output_lines) + + with open(output_txt, "w", encoding="utf-8") as f: + f.write(result_text) + + # 同时打印到控制台 + print("\n" + result_text) + print(f"\n✅ Statistics saved to: {output_txt}") + + print("\nStatistics collection completed!") diff --git a/Helios-main/tools/others/latent_statistics_size21.txt b/Helios-main/tools/others/latent_statistics_size21.txt new file mode 100644 index 0000000000000000000000000000000000000000..6289a09d665d55330718e241f721f320a8da3d03 --- /dev/null +++ b/Helios-main/tools/others/latent_statistics_size21.txt @@ -0,0 +1,26 @@ +================================================================================ +VAE Latent Statistics Report +================================================================================ +Generated at: 2026-01-13 13:24:10 +Total sampled videos: 500000 +Random seed: 0 +================================================================================ + +x0_latents: + Total elements: 30,720,000,000 + Mean (μ): -0.01618061 + Variance (σ²): 0.27996052 + Std Dev (σ): 0.52911295 + +target_latents: + Total elements: 645,120,000,000 + Mean (μ): c + Variance (σ²): 0.85126512 + Std Dev (σ): 0.92264030 + +================================================================================ +Recommended regularization values for training: +================================================================================ +μ_target = -0.00480520 +σ²_target = 0.56561282 +================================================================================ \ No newline at end of file diff --git a/Helios-main/tools/others/latent_statistics_size9.txt b/Helios-main/tools/others/latent_statistics_size9.txt new file mode 100644 index 0000000000000000000000000000000000000000..5dcee6e29055de6fe655e27c529903d375d08927 --- /dev/null +++ b/Helios-main/tools/others/latent_statistics_size9.txt @@ -0,0 +1,33 @@ +================================================================================ +VAE Latent Statistics Report +================================================================================ +Generated at: 2025-12-28 11:15:26 +Total sampled videos: 500000 +Dataset: /mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-pexels-45k/latents-fp9-384_with_prompt +Random seed: 0 +================================================================================ + +x0_latents: + Total elements: 30,720,000,000 + Mean (μ): -0.01578601 + Variance (σ²): 0.29913200 + Std Dev (σ): 0.54692961 + +history_latents: + Total elements: 583,680,000,000 + Mean (μ): 0.01774882 + Variance (σ²): 0.73409494 + Std Dev (σ): 0.85679341 + +target_latents: + Total elements: 276,480,000,000 + Mean (μ): 0.01906107 + Variance (σ²): 0.81397036 + Std Dev (σ): 0.90220306 + +================================================================================ +Recommended regularization values for training: +================================================================================ +μ_target = 0.00700796 +σ²_target = 0.61573244 +================================================================================ \ No newline at end of file diff --git a/LongLive-main/wan/modules/causal_model.py b/LongLive-main/wan/modules/causal_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a2170ef352f4b38c14fd2ed1a1d627d46fbc8f12 --- /dev/null +++ b/LongLive-main/wan/modules/causal_model.py @@ -0,0 +1,1269 @@ +# Adopted from https://github.com/guandeh17/Self-Forcing +# SPDX-License-Identifier: CC-BY-NC-SA-4.0 +from wan.modules.attention import attention +from wan.modules.model import ( + WanRMSNorm, + rope_apply, + WanLayerNorm, + WAN_CROSSATTENTION_CLASSES, + rope_params, + MLPProj, + sinusoidal_embedding_1d +) +from torch.nn.attention.flex_attention import create_block_mask, flex_attention +from diffusers.configuration_utils import ConfigMixin, register_to_config +from torch.nn.attention.flex_attention import BlockMask +from diffusers.models.modeling_utils import ModelMixin +import torch.nn as nn +import torch +import math +import torch.distributed as dist +from utils.memory import gpu, get_cuda_free_memory_gb, DynamicSwapInstaller, log_gpu_memory + +from utils.debug_option import DEBUG + +# wan 1.3B model has a weird channel / head configurations and require max-autotune to work with flexattention +# see https://github.com/pytorch/pytorch/issues/133254 +# change to default for other models +flex_attention = torch.compile( + flex_attention, dynamic=False, mode="max-autotune-no-cudagraphs") + + +def causal_rope_apply(x, grid_sizes, freqs, start_frame=0): + n, c = x.size(2), x.size(3) // 2 + + # split freqs + freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1) + + # loop over samples + output = [] + + for i, (f, h, w) in enumerate(grid_sizes.tolist()): + seq_len = f * h * w + + # precompute multipliers + x_i = torch.view_as_complex(x[i, :seq_len].to(torch.float64).reshape( + seq_len, n, -1, 2)) + freqs_i = torch.cat([ + freqs[0][start_frame:start_frame + f].view(f, 1, 1, -1).expand(f, h, w, -1), + freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1), + freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1) + ], + dim=-1).reshape(seq_len, 1, -1) + + # apply rotary embedding + x_i = torch.view_as_real(x_i * freqs_i).flatten(2) + x_i = torch.cat([x_i, x[i, seq_len:]]) + + # append to collection + output.append(x_i) + return torch.stack(output).type_as(x) + + +class CausalWanSelfAttention(nn.Module): + + def __init__(self, + dim, + num_heads, + local_attn_size=-1, + sink_size=0, + qk_norm=True, + eps=1e-6): + assert dim % num_heads == 0 + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.local_attn_size = local_attn_size + self.sink_size = sink_size + self.qk_norm = qk_norm + self.eps = eps + # Support list/tuple local_attn_size by converting to list first (handles OmegaConf ListConfig) + if not isinstance(local_attn_size, int) and hasattr(local_attn_size, "__iter__"): + values = list(local_attn_size) + else: + values = [int(local_attn_size)] + non_neg_vals = [int(v) for v in values if int(v) != -1] + max_local = max(non_neg_vals) if len(non_neg_vals) > 0 else -1 + self.max_attention_size = 32760 if max_local == -1 else max_local * 1560 + # layers + self.q = nn.Linear(dim, dim) + self.k = nn.Linear(dim, dim) + self.v = nn.Linear(dim, dim) + self.o = nn.Linear(dim, dim) + self.norm_q = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity() + self.norm_k = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity() + + def forward( + self, + x, + seq_lens, + grid_sizes, + freqs, + block_mask, + kv_cache=None, + current_start=0, + cache_start=None, + sink_recache_after_switch=False + ): + r""" + Args: + x(Tensor): Shape [B, L, num_heads, C / num_heads] + seq_lens(Tensor): Shape [B] + grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W) + freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2] + block_mask (BlockMask) + """ + b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim + if cache_start is None: + cache_start = current_start + + # query, key, value function + def qkv_fn(x): + q = self.norm_q(self.q(x)).view(b, s, n, d) + k = self.norm_k(self.k(x)).view(b, s, n, d) + v = self.v(x).view(b, s, n, d) + return q, k, v + + q, k, v = qkv_fn(x) + + if kv_cache is None: + # if it is teacher forcing training? + is_tf = (s == seq_lens[0].item() * 2) + if is_tf: + q_chunk = torch.chunk(q, 2, dim=1) + k_chunk = torch.chunk(k, 2, dim=1) + roped_query = [] + roped_key = [] + # rope should be same for clean and noisy parts + for ii in range(2): + rq = rope_apply(q_chunk[ii], grid_sizes, freqs).type_as(v) + rk = rope_apply(k_chunk[ii], grid_sizes, freqs).type_as(v) + roped_query.append(rq) + roped_key.append(rk) + + roped_query = torch.cat(roped_query, dim=1) + roped_key = torch.cat(roped_key, dim=1) + + padded_length = math.ceil(q.shape[1] / 128) * 128 - q.shape[1] + padded_roped_query = torch.cat( + [roped_query, + torch.zeros([q.shape[0], padded_length, q.shape[2], q.shape[3]], + device=q.device, dtype=v.dtype)], + dim=1 + ) + + padded_roped_key = torch.cat( + [roped_key, torch.zeros([k.shape[0], padded_length, k.shape[2], k.shape[3]], + device=k.device, dtype=v.dtype)], + dim=1 + ) + + padded_v = torch.cat( + [v, torch.zeros([v.shape[0], padded_length, v.shape[2], v.shape[3]], + device=v.device, dtype=v.dtype)], + dim=1 + ) + + x = flex_attention( + query=padded_roped_query.transpose(2, 1), + key=padded_roped_key.transpose(2, 1), + value=padded_v.transpose(2, 1), + block_mask=block_mask + )[:, :, :-padded_length].transpose(2, 1) + + else: + roped_query = rope_apply(q, grid_sizes, freqs).type_as(v) + roped_key = rope_apply(k, grid_sizes, freqs).type_as(v) + + padded_length = math.ceil(q.shape[1] / 128) * 128 - q.shape[1] + padded_roped_query = torch.cat( + [roped_query, + torch.zeros([q.shape[0], padded_length, q.shape[2], q.shape[3]], + device=q.device, dtype=v.dtype)], + dim=1 + ) + + padded_roped_key = torch.cat( + [roped_key, torch.zeros([k.shape[0], padded_length, k.shape[2], k.shape[3]], + device=k.device, dtype=v.dtype)], + dim=1 + ) + + padded_v = torch.cat( + [v, torch.zeros([v.shape[0], padded_length, v.shape[2], v.shape[3]], + device=v.device, dtype=v.dtype)], + dim=1 + ) + + x = flex_attention( + query=padded_roped_query.transpose(2, 1), + key=padded_roped_key.transpose(2, 1), + value=padded_v.transpose(2, 1), + block_mask=block_mask + )[:, :, :-padded_length].transpose(2, 1) + else: + frame_seqlen = math.prod(grid_sizes[0][1:]).item() + current_start_frame = current_start // frame_seqlen + roped_query = causal_rope_apply( + q, grid_sizes, freqs, start_frame=current_start_frame).type_as(v) + roped_key = causal_rope_apply( + k, grid_sizes, freqs, start_frame=current_start_frame).type_as(v) + + current_end = current_start + roped_query.shape[1] + sink_tokens = self.sink_size * frame_seqlen + # If we are using local attention and the current KV cache size is larger than the local attention size, we need to truncate the KV cache + kv_cache_size = kv_cache["k"].shape[1] + num_new_tokens = roped_query.shape[1] + # if (not dist.is_initialized() or dist.get_rank() == 0) and DEBUG: + # print("***********before attention***********") + # print(f"kv_cache_size = {kv_cache_size / frame_seqlen}") + # print(f"torch.is_grad_enabled() = {torch.is_grad_enabled()}") + # print(f"current_end = {current_end / frame_seqlen}") + # print(f"current_start = {current_start / frame_seqlen}") + # print(f"kv_cache['global_end_index'] = {kv_cache['global_end_index']}") + # print(f"kv_cache['local_end_index'] = {kv_cache['local_end_index']}") + # print(f"num_new_tokens = {num_new_tokens}") + + # Compute cache update parameters without modifying kv_cache directly + cache_update_info = None + is_recompute = current_end <= kv_cache["global_end_index"].item() and current_start > 0 + if self.local_attn_size != -1 and (current_end > kv_cache["global_end_index"].item()) and ( + num_new_tokens + kv_cache["local_end_index"].item() > kv_cache_size): + # Calculate the number of new tokens added in this step + # Shift existing cache content left to discard oldest tokens + num_evicted_tokens = num_new_tokens + kv_cache["local_end_index"].item() - kv_cache_size + num_rolled_tokens = kv_cache["local_end_index"].item() - num_evicted_tokens - sink_tokens + # if (not dist.is_initialized() or dist.get_rank() == 0) and DEBUG: + # print(f"need roll") + # print(f"num_rolled_tokens: {num_rolled_tokens / frame_seqlen}") + # print(f"num_evicted_tokens: {num_evicted_tokens / frame_seqlen}") + # print(f"sink_tokens: {sink_tokens / frame_seqlen}") + + # Compute updated local indices + local_end_index = kv_cache["local_end_index"].item() + current_end - \ + kv_cache["global_end_index"].item() - num_evicted_tokens + local_start_index = local_end_index - num_new_tokens + + # Construct full k, v for attention computation (without modifying the original cache) + # Create temporary k, v for computation + temp_k = kv_cache["k"].clone() + temp_v = kv_cache["v"].clone() + + # Apply rolling update to the temporary cache + temp_k[:, sink_tokens:sink_tokens + num_rolled_tokens] = \ + temp_k[:, sink_tokens + num_evicted_tokens:sink_tokens + num_evicted_tokens + num_rolled_tokens].clone() + temp_v[:, sink_tokens:sink_tokens + num_rolled_tokens] = \ + temp_v[:, sink_tokens + num_evicted_tokens:sink_tokens + num_evicted_tokens + num_rolled_tokens].clone() + + # Insert new key/value into the temporary cache + # Protect sink_tokens only during recomputation; regular forward generation allows writing into the initial sink region + write_start_index = max(local_start_index, sink_tokens) if is_recompute else local_start_index + roped_offset = max(0, write_start_index - local_start_index) + write_len = max(0, local_end_index - write_start_index) + if write_len > 0: + temp_k[:, write_start_index:local_end_index] = roped_key[:, roped_offset:roped_offset + write_len] + temp_v[:, write_start_index:local_end_index] = v[:, roped_offset:roped_offset + write_len] + + # Save cache update info for later use + cache_update_info = { + "action": "roll_and_insert", + "sink_tokens": sink_tokens, + "num_rolled_tokens": num_rolled_tokens, + "num_evicted_tokens": num_evicted_tokens, + "local_start_index": local_start_index, + "local_end_index": local_end_index, + "write_start_index": write_start_index, + "write_end_index": local_end_index, + "new_k": roped_key[:, roped_offset:roped_offset + write_len], + "new_v": v[:, roped_offset:roped_offset + write_len], + "current_end": current_end, + "is_recompute": is_recompute + } + + # if (not dist.is_initialized() or dist.get_rank() == 0) and DEBUG: + # print(f"used kv cache size: local_end_index - local_start_index = {local_end_index - local_start_index}") + else: + # Assign new keys/values directly up to current_end + local_end_index = kv_cache["local_end_index"].item() + current_end - kv_cache["global_end_index"].item() + local_start_index = local_end_index - num_new_tokens + + # Construct full k, v for attention computation (without modifying the original cache) + temp_k = kv_cache["k"].clone() + temp_v = kv_cache["v"].clone() + # Protect sink_tokens only during recomputation; regular forward generation allows writing into the initial sink region + write_start_index = max(local_start_index, sink_tokens) if is_recompute else local_start_index + if sink_recache_after_switch: + write_start_index = local_start_index + roped_offset = max(0, write_start_index - local_start_index) + write_len = max(0, local_end_index - write_start_index) + if write_len > 0: + temp_k[:, write_start_index:local_end_index] = roped_key[:, roped_offset:roped_offset + write_len] + temp_v[:, write_start_index:local_end_index] = v[:, roped_offset:roped_offset + write_len] + + # Save cache update info for later use + cache_update_info = { + "action": "direct_insert", + "local_start_index": local_start_index, + "local_end_index": local_end_index, + "write_start_index": write_start_index, + "write_end_index": local_end_index, + "new_k": roped_key[:, roped_offset:roped_offset + write_len], + "new_v": v[:, roped_offset:roped_offset + write_len], + "current_end": current_end, + "is_recompute": is_recompute + } + + # if (not dist.is_initialized() or dist.get_rank() == 0) and DEBUG: + # print(f"local_start_index: {local_start_index}, local_end_index: {local_end_index}") + + # Use temporary k, v to compute attention + if sink_tokens > 0: + # Concatenate sink tokens and local window tokens, keeping total length strictly below max_attention_size + local_budget = self.max_attention_size - sink_tokens + k_sink = temp_k[:, :sink_tokens] + v_sink = temp_v[:, :sink_tokens] + # if (not dist.is_initialized() or dist.get_rank() == 0) and DEBUG: + # print(f"local_budget: {local_budget}") + if local_budget > 0: + local_start_for_window = max(sink_tokens, local_end_index - local_budget) + k_local = temp_k[:, local_start_for_window:local_end_index] + v_local = temp_v[:, local_start_for_window:local_end_index] + k_cat = torch.cat([k_sink, k_local], dim=1) + v_cat = torch.cat([v_sink, v_local], dim=1) + else: + k_cat = k_sink + v_cat = v_sink + x = attention( + roped_query, + k_cat, + v_cat + ) + else: + window_start = max(0, local_end_index - self.max_attention_size) + x = attention( + roped_query, + temp_k[:, window_start:local_end_index], + temp_v[:, window_start:local_end_index] + ) + + # output + x = x.flatten(2) + x = self.o(x) + + # Return both output and cache update info + if kv_cache is not None: + return x, (current_end, local_end_index, cache_update_info) + else: + return x + + +class CausalWanAttentionBlock(nn.Module): + + def __init__(self, + cross_attn_type, + dim, + ffn_dim, + num_heads, + local_attn_size=-1, + sink_size=0, + qk_norm=True, + cross_attn_norm=False, + eps=1e-6): + super().__init__() + self.dim = dim + self.ffn_dim = ffn_dim + self.num_heads = num_heads + self.local_attn_size = local_attn_size + self.qk_norm = qk_norm + self.cross_attn_norm = cross_attn_norm + self.eps = eps + + # layers + self.norm1 = WanLayerNorm(dim, eps) + self.self_attn = CausalWanSelfAttention(dim, num_heads, local_attn_size, sink_size, qk_norm, eps) + self.norm3 = WanLayerNorm( + dim, eps, + elementwise_affine=True) if cross_attn_norm else nn.Identity() + self.cross_attn = WAN_CROSSATTENTION_CLASSES[cross_attn_type](dim, + num_heads, + (-1, -1), + qk_norm, + eps) + self.norm2 = WanLayerNorm(dim, eps) + self.ffn = nn.Sequential( + nn.Linear(dim, ffn_dim), nn.GELU(approximate='tanh'), + nn.Linear(ffn_dim, dim)) + + # modulation + self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5) + + def forward( + self, + x, + e, + seq_lens, + grid_sizes, + freqs, + context, + context_lens, + block_mask, + kv_cache=None, + crossattn_cache=None, + current_start=0, + cache_start=None, + sink_recache_after_switch=False, + ): + r""" + Args: + x(Tensor): Shape [B, L, C] + e(Tensor): Shape [B, F, 6, C] + seq_lens(Tensor): Shape [B], length of each sequence in batch + grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W) + freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2] + """ + num_frames, frame_seqlen = e.shape[1], x.shape[1] // e.shape[1] + # assert e.dtype == torch.float32 + # with amp.autocast(dtype=torch.float32): + e = (self.modulation.unsqueeze(1) + e).chunk(6, dim=2) + # assert e[0].dtype == torch.float32 + + # self-attention + self_attn_result = self.self_attn( + (self.norm1(x).unflatten(dim=1, sizes=(num_frames, frame_seqlen)) * (1 + e[1]) + e[0]).flatten(1, 2), + seq_lens, grid_sizes, + freqs, block_mask, kv_cache, current_start, cache_start, sink_recache_after_switch) + + if kv_cache is not None: + y, cache_update_info = self_attn_result + else: + y = self_attn_result + cache_update_info = None + + # with amp.autocast(dtype=torch.float32): + x = x + (y.unflatten(dim=1, sizes=(num_frames, frame_seqlen)) * e[2]).flatten(1, 2) + + # cross-attention & ffn function + def cross_attn_ffn(x, context, context_lens, e, crossattn_cache=None): + x = x + self.cross_attn(self.norm3(x), context, + context_lens, crossattn_cache=crossattn_cache) + y = self.ffn( + (self.norm2(x).unflatten(dim=1, sizes=(num_frames, + frame_seqlen)) * (1 + e[4]) + e[3]).flatten(1, 2) + ) + # with amp.autocast(dtype=torch.float32): + x = x + (y.unflatten(dim=1, sizes=(num_frames, + frame_seqlen)) * e[5]).flatten(1, 2) + return x + + x = cross_attn_ffn(x, context, context_lens, e, crossattn_cache) + + if cache_update_info is not None: + # cache_update_info is already in the format (current_end, local_end_index, cache_update_info) + return x, cache_update_info + else: + return x + + +class CausalHead(nn.Module): + + def __init__(self, dim, out_dim, patch_size, eps=1e-6): + super().__init__() + self.dim = dim + self.out_dim = out_dim + self.patch_size = patch_size + self.eps = eps + + # layers + out_dim = math.prod(patch_size) * out_dim + self.norm = WanLayerNorm(dim, eps) + self.head = nn.Linear(dim, out_dim) + + # modulation + self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5) + + def forward(self, x, e): + r""" + Args: + x(Tensor): Shape [B, L1, C] + e(Tensor): Shape [B, F, 1, C] + """ + # assert e.dtype == torch.float32 + # with amp.autocast(dtype=torch.float32): + num_frames, frame_seqlen = e.shape[1], x.shape[1] // e.shape[1] + e = (self.modulation.unsqueeze(1) + e).chunk(2, dim=2) + x = (self.head(self.norm(x).unflatten(dim=1, sizes=(num_frames, frame_seqlen)) * (1 + e[1]) + e[0])) + return x + + +class CausalWanModel(ModelMixin, ConfigMixin): + r""" + Wan diffusion backbone supporting both text-to-video and image-to-video. + """ + + ignore_for_config = [ + 'patch_size', 'cross_attn_norm', 'qk_norm', 'text_dim' + ] + _no_split_modules = ['WanAttentionBlock'] + _supports_gradient_checkpointing = True + + @register_to_config + def __init__(self, + model_type='t2v', + patch_size=(1, 2, 2), + text_len=512, + in_dim=16, + dim=2048, + ffn_dim=8192, + freq_dim=256, + text_dim=4096, + out_dim=16, + num_heads=16, + num_layers=32, + local_attn_size=-1, + sink_size=0, + qk_norm=True, + cross_attn_norm=True, + eps=1e-6): + r""" + Initialize the diffusion model backbone. + + Args: + model_type (`str`, *optional*, defaults to 't2v'): + Model variant - 't2v' (text-to-video) or 'i2v' (image-to-video) + patch_size (`tuple`, *optional*, defaults to (1, 2, 2)): + 3D patch dimensions for video embedding (t_patch, h_patch, w_patch) + text_len (`int`, *optional*, defaults to 512): + Fixed length for text embeddings + in_dim (`int`, *optional*, defaults to 16): + Input video channels (C_in) + dim (`int`, *optional*, defaults to 2048): + Hidden dimension of the transformer + ffn_dim (`int`, *optional*, defaults to 8192): + Intermediate dimension in feed-forward network + freq_dim (`int`, *optional*, defaults to 256): + Dimension for sinusoidal time embeddings + text_dim (`int`, *optional*, defaults to 4096): + Input dimension for text embeddings + out_dim (`int`, *optional*, defaults to 16): + Output video channels (C_out) + num_heads (`int`, *optional*, defaults to 16): + Number of attention heads + num_layers (`int`, *optional*, defaults to 32): + Number of transformer blocks + local_attn_size (`int`, *optional*, defaults to -1): + Window size for temporal local attention (-1 indicates global attention) + sink_size (`int`, *optional*, defaults to 0): + Size of the attention sink, we keep the first `sink_size` frames unchanged when rolling the KV cache + qk_norm (`bool`, *optional*, defaults to True): + Enable query/key normalization + cross_attn_norm (`bool`, *optional*, defaults to False): + Enable cross-attention normalization + eps (`float`, *optional*, defaults to 1e-6): + Epsilon value for normalization layers + """ + + super().__init__() + + assert model_type in ['t2v', 'i2v'] + self.model_type = model_type + + self.patch_size = patch_size + self.text_len = text_len + self.in_dim = in_dim + self.dim = dim + self.ffn_dim = ffn_dim + self.freq_dim = freq_dim + self.text_dim = text_dim + self.out_dim = out_dim + self.num_heads = num_heads + self.num_layers = num_layers + self.local_attn_size = local_attn_size + self.qk_norm = qk_norm + self.cross_attn_norm = cross_attn_norm + self.eps = eps + + # embeddings + self.patch_embedding = nn.Conv3d( + in_dim, dim, kernel_size=patch_size, stride=patch_size) + self.text_embedding = nn.Sequential( + nn.Linear(text_dim, dim), nn.GELU(approximate='tanh'), + nn.Linear(dim, dim)) + + self.time_embedding = nn.Sequential( + nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim)) + self.time_projection = nn.Sequential( + nn.SiLU(), nn.Linear(dim, dim * 6)) + + # blocks + cross_attn_type = 't2v_cross_attn' if model_type == 't2v' else 'i2v_cross_attn' + self.blocks = nn.ModuleList([ + CausalWanAttentionBlock(cross_attn_type, dim, ffn_dim, num_heads, + local_attn_size, sink_size, qk_norm, cross_attn_norm, eps) + for _ in range(num_layers) + ]) + + # head + self.head = CausalHead(dim, out_dim, patch_size, eps) + + # buffers (don't use register_buffer otherwise dtype will be changed in to()) + assert (dim % num_heads) == 0 and (dim // num_heads) % 2 == 0 + d = dim // num_heads + self.freqs = torch.cat([ + rope_params(1024, d - 4 * (d // 6)), + rope_params(1024, 2 * (d // 6)), + rope_params(1024, 2 * (d // 6)) + ], + dim=1) + + if model_type == 'i2v': + self.img_emb = MLPProj(1280, dim) + + # initialize weights + self.init_weights() + + self.gradient_checkpointing = False + + self.block_mask = None + + self.num_frame_per_block = 1 + self.independent_first_frame = False + + def _set_gradient_checkpointing(self, module, value=False): + self.gradient_checkpointing = value + + @staticmethod + def _prepare_blockwise_causal_attn_mask( + device: torch.device | str, num_frames: int = 21, + frame_seqlen: int = 1560, num_frame_per_block=1, local_attn_size=-1 + ) -> BlockMask: + """ + we will divide the token sequence into the following format + [1 latent frame] [1 latent frame] ... [1 latent frame] + We use flexattention to construct the attention mask + """ + total_length = num_frames * frame_seqlen + + # we do right padding to get to a multiple of 128 + padded_length = math.ceil(total_length / 128) * 128 - total_length + + ends = torch.zeros(total_length + padded_length, + device=device, dtype=torch.long) + + # Block-wise causal mask will attend to all elements that are before the end of the current chunk + frame_indices = torch.arange( + start=0, + end=total_length, + step=frame_seqlen * num_frame_per_block, + device=device + ) + + for tmp in frame_indices: + ends[tmp:tmp + frame_seqlen * num_frame_per_block] = tmp + \ + frame_seqlen * num_frame_per_block + + def attention_mask(b, h, q_idx, kv_idx): + if local_attn_size == -1: + return (kv_idx < ends[q_idx]) | (q_idx == kv_idx) + else: + return ((kv_idx < ends[q_idx]) & (kv_idx >= (ends[q_idx] - local_attn_size * frame_seqlen))) | (q_idx == kv_idx) + # return ((kv_idx < total_length) & (q_idx < total_length)) | (q_idx == kv_idx) # bidirectional mask + + block_mask = create_block_mask(attention_mask, B=None, H=None, Q_LEN=total_length + padded_length, + KV_LEN=total_length + padded_length, _compile=False, device=device) + + import torch.distributed as dist + if (not dist.is_initialized() or dist.get_rank() == 0) and DEBUG: + pass + + # import imageio + # import numpy as np + # from torch.nn.attention.flex_attention import create_mask + + # mask = create_mask(attention_mask, B=None, H=None, Q_LEN=total_length + + # padded_length, KV_LEN=total_length + padded_length, device=device) + # import cv2 + # mask = cv2.resize(mask[0, 0].cpu().float().numpy(), (1024, 1024)) + # imageio.imwrite("mask_%d.jpg" % (0), np.uint8(255. * mask)) + + return block_mask + + @staticmethod + def _prepare_teacher_forcing_mask( + device: torch.device | str, num_frames: int = 21, + frame_seqlen: int = 1560, num_frame_per_block=1 + ) -> BlockMask: + """ + we will divide the token sequence into the following format + [1 latent frame] [1 latent frame] ... [1 latent frame] + We use flexattention to construct the attention mask + """ + # # debug + # DEBUG = False + # if DEBUG: + # num_frames = 9 + # frame_seqlen = 256 + + total_length = num_frames * frame_seqlen * 2 + + # we do right padding to get to a multiple of 128 + padded_length = math.ceil(total_length / 128) * 128 - total_length + + clean_ends = num_frames * frame_seqlen + # for clean context frames, we can construct their flex attention mask based on a [start, end] interval + context_ends = torch.zeros(total_length + padded_length, device=device, dtype=torch.long) + # for noisy frames, we need two intervals to construct the flex attention mask [context_start, context_end] [noisy_start, noisy_end] + noise_context_starts = torch.zeros(total_length + padded_length, device=device, dtype=torch.long) + noise_context_ends = torch.zeros(total_length + padded_length, device=device, dtype=torch.long) + noise_noise_starts = torch.zeros(total_length + padded_length, device=device, dtype=torch.long) + noise_noise_ends = torch.zeros(total_length + padded_length, device=device, dtype=torch.long) + + # Block-wise causal mask will attend to all elements that are before the end of the current chunk + attention_block_size = frame_seqlen * num_frame_per_block + frame_indices = torch.arange( + start=0, + end=num_frames * frame_seqlen, + step=attention_block_size, + device=device, dtype=torch.long + ) + + # attention for clean context frames + for start in frame_indices: + context_ends[start:start + attention_block_size] = start + attention_block_size + + noisy_image_start_list = torch.arange( + num_frames * frame_seqlen, total_length, + step=attention_block_size, + device=device, dtype=torch.long + ) + noisy_image_end_list = noisy_image_start_list + attention_block_size + + # attention for noisy frames + for block_index, (start, end) in enumerate(zip(noisy_image_start_list, noisy_image_end_list)): + # attend to noisy tokens within the same block + noise_noise_starts[start:end] = start + noise_noise_ends[start:end] = end + # attend to context tokens in previous blocks + # noise_context_starts[start:end] = 0 + noise_context_ends[start:end] = block_index * attention_block_size + + def attention_mask(b, h, q_idx, kv_idx): + # first design the mask for clean frames + clean_mask = (q_idx < clean_ends) & (kv_idx < context_ends[q_idx]) + # then design the mask for noisy frames + # noisy frames will attend to all clean preceeding clean frames + itself + C1 = (kv_idx < noise_noise_ends[q_idx]) & (kv_idx >= noise_noise_starts[q_idx]) + C2 = (kv_idx < noise_context_ends[q_idx]) & (kv_idx >= noise_context_starts[q_idx]) + noise_mask = (q_idx >= clean_ends) & (C1 | C2) + + eye_mask = q_idx == kv_idx + return eye_mask | clean_mask | noise_mask + + block_mask = create_block_mask(attention_mask, B=None, H=None, Q_LEN=total_length + padded_length, + KV_LEN=total_length + padded_length, _compile=False, device=device) + + if DEBUG: + import imageio + import numpy as np + from torch.nn.attention.flex_attention import create_mask + + mask = create_mask(attention_mask, B=None, H=None, Q_LEN=total_length + + padded_length, KV_LEN=total_length + padded_length, device=device) + import cv2 + mask = cv2.resize(mask[0, 0].cpu().float().numpy(), (1024, 1024)) + imageio.imwrite("mask_%d.jpg" % (0), np.uint8(255. * mask)) + + return block_mask + + @staticmethod + def _prepare_blockwise_causal_attn_mask_i2v( + device: torch.device | str, num_frames: int = 21, + frame_seqlen: int = 1560, num_frame_per_block=4, local_attn_size=-1 + ) -> BlockMask: + """ + we will divide the token sequence into the following format + [1 latent frame] [N latent frame] ... [N latent frame] + The first frame is separated out to support I2V generation + We use flexattention to construct the attention mask + """ + total_length = num_frames * frame_seqlen + + # we do right padding to get to a multiple of 128 + padded_length = math.ceil(total_length / 128) * 128 - total_length + + ends = torch.zeros(total_length + padded_length, + device=device, dtype=torch.long) + + # special handling for the first frame + ends[:frame_seqlen] = frame_seqlen + + # Block-wise causal mask will attend to all elements that are before the end of the current chunk + frame_indices = torch.arange( + start=frame_seqlen, + end=total_length, + step=frame_seqlen * num_frame_per_block, + device=device + ) + + for idx, tmp in enumerate(frame_indices): + ends[tmp:tmp + frame_seqlen * num_frame_per_block] = tmp + \ + frame_seqlen * num_frame_per_block + + def attention_mask(b, h, q_idx, kv_idx): + if local_attn_size == -1: + return (kv_idx < ends[q_idx]) | (q_idx == kv_idx) + else: + return ((kv_idx < ends[q_idx]) & (kv_idx >= (ends[q_idx] - local_attn_size * frame_seqlen))) | \ + (q_idx == kv_idx) + + block_mask = create_block_mask(attention_mask, B=None, H=None, Q_LEN=total_length + padded_length, + KV_LEN=total_length + padded_length, _compile=False, device=device) + + if not dist.is_initialized() or dist.get_rank() == 0: + pass + + # import imageio + # import numpy as np + # from torch.nn.attention.flex_attention import create_mask + + # mask = create_mask(attention_mask, B=None, H=None, Q_LEN=total_length + + # padded_length, KV_LEN=total_length + padded_length, device=device) + # import cv2 + # mask = cv2.resize(mask[0, 0].cpu().float().numpy(), (1024, 1024)) + # imageio.imwrite("mask_%d.jpg" % (0), np.uint8(255. * mask)) + + return block_mask + + def _apply_cache_updates(self, kv_cache, cache_update_infos): + """ + Applies cache updates collected from multiple blocks. + Args: + kv_cache: List of cache dictionaries for each block + cache_update_infos: List of (block_index, cache_update_info) tuples + """ + for block_index, (current_end, local_end_index, update_info) in cache_update_infos: + if update_info is not None: + cache = kv_cache[block_index] + + if update_info["action"] == "roll_and_insert": + # Apply rolling update + sink_tokens = update_info["sink_tokens"] + num_rolled_tokens = update_info["num_rolled_tokens"] + num_evicted_tokens = update_info["num_evicted_tokens"] + local_start_index = update_info["local_start_index"] + local_end_index = update_info["local_end_index"] + write_start_index = update_info.get("write_start_index", local_start_index) + write_end_index = update_info.get("write_end_index", local_end_index) + new_k = update_info["new_k"] + new_v = update_info["new_v"] + + # Perform the rolling operation + cache["k"][:, sink_tokens:sink_tokens + num_rolled_tokens] = \ + cache["k"][:, sink_tokens + num_evicted_tokens:sink_tokens + num_evicted_tokens + num_rolled_tokens].clone() + cache["v"][:, sink_tokens:sink_tokens + num_rolled_tokens] = \ + cache["v"][:, sink_tokens + num_evicted_tokens:sink_tokens + num_evicted_tokens + num_rolled_tokens].clone() + + # Insert new key/value + if write_end_index > write_start_index and new_k.shape[1] == (write_end_index - write_start_index): + cache["k"][:, write_start_index:write_end_index] = new_k + cache["v"][:, write_start_index:write_end_index] = new_v + + elif update_info["action"] == "direct_insert": + # Direct insert + local_start_index = update_info["local_start_index"] + local_end_index = update_info["local_end_index"] + write_start_index = update_info.get("write_start_index", local_start_index) + write_end_index = update_info.get("write_end_index", local_end_index) + new_k = update_info["new_k"] + new_v = update_info["new_v"] + + # Insert new key/value + if write_end_index > write_start_index and new_k.shape[1] == (write_end_index - write_start_index): + cache["k"][:, write_start_index:write_end_index] = new_k + cache["v"][:, write_start_index:write_end_index] = new_v + + # Update indices: do not roll back pointers during recomputation + is_recompute = False if update_info is None else update_info.get("is_recompute", False) + if not is_recompute: + kv_cache[block_index]["global_end_index"].fill_(current_end) + kv_cache[block_index]["local_end_index"].fill_(local_end_index) + + def _forward_inference( + self, + x, + t, + context, + seq_len, + clip_fea=None, + y=None, + kv_cache: dict = None, + crossattn_cache: dict = None, + current_start: int = 0, + cache_start: int = 0, + sink_recache_after_switch=False + ): + r""" + Run the diffusion model with kv caching. + See Algorithm 2 of CausVid paper https://arxiv.org/abs/2412.07772 for details. + This function will be run for num_frame times. + Process the latent frames one by one (1560 tokens each) + + Args: + x (List[Tensor]): + List of input video tensors, each with shape [C_in, F, H, W] + t (Tensor): + Diffusion timesteps tensor of shape [B] + context (List[Tensor]): + List of text embeddings each with shape [L, C] + seq_len (`int`): + Maximum sequence length for positional encoding + clip_fea (Tensor, *optional*): + CLIP image features for image-to-video mode + y (List[Tensor], *optional*): + Conditional video inputs for image-to-video mode, same shape as x + + Returns: + List[Tensor]: + List of denoised video tensors with original input shapes [C_out, F, H / 8, W / 8] + """ + + if self.model_type == 'i2v': + assert clip_fea is not None and y is not None + # params + device = self.patch_embedding.weight.device + if self.freqs.device != device: + self.freqs = self.freqs.to(device) + + if y is not None: + x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)] + + # print(f"x.device: {x[0].device}, t.device: {t.device}, context.device: {context.device}, seq_len: {seq_len}") + + # embeddings + x = [self.patch_embedding(u.unsqueeze(0)) for u in x] + # print("patch embedding done") + grid_sizes = torch.stack( + [torch.tensor(u.shape[2:], dtype=torch.long) for u in x]) + x = [u.flatten(2).transpose(1, 2) for u in x] + seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long) + assert seq_lens.max() <= seq_len + x = torch.cat(x) + """ + torch.cat([ + torch.cat([u, u.new_zeros(1, seq_len - u.size(1), u.size(2))], + dim=1) for u in x + ]) + """ + + # time embeddings + # with amp.autocast(dtype=torch.float32): + e = self.time_embedding( + sinusoidal_embedding_1d(self.freq_dim, t.flatten()).type_as(x)) + e0 = self.time_projection(e).unflatten( + 1, (6, self.dim)).unflatten(dim=0, sizes=t.shape) + # assert e.dtype == torch.float32 and e0.dtype == torch.float32 + # print("time embedding done") + # context + context_lens = None + context = self.text_embedding( + torch.stack([ + torch.cat( + [u, u.new_zeros(self.text_len - u.size(0), u.size(1))]) + for u in context + ])) + # print("text embedding done") + if clip_fea is not None: + context_clip = self.img_emb(clip_fea) # bs x 257 x dim + context = torch.concat([context_clip, context], dim=1) + + # arguments + kwargs = dict( + e=e0, + seq_lens=seq_lens, + grid_sizes=grid_sizes, + freqs=self.freqs, + context=context, + context_lens=context_lens, + block_mask=self.block_mask, + sink_recache_after_switch=sink_recache_after_switch + ) + # print("kwargs done") + def create_custom_forward(module): + def custom_forward(*inputs, **kwargs): + return module(*inputs, **kwargs) + return custom_forward + + cache_update_info = None + cache_update_infos = [] # Collect cache update info for all blocks + for block_index, block in enumerate(self.blocks): + # print(f"block_index: {block_index}") + if torch.is_grad_enabled() and self.gradient_checkpointing: + kwargs.update( + { + "kv_cache": kv_cache[block_index], + "current_start": current_start, + "cache_start": cache_start + } + ) + # print(f"forward checkpointing") + result = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, **kwargs, + use_reentrant=False, + ) + # Handle the result + if kv_cache is not None and isinstance(result, tuple): + x, block_cache_update_info = result + cache_update_infos.append((block_index, block_cache_update_info)) + # Extract base info for subsequent blocks (without concrete cache update details) + cache_update_info = block_cache_update_info[:2] # (current_end, local_end_index) + else: + x = result + else: + kwargs.update( + { + "kv_cache": kv_cache[block_index], + "crossattn_cache": crossattn_cache[block_index], + "current_start": current_start, + "cache_start": cache_start + } + ) + # print(f"forward no checkpointing") + result = block(x, **kwargs) + # Handle the result + if kv_cache is not None and isinstance(result, tuple): + x, block_cache_update_info = result + cache_update_infos.append((block_index, block_cache_update_info)) + # Extract base info for subsequent blocks (without concrete cache update details) + cache_update_info = block_cache_update_info[:2] # (current_end, local_end_index) + else: + x = result + # log_gpu_memory(f"in _forward_inference: {x[0].device}") + # After all blocks are processed, apply cache updates in a single pass + if kv_cache is not None and cache_update_infos: + self._apply_cache_updates(kv_cache, cache_update_infos) + + # head + x = self.head(x, e.unflatten(dim=0, sizes=t.shape).unsqueeze(2)) + # unpatchify + x = self.unpatchify(x, grid_sizes) + return torch.stack(x) + + def _forward_train( + self, + x, + t, + context, + seq_len, + clean_x=None, + aug_t=None, + clip_fea=None, + y=None, + ): + r""" + Forward pass through the diffusion model + + Args: + x (List[Tensor]): + List of input video tensors, each with shape [C_in, F, H, W] + t (Tensor): + Diffusion timesteps tensor of shape [B] + context (List[Tensor]): + List of text embeddings each with shape [L, C] + seq_len (`int`): + Maximum sequence length for positional encoding + clip_fea (Tensor, *optional*): + CLIP image features for image-to-video mode + y (List[Tensor], *optional*): + Conditional video inputs for image-to-video mode, same shape as x + + Returns: + List[Tensor]: + List of denoised video tensors with original input shapes [C_out, F, H / 8, W / 8] + """ + pass + raise NotImplementedError() + + if self.model_type == 'i2v': + assert clip_fea is not None and y is not None + # params + device = self.patch_embedding.weight.device + if self.freqs.device != device: + self.freqs = self.freqs.to(device) + + # Construct blockwise causal attn mask + if self.block_mask is None: + if clean_x is not None: + if self.independent_first_frame: + raise NotImplementedError() + else: + self.block_mask = self._prepare_teacher_forcing_mask( + device, num_frames=x.shape[2], + frame_seqlen=x.shape[-2] * x.shape[-1] // (self.patch_size[1] * self.patch_size[2]), + num_frame_per_block=self.num_frame_per_block + ) + else: + if self.independent_first_frame: + self.block_mask = self._prepare_blockwise_causal_attn_mask_i2v( + device, num_frames=x.shape[2], + frame_seqlen=x.shape[-2] * x.shape[-1] // (self.patch_size[1] * self.patch_size[2]), + num_frame_per_block=self.num_frame_per_block, + local_attn_size=self.local_attn_size + ) + else: + self.block_mask = self._prepare_blockwise_causal_attn_mask( + device, num_frames=x.shape[2], + frame_seqlen=x.shape[-2] * x.shape[-1] // (self.patch_size[1] * self.patch_size[2]), + num_frame_per_block=self.num_frame_per_block, + local_attn_size=self.local_attn_size + ) + + if y is not None: + x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)] + + # embeddings + x = [self.patch_embedding(u.unsqueeze(0)) for u in x] + + grid_sizes = torch.stack( + [torch.tensor(u.shape[2:], dtype=torch.long) for u in x]) + x = [u.flatten(2).transpose(1, 2) for u in x] + + seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long) + assert seq_lens.max() <= seq_len + x = torch.cat([ + torch.cat([u, u.new_zeros(1, seq_lens[0] - u.size(1), u.size(2))], + dim=1) for u in x + ]) + + # time embeddings + # with amp.autocast(dtype=torch.float32): + e = self.time_embedding( + sinusoidal_embedding_1d(self.freq_dim, t.flatten()).type_as(x)) + e0 = self.time_projection(e).unflatten( + 1, (6, self.dim)).unflatten(dim=0, sizes=t.shape) + # assert e.dtype == torch.float32 and e0.dtype == torch.float32 + + # context + context_lens = None + context = self.text_embedding( + torch.stack([ + torch.cat( + [u, u.new_zeros(self.text_len - u.size(0), u.size(1))]) + for u in context + ])) + + if clip_fea is not None: + context_clip = self.img_emb(clip_fea) # bs x 257 x dim + context = torch.concat([context_clip, context], dim=1) + + if clean_x is not None: + clean_x = [self.patch_embedding(u.unsqueeze(0)) for u in clean_x] + clean_x = [u.flatten(2).transpose(1, 2) for u in clean_x] + + seq_lens_clean = torch.tensor([u.size(1) for u in clean_x], dtype=torch.long) + assert seq_lens_clean.max() <= seq_len + clean_x = torch.cat([ + torch.cat([u, u.new_zeros(1, seq_lens_clean[0] - u.size(1), u.size(2))], dim=1) for u in clean_x + ]) + + x = torch.cat([clean_x, x], dim=1) + if aug_t is None: + aug_t = torch.zeros_like(t) + e_clean = self.time_embedding( + sinusoidal_embedding_1d(self.freq_dim, aug_t.flatten()).type_as(x)) + e0_clean = self.time_projection(e_clean).unflatten( + 1, (6, self.dim)).unflatten(dim=0, sizes=t.shape) + e0 = torch.cat([e0_clean, e0], dim=1) + + # arguments + kwargs = dict( + e=e0, + seq_lens=seq_lens, + grid_sizes=grid_sizes, + freqs=self.freqs, + context=context, + context_lens=context_lens, + block_mask=self.block_mask) + + def create_custom_forward(module): + def custom_forward(*inputs, **kwargs): + return module(*inputs, **kwargs) + return custom_forward + + for block in self.blocks: + if torch.is_grad_enabled() and self.gradient_checkpointing: + x = torch.utils.checkpoint.checkpoint( + create_custom_forward(block), + x, **kwargs, + use_reentrant=False, + ) + else: + x = block(x, **kwargs) + if clean_x is not None: + x = x[:, x.shape[1] // 2:] + + # head + x = self.head(x, e.unflatten(dim=0, sizes=t.shape).unsqueeze(2)) + + # unpatchify + x = self.unpatchify(x, grid_sizes) + return torch.stack(x) + + def forward( + self, + *args, + **kwargs + ): + if kwargs.get('kv_cache', None) is not None: + return self._forward_inference(*args, **kwargs) + else: + return self._forward_train(*args, **kwargs) + + def unpatchify(self, x, grid_sizes): + r""" + Reconstruct video tensors from patch embeddings. + + Args: + x (List[Tensor]): + List of patchified features, each with shape [L, C_out * prod(patch_size)] + grid_sizes (Tensor): + Original spatial-temporal grid dimensions before patching, + shape [B, 3] (3 dimensions correspond to F_patches, H_patches, W_patches) + + Returns: + List[Tensor]: + Reconstructed video tensors with shape [C_out, F, H / 8, W / 8] + """ + + c = self.out_dim + out = [] + for u, v in zip(x, grid_sizes.tolist()): + u = u[:math.prod(v)].view(*v, *self.patch_size, c) + u = torch.einsum('fhwpqrc->cfphqwr', u) + u = u.reshape(c, *[i * j for i, j in zip(v, self.patch_size)]) + out.append(u) + return out + + def init_weights(self): + r""" + Initialize model parameters using Xavier initialization. + """ + + # basic init + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.zeros_(m.bias) + + # init embeddings + nn.init.xavier_uniform_(self.patch_embedding.weight.flatten(1)) + for m in self.text_embedding.modules(): + if isinstance(m, nn.Linear): + nn.init.normal_(m.weight, std=.02) + for m in self.time_embedding.modules(): + if isinstance(m, nn.Linear): + nn.init.normal_(m.weight, std=.02) + + # init output layer + nn.init.zeros_(self.head.head.weight) diff --git a/LongLive-main/wan/modules/tokenizers.py b/LongLive-main/wan/modules/tokenizers.py new file mode 100644 index 0000000000000000000000000000000000000000..121e591c48f82f82daa51a6ce38ae9a27beea8d2 --- /dev/null +++ b/LongLive-main/wan/modules/tokenizers.py @@ -0,0 +1,82 @@ +# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. +import html +import string + +import ftfy +import regex as re +from transformers import AutoTokenizer + +__all__ = ['HuggingfaceTokenizer'] + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +def canonicalize(text, keep_punctuation_exact_string=None): + text = text.replace('_', ' ') + if keep_punctuation_exact_string: + text = keep_punctuation_exact_string.join( + part.translate(str.maketrans('', '', string.punctuation)) + for part in text.split(keep_punctuation_exact_string)) + else: + text = text.translate(str.maketrans('', '', string.punctuation)) + text = text.lower() + text = re.sub(r'\s+', ' ', text) + return text.strip() + + +class HuggingfaceTokenizer: + + def __init__(self, name, seq_len=None, clean=None, **kwargs): + assert clean in (None, 'whitespace', 'lower', 'canonicalize') + self.name = name + self.seq_len = seq_len + self.clean = clean + + # init tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(name, **kwargs) + self.vocab_size = self.tokenizer.vocab_size + + def __call__(self, sequence, **kwargs): + return_mask = kwargs.pop('return_mask', False) + + # arguments + _kwargs = {'return_tensors': 'pt'} + if self.seq_len is not None: + _kwargs.update({ + 'padding': 'max_length', + 'truncation': True, + 'max_length': self.seq_len + }) + _kwargs.update(**kwargs) + + # tokenization + if isinstance(sequence, str): + sequence = [sequence] + if self.clean: + sequence = [self._clean(u) for u in sequence] + ids = self.tokenizer(sequence, **_kwargs) + + # output + if return_mask: + return ids.input_ids, ids.attention_mask + else: + return ids.input_ids + + def _clean(self, text): + if self.clean == 'whitespace': + text = whitespace_clean(basic_clean(text)) + elif self.clean == 'lower': + text = whitespace_clean(basic_clean(text)).lower() + elif self.clean == 'canonicalize': + text = canonicalize(basic_clean(text)) + return text diff --git a/LongLive-main/wan/modules/vae.py b/LongLive-main/wan/modules/vae.py new file mode 100644 index 0000000000000000000000000000000000000000..c50dea913c32eccf971fd528bb15b3173ea5f9b9 --- /dev/null +++ b/LongLive-main/wan/modules/vae.py @@ -0,0 +1,683 @@ +# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. +import logging + +import torch +import torch.cuda.amp as amp +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange + +__all__ = [ + 'WanVAE', +] + +CACHE_T = 2 + + +class CausalConv3d(nn.Conv3d): + """ + Causal 3d convolusion. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._padding = (self.padding[2], self.padding[2], self.padding[1], + self.padding[1], 2 * self.padding[0], 0) + self.padding = (0, 0, 0) + + def forward(self, x, cache_x=None): + padding = list(self._padding) + if cache_x is not None and self._padding[4] > 0: + cache_x = cache_x.to(x.device) + x = torch.cat([cache_x, x], dim=2) + padding[4] -= cache_x.shape[2] + x = F.pad(x, padding) + + return super().forward(x) + + +class RMS_norm(nn.Module): + + def __init__(self, dim, channel_first=True, images=True, bias=False): + super().__init__() + broadcastable_dims = (1, 1, 1) if not images else (1, 1) + shape = (dim, *broadcastable_dims) if channel_first else (dim,) + + self.channel_first = channel_first + self.scale = dim**0.5 + self.gamma = nn.Parameter(torch.ones(shape)) + self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0. + + def forward(self, x): + return F.normalize( + x, dim=(1 if self.channel_first else + -1)) * self.scale * self.gamma + self.bias + + +class Upsample(nn.Upsample): + + def forward(self, x): + """ + Fix bfloat16 support for nearest neighbor interpolation. + """ + return super().forward(x.float()).type_as(x) + + +class Resample(nn.Module): + + def __init__(self, dim, mode): + assert mode in ('none', 'upsample2d', 'upsample3d', 'downsample2d', + 'downsample3d') + super().__init__() + self.dim = dim + self.mode = mode + + # layers + if mode == 'upsample2d': + self.resample = nn.Sequential( + Upsample(scale_factor=(2., 2.), mode='nearest'), + nn.Conv2d(dim, dim // 2, 3, padding=1)) + elif mode == 'upsample3d': + self.resample = nn.Sequential( + Upsample(scale_factor=(2., 2.), mode='nearest'), + nn.Conv2d(dim, dim // 2, 3, padding=1)) + self.time_conv = CausalConv3d( + dim, dim * 2, (3, 1, 1), padding=(1, 0, 0)) + + elif mode == 'downsample2d': + self.resample = nn.Sequential( + nn.ZeroPad2d((0, 1, 0, 1)), + nn.Conv2d(dim, dim, 3, stride=(2, 2))) + elif mode == 'downsample3d': + self.resample = nn.Sequential( + nn.ZeroPad2d((0, 1, 0, 1)), + nn.Conv2d(dim, dim, 3, stride=(2, 2))) + self.time_conv = CausalConv3d( + dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0)) + + else: + self.resample = nn.Identity() + + def forward(self, x, feat_cache=None, feat_idx=[0]): + b, c, t, h, w = x.size() + if self.mode == 'upsample3d': + if feat_cache is not None: + idx = feat_idx[0] + if feat_cache[idx] is None: + feat_cache[idx] = 'Rep' + feat_idx[0] += 1 + else: + + cache_x = x[:, :, -CACHE_T:, :, :].clone() + if cache_x.shape[2] < 2 and feat_cache[ + idx] is not None and feat_cache[idx] != 'Rep': + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + if cache_x.shape[2] < 2 and feat_cache[ + idx] is not None and feat_cache[idx] == 'Rep': + cache_x = torch.cat([ + torch.zeros_like(cache_x).to(cache_x.device), + cache_x + ], + dim=2) + if feat_cache[idx] == 'Rep': + x = self.time_conv(x) + else: + x = self.time_conv(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + + x = x.reshape(b, 2, c, t, h, w) + x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]), + 3) + x = x.reshape(b, c, t * 2, h, w) + t = x.shape[2] + x = rearrange(x, 'b c t h w -> (b t) c h w') + x = self.resample(x) + x = rearrange(x, '(b t) c h w -> b c t h w', t=t) + + if self.mode == 'downsample3d': + if feat_cache is not None: + idx = feat_idx[0] + if feat_cache[idx] is None: + feat_cache[idx] = x.clone() + feat_idx[0] += 1 + else: + + cache_x = x[:, :, -1:, :, :].clone() + # if cache_x.shape[2] < 2 and feat_cache[idx] is not None and feat_cache[idx]!='Rep': + # # cache last frame of last two chunk + # cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2) + + x = self.time_conv( + torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2)) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + return x + + def init_weight(self, conv): + conv_weight = conv.weight + nn.init.zeros_(conv_weight) + c1, c2, t, h, w = conv_weight.size() + one_matrix = torch.eye(c1, c2) + init_matrix = one_matrix + nn.init.zeros_(conv_weight) + # conv_weight.data[:,:,-1,1,1] = init_matrix * 0.5 + conv_weight.data[:, :, 1, 0, 0] = init_matrix # * 0.5 + conv.weight.data.copy_(conv_weight) + nn.init.zeros_(conv.bias.data) + + def init_weight2(self, conv): + conv_weight = conv.weight.data + nn.init.zeros_(conv_weight) + c1, c2, t, h, w = conv_weight.size() + init_matrix = torch.eye(c1 // 2, c2) + # init_matrix = repeat(init_matrix, 'o ... -> (o 2) ...').permute(1,0,2).contiguous().reshape(c1,c2) + conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix + conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix + conv.weight.data.copy_(conv_weight) + nn.init.zeros_(conv.bias.data) + + +class ResidualBlock(nn.Module): + + def __init__(self, in_dim, out_dim, dropout=0.0): + super().__init__() + self.in_dim = in_dim + self.out_dim = out_dim + + # layers + self.residual = nn.Sequential( + RMS_norm(in_dim, images=False), nn.SiLU(), + CausalConv3d(in_dim, out_dim, 3, padding=1), + RMS_norm(out_dim, images=False), nn.SiLU(), nn.Dropout(dropout), + CausalConv3d(out_dim, out_dim, 3, padding=1)) + self.shortcut = CausalConv3d(in_dim, out_dim, 1) \ + if in_dim != out_dim else nn.Identity() + + def forward(self, x, feat_cache=None, feat_idx=[0]): + h = self.shortcut(x) + for layer in self.residual: + if isinstance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].clone() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + return x + h + + +class AttentionBlock(nn.Module): + """ + Causal self-attention with a single head. + """ + + def __init__(self, dim): + super().__init__() + self.dim = dim + + # layers + self.norm = RMS_norm(dim) + self.to_qkv = nn.Conv2d(dim, dim * 3, 1) + self.proj = nn.Conv2d(dim, dim, 1) + + # zero out the last layer params + nn.init.zeros_(self.proj.weight) + + def forward(self, x): + identity = x + b, c, t, h, w = x.size() + x = rearrange(x, 'b c t h w -> (b t) c h w') + x = self.norm(x) + # compute query, key, value + q, k, v = self.to_qkv(x).reshape(b * t, 1, c * 3, + -1).permute(0, 1, 3, + 2).contiguous().chunk( + 3, dim=-1) + + # apply attention + x = F.scaled_dot_product_attention( + q, + k, + v, + ) + x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w) + + # output + x = self.proj(x) + x = rearrange(x, '(b t) c h w-> b c t h w', t=t) + return x + identity + + +class Encoder3d(nn.Module): + + def __init__(self, + dim=128, + z_dim=4, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_downsample=[True, True, False], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_downsample = temperal_downsample + + # dimensions + dims = [dim * u for u in [1] + dim_mult] + scale = 1.0 + + # init block + self.conv1 = CausalConv3d(3, dims[0], 3, padding=1) + + # downsample blocks + downsamples = [] + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + # residual (+attention) blocks + for _ in range(num_res_blocks): + downsamples.append(ResidualBlock(in_dim, out_dim, dropout)) + if scale in attn_scales: + downsamples.append(AttentionBlock(out_dim)) + in_dim = out_dim + + # downsample block + if i != len(dim_mult) - 1: + mode = 'downsample3d' if temperal_downsample[ + i] else 'downsample2d' + downsamples.append(Resample(out_dim, mode=mode)) + scale /= 2.0 + self.downsamples = nn.Sequential(*downsamples) + + # middle blocks + self.middle = nn.Sequential( + ResidualBlock(out_dim, out_dim, dropout), AttentionBlock(out_dim), + ResidualBlock(out_dim, out_dim, dropout)) + + # output blocks + self.head = nn.Sequential( + RMS_norm(out_dim, images=False), nn.SiLU(), + CausalConv3d(out_dim, z_dim, 3, padding=1)) + + def forward(self, x, feat_cache=None, feat_idx=[0]): + if feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].clone() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = self.conv1(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = self.conv1(x) + + # downsamples + for layer in self.downsamples: + if feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + # middle + for layer in self.middle: + if isinstance(layer, ResidualBlock) and feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + # head + for layer in self.head: + if isinstance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].clone() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + return x + + +class Decoder3d(nn.Module): + + def __init__(self, + dim=128, + z_dim=4, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_upsample=[False, True, True], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_upsample = temperal_upsample + + # dimensions + dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]] + scale = 1.0 / 2**(len(dim_mult) - 2) + + # init block + self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1) + + # middle blocks + self.middle = nn.Sequential( + ResidualBlock(dims[0], dims[0], dropout), AttentionBlock(dims[0]), + ResidualBlock(dims[0], dims[0], dropout)) + + # upsample blocks + upsamples = [] + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + # residual (+attention) blocks + if i == 1 or i == 2 or i == 3: + in_dim = in_dim // 2 + for _ in range(num_res_blocks + 1): + upsamples.append(ResidualBlock(in_dim, out_dim, dropout)) + if scale in attn_scales: + upsamples.append(AttentionBlock(out_dim)) + in_dim = out_dim + + # upsample block + if i != len(dim_mult) - 1: + mode = 'upsample3d' if temperal_upsample[i] else 'upsample2d' + upsamples.append(Resample(out_dim, mode=mode)) + scale *= 2.0 + self.upsamples = nn.Sequential(*upsamples) + + # output blocks + self.head = nn.Sequential( + RMS_norm(out_dim, images=False), nn.SiLU(), + CausalConv3d(out_dim, 3, 3, padding=1)) + + def forward(self, x, feat_cache=None, feat_idx=[0]): + # conv1 + if feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].clone() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = self.conv1(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = self.conv1(x) + + # middle + for layer in self.middle: + if isinstance(layer, ResidualBlock) and feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + # upsamples + for layer in self.upsamples: + if feat_cache is not None: + x = layer(x, feat_cache, feat_idx) + else: + x = layer(x) + + # head + for layer in self.head: + if isinstance(layer, CausalConv3d) and feat_cache is not None: + idx = feat_idx[0] + cache_x = x[:, :, -CACHE_T:, :, :].clone() + if cache_x.shape[2] < 2 and feat_cache[idx] is not None: + # cache last frame of last two chunk + cache_x = torch.cat([ + feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to( + cache_x.device), cache_x + ], + dim=2) + x = layer(x, feat_cache[idx]) + feat_cache[idx] = cache_x + feat_idx[0] += 1 + else: + x = layer(x) + return x + + +def count_conv3d(model): + count = 0 + for m in model.modules(): + if isinstance(m, CausalConv3d): + count += 1 + return count + + +class WanVAE_(nn.Module): + + def __init__(self, + dim=128, + z_dim=4, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_downsample=[True, True, False], + dropout=0.0): + super().__init__() + self.dim = dim + self.z_dim = z_dim + self.dim_mult = dim_mult + self.num_res_blocks = num_res_blocks + self.attn_scales = attn_scales + self.temperal_downsample = temperal_downsample + self.temperal_upsample = temperal_downsample[::-1] + + # modules + self.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks, + attn_scales, self.temperal_downsample, dropout) + self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1) + self.conv2 = CausalConv3d(z_dim, z_dim, 1) + self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks, + attn_scales, self.temperal_upsample, dropout) + self.clear_cache() + + def forward(self, x): + mu, log_var = self.encode(x) + z = self.reparameterize(mu, log_var) + x_recon = self.decode(z) + return x_recon, mu, log_var + + def encode(self, x, scale): + self.clear_cache() + # cache + t = x.shape[2] + iter_ = 1 + (t - 1) // 4 + # 对encode输入的x,按时间拆分为1、4、4、4.... + for i in range(iter_): + self._enc_conv_idx = [0] + if i == 0: + out = self.encoder( + x[:, :, :1, :, :], + feat_cache=self._enc_feat_map, + feat_idx=self._enc_conv_idx) + else: + out_ = self.encoder( + x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :], + feat_cache=self._enc_feat_map, + feat_idx=self._enc_conv_idx) + out = torch.cat([out, out_], 2) + mu, log_var = self.conv1(out).chunk(2, dim=1) + if isinstance(scale[0], torch.Tensor): + mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view( + 1, self.z_dim, 1, 1, 1) + else: + mu = (mu - scale[0]) * scale[1] + self.clear_cache() + return mu + + def decode(self, z, scale): + self.clear_cache() + # z: [b,c,t,h,w] + if isinstance(scale[0], torch.Tensor): + z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view( + 1, self.z_dim, 1, 1, 1) + else: + z = z / scale[1] + scale[0] + iter_ = z.shape[2] + x = self.conv2(z) + for i in range(iter_): + self._conv_idx = [0] + if i == 0: + out = self.decoder( + x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx) + else: + out_ = self.decoder( + x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx) + out = torch.cat([out, out_], 2) + self.clear_cache() + return out + + def cached_decode(self, z, scale): + # z: [b,c,t,h,w] + if isinstance(scale[0], torch.Tensor): + z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view( + 1, self.z_dim, 1, 1, 1) + else: + z = z / scale[1] + scale[0] + iter_ = z.shape[2] + x = self.conv2(z) + for i in range(iter_): + self._conv_idx = [0] + if i == 0: + out = self.decoder( + x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx) + else: + out_ = self.decoder( + x[:, :, i:i + 1, :, :], + feat_cache=self._feat_map, + feat_idx=self._conv_idx) + out = torch.cat([out, out_], 2) + return out + + def sample(self, imgs, deterministic=False): + mu, log_var = self.encode(imgs) + if deterministic: + return mu + std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0)) + return mu + std * torch.randn_like(std) + + def clear_cache(self): + self._conv_num = count_conv3d(self.decoder) + self._conv_idx = [0] + self._feat_map = [None] * self._conv_num + # cache encode + self._enc_conv_num = count_conv3d(self.encoder) + self._enc_conv_idx = [0] + self._enc_feat_map = [None] * self._enc_conv_num + + +def _video_vae(pretrained_path=None, z_dim=None, device='cpu', **kwargs): + """ + Autoencoder3d adapted from Stable Diffusion 1.x, 2.x and XL. + """ + # params + cfg = dict( + dim=96, + z_dim=z_dim, + dim_mult=[1, 2, 4, 4], + num_res_blocks=2, + attn_scales=[], + temperal_downsample=[False, True, True], + dropout=0.0) + cfg.update(**kwargs) + + # init model + with torch.device('meta'): + model = WanVAE_(**cfg) + + # load checkpoint + logging.info(f'loading {pretrained_path}') + model.load_state_dict( + torch.load(pretrained_path, map_location=device), assign=True) + + return model + + +class WanVAE: + + def __init__(self, + z_dim=16, + vae_pth='cache/vae_step_411000.pth', + dtype=torch.float, + device="cuda"): + self.dtype = dtype + self.device = device + + mean = [ + -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508, + 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921 + ] + std = [ + 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743, + 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160 + ] + self.mean = torch.tensor(mean, dtype=dtype, device=device) + self.std = torch.tensor(std, dtype=dtype, device=device) + self.scale = [self.mean, 1.0 / self.std] + + # init model + self.model = _video_vae( + pretrained_path=vae_pth, + z_dim=z_dim, + ).eval().requires_grad_(False).to(device) + + def encode(self, videos): + """ + videos: A list of videos each with shape [C, T, H, W]. + """ + with amp.autocast(dtype=self.dtype): + return [ + self.model.encode(u.unsqueeze(0), self.scale).float().squeeze(0) + for u in videos + ] + + def decode(self, zs): + with amp.autocast(dtype=self.dtype): + return [ + self.model.decode(u.unsqueeze(0), + self.scale).float().clamp_(-1, 1).squeeze(0) + for u in zs + ] diff --git a/LongLive-main/wan/modules/xlm_roberta.py b/LongLive-main/wan/modules/xlm_roberta.py new file mode 100644 index 0000000000000000000000000000000000000000..4bd38c1016fdaec90b77a6222d75d01c38c1291c --- /dev/null +++ b/LongLive-main/wan/modules/xlm_roberta.py @@ -0,0 +1,170 @@ +# Modified from transformers.models.xlm_roberta.modeling_xlm_roberta +# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F + +__all__ = ['XLMRoberta', 'xlm_roberta_large'] + + +class SelfAttention(nn.Module): + + def __init__(self, dim, num_heads, dropout=0.1, eps=1e-5): + assert dim % num_heads == 0 + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.eps = eps + + # layers + self.q = nn.Linear(dim, dim) + self.k = nn.Linear(dim, dim) + self.v = nn.Linear(dim, dim) + self.o = nn.Linear(dim, dim) + self.dropout = nn.Dropout(dropout) + + def forward(self, x, mask): + """ + x: [B, L, C]. + """ + b, s, c, n, d = *x.size(), self.num_heads, self.head_dim + + # compute query, key, value + q = self.q(x).reshape(b, s, n, d).permute(0, 2, 1, 3) + k = self.k(x).reshape(b, s, n, d).permute(0, 2, 1, 3) + v = self.v(x).reshape(b, s, n, d).permute(0, 2, 1, 3) + + # compute attention + p = self.dropout.p if self.training else 0.0 + x = F.scaled_dot_product_attention(q, k, v, mask, p) + x = x.permute(0, 2, 1, 3).reshape(b, s, c) + + # output + x = self.o(x) + x = self.dropout(x) + return x + + +class AttentionBlock(nn.Module): + + def __init__(self, dim, num_heads, post_norm, dropout=0.1, eps=1e-5): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.post_norm = post_norm + self.eps = eps + + # layers + self.attn = SelfAttention(dim, num_heads, dropout, eps) + self.norm1 = nn.LayerNorm(dim, eps=eps) + self.ffn = nn.Sequential( + nn.Linear(dim, dim * 4), nn.GELU(), nn.Linear(dim * 4, dim), + nn.Dropout(dropout)) + self.norm2 = nn.LayerNorm(dim, eps=eps) + + def forward(self, x, mask): + if self.post_norm: + x = self.norm1(x + self.attn(x, mask)) + x = self.norm2(x + self.ffn(x)) + else: + x = x + self.attn(self.norm1(x), mask) + x = x + self.ffn(self.norm2(x)) + return x + + +class XLMRoberta(nn.Module): + """ + XLMRobertaModel with no pooler and no LM head. + """ + + def __init__(self, + vocab_size=250002, + max_seq_len=514, + type_size=1, + pad_id=1, + dim=1024, + num_heads=16, + num_layers=24, + post_norm=True, + dropout=0.1, + eps=1e-5): + super().__init__() + self.vocab_size = vocab_size + self.max_seq_len = max_seq_len + self.type_size = type_size + self.pad_id = pad_id + self.dim = dim + self.num_heads = num_heads + self.num_layers = num_layers + self.post_norm = post_norm + self.eps = eps + + # embeddings + self.token_embedding = nn.Embedding(vocab_size, dim, padding_idx=pad_id) + self.type_embedding = nn.Embedding(type_size, dim) + self.pos_embedding = nn.Embedding(max_seq_len, dim, padding_idx=pad_id) + self.dropout = nn.Dropout(dropout) + + # blocks + self.blocks = nn.ModuleList([ + AttentionBlock(dim, num_heads, post_norm, dropout, eps) + for _ in range(num_layers) + ]) + + # norm layer + self.norm = nn.LayerNorm(dim, eps=eps) + + def forward(self, ids): + """ + ids: [B, L] of torch.LongTensor. + """ + b, s = ids.shape + mask = ids.ne(self.pad_id).long() + + # embeddings + x = self.token_embedding(ids) + \ + self.type_embedding(torch.zeros_like(ids)) + \ + self.pos_embedding(self.pad_id + torch.cumsum(mask, dim=1) * mask) + if self.post_norm: + x = self.norm(x) + x = self.dropout(x) + + # blocks + mask = torch.where( + mask.view(b, 1, 1, s).gt(0), 0.0, + torch.finfo(x.dtype).min) + for block in self.blocks: + x = block(x, mask) + + # output + if not self.post_norm: + x = self.norm(x) + return x + + +def xlm_roberta_large(pretrained=False, + return_tokenizer=False, + device='cpu', + **kwargs): + """ + XLMRobertaLarge adapted from Huggingface. + """ + # params + cfg = dict( + vocab_size=250002, + max_seq_len=514, + type_size=1, + pad_id=1, + dim=1024, + num_heads=16, + num_layers=24, + post_norm=True, + dropout=0.1, + eps=1e-5) + cfg.update(**kwargs) + + # init a model on device + with torch.device(device): + model = XLMRoberta(**cfg) + return model diff --git a/benchmarks/edit/code/EditBoard/LICENSE b/benchmarks/edit/code/EditBoard/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0c34ae8e33972792b645520920719af370cdab8 --- /dev/null +++ b/benchmarks/edit/code/EditBoard/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Samchen2003 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/benchmarks/edit/code/EditBoard/README.md b/benchmarks/edit/code/EditBoard/README.md new file mode 100644 index 0000000000000000000000000000000000000000..87718581a9b38b8ffcacc214d39557b6b3187bf8 --- /dev/null +++ b/benchmarks/edit/code/EditBoard/README.md @@ -0,0 +1,174 @@ +# [AAAI 2025] EditBoard: Towards a Comprehensive Evaluation Benchmark for Text-Based Video Editing Models +[AAAI 2025] This is the official repo of the paper "EditBoard, a comprehensive evaluation benchmark for text-based video editing models" [[Paper]](https://arxiv.org/pdf/2409.09668). + +### :book: Table of Contents +- [Installation](#installation) +- [Dataset structure](#data) +- [Usage](#usage) +- [Acknowledgement](#acknowledgement) +- [Citation](#citation) + + +## :hammer: Installation + +~~~bash +conda create -n EditBoard python==3.9 +conda activate EditBoard +pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118 # or other version with CUDA<=12.1 +pip install -r requirements.txt +~~~ + + + +## :file_folder: Dataset Structure + +For any given video, you need to segment it into frames and save all the frames into a directory named after the video. All frames must be resized to 512x512 pixels. To simplify this process, we provide a preprocessing script, `preprocess.py`, which supports MP4 and GIF video formats. + +The command to run the script is: +```bash +python preprocess.py --input_path --output_path +``` +- `--input_path`: The path to the directory containing your videos. +- `--output_path`: The path where the resulting frame directories will be saved. + +Each frame folder will contain all frames from the corresponding video, e.g.: + +``` +dataset/ +├── bear/ +│ ├── frame_00000.png +│ ├── frame_00001.png +│ ├── frame_00002.png +│ └── ... +├── bear_white/ +│ ├── frame_00000.png +│ ├── frame_00001.png +│ └── ... +└── bear_mask/ + ├── frame_00000.png + ├── frame_00001.png + └── ... +``` + +:warning: **Important:** +It is crucial that the corresponding original video, edited video, and semantic_mask folders contain the same number of image frames. + + + +## :rocket: Usage + +We have implemented all nine evaluation dimensions used in our paper: +`["ff_alpha", "ff_beta", "semantic_score", "success_rate", "clip_similarity", 'subject_consistency', 'background_consistency', 'aesthetic_quality', 'imaging_quality']` + +We offer two forms of commands for evaluation: +- **Normal Command** – evaluate one pair of videos at a time. +- **Script Command** – evaluate multiple pairs in batch mode using a CSV or Excel file. + +The final evaluation results will be saved in `{output_path}/{result_name}_eval_results.json`. + + +### Normal Command + +This is a full example for evaluating all nine dimensions on a single pair of videos. + +```bash +python -W ignore evaluate.py \ + --output_path './output/' \ + --result_name "result" \ + --dimension "ff_alpha" "ff_beta" "semantic_score" "success_rate" "clip_similarity" 'subject_consistency' 'background_consistency' 'aesthetic_quality' 'imaging_quality' \ + --original_video_path './sample/bear' \ + --edited_video_path './sample/bear_white' \ + --semantic_mask_path './sample/bear_mask' \ + --source_prompt 'a brown bear walks on rocks' \ + --target_prompt 'a white bear walks on rocks' +``` + + +### Script Command + +This command evaluates multiple pairs in batch mode using a CSV or Excel file. The `--dimension` and `--script` arguments are mandatory. + +```bash +python -W ignore evaluate.py \ + --output_path './output/' \ + --result_name "result" \ + --dimension "ff_alpha" "ff_beta" "semantic_score" "success_rate" "clip_similarity" 'subject_consistency' 'background_consistency' 'aesthetic_quality' 'imaging_quality' \ + --script './sample/script.csv' +``` + +The script file (e.g., `--script`) must be a `.csv` or `.xlsx` file with the following header and format: +| original_video_path | edited_video_path | semantic_mask_path | source_prompt | target_prompt | +|----------------------|------------------|--------------------|----------------|----------------| +| ./sample/bear | ./sample/bear_autumn | ./sample/bear_mask | a brown bear walks on rocks | a brown bear walks on rocks in the autumn | + +An example script file is available at `/EditBoard/sample/script.csv`. + + +### Required Inputs for Each Dimension + +Different dimensions require different input fields. Please ensure all necessary arguments are provided when running evaluation. + +| Dimension | Required Inputs | +|------------|----------------| +| `ff_alpha`, `ff_beta` | `original_video_path`, `edited_video_path` | +| `semantic_score` | `original_video_path`, `edited_video_path`, `semantic_mask_path` | +| `success_rate`, `clip_similarity` | `edited_video_path`, `source_prompt`, `target_prompt` | +| `subject_consistency`, `background_consistency`, `aesthetic_quality`, `imaging_quality` | `edited_video_path` | + +**Example Commands for Each Dimension** + +- **`ff_alpha`, `ff_beta`** + ```bash + python -W ignore evaluate.py \ + --dimension "ff_alpha" "ff_beta" \ + --original_video_path './sample/bear' \ + --edited_video_path './sample/bear_white' + ``` + +- **`semantic_score`** + ```bash + python -W ignore evaluate.py \ + --dimension "semantic_score" \ + --original_video_path './sample/bear' \ + --edited_video_path './sample/bear_white' \ + --semantic_mask_path './sample/bear_mask' + ``` + +- **`success_rate`, `clip_similarity`** + ```bash + python -W ignore evaluate.py \ + --dimension "success_rate" "clip_similarity" \ + --edited_video_path './sample/bear_white' \ + --source_prompt 'a brown bear walks on rocks' \ + --target_prompt 'a white bear walks on rocks' + ``` + +- **`subject_consistency`, `background_consistency`, `aesthetic_quality`, `imaging_quality`** + ```bash + python -W ignore evaluate.py \ + --dimension "subject_consistency" "background_consistency" "aesthetic_quality" "imaging_quality" \ + --edited_video_path './sample/bear_white' + ``` + + + +## :hearts: Acknowledgement + +This project wouldn't be possible without the following open-sourced repositories: [CLIP](https://github.com/openai/CLIP) and [VBench](https://github.com/Vchitect/VBench). + + +## :mailbox: Citation + +If you find this repo useful for your research, please consider citing our work: + +~~~ +@inproceedings{chen2025editboard, + title={Editboard: Towards a comprehensive evaluation benchmark for text-based video editing models}, + author={Chen, Yupeng and Chen, Penglin and Zhang, Xiaoyu and Huang, Yixian and Xie, Qian}, + booktitle={Proceedings of the AAAI Conference on Artificial Intelligence}, + volume={39}, + number={15}, + pages={15975--15983}, + year={2025} +} +~~~ diff --git a/benchmarks/edit/code/EditBoard/evaluate.py b/benchmarks/edit/code/EditBoard/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..360e1861ba82df57f9b2cd749f7aa8235d36ab74 --- /dev/null +++ b/benchmarks/edit/code/EditBoard/evaluate.py @@ -0,0 +1,99 @@ +# export CUDA_VISIBLE_DEVICES=0,1 +# python -W ignore evaluate.py --dimension 'subject_consistency' 'background_consistency' 'aesthetic_quality' 'imaging_quality' --edited_video_path './sample/test' + +# python -W ignore evaluate.py --dimension 'subject_consistency' 'background_consistency' 'aesthetic_quality' 'imaging_quality' "ff_alpha" "ff_beta" "semantic_score" "clip_similarity" "success_rate" --original_video_path './sample/bear' --edited_video_path './sample/bear_white' --semantic_mask_path './sample/bear_mask' --source_prompt 'a brown bear walks on rocks' --target_prompt 'a white bear walks on rocks' +# python -W ignore evaluate.py --dimension 'subject_consistency' 'background_consistency' 'aesthetic_quality' 'imaging_quality' "ff_alpha" "ff_beta" "semantic_score" "clip_similarity" "success_rate" --script './script.csv' +# ff_alpha ! +# ff_beta ! +# semantic_score ! +# clip_similarity +# success_rate + +import torch +import os +from editboard import EditBoard +import argparse +import json + +def parse_args(): + parser = argparse.ArgumentParser(description='EditBoard', formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + "--output_path", + type=str, + default='./output/', + help="output path to save the evaluation results", + ) + parser.add_argument( + "--dimension", + nargs='+', + required=True, + help="list of evaluation dimensions, usage: --dimension ", + ) + parser.add_argument( + "--result_name", + type=str, + default = "result" + ) + + parser.add_argument( + "--original_video_path", + type=str, + help="folder that contains all frames of the original video", + default=None + ) + parser.add_argument( + "--edited_video_path", + type=str, + help="folder that contains all frames of the edited video", + default=None + ) + parser.add_argument( + "--semantic_mask_path", + type=str, + help="folder that contains the semantic mask", + default=None + ) + parser.add_argument( + "--source_prompt", + type=str, + default=None + ) + parser.add_argument( + "--target_prompt", + type=str, + default=None + ) + parser.add_argument( + "--script", + type=str, + default=None, + help="csv or excel are both fine" + ) + + args = parser.parse_args() + return args + +def main(): + args = parse_args() + device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") + print(f"Using {device}") + os.makedirs(args.output_path, exist_ok=True) + my_EditBoard = EditBoard(device, args.output_path) + + print(f'Start EditBoard Evaluation!') + + my_EditBoard.evaluate( + original_video_path = args.original_video_path, + edited_video_path = args.edited_video_path, + semantic_mask_path = args.semantic_mask_path, + source_prompt = args.source_prompt, + target_prompt = args.target_prompt, + + dimension_list = args.dimension, + name = args.result_name, + script = args.script + ) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/edit/code/EditBoard/preprocess.py b/benchmarks/edit/code/EditBoard/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..0131d86383ef777998fe1dcee46a71b4ad42e4c0 --- /dev/null +++ b/benchmarks/edit/code/EditBoard/preprocess.py @@ -0,0 +1,70 @@ +import os +import cv2 +import argparse +from PIL import Image, ImageSequence +from tqdm import tqdm + +def extract_frames_from_mp4(video_path, output_dir): + """Extract frames from an MP4 video.""" + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + print(f"[ERROR] Failed to open video: {video_path}") + return + + count = 0 + while True: + ret, frame = cap.read() + if not ret: + break + frame = cv2.resize(frame, (512, 512)) + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + img = Image.fromarray(frame) + img.save(os.path.join(output_dir, f"frame_{count:04d}.png")) + count += 1 + cap.release() + +def extract_frames_from_gif(gif_path, output_dir): + """Extract frames from a GIF file.""" + with Image.open(gif_path) as im: + count = 0 + for frame in ImageSequence.Iterator(im): + frame = frame.convert("RGB").resize((512, 512)) + frame.save(os.path.join(output_dir, f"frame_{count:04d}.png")) + count += 1 + +def main(args): + input_path = args.input_path + output_path = args.output_path + + if not os.path.exists(output_path): + os.makedirs(output_path) + + video_files = [f for f in os.listdir(input_path) + if f.lower().endswith(('.mp4', '.gif'))] + + if not video_files: + print("[WARNING] No MP4 or GIF files found in the input directory.") + return + + for video_file in tqdm(video_files): + video_name = os.path.splitext(video_file)[0] + video_path = os.path.join(input_path, video_file) + save_dir = os.path.join(output_path, video_name) + os.makedirs(save_dir, exist_ok=True) + + if video_file.lower().endswith('.mp4'): + extract_frames_from_mp4(video_path, save_dir) + elif video_file.lower().endswith('.gif'): + extract_frames_from_gif(video_path, save_dir) + print("All done!") + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Video preprocessing script (supports MP4 and GIF).") + parser.add_argument("--input_path", type=str, required=True, + help="Path to the folder containing videos.") + parser.add_argument("--output_path", type=str, required=True, + help="Path to save extracted frames.") + args = parser.parse_args() + main(args) + +# python preprocess.py --input_path ./test/input --output_path ./test/output diff --git a/benchmarks/edit/code/EditBoard/requirements.txt b/benchmarks/edit/code/EditBoard/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..64eb0ce03c7367ab1f43292a6a235a6932cd76e4 --- /dev/null +++ b/benchmarks/edit/code/EditBoard/requirements.txt @@ -0,0 +1,27 @@ +Pillow +numpy<2.0.0 +matplotlib +timm>=0.9,<=1.0.12 +wheel +cython +tensorboard +scipy +opencv-python +scikit-learn +scikit-image +openai-clip +decord +requests +pyyaml +easydict +pyiqa +lvis +fairscale>=0.4.4 +fvcore +easydict +urllib3 +boto3 +omegaconf +transformers==4.33.2 +pycocoevalcap +openpyxl diff --git a/benchmarks/edit/code/FiVE-Bench/.gitignore b/benchmarks/edit/code/FiVE-Bench/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..74b815a42e77279aa73e7bcf16efe03d570d6c88 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/.gitignore @@ -0,0 +1,96 @@ +# Xcode +.DS_Store +.idea + +# tyte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# data +data/ +outputs/ + +# checkpoints +models/wan-edit/hf/ +models/pyramid-edit/hf/ + +# Model weights and large files +*.pth +*.pt +*.ckpt +*.bin +*.safetensors + +# Video files +*.mp4 +*.avi +*.mov +*.mkv +*.webm + +# Temporary files +*.tmp +*.temp +*~ +.*.swp +.*.swo + +# Logs +*.log +logs/ +*.out + +# Environment and virtual environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IDE files +.vscode/ +*.sublime-project +*.sublime-workspace + +# OS generated files +Thumbs.db +*.lnk + +# Cache directories +.cache/ +__pycache__/ +.pytest_cache/ + +CLAUDE.md \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/INSTALL.md b/benchmarks/edit/code/FiVE-Bench/INSTALL.md new file mode 100644 index 0000000000000000000000000000000000000000..224fd8a0fc67992c1e494dc5f303ec6531e6f6e9 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/INSTALL.md @@ -0,0 +1,160 @@ +# Installation Guide + +## Table of Contents +- [Step 1: Create Conda Environment](#step-1-create-conda-environment) +- [Step 2: Install FiVE-Bench and Dependencies](#step-2-install-five-bench-and-dependencies) + - [Clone FiVE-Bench Repository](#clone-five-bench-repository) + - [Install Co-Tracker and IQA Repos](#install-co-tracker-and-iqa-repos) +- [Step 3: Run FiVE-Bench Evaluation](#step-3-run-five-bench-evaluation) + - [Evaluation Example: Wan-Edit](#evaluation-example-wan-edit) + - [Evaluate Your Own Method](#evaluate-your-own-method) + + + +--- +## Step 1: Create Conda Environment + +```bash +conda create -n five-bench python=3.11 -y +conda activate five-bench +conda install pytorch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 pytorch-cuda=12.1 -c pytorch -c nvidia +``` + +--- + +## Step 2: Install FiVE-Bench and Dependencies + +⭐ After installation, your directory structure should look like this: + +``` +📁 /path/to/code +├── 📁 co-tracker +├── 📁 FiVE-Bench +├── 📁 IQA-PyTorch +``` +Make sure all dependencies for each subproject are installed accordingly. + +> ⚠️ **NOTE:** Replace `/path/to/code` in the [`./config.yaml`](./config.yaml) file with the actual path to your ***code*** directory. + +### ⬇️ Install Co-Tracker and IQA Repos +- Motion Fidelity Score (MFS) @ Co-Tracker: To evaluate temporal consistency using MFS, install [Co-Tracker](https://github.com/facebookresearch/co-tracker) in the following path: `./code/co-tracker`. + ```bash + cd ./code + git clone https://github.com/facebookresearch/co-tracker + cd co-tracker + pip install -e . + pip install matplotlib flow_vis tqdm tensorboard + + + mkdir -p checkpoints + cd checkpoints + # download the offline (single window) model + wget https://huggingface.co/facebook/cotracker3/resolve/main/scaled_offline.pth + cd .. + ``` + + +- Image Quality Assessment (IQA) @ NIQE: To evaluate image quality with NIQE, install [IQA-PyTorch](https://github.com/chaofengc/IQA-PyTorch) under `./code/IQA-PyTorch`. +Then, replace the default `inference_iqa.py` with the version provided in our repo at [`./files/inference_iqa.py`](./files/inference_iqa.py). + + ```bash + # Install with pip + pip install pyiqa + + # Install latest github version + pip uninstall pyiqa # if have older version installed already + pip install git+https://github.com/chaofengc/IQA-PyTorch.git + + # Install with git clone + cd ./code + git clone https://github.com/chaofengc/IQA-PyTorch.git + cd IQA-PyTorch + # pip install -r requirements.txt + python setup.py develop + ``` + + 💡 Don’t forget to replace `inference_iqa.py`: + ```bash + cp ../../files/inference_iqa.py ./inference_iqa.py + ``` + +### ⬇️ Clone FiVE-Bench Repository +Download dataset and install the evaluation code + +```bash +cd ./code +# evaluation code +git clone https://github.com/minghanli/FiVE-Bench.git +pip install -r requirements.txt + +# FiVE-Bench dataset +cd ./FiVE-Bench +git clone https://huggingface.co/datasets/LIMinghan/FiVE-Fine-Grained-Video-Editing-Benchmark +mv FiVE-Fine-Grained-Video-Editing-Benchmark data +unzip bmasks.zip images.zip videos.zip +``` + +The data structure should looks like: + + ```json + 📁 data + ├── 📁 assets/ + ├── 📁 edit_prompt/ + │ ├── 📄 edit1_FiVE.json + │ ├── 📄 edit2_FiVE.json + │ ├── 📄 edit3_FiVE.json + │ ├── 📄 edit4_FiVE.json + │ ├── 📄 edit5_FiVE.json + │ └── 📄 edit6_FiVE.json + ├── 📄 README.md + ├── 📦 bmasks.zip + ├── 📁 bmasks + │ ├── 📁 0001_bus + │ ├── 🖼️ 00001.jpg + │ ├── 🖼️ 00002.jpg + │ ├── 🖼️ ... + │ ├── 📁 ... + ├── 📦 images.zip + ├── 📁 images + │ ├── 📁 0001_bus + │ ├── 🖼️ 00001.jpg + │ ├── 🖼️ 00002.jpg + │ ├── 🖼️ ... + │ ├── 📁 ... + ├── 📦 videos.zip + ├── 📁 videos + │ ├── 🎞️ 0001_bus.mp4 + │ ├── 🎞️ 0002_girl-dog.mp4 + │ ├── 🎞️ ... + ``` + +--- + +## Step 3: Run FiVE-Bench Evaluation + +### 🎯 Evaluation Example: Wan-Edit +As an example, you can run evaluation using the **Wan-Edit** results. We use the edited results in `./data/results/Wan-Edit` with prompts from `./data/edit_prompt/edit5_FiVE.json`. Then run: + +```bash +cd FiVE-Bench +sh scripts/eval_FiVE.sh --annotation_mapping_files "data/edit_prompt/edit5_FiVE.json" --tgt_methods "8_Wan_Edit" +``` + +The evaluation result files should be found in: + + +``` +📁 outputs +├── 📄 edit5_FiVE_evaluation_result_frame_stride8.csv +├── 📄 edit5_FiVE_evaluation_result_frame_stride8_avg.csv +``` + +### 🎯 Evaluate Your Own Method +If you want to evaluate **your own method**, you can modify the following parameters in [`config.yaml`](./config.yaml) and [`evaluation/evaluate.py`](evaluation/evaluate.py): + +- `root_tgt_video_folder`: the root directory where your edited videos are stored +- `all_tgt_video_folders`: a list of subfolders corresponding to your method(s) + +Updating these paths allows the evaluation script to locate and assess your results accordingly. + +--- \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/README.md b/benchmarks/edit/code/FiVE-Bench/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2ead6dc0247794138b48e1cf5cad0bcc11c12561 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/README.md @@ -0,0 +1,260 @@ +# [FiVE-Bench](https://arxiv.org/abs/2503.13684) (ICCV 2025) + +[FiVE-Bench: A Fine-Grained Video Editing Benchmark for Evaluating Emerging Diffusion and Rectified Flow Models](https://arxiv.org/abs/2503.13684) + +> [Minghan Li](https://scholar.google.com/citations?user=LhdBgMAAAAAJ&hl=en)1*, [Chenxi Xie](https://openreview.net/profile?id=%7EChenxi_Xie1)2*, [Yichen Wu](https://scholar.google.com/citations?hl=zh-CN&user=p53r6j0AAAAJ&hl=en)13, [Lei Zhang](https://scholar.google.com/citations?user=tAK5l1IAAAAJ&hl=en)2, [Mengyu Wang](https://scholar.google.com/citations?user=i9B02k4AAAAJ&hl=en)1†
+> 1Harvard University 2The Hong Kong Polytechnic University 3City University of Hong Kong
+> *Equal contribution Corresponding Author + +💜 [Leaderboard](https://huggingface.co/spaces/LIMinghan/FiVE-Bench-leaderboard)   |   +💻 [GitHub](https://github.com/MinghanLi/FiVE-Bench)   |   +🤗 [Hugging Face](https://huggingface.co/datasets/LIMinghan/FiVE-Fine-Grained-Video-Editing-Benchmark)   + +📝 [Project Page](https://sites.google.com/view/five-benchmark)   |   +📰 [Paper](https://arxiv.org/abs/2503.13684)   |   +🎥 [Video Demo](https://sites.google.com/view/five-benchmark)   + + +five-pipe + +--- +## Follow-up Works +- [DNAEdit (NeurIPS25 SpotLight)](https://github.com/xiechenxi99/DNAEdit_code) Direct Noise Alignment for Text-Guided Rectified Flow Editing +- [SplitFlow (NeurIPS25)](https://github.com/Harvard-AI-and-Robotics-Lab/SplitFlow) Flow Decomposition for Inversion-Free Text-to-Image Editing +- [DVRF (CVPR26)](https://arxiv.org/abs/2509.05342) Delta Velocity Rectified Flow for Text-to-Image Editing + +--- +## 📝 TODO List +- [🔜] Add `Wan-Edit` demo page on HF +- [✅ Oct-30-2025] Add [leaderboard](https://huggingface.co/spaces/LIMinghan/FiVE-Bench-leaderboard) support 🔥🔥🔥🔥🔥 +- [✅ Oct-30-2025] Reorganized original results following Wan-Edit naming, kept only MP4s, [Google Drive](https://drive.google.com/file/d/1sNfds0tNrbCVZ5STdzlNiHdGUIe2e8KF/view?usp=sharing ). Thanks @Kunlin Yang. 🔥🔥🔥🔥🔥 +- [✅ Oct-28-2025] [The original results of all comparison methods](https://drive.google.com/drive/folders/1aTrLlUX9ug0vh6itBaDujwFvmlcgh_bE?usp=sharing) reported in the paper have been released for reference. 🔥🔥🔥🔥🔥 +- [✅ Aug-26-2025] Fix two issues: mp4_to_frames_ffmpeg and skip_timestep=17. Raw [quantitative results](results/8_wan_edit) of [`Wan-Edit'](models/wan-edit/) is included. +- [✅ Aug-05-2025] Release [`Wan-Edit'](models/wan-edit/) implementation +- [✅ Aug-05-2025] Release [`Pyramid-Edit`](models/pyramid-edit/) implementation +- [✅ Aug-02-2025] Add Wan-Edit results to HF for eval demo +- [✅ Aug-02-2025] Evaluation code released +- [✅ Mar-31-2025] Dataset uploaded to Hugging Face + +## Human Evaluation Example via Netlify [Link1](https://five-all-models-0.netlify.app/) [Link2](https://five-all-models-1.netlify.app/) + +## 🚀 Submit Your Results + +We welcome contributions! +If you’ve evaluated your method on FiVE-Bench, please share your results so we can include them in the [leaderboard](https://huggingface.co/spaces/LIMinghan/FiVE-Bench-leaderboard). +You can submit via a GitHub Issue or Pull Request following the leaderboard format. + +📩 For large files or additional details, feel free to contact us directly. + + +## 📚 Table of Contents + +- [FiVE-Bench Overview](#-five-bench-overview) +- [Running Your Model on FiVE-Bench](#running-your-model-on-five-bench) + - [Step 1: Download the Dataset and Set Up Evaluation Code](#️-step-1-download-the-dataset-and-set-up-evaluation-code) + - [Step 2: Apply Your Video Editing Method](#-step-2-apply-your-video-editing-method) + - [Step 3: Evaluate Editing Results](#-step-3-evaluate-editing-results) +- [Evaluate Editing Results](#-step-3-evaluate-editing-results) + - [Conventional Metrics](#-1-conventional-metrics-across-six-key-aspects) + - [FiVE-Acc: VLM-Based Metric](#-2-five-acc-a-vlm-based-metric-for-editing-success) +- [Citation](#-citation) +- [Acknowledgement](#️-acknowledgement) + + +--- + +## 📦 FiVE-Bench Overview + +five + +The FiVE-Bench dataset offers a rich, structured benchmark for fine-grained video editing. The dataset includes ***420*** high-quality source-target prompt pairs spanning ***six fine-grained video editing*** tasks: + 1. Object Replacement (Rigid) + 2. Object Replacement (Non-Rigid) + 3. Color Alteration + 4. Material Modification + 5. Object Addition + 6. Object Removal + + +--- +## Running Your Model on FiVE-Bench + +five-bench1 + +--- +### ⬇️ Step 1: Download the Dataset and Set Up Evaluation Code + +- Download the dataset from Hugging Face: 🔗 [FiVE-Bench on Hugging Face](https://huggingface.co/datasets/LIMinghan/FiVE-Fine-Grained-Video-Editing-Benchmark) + +- Follow the instructions in [Installation Guide](INSTALL.md) to download the dataset and install the evaluation code (`FiVE_Bench`). + +- Place the downloaded dataset in the directory: `./FiVE_Bench/data`. The data structure should looks like: + + ```json + 📁 /path/to/code/FiVE_Bench/data + ├── 📁 assets/ + ├── 📁 edit_prompt/ + │ ├── 📄 edit1_FiVE.json + │ ├── 📄 edit2_FiVE.json + │ ├── 📄 edit3_FiVE.json + │ ├── 📄 edit4_FiVE.json + │ ├── 📄 edit5_FiVE.json + │ └── 📄 edit6_FiVE.json + ├── 📄 README.md + ├── 📦 bmasks.zip + ├── 📁 bmasks + │ ├── 📁 0001_bus + │ ├── 🖼️ 00001.jpg + │ ├── 🖼️ 00002.jpg + │ ├── 🖼️ ... + │ ├── 📁 ... + ├── 📦 images.zip + ├── 📁 images + │ ├── 📁 0001_bus + │ ├── 🖼️ 00001.jpg + │ ├── 🖼️ 00002.jpg + │ ├── 🖼️ ... + │ ├── 📁 ... + ├── 📦 videos.zip + ├── 📁 videos + │ ├── 🎞️ 0001_bus.mp4 + │ ├── 🎞️ 0002_girl-dog.mp4 + │ ├── 🎞️ ... + ``` + + +--- +### 🛠️ Step 2: Apply Your Video Editing Method + +Use your video editing method to edit the FiVE-Bench videos based on the provided text prompts and generate the corresponding edited results. + +rf-editing + +Example implementations of our proposed rectified flow (RF)-based video editing methods are provided provided in the [`models/`](models/) directory: + + - **[Pyramid-Edit](models/README.md#pyramid-edit)**: Diffusion-based video editing using Pyramid-Flow architecture + + - **[Wan-Edit](models/README.md#wan-edit)**: Rectified flow-based video editing with Wan2.1-T2V-1.3B model + + +#### Quick Start with Provided Models + + **Run Pyramid-Edit:** + ```bash + # Setup model + cd models/pyramid-edit && mkdir -p hf/pyramid-flow-miniflux + # Download model checkpoint to hf/ directory + bash scripts/run_FiVE.sh + ``` + +**Run Wan-Edit:** +```bash +# Setup model +cd models/wan-edit && mkdir -p hf/Wan2.1-T2V-1.3B +# Download model checkpoint to hf/ directory +bash scripts/run_FiVE.sh +``` + +For detailed setup instructions and configuration options, see the [Models +Documentation](models/README.md). + + + + +--- +### 📊 Step 3: Evaluate Editing Results + +Follow the installation guide in [Installation Guide](INSTALL.md) to get the evaluation results. + +```bash +sh scripts/eval_FiVE.sh +``` +*** + +**Evaluation Support Elements:** + +- **Editing Masks:** Generated using SAM2 to assist in localized metric evaluation. + +- **Editing Instructions:** Structured directives for each source-target pair to guide model behavior. + + +FiVE-Bench provides **comprehensive evaluation** through **two major components**: + +#### 📐 1. Conventional Metrics (Across Six Key Aspects) + +These metrics quantitatively measure various dimensions of video editing quality: + +- **Structure Preservation** +- **Background Preservation** + (PSNR, LPIPS, MSE, SSIM outside the editing mask) +- **Edit Prompt–Image Consistency** + (CLIP similarity on full and masked images) +- **Image Quality Assessment** + ([NIQE](https://github.com/chaofengc/IQA-PyTorch)) +- **Temporal Consistency** + (MFS: [Motion Fidelity Score](https://github.com/diffusion-motion-transfer/diffusion-motion-transfer/blob/main/motion_fidelity_score.py)): +- **Runtime Efficiency** + +five-bench-eval1 + +#### 🤖 2. FiVE-Acc: A VLM-based Metric for Editing Success +We use a vision-language model (VLM) to automatically assess whether the intended edits are reflected in the video outputs by asking it questions about the content. If the source video contains **a swan**, and the target prompt requests **a flamingo**. For the edited video, we ask +- **Yes/No Questions:** + - Is there **a swan** in the video? + - Is there **a flamingo** in the video? + + ✅ The edit is considered successful **only if** the answers are **"No"** to the first question and **"Yes"** to the second. +- **Multiple-choice Questions:** + - What is in the video? a) A swan b) A flamingo + + ✅ The edit is considered successful **if the model selects the correct target object** (e.g., **b) A flamingo**) and avoids selecting the original source object. + +FiVE-Acc evaluates editing success using a vision-language model (VLM) by asking content-related questions: + +- **YN-Acc**: Yes/No question accuracy +- **MC-Acc**: Multiple-choice question accuracy +- **U-Acc**: Union accuracy – success if any question is correct +- **∩-Acc**: Intersection accuracy – success only if all questions are correct +- **FiVE-Acc** ↑: Final score = average of all above metrics (higher is better) + +five-bench-eval2 + + + +### 📚 Citation + +If you use **FiVE-Bench** in your research, please cite us: + +```bibtex +@article{li2025five, + title={Five: A fine-grained video editing benchmark for evaluating emerging diffusion and rectified flow models}, + author={Li, Minghan and Xie, Chenxi and Wu, Yichen and Zhang, Lei and Wang, Mengyu}, + journal={arXiv preprint arXiv:2503.13684}, + year={2025} +} +``` + +Recommended our recent papers on image/video editing: + +```bibtex +@article{xie2025dnaedit, + title={DNAEdit: Direct Noise Alignment for Text-Guided Rectified Flow Editing}, + author={Xie, Chenxi and Li, Minghan and Li, Shuai and Wu, Yuhui and Yi, Qiaosi and Zhang, Lei}, + journal={arXiv preprint arXiv:2506.01430}, + year={2025} # NeurIPS 2025 +} +``` + +```bibtex +@article{beaudouin2025delta, + title={Delta Velocity Rectified Flow for Text-to-Image Editing}, + author={Beaudouin, Gaspard and Li, Minghan and Kim, Jaeyeon and Yoon, Sung-Hoon and Wang, Mengyu}, + journal={arXiv preprint arXiv:2509.05342}, + year={2025} +} +``` + +### ❤️ Acknowledgement + +Part of the code is adapted from [PIE-Bench](https://github.com/cure-lab/PnPInversion), [FlowEdit (ICCV25 Best Student Paper)](https://github.com/fallenshock/FlowEdit), [Pyramid-Flow](https://github.com/jy0205/Pyramid-Flow) and [Wan model](https://github.com/Wan-Video/Wan2.1). +We thank the authors for their excellent work and for making their code publicly available. diff --git a/benchmarks/edit/code/FiVE-Bench/config.yaml b/benchmarks/edit/code/FiVE-Bench/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e064bd029d4dd8d1566f096f4e5fc26c461afd2a --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/config.yaml @@ -0,0 +1,50 @@ +root_tgt_video_folder: data/results +cotracker_model_path: /PHShome/ml1833/code/co-tracker/checkpoints/scaled_offline.pth +IQA_PyTorch_model_path: /PHShome/ml1833/code/IQA-PyTorch +# num frames are fed into VLM for five_acc calculation +five_acc_vlm_num_frames: 4 +five_acc_vlm_model_id: Qwen/Qwen2.5-VL-7B-Instruct + +# evaluation settings +device: cuda +src_image_folder: data/ +frame_stride: 8 +annotation_mapping_files: + - data/edit_prompt/edit1_FiVE.json + - data/edit_prompt/edit2_FiVE.json + - data/edit_prompt/edit3_FiVE.json + - data/edit_prompt/edit4_FiVE.json + - data/edit_prompt/edit5_FiVE.json + - data/edit_prompt/edit6_FiVE.json +metrics: + - structure_distance + - psnr_unedit_part + - lpips_unedit_part + - mse_unedit_part + - ssim_unedit_part + - clip_similarity_source_image + - clip_similarity_target_image + - clip_similarity_target_image_edit_part + - niqe_source_image + - niqe_target_image + - motion_fidelity_score + - motion_fidelity_score_edit_part + - five_acc +tgt_methods: + - 1_TokenFlow + - 2_DMT + - 4-VidToMe + - 5-AnyV2V + - 6-VideoGrain + - 7-Pyramid-Edit + - 8-Wan-Edit +result_path: outputs/evaluation_result.csv +edit_category_list: + - "1" + - "2" + - "3" + - "4" + - "5" + - "6" +evaluate_whole_table: true +evaluate_source_video: true \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/evaluation/evaluate.py b/benchmarks/edit/code/FiVE-Bench/evaluation/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..29b50c9943ec6f04145ad915252dd6994bb0e233 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/evaluation/evaluate.py @@ -0,0 +1,593 @@ +import json +import argparse +import math +import os +import numpy as np +import glob +import csv +import cv2 +import torch +import subprocess +from pathlib import Path +from PIL import Image +from tqdm import tqdm +from omegaconf import OmegaConf + + +from torchvision.io import read_video +from decord import VideoReader, cpu +import imageio + +from metrics_calculator import MetricsCalculator, average_niqe_from_txt + + +def mask_decode(encoded_mask, image_shape=[512,512]): + length = image_shape[0] * image_shape[1] + mask_array = np.zeros((length,)) + + for i in range(0, len(encoded_mask), 2): + splice_len = min(encoded_mask[i+1], length-encoded_mask[i]) + for j in range(splice_len): + mask_array[encoded_mask[i]+j]=1 + + mask_array = mask_array.reshape(image_shape[0], image_shape[1]) + # to avoid annotation errors in boundary + mask_array[0,:]=1 + mask_array[-1,:]=1 + mask_array[:,0]=1 + mask_array[:,-1]=1 + + return mask_array + + + +def calculate_metric(metrics_calculator, metric, src_image, tgt_image, src_mask, tgt_mask,src_prompt,tgt_prompt, + src_image_path, tgt_image_path, src_save_file_niqe, tgt_save_file_niqe): + if metric=="psnr": + return metrics_calculator.calculate_psnr(src_image, tgt_image, None, None) + if metric=="lpips": + return metrics_calculator.calculate_lpips(src_image, tgt_image, None, None) + if metric=="mse": + return metrics_calculator.calculate_mse(src_image, tgt_image, None, None) + if metric=="ssim": + return metrics_calculator.calculate_ssim(src_image, tgt_image, None, None) + if metric=="structure_distance": + return metrics_calculator.calculate_structure_distance(src_image, tgt_image, None, None) + if metric=="psnr_unedit_part": + if (1-src_mask).sum()==0 or (1-tgt_mask).sum()==0: + return "nan" + else: + return metrics_calculator.calculate_psnr(src_image, tgt_image, 1-src_mask, 1-tgt_mask) + if metric=="lpips_unedit_part": + if (1-src_mask).sum()==0 or (1-tgt_mask).sum()==0: + return "nan" + else: + return metrics_calculator.calculate_lpips(src_image, tgt_image, 1-src_mask, 1-tgt_mask) + if metric=="mse_unedit_part": + if (1-src_mask).sum()==0 or (1-tgt_mask).sum()==0: + return "nan" + else: + return metrics_calculator.calculate_mse(src_image, tgt_image, 1-src_mask, 1-tgt_mask) + if metric=="ssim_unedit_part": + if (1-src_mask).sum()==0 or (1-tgt_mask).sum()==0: + return "nan" + else: + return metrics_calculator.calculate_ssim(src_image, tgt_image, 1-src_mask, 1-tgt_mask) + if metric=="structure_distance_unedit_part": + if (1-src_mask).sum()==0 or (1-tgt_mask).sum()==0: + return "nan" + else: + return metrics_calculator.calculate_structure_distance(src_image, tgt_image, 1-src_mask, 1-tgt_mask) + if metric=="psnr_edit_part": + if src_mask.sum()==0 or tgt_mask.sum()==0: + return "nan" + else: + return metrics_calculator.calculate_psnr(src_image, tgt_image, src_mask, tgt_mask) + if metric=="lpips_edit_part": + if src_mask.sum()==0 or tgt_mask.sum()==0: + return "nan" + else: + return metrics_calculator.calculate_lpips(src_image, tgt_image, src_mask, tgt_mask) + if metric=="mse_edit_part": + if src_mask.sum()==0 or tgt_mask.sum()==0: + return "nan" + else: + return metrics_calculator.calculate_mse(src_image, tgt_image, src_mask, tgt_mask) + if metric=="ssim_edit_part": + if src_mask.sum()==0 or tgt_mask.sum()==0: + return "nan" + else: + return metrics_calculator.calculate_ssim(src_image, tgt_image, src_mask, tgt_mask) + if metric=="structure_distance_edit_part": + if src_mask.sum()==0 or tgt_mask.sum()==0: + return "nan" + else: + return metrics_calculator.calculate_structure_distance(src_image, tgt_image, src_mask, tgt_mask) + if metric=="clip_similarity_source_image": + return metrics_calculator.calculate_clip_similarity(src_image, src_prompt,None) + if metric=="clip_similarity_target_image": + return metrics_calculator.calculate_clip_similarity(tgt_image, tgt_prompt,None) + if metric=="clip_similarity_target_image_edit_part": + if tgt_mask.sum()==0: + return "nan" + else: + return metrics_calculator.calculate_clip_similarity(tgt_image, tgt_prompt, tgt_mask) + if metric == "niqe_source_image": + return metrics_calculator.calculate_NIQE(src_save_file_niqe, img_pred_path=src_image_path, img_gt_path=None) + if metric == "niqe_target_image": + return metrics_calculator.calculate_NIQE(tgt_save_file_niqe, img_pred_path=None, img_gt_path=tgt_image_path) + +def calculate_metric_video_level(metrics_calculator, metric, src_video_path, tgt_video_path, + multiple_choice_question=None, source_yes_no_question=None, target_yes_no_question=None, + tgt_prompt=None, tgt_images=None, tgt_word=None, tgt_video_mask=None, + ): + if metric in {"motion_fidelity_score", "motion_fidelity_score_edit_part"}: + return metrics_calculator.calculate_motion_fidelity_score( + src_video_path, tgt_video_path, + video_masks=tgt_video_mask if metric == "motion_fidelity_score_edit_part" else None + ) + elif metric == "five_acc": + return metrics_calculator.calculate_five_acc( + source_yes_no_question, target_yes_no_question, multiple_choice_question, tgt_video_path + ) + else: + raise ValueError(f"Metric {metric} not supported") + + +def list_images(directory): + image_extensions = ('*.png', '*.jpg', '*.jpeg') + + # Create a list to store image paths + image_files = [] + + # Loop through each extension and find matching files + for ext in image_extensions: + image_files.extend(glob.glob(os.path.join(directory, ext))) + + return sorted(image_files) + +def mp4_to_frames_ffmpeg(video_path): + output_dir = video_path.replace(".mp4", "") + os.makedirs(output_dir, exist_ok=True) + + # Use ffmpeg to extract frames + output_pattern = os.path.join(output_dir, "%05d.jpg") # Frame naming pattern + command = [ + "ffmpeg", + "-i", video_path, # Input video file + output_pattern # Output frame pattern + ] + + subprocess.run(command, check=True) + return output_dir + +def calculate_mean(evaluation_result): + if evaluation_result is None: + return "nan" + + # Filter out 'nan' values + non_nan_values = [x for x in evaluation_result if x != "nan" and not math.isnan(x)] + + # If all values are 'nan', return 'nan' + if not non_nan_values: + return "nan" + + # Calculate the mean of non-'nan' values + return sum(non_nan_values) / len(non_nan_values) + + +def main(args, config, all_tgt_video_folders): + annotation_mapping_files = args.annotation_mapping_files + metrics = args.metrics + src_image_folder = args.src_image_folder + tgt_methods = args.tgt_methods + edit_category_list = args.edit_category_list + evaluate_whole_table = args.evaluate_whole_table + frame_stride = args.frame_stride + if args.evaluate_source_video: + tgt_video_folders = { + "source_videos": (os.path.join(src_image_folder, "images"), "") + } + args.result_path = args.result_path.replace(".csv", "_source_videos.csv") + else: + tgt_video_folders = {} + if evaluate_whole_table: + for key in all_tgt_video_folders: + if key[0] in tgt_methods: + tgt_video_folders[key] = all_tgt_video_folders[key] + else: + for key in tgt_methods: + tgt_video_folders[key] = all_tgt_video_folders[key] + + result_path = args.result_path.replace(".csv", f"_frame_stride{frame_stride}.csv") + result_path_name = result_path.split('/')[-1] + result_dir = '/'.join(result_path.split('/')[:-1]) + Path(result_dir).mkdir(parents=True, exist_ok=True) + + metrics_calculator = MetricsCalculator(args.device, config=config) + + result_avg_files = [] + for annotation_mapping_file in tqdm(annotation_mapping_files, desc="Evaluating annotation mapping files", total=len(annotation_mapping_files)): + print(f"evaluating {annotation_mapping_file} ...") + + annotation_mapping_file_name = annotation_mapping_file.split("/")[-1].replace(".json", "") + result_path = os.path.join( + result_dir, + "_".join([annotation_mapping_file_name, result_path_name]) + ) + + with open(result_path,'w',newline="") as f: + csv_write = csv.writer(f) + + csv_head = [] + for tgt_video_folder_key, _ in tgt_video_folders.items(): + for metric in metrics: + if metric in {"five_acc"}: + csv_head.append(f"{tgt_video_folder_key}|{metric}_yes_no") + csv_head.append(f"{tgt_video_folder_key}|{metric}_multi_choice") + csv_head.append(f"{tgt_video_folder_key}|{metric}_union") + csv_head.append(f"{tgt_video_folder_key}|{metric}_inter") + csv_head.append(f"{tgt_video_folder_key}|{metric}") + else: + csv_head.append(f"{tgt_video_folder_key}|{metric}") + + data_row = ["file_id"] + csv_head + csv_write.writerow(data_row) + + with open(annotation_mapping_file, "r") as f: + annotation_file = json.load(f) + + for key, item in tqdm(enumerate(annotation_file), desc="Evaluating videos", total=len(annotation_file)): + if str(item["editing_type_id"]) not in edit_category_list: + continue + + video_name = item["video_name"] + save_dir = str(item["editing_type_id"]) + "_" + item["target_prompt"][:len(item["save_dir"])-2] # item["save_dir"] + source_prompt = item["source_prompt"].replace("[", "").replace("]", "") + target_prompt = item["target_prompt"].replace("[", "").replace("]", "") + # FiVE_acc + # "multiple_choice_question": "Is the cyclist wearing a helmet? \na) Yes \nb) No", + # "source_yes_no_question": "Is the cyclist wearing a helmet in the image?", + # "target_yes_no_question": "Is the cyclist not wearing a helmet in the image?" + if "multiple_choice_question" in item: + multiple_choice_question = item["multiple_choice_question"] + source_yes_no_question = item["source_yes_no_question"] + target_yes_no_question = item["target_yes_no_question"] + else: + multiple_choice_question = None + source_yes_no_question = None + target_yes_no_question = None + + src_video_path = os.path.join(src_image_folder, "images", video_name) + src_image_names = list_images(src_video_path)[::frame_stride] + if args.evaluate_source_video: + src_image_names = src_image_names[:40//frame_stride] + + src_images = [ + Image.open(src_image_name) + for src_image_name in src_image_names + ] + + mask_path = os.path.join(src_image_folder, "bmasks", video_name) + if not os.path.exists(mask_path): + print(f"{video_name}'s mask cannot be found!! Skip ...") + continue + + masks = [] + for src_image_name in src_image_names: + mask = Image.open(os.path.join(mask_path, src_image_name.split('/')[-1])) + + # Convert the mask to a numpy array and ensure it's binary (0 and 1) + # mask = mask_decode(item["mask"]) + mask = np.array(mask) # Convert to numpy array + mask = (mask > 0) + mask = mask[:,:,np.newaxis].repeat([3],axis=2) + masks.append(mask) + + evaluation_result = [key] + + for m_i, (tgt_video_folder_key, (tgt_video_folder, terminal_folder)) in enumerate(tgt_video_folders.items()): + src_save_file_niqe = "_".join([ + result_path.replace(".csv", ""), "niqe_src.txt" + ]) + tgt_save_file_niqe = "_".join([ + result_path.replace(".csv", ""), "niqe_"+tgt_video_folder_key+"_tgt.txt" + ]) + + if not args.evaluate_source_video: + if tgt_video_folder_key != "6_VideoGrain": + tgt_video_name = os.path.join(video_name, save_dir, terminal_folder) # terminal_folder = "image_ode" in TokenFlow + else: + prefix = annotation_mapping_file.split('/')[-1][:5] + assert prefix.startswith("edit") + tgt_video_name = os.path.join(prefix, video_name) + tgt_video_path = os.path.join(tgt_video_folder, tgt_video_name) + else: + tgt_video_path = src_video_path + print(f"\n\nevaluating method: {tgt_video_folder_key}") + + if tgt_video_path.endswith("/"): + tgt_video_path = tgt_video_path[:-1] + tgt_video_path_mp4 = tgt_video_path + '.mp4' + if os.path.exists(tgt_video_path_mp4): + # NOTE: must use ffmpeg!! + tgt_video_path = mp4_to_frames_ffmpeg(tgt_video_path_mp4) + + tgt_image_names = list_images(tgt_video_path) + tgt_image_names = tgt_image_names[::frame_stride] + tgt_images = [] + for f_i, tgt_image_name in enumerate(tgt_image_names): + if tgt_image_name.endswith(".jpg") or tgt_image_name.endswith(".png"): + tgt_image = Image.open(tgt_image_name).resize(src_images[0].size) + tgt_images.append(tgt_image) + + tgt_image_name = os.path.join( + "/".join(tgt_image_name.split('/')[:-1])+"_resize", + os.path.basename(tgt_image_name) + ) + tgt_image_names[f_i] = tgt_image_name + Path("/".join(tgt_image_name.split('/')[:-1])).mkdir(parents=True, exist_ok=True) + tgt_image.save(tgt_image_name) + + for m_j, metric in enumerate(metrics): + if metric in {"niqe_source_image"} and m_i > 0: + continue + + print(f"\nevaluating metric: {metric}") + if len(tgt_images) == 0: + print(f"No images are founded {tgt_video_path}! Skip ...") + if metric in {"five_acc"}: + evaluation_result += ["nan"] * 5 + else: + evaluation_result.append("nan") + continue + + assert len(os.listdir(src_video_path)) > 0 and \ + len(tgt_images) > 0, f"No images are founded!" + + try: + if metric in {"motion_fidelity_score", "motion_fidelity_score_edit_part", "five_acc"}: + if args.evaluate_source_video: + eval_result_ = ( + calculate_metric_video_level( + metrics_calculator, metric, + src_video_path, src_video_path, + multiple_choice_question=multiple_choice_question, + source_yes_no_question=source_yes_no_question, + target_yes_no_question=target_yes_no_question, + tgt_video_mask=masks + ) + ) + else: + eval_result_ = ( + calculate_metric_video_level( + metrics_calculator, metric, + src_video_path, tgt_video_path, + multiple_choice_question=multiple_choice_question, + source_yes_no_question=source_yes_no_question, + target_yes_no_question=target_yes_no_question, + tgt_video_mask=masks + ) + ) + # Five_acc ouputs YN-acc and MC-acc + if metric in {"five_acc"}: + if "nan" in eval_result_: + evaluation_result += ["nan"] * 5 + else: + eval_result_ = list(eval_result_) + evaluation_result_five = [] + for eval_result_s in list(eval_result_): + evaluation_result_five.append(eval_result_s) + evaluation_result_five.append(int(sum(eval_result_) > 0)) + evaluation_result_five.append(int(sum(eval_result_) >= len(eval_result_))) + evaluation_result_five.append(calculate_mean(evaluation_result_five)) + evaluation_result += evaluation_result_five + else: + evaluation_result.append(eval_result_) + + else: + + if metric in {"niqe_source_image", "niqe_target_image"}: + if os.path.exists(src_save_file_niqe if metric == "niqe_source_image" else tgt_save_file_niqe): + os.remove(src_save_file_niqe if metric == "niqe_source_image" else tgt_save_file_niqe) + + evaluation_result_each_frame = [] + for src_image, tgt_image, mask, src_image_path, tgt_image_path, in zip(src_images[:len(tgt_images)], tgt_images, masks, src_image_names[:len(tgt_images)], tgt_image_names): + assert src_image.size[0] == tgt_image.size[0] and src_image.size[1] == tgt_image.size[1], \ + f"{tgt_video_folder_key}: {src_image.size} != {tgt_image.size})" + + if args.evaluate_source_video: + evaluation_result_each_frame.append( + calculate_metric( + metrics_calculator, metric, + src_image, src_image, + mask, mask, + source_prompt, target_prompt, + src_image_path, src_image_path, + src_save_file_niqe, src_save_file_niqe, + ) + ) + else: + evaluation_result_each_frame.append( + calculate_metric( + metrics_calculator, metric, + src_image, tgt_image, + mask, mask, + source_prompt, target_prompt, + src_image_path, tgt_image_path, + src_save_file_niqe, tgt_save_file_niqe, + ) + ) + + if metric in {"niqe_source_image", "niqe_target_image"}: + evaluation_result.append( + average_niqe_from_txt(src_save_file_niqe if metric == "niqe_source_image" else tgt_save_file_niqe) + ) + else: + evaluation_result.append( + calculate_mean(evaluation_result_each_frame) + ) + + except Exception as e: + print(f"Error: {metric}: {e}") + continue + + with open(result_path, 'a+', newline="") as f: + csv_write = csv.writer(f) + csv_write.writerow(evaluation_result) + + # calculate the average of each metric (each column) + with open(result_path, 'r') as f: + reader = list(csv.reader(f)) + header, rows = reader[0], reader[1:] + + avg_row = [] + # Process each column by index to handle rows with different lengths + for col_idx, name in enumerate(header): + print("processing", name) + # Extract column values, handling missing values + col_values = [] + for row in rows: + if col_idx < len(row): + col_values.append(row[col_idx]) + else: + col_values.append("") # Use empty string for missing values + + try: + # Filter out empty strings and convert to float + values = [float(x) for x in col_values if x != "" and x != "nan"] + if values: # Only calculate average if there are valid values + avg = sum(values) / len(values) + if 'structure_distance' in name: + avg *= 1000 + elif 'lpips_' in name: + avg *= 1000 + elif 'mse_' in name: + avg *= 10000 + elif 'ssim_' in name: + avg *= 100 + elif 'motion_fidelity_score' in name: + avg *= 100 + elif name.startswith('five_acc'): + avg *= 100 + avg_row.append(f"{avg:.4f}") + else: + avg_row.append("N/A") + except ValueError: + avg_row.append("N/A") + + result_avg_files.append(result_path.replace('.csv', '_avg.csv')) + with open(result_avg_files[-1], 'w', newline='') as f_out: + writer = csv.writer(f_out) + writer.writerow(header) + writer.writerow(avg_row) + + # average the results in result_avg_files + if result_avg_files: + all_avg_rows = [] + + # Read all average files + for result_avg_file in result_avg_files: + with open(result_avg_file, 'r') as f: + reader = list(csv.reader(f)) + header, rows = reader[0], reader[1:] + if rows: # Make sure there's data + all_avg_rows.append(rows[0]) # Get the average row + + # Calculate final averages across all files + final_avg_row = [] + for col_idx, name in enumerate(header): + print("final averaging", name) + + # Extract values from all average files for this column + col_values = [] + for avg_row in all_avg_rows: + if col_idx < len(avg_row) and avg_row[col_idx] != "N/A": + try: + col_values.append(float(avg_row[col_idx])) + except ValueError: + pass # Skip non-numeric values + + # Calculate final average + if col_values: + final_avg = sum(col_values) / len(col_values) + final_avg_row.append(f"{final_avg:.4f}") + else: + final_avg_row.append("N/A") + + # Write final averaged results + with open(f"{os.path.dirname(result_avg_files[0])}/final_averaged_results.csv", 'w', newline='') as f_out: + writer = csv.writer(f_out) + writer.writerow(header) + writer.writerow(final_avg_row) + + +if __name__=="__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--frame_stride", type=int, default=8) + parser.add_argument('--annotation_mapping_files', nargs = '+', type=str, default=[ + "data/edit_prompt/edit1_FiVE.json", + "data/edit_prompt/edit2_FiVE.json", + "data/edit_prompt/edit3_FiVE.json", + "data/edit_prompt/edit4_FiVE.json", + "data/edit_prompt/edit5_FiVE.json", + "data/edit_prompt/edit6_FiVE.json", + ]) + parser.add_argument('--metrics', nargs = '+', type=str, default=[ + "structure_distance", + "psnr_unedit_part", + "lpips_unedit_part", + "mse_unedit_part", + "ssim_unedit_part", + "clip_similarity_source_image", + "clip_similarity_target_image", + "clip_similarity_target_image_edit_part", + # "niqe_source_image", + "niqe_target_image", + "motion_fidelity_score", + "motion_fidelity_score_edit_part", + "five_acc", + ]) + parser.add_argument('--src_image_folder', type=str, default="data/") + parser.add_argument('--tgt_methods', nargs = '+', type=str, default=[ + # "1_TokenFlow", + # "2_DMT", + # "4_VidToMe", + # "5_AnyV2V", + # "6_VideoGrain", + # "7_Pyramid_Edit", + "8_Wan_Edit", + ]) + parser.add_argument('--result_path', type=str, default="outputs/evaluation_result.csv") + parser.add_argument('--device', type=str, default="cuda") + parser.add_argument('--edit_category_list', nargs = '+', type=str, default=[ + "1", + "2", + "3", + "4", + "5", + "6", + ]) # the editing category that needed to run + parser.add_argument('--evaluate_whole_table', action= "store_true") # rerun existing images + parser.add_argument('--evaluate_source_video', action= "store_true") + parser.add_argument('--config_path', type=str, default="config.yaml") + args = parser.parse_args() + + config = OmegaConf.load(args.config_path) + args_dict = vars(args) + for key, value in args_dict.items(): + if key in config and value is not None: + config[key] = value + + # NOTE: Modify the target video folders here!!!!! + all_tgt_video_folders = { + # "1_TokenFlow": (f"{config.root_tgt_video_folder}/TokenFlow/", "img_ode"), + # "2_DMT": (f"{config.root_tgt_video_folder}/diffusion-motion-transfer/", "result_frames"), + # "4_VidToMe": (f"{config.root_tgt_video_folder}/VidToMe/", "frames"), + # "5_AnyV2V": (f"{config.root_tgt_video_folder}/AnyV2V/Results/Prompt-Based-Editing_frames32/i2vgen-xl", "ddim_init_latents_t_idx_0_nsteps_50_cfg_9.0_pnpf0.2_pnps0.2_pnpt0.5"), + # "6_VideoGrain": (f"{config.root_tgt_video_folder}/video_grain/", ""), + "7_Pyramid_Edit": (f"{config.root_tgt_video_folder}/Pyramid-edit/", "result_all_frames"), + "8_Wan_Edit": (f"{config.root_tgt_video_folder}/Wan-Edit/", ""), + } + + main(args, config, all_tgt_video_folders) \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/evaluation/metrics_calculator.py b/benchmarks/edit/code/FiVE-Bench/evaluation/metrics_calculator.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc47e68a1f0c1983758edbdf362e1c37262f99b --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/evaluation/metrics_calculator.py @@ -0,0 +1,795 @@ +import os +import torch +import imageio +import subprocess +from torchvision.transforms import Resize +from torchvision import transforms +from einops import rearrange +import torch.nn.functional as F +import numpy as np +from PIL import Image +from omegaconf import OmegaConf + +from torchmetrics.multimodal import CLIPScore +from torchmetrics.image import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity +from torchmetrics.regression import MeanSquaredError + +try: + from cotracker.predictor import CoTrackerPredictor + from cotracker.utils.visualizer import read_video_from_path +except: + print("No found cotracker, skipped!") + +from transformers import AutoProcessor, AutoModel +from qwen_vl_utils import process_vision_info + + +def find_images_in_dir(directory): + assert os.path.isdir(directory), f"{directory}" + image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp') + image_files = sorted([ + os.path.join(directory, f) + for f in os.listdir(directory) + if f.lower().endswith(image_extensions) + ]) + return image_files + +def average_niqe_from_txt(save_file): + values = [] + + with open(save_file, 'r') as file: + for line in file: + parts = line.strip().split(",") # Split by comma + if len(parts) == 2: # Ensure there are two parts + try: + values.append(float(parts[1])) # Extract number and convert to float + except ValueError: + continue # Skip lines that do not match expected format + + # Compute the average + average = sum(values) / len(values) if values else 0 + + print(f"Total Number of Frames: {len(values)}, Average NIQE Score: {average}") + + return average + + +class FiVEAcc_Qwen_VL(torch.nn.Module): + def __init__(self, num_frames=4, model_id="Qwen/Qwen2.5-VL-7B-Instruct"): + super().__init__() + + # num frames are fed into Qwen-VL + self.num_frames = num_frames + + # different transformer version + from transformers import Qwen2_5_VLForConditionalGeneration + self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained( + model_id, + torch_dtype=torch.bfloat16, + attn_implementation="flash_attention_2", + device_map="auto", + ) + + # default processer + self.processor = AutoProcessor.from_pretrained(model_id) + + def get_template(self, q, q_type="yes/no"): + if q_type == "yes/no": + input_text = ( + "Answer the following question using only 'YES' or 'NO:\n" + f"{q}" + ) + elif q_type == "multi-choice": + input_text = ( + "Select the correct answer from the given choices, onlyt output the answer:\n" + f"{q}" + ) + else: + raise NotImplementedError + + return input_text + + def run_each_iter(self, text, video_path): + if os.path.isdir(video_path): + video_path = find_images_in_dir(video_path) + + if isinstance(video_path, list): + stride = len(video_path)//(len(video_path)//self.num_frames) + video_path = video_path[int(0.5*stride)::stride] + messages = [ + { + "role": "user", + "content": [ + { + "type": "video", + # "video": [ + # "file:///path/to/frame1.jpg", + # "file:///path/to/frame2.jpg", + # "file:///path/to/frame3.jpg", + # "file:///path/to/frame4.jpg", + # ], + "video": video_path, + }, + {"type": "text", "text": text}, + ], + } + ] + elif video_path.endswith('.mp4'): + messages = [ + { + "role": "user", + "content": [ + { + "type": "video", + # "video": "file:///path/to/video1.mp4", + "video": video_path, + "max_pixels": 360 * 420, + "fps": 1.0, + }, + {"type": "text", "text": text}, + ], + } + ] + else: + assert video_path.endswith('.jpg') or video_path.endswith('png'), \ + f"unsupported file format {video_path}" + messages = [ + { + "role": "user", + "content": [ + { + "type": "image", + # "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg", + "image": video_path, + }, + {"type": "text", "text": text}, + ], + } + ] + + # Preparation for inference + text = self.processor.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True + ) + + image_inputs, video_inputs = process_vision_info(messages) + # image_inputs, video_inputs, video_kwargs = process_vision_info(messages, return_video_kwargs=True) + inputs = self.processor( + text=[text], + images=image_inputs, + videos=video_inputs, + fps=10, ## Important!! + padding=True, + return_tensors="pt", + # **video_kwargs + ) + inputs = inputs.to("cuda") + + # Inference: Generation of the output + generated_ids = self.model.generate(**inputs, max_new_tokens=128) + generated_ids_trimmed = [ + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) + ] + output_text = self.processor.batch_decode( + generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + + return output_text[0] + + + def get_score(self, src_q, tgt_q, multi_choice_q, video_path): + """ + Evaluate answers for source, target, and multiple-choice questions. + + Args: + src_q (str): Source question. + tgt_q (str): Target question. + multi_choice_q (str): Multiple-choice question. + video_path (str): Path to the video file. + + Returns: + tuple: A tuple containing: + - yn_acc (bool): Whether the yes/no answers are correct. + - mc_acc (bool): Whether the multiple-choice answer is correct. + """ + assert tgt_q is not None and multi_choice_q is not None + assert len(tgt_q) > 0 and len(multi_choice_q) > 0 + print(src_q, tgt_q, multi_choice_q) + + try: + # Process multiple-choice question + multi_choice_q = self.get_template(multi_choice_q, q_type="multi-choice") + multi_choice_a = self.run_each_iter(multi_choice_q, video_path) + mc_acc = multi_choice_a.strip()[:1].lower() == "b" # Check if the answer is "B" + print("mc:", multi_choice_a) + + # Process source question + if src_q is not None and len(src_q) > 0: + src_q = self.get_template(src_q, q_type="yes/no") + src_a = self.run_each_iter(src_q, video_path) + print("src_a:", src_a) + src_a_cleaned = src_a.strip()[:2].lower() # Clean and normalize source answer + + # Process target question + tgt_q = self.get_template(tgt_q, q_type="yes/no") + tgt_a = self.run_each_iter(tgt_q, video_path) + print("tgt_a:", tgt_a) + + tgt_a_cleaned = tgt_a.strip()[:3].lower() # Clean and normalize target answer + + # Evaluate yes/no answers + if src_q is not None and len(src_q) > 0: + yn_acc = (src_a_cleaned == "no" and tgt_a_cleaned == "yes") + else: + yn_acc = tgt_a_cleaned == "yes" + print("yn / mc: ", int(yn_acc), int(mc_acc)) + + return int(yn_acc), int(mc_acc) + + except Exception as e: + # Handle unexpected errors gracefully + print(f"An error occurred: {e}") + return "nan", "nan" # Return default values in case of an error + + +class MotionFidelityScore(torch.nn.Module): + def __init__(self, cotracker_model_path): + super().__init__() + + self.model = CoTrackerPredictor(checkpoint=cotracker_model_path) + self.model = self.model.cuda() + + def get_similarity_matrix(self, tracklets1, tracklets2): + displacements1 = tracklets1[:, 1:] - tracklets1[:, :-1] + displacements1 = displacements1 / displacements1.norm(dim=-1, keepdim=True) + + displacements2 = tracklets2[:, 1:] - tracklets2[:, :-1] + displacements2 = displacements2 / displacements2.norm(dim=-1, keepdim=True) + + similarity_matrix = torch.einsum("ntc, mtc -> nmt", displacements1, displacements2).mean(dim=-1) + return similarity_matrix + + def get_score(self, similarity_matrix): + similarity_matrix_eye = similarity_matrix - torch.eye(similarity_matrix.shape[0]).to(similarity_matrix.device) + # for each row find the most similar element + max_similarity, _ = similarity_matrix_eye.max(dim=1) + average_score = max_similarity.mean() + return { + "average_score": average_score.item(), + } + + def read_frames_from_dir(self, dir_path): + """ + Read frames from a directory of images. + + Parameters: + - dir_path (str): Path to the directory containing image frames. + + Returns: + - np.ndarray: A NumPy array of frames, or None if the directory is empty or invalid. + """ + try: + # List all image files in the directory (sorted for consistent ordering) + image_files = sorted( + [os.path.join(dir_path, f) for f in os.listdir(dir_path) if f.lower().endswith(('.png', '.jpg', '.jpeg'))] + ) + if not image_files: + print(f"No image files found in directory: {dir_path}") + return None + + # Load all images into a list + frames = [imageio.imread(img) for img in image_files] + return np.stack(frames) + except Exception as e: + print("Error reading frames from directory:", e) + return None + + def get_tracklets(self, video_path, mask=None, dw8_after_video_vae=False, cut_frames=None): + if video_path.endswith('.mp4'): + video = read_video_from_path(video_path) + else: + assert os.path.isdir(video_path), f'{video_path} must be a dir!' + video = self.read_frames_from_dir(video_path) # t, h, w, 3 + if cut_frames is not None: + video = video[:cut_frames] + + len_video = len(video) + if dw8_after_video_vae: + video = video[::8] # downsampling ratio of video vae + + video = torch.from_numpy(video).permute(0, 3, 1, 2)[None].float().cuda() + pred_tracks_small, pred_visibility_small = self.model(video, grid_size=55, segm_mask=mask) + pred_tracks_small = rearrange(pred_tracks_small, "b t l c -> (b l) t c ") + return pred_tracks_small, len_video + + def calculate_MFS(self, original_video_path, edit_video_path, video_masks=None, dw8_after_video_vae=False): + """ + Args: + video_masks: 0 or 1 mask, 0 for background, 1 for foreground + dw8_after_video_vae: enable downsample 8x, cause video_vae has 8x temporal downsample + + """ + + if video_masks is not None: # calculate trajectories only on the foreground of the video + if isinstance(video_masks, list): + minx_list, maxx_list, miny_list, maxy_list = [], [], [], [] + for segm_mask in video_masks: + if segm_mask.ndim == 3 and segm_mask.shape[-1] == 3: + segm_mask = segm_mask[..., 0] + assert segm_mask.ndim == 2 + if isinstance(segm_mask, np.ndarray): + segm_mask = torch.from_numpy(segm_mask).float() + minx = segm_mask.nonzero(as_tuple=False)[:, 0].min() + maxx = segm_mask.nonzero(as_tuple=False)[:, 0].max() + miny = segm_mask.nonzero(as_tuple=False)[:, 1].min() + maxy = segm_mask.nonzero(as_tuple=False)[:, 1].max() + minx_list.append(minx) + maxx_list.append(maxx) + miny_list.append(miny) + maxy_list.append(maxy) + + # get bounding box mask from segmentation mask - rectangular mask that covers the segmentation mask + minx, maxx = min(minx_list), max(maxx_list) + miny, maxy = min(miny_list), max(maxy_list) + box_mask = torch.zeros_like(segm_mask) + box_mask[minx:maxx, miny:maxy] = 1 + box_mask = box_mask[None, None] + else: + raise ValueError("video_masks must be a list") + + else: + box_mask = None + + edit_tracklets, len_video_edit = self.get_tracklets(edit_video_path, mask=box_mask) + original_tracklets, len_video_ori = self.get_tracklets( + original_video_path, mask=box_mask, dw8_after_video_vae=dw8_after_video_vae, cut_frames=len_video_edit + ) + assert len_video_edit == len_video_ori + + similarity_matrix = self.get_similarity_matrix(edit_tracklets, original_tracklets) + similarity_scores_dict = self.get_score(similarity_matrix) + + return similarity_scores_dict["average_score"] + + + +class VitExtractor: + BLOCK_KEY = 'block' + ATTN_KEY = 'attn' + PATCH_IMD_KEY = 'patch_imd' + QKV_KEY = 'qkv' + KEY_LIST = [BLOCK_KEY, ATTN_KEY, PATCH_IMD_KEY, QKV_KEY] + + def __init__(self, model_name, device): + self.model = torch.hub.load('facebookresearch/dino:main', model_name).to(device) + self.model.eval() + self.model_name = model_name + self.hook_handlers = [] + self.layers_dict = {} + self.outputs_dict = {} + for key in VitExtractor.KEY_LIST: + self.layers_dict[key] = [] + self.outputs_dict[key] = [] + self._init_hooks_data() + self.device=device + + def _init_hooks_data(self): + self.layers_dict[VitExtractor.BLOCK_KEY] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + self.layers_dict[VitExtractor.ATTN_KEY] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + self.layers_dict[VitExtractor.QKV_KEY] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + self.layers_dict[VitExtractor.PATCH_IMD_KEY] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + for key in VitExtractor.KEY_LIST: + # self.layers_dict[key] = kwargs[key] if key in kwargs.keys() else [] + self.outputs_dict[key] = [] + + def _register_hooks(self, **kwargs): + for block_idx, block in enumerate(self.model.blocks): + if block_idx in self.layers_dict[VitExtractor.BLOCK_KEY]: + self.hook_handlers.append(block.register_forward_hook(self._get_block_hook())) + if block_idx in self.layers_dict[VitExtractor.ATTN_KEY]: + self.hook_handlers.append(block.attn.attn_drop.register_forward_hook(self._get_attn_hook())) + if block_idx in self.layers_dict[VitExtractor.QKV_KEY]: + self.hook_handlers.append(block.attn.qkv.register_forward_hook(self._get_qkv_hook())) + if block_idx in self.layers_dict[VitExtractor.PATCH_IMD_KEY]: + self.hook_handlers.append(block.attn.register_forward_hook(self._get_patch_imd_hook())) + + def _clear_hooks(self): + for handler in self.hook_handlers: + handler.remove() + self.hook_handlers = [] + + def _get_block_hook(self): + def _get_block_output(model, input, output): + self.outputs_dict[VitExtractor.BLOCK_KEY].append(output) + + return _get_block_output + + def _get_attn_hook(self): + def _get_attn_output(model, inp, output): + self.outputs_dict[VitExtractor.ATTN_KEY].append(output) + + return _get_attn_output + + def _get_qkv_hook(self): + def _get_qkv_output(model, inp, output): + self.outputs_dict[VitExtractor.QKV_KEY].append(output) + + return _get_qkv_output + + # TODO: CHECK ATTN OUTPUT TUPLE + def _get_patch_imd_hook(self): + def _get_attn_output(model, inp, output): + self.outputs_dict[VitExtractor.PATCH_IMD_KEY].append(output[0]) + + return _get_attn_output + + def get_feature_from_input(self, input_img): # List([B, N, D]) + self._register_hooks() + self.model(input_img) + feature = self.outputs_dict[VitExtractor.BLOCK_KEY] + self._clear_hooks() + self._init_hooks_data() + return feature + + def get_qkv_feature_from_input(self, input_img): + self._register_hooks() + self.model(input_img) + feature = self.outputs_dict[VitExtractor.QKV_KEY] + self._clear_hooks() + self._init_hooks_data() + return feature + + def get_attn_feature_from_input(self, input_img): + self._register_hooks() + self.model(input_img) + feature = self.outputs_dict[VitExtractor.ATTN_KEY] + self._clear_hooks() + self._init_hooks_data() + return feature + + def get_patch_size(self): + return 8 if "8" in self.model_name else 16 + + def get_width_patch_num(self, input_img_shape): + b, c, h, w = input_img_shape + patch_size = self.get_patch_size() + return w // patch_size + + def get_height_patch_num(self, input_img_shape): + b, c, h, w = input_img_shape + patch_size = self.get_patch_size() + return h // patch_size + + def get_patch_num(self, input_img_shape): + patch_num = 1 + (self.get_height_patch_num(input_img_shape) * self.get_width_patch_num(input_img_shape)) + return patch_num + + def get_head_num(self): + if "dino" in self.model_name: + return 6 if "s" in self.model_name else 12 + return 6 if "small" in self.model_name else 12 + + def get_embedding_dim(self): + if "dino" in self.model_name: + return 384 if "s" in self.model_name else 768 + return 384 if "small" in self.model_name else 768 + + def get_queries_from_qkv(self, qkv, input_img_shape): + patch_num = self.get_patch_num(input_img_shape) + head_num = self.get_head_num() + embedding_dim = self.get_embedding_dim() + q = qkv.reshape(patch_num, 3, head_num, embedding_dim // head_num).permute(1, 2, 0, 3)[0] + return q + + def get_keys_from_qkv(self, qkv, input_img_shape): + patch_num = self.get_patch_num(input_img_shape) + head_num = self.get_head_num() + embedding_dim = self.get_embedding_dim() + k = qkv.reshape(patch_num, 3, head_num, embedding_dim // head_num).permute(1, 2, 0, 3)[1] + return k + + def get_values_from_qkv(self, qkv, input_img_shape): + patch_num = self.get_patch_num(input_img_shape) + head_num = self.get_head_num() + embedding_dim = self.get_embedding_dim() + v = qkv.reshape(patch_num, 3, head_num, embedding_dim // head_num).permute(1, 2, 0, 3)[2] + return v + + def get_keys_from_input(self, input_img, layer_num): + qkv_features = self.get_qkv_feature_from_input(input_img)[layer_num] + keys = self.get_keys_from_qkv(qkv_features, input_img.shape) + return keys + + def get_keys_self_sim_from_input(self, input_img, layer_num): + keys = self.get_keys_from_input(input_img, layer_num=layer_num) + h, t, d = keys.shape + concatenated_keys = keys.transpose(0, 1).reshape(t, h * d) + ssim_map = self.attn_cosine_sim(concatenated_keys[None, None, ...]) + return ssim_map + + def attn_cosine_sim(self,x, eps=1e-08): + x = x[0] # TEMP: getting rid of redundant dimension, TBF + norm1 = x.norm(dim=2, keepdim=True) + factor = torch.clamp(norm1 @ norm1.permute(0, 2, 1), min=eps) + sim_matrix = (x @ x.permute(0, 2, 1)) / factor + return sim_matrix + + +class LossG(torch.nn.Module): + def __init__(self, cfg,device): + super().__init__() + + self.cfg = cfg + self.device=device + self.extractor = VitExtractor(model_name=cfg['dino_model_name'], device=device) + + imagenet_norm = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) + global_resize_transform = Resize(cfg['dino_global_patch_size'], max_size=480) + + self.global_transform = transforms.Compose([global_resize_transform, + imagenet_norm + ]) + + self.lambdas = dict( + lambda_global_cls=cfg['lambda_global_cls'], + lambda_global_ssim=0, + lambda_entire_ssim=0, + lambda_entire_cls=0, + lambda_global_identity=0 + ) + + def update_lambda_config(self, step): + if step == self.cfg['cls_warmup']: + self.lambdas['lambda_global_ssim'] = self.cfg['lambda_global_ssim'] + self.lambdas['lambda_global_identity'] = self.cfg['lambda_global_identity'] + + if step % self.cfg['entire_A_every'] == 0: + self.lambdas['lambda_entire_ssim'] = self.cfg['lambda_entire_ssim'] + self.lambdas['lambda_entire_cls'] = self.cfg['lambda_entire_cls'] + else: + self.lambdas['lambda_entire_ssim'] = 0 + self.lambdas['lambda_entire_cls'] = 0 + + def forward(self, outputs, inputs): + self.update_lambda_config(inputs['step']) + losses = {} + loss_G = 0 + + if self.lambdas['lambda_global_ssim'] > 0: + losses['loss_global_ssim'] = self.calculate_global_ssim_loss(outputs['x_global'], inputs['A_global']) + loss_G += losses['loss_global_ssim'] * self.lambdas['lambda_global_ssim'] + + if self.lambdas['lambda_entire_ssim'] > 0: + losses['loss_entire_ssim'] = self.calculate_global_ssim_loss(outputs['x_entire'], inputs['A']) + loss_G += losses['loss_entire_ssim'] * self.lambdas['lambda_entire_ssim'] + + if self.lambdas['lambda_entire_cls'] > 0: + losses['loss_entire_cls'] = self.calculate_crop_cls_loss(outputs['x_entire'], inputs['B_global']) + loss_G += losses['loss_entire_cls'] * self.lambdas['lambda_entire_cls'] + + if self.lambdas['lambda_global_cls'] > 0: + losses['loss_global_cls'] = self.calculate_crop_cls_loss(outputs['x_global'], inputs['B_global']) + loss_G += losses['loss_global_cls'] * self.lambdas['lambda_global_cls'] + + if self.lambdas['lambda_global_identity'] > 0: + losses['loss_global_id_B'] = self.calculate_global_id_loss(outputs['y_global'], inputs['B_global']) + loss_G += losses['loss_global_id_B'] * self.lambdas['lambda_global_identity'] + + losses['loss'] = loss_G + return losses + + def calculate_global_ssim_loss(self, outputs, inputs): + loss = 0.0 + for a, b in zip(inputs, outputs): # avoid memory limitations + a = self.global_transform(a) + b = self.global_transform(b) + with torch.no_grad(): + target_keys_self_sim = self.extractor.get_keys_self_sim_from_input(a.unsqueeze(0), layer_num=11) + keys_ssim = self.extractor.get_keys_self_sim_from_input(b.unsqueeze(0), layer_num=11) + loss += F.mse_loss(keys_ssim, target_keys_self_sim) + return loss + + def calculate_crop_cls_loss(self, outputs, inputs): + loss = 0.0 + for a, b in zip(outputs, inputs): # avoid memory limitations + a = self.global_transform(a).unsqueeze(0).to(self.device) + b = self.global_transform(b).unsqueeze(0).to(self.device) + cls_token = self.extractor.get_feature_from_input(a)[-1][0, 0, :] + with torch.no_grad(): + target_cls_token = self.extractor.get_feature_from_input(b)[-1][0, 0, :] + loss += F.mse_loss(cls_token, target_cls_token) + return loss + + def calculate_global_id_loss(self, outputs, inputs): + loss = 0.0 + for a, b in zip(inputs, outputs): + a = self.global_transform(a) + b = self.global_transform(b) + with torch.no_grad(): + keys_a = self.extractor.get_keys_from_input(a.unsqueeze(0), 11) + keys_b = self.extractor.get_keys_from_input(b.unsqueeze(0), 11) + loss += F.mse_loss(keys_a, keys_b) + return loss + + +class MetricsCalculator: + def __init__(self, device, config) -> None: + self.device=device + self.config = config + self.clip_metric_calculator = CLIPScore(model_name_or_path="openai/clip-vit-large-patch14").to(device) + self.psnr_metric_calculator = PeakSignalNoiseRatio(data_range=1.0).to(device) + self.lpips_metric_calculator = LearnedPerceptualImagePatchSimilarity(net_type='squeeze').to(device) + self.mse_metric_calculator = MeanSquaredError().to(device) + self.ssim_metric_calculator = StructuralSimilarityIndexMeasure(data_range=1.0).to(device) + self.structure_distance_metric_calculator = LossG(cfg={ + 'dino_model_name': 'dino_vitb8', # ['dino_vitb8', 'dino_vits8', 'dino_vitb16', 'dino_vits16'] + 'dino_global_patch_size': 224, + 'lambda_global_cls': 10.0, + 'lambda_global_ssim': 1.0, + 'lambda_global_identity': 1.0, + 'entire_A_every':75, + 'lambda_entire_cls':10, + 'lambda_entire_ssim':1.0 + }, device=device) + + try: + self.motion_fidelity_score_calculator = MotionFidelityScore( + cotracker_model_path=config.cotracker_model_path + ) + except Exception as e: + print("Error: ", e) + print("Failed to load MotionFidelityScore!") + exit() + + try: + self.five_acc_calculator = FiVEAcc_Qwen_VL( + num_frames=config.five_acc_vlm_num_frames, + model_id=config.five_acc_vlm_model_id + ) + except Exception as e: + print("Error: ", e) + print("Failed to load FiVEAcc_Qwen_VL") + exit() + + def calculate_clip_similarity(self, img, txt, mask=None): + img = np.array(img) + + if mask is not None: + mask = np.array(mask) + img = np.uint8(img * mask) + + img_tensor=torch.tensor(img).permute(2,0,1).to(self.device) + + score = self.clip_metric_calculator(img_tensor, txt) + score = score.cpu().item() + + return score + + def calculate_psnr(self, img_pred, img_gt, mask_pred=None, mask_gt=None): + img_pred = np.array(img_pred).astype(np.float32)/255 + img_gt = np.array(img_gt).astype(np.float32)/255 + assert img_pred.shape == img_gt.shape, "Image shapes should be the same." + + if mask_pred is not None: + mask_pred = np.array(mask_pred).astype(np.float32) + img_pred = img_pred * mask_pred + if mask_gt is not None: + mask_gt = np.array(mask_gt).astype(np.float32) + img_gt = img_gt * mask_gt + + img_pred_tensor=torch.tensor(img_pred).permute(2,0,1).unsqueeze(0).to(self.device) + img_gt_tensor=torch.tensor(img_gt).permute(2,0,1).unsqueeze(0).to(self.device) + + score = self.psnr_metric_calculator(img_pred_tensor,img_gt_tensor) + score = score.cpu().item() + + return score + + def calculate_lpips(self, img_pred, img_gt, mask_pred=None, mask_gt=None): + img_pred = np.array(img_pred).astype(np.float32)/255 + img_gt = np.array(img_gt).astype(np.float32)/255 + assert img_pred.shape == img_gt.shape, "Image shapes should be the same." + + if mask_pred is not None: + mask_pred = np.array(mask_pred).astype(np.float32) + img_pred = img_pred * mask_pred + if mask_gt is not None: + mask_gt = np.array(mask_gt).astype(np.float32) + img_gt = img_gt * mask_gt + + img_pred_tensor=torch.tensor(img_pred).permute(2,0,1).unsqueeze(0).to(self.device) + img_gt_tensor=torch.tensor(img_gt).permute(2,0,1).unsqueeze(0).to(self.device) + + score = self.lpips_metric_calculator(img_pred_tensor*2-1, img_gt_tensor*2-1) + score = score.cpu().item() + + return score + + def calculate_mse(self, img_pred, img_gt, mask_pred=None, mask_gt=None): + img_pred = np.array(img_pred).astype(np.float32)/255 + img_gt = np.array(img_gt).astype(np.float32)/255 + assert img_pred.shape == img_gt.shape, "Image shapes should be the same." + + if mask_pred is not None: + mask_pred = np.array(mask_pred).astype(np.float32) + img_pred = img_pred * mask_pred + if mask_gt is not None: + mask_gt = np.array(mask_gt).astype(np.float32) + img_gt = img_gt * mask_gt + + img_pred_tensor=torch.tensor(img_pred).permute(2,0,1).to(self.device) + img_gt_tensor=torch.tensor(img_gt).permute(2,0,1).to(self.device) + + score = self.mse_metric_calculator(img_pred_tensor.contiguous(),img_gt_tensor.contiguous()) + score = score.cpu().item() + + return score + + def calculate_ssim(self, img_pred, img_gt, mask_pred=None, mask_gt=None): + img_pred = np.array(img_pred).astype(np.float32)/255 + img_gt = np.array(img_gt).astype(np.float32)/255 + assert img_pred.shape == img_gt.shape, "Image shapes should be the same." + + if mask_pred is not None: + mask_pred = np.array(mask_pred).astype(np.float32) + img_pred = img_pred * mask_pred + if mask_gt is not None: + mask_gt = np.array(mask_gt).astype(np.float32) + img_gt = img_gt * mask_gt + + img_pred_tensor=torch.tensor(img_pred).permute(2,0,1).unsqueeze(0).to(self.device) + img_gt_tensor=torch.tensor(img_gt).permute(2,0,1).unsqueeze(0).to(self.device) + + score = self.ssim_metric_calculator(img_pred_tensor,img_gt_tensor) + score = score.cpu().item() + + return score + + + def calculate_structure_distance(self, img_pred, img_gt, mask_pred=None, mask_gt=None, use_gpu = True): + img_pred = np.array(img_pred).astype(np.float32) + img_gt = np.array(img_gt).astype(np.float32) + assert img_pred.shape == img_gt.shape, "Image shapes should be the same." + + if mask_pred is not None: + mask_pred = np.array(mask_pred).astype(np.float32) + img_pred = img_pred * mask_pred + if mask_gt is not None: + mask_gt = np.array(mask_gt).astype(np.float32) + img_gt = img_gt * mask_gt + + + img_pred = torch.from_numpy(np.transpose(img_pred, axes=(2, 0, 1))).to(self.device) + img_gt = torch.from_numpy(np.transpose(img_gt, axes=(2, 0, 1))).to(self.device) + img_pred = torch.unsqueeze(img_pred, 0) + img_gt = torch.unsqueeze(img_gt, 0) + + structure_distance = self.structure_distance_metric_calculator.calculate_global_ssim_loss(img_gt, img_pred) + + return structure_distance.data.cpu().numpy() + + def calculate_NIQE(self, save_file, img_pred_path=None, img_gt_path=None, use_gpu=True): + assert img_pred_path is not None or img_gt_path is not None + + model = "NIQE" + image_path = img_pred_path if img_pred_path is not None else img_gt_path + # Construct the command + IQA_PyTorch_model_path = self.config.IQA_PyTorch_model_path + command = f'python {IQA_PyTorch_model_path}/inference_iqa.py -m {model} -t "{image_path}" --save_file "{save_file}"' + print(f"Running command: {command}") + # Run the command and capture output + try: + result = subprocess.run(command, shell=True, capture_output=True, text=True) + except subprocess.CalledProcessError as e: + print(f"Error running command: {e}") + + return "nan" + + def calculate_motion_fidelity_score(self, original_video_path, edit_video_path, video_masks=None, dw8_after_video_vae=False): + return self.motion_fidelity_score_calculator.calculate_MFS( + original_video_path, edit_video_path, video_masks, dw8_after_video_vae + ) + + def calculate_five_acc(self, src_q, tgt_q, multi_choice_q, video_path): + return self.five_acc_calculator.get_score(src_q, tgt_q, multi_choice_q, video_path) \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/files/inference_iqa.py b/benchmarks/edit/code/FiVE-Bench/files/inference_iqa.py new file mode 100644 index 0000000000000000000000000000000000000000..04f7dfb35c60fe589d0deb8d7f8107f33a2db355 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/files/inference_iqa.py @@ -0,0 +1,99 @@ +import argparse +import glob +import os +from pyiqa import create_metric +from tqdm import tqdm +import csv +from time import time + +import torch + + +def main(): + """Inference demo for pyiqa. + """ + parser = argparse.ArgumentParser() + parser.add_argument('-t', '--target', type=str, default=None, help='input image/folder path.') + parser.add_argument('-r', '--ref', type=str, default=None, help='reference image/folder path if needed.') + parser.add_argument('--device', type=str, default=None, help='reference image/folder path if needed.') + parser.add_argument( + '--metric_mode', + type=str, + default='FR', + help='metric mode Full Reference or No Reference. options: FR|NR.') + parser.add_argument('-m', '--metric_name', type=str, default='PSNR', help='IQA metric name, case sensitive.') + parser.add_argument('--save_file', type=str, default=None, help='path to save results.') + + # Add a --verbose flag + parser.add_argument( + '-v', '--verbose', + action='store_true', # This makes it a flag (True when used, False otherwise) + help='Enable verbose output' + ) + + args = parser.parse_args() + + metric_name = args.metric_name.lower() + + # set up IQA model + iqa_model = create_metric(metric_name, metric_mode=args.metric_mode, device=args.device) + metric_mode = iqa_model.metric_mode + + if os.path.isfile(args.target): + input_paths = [args.target] + if args.ref is not None: + ref_paths = [args.ref] + else: + input_paths = sorted(glob.glob(os.path.join(args.target, '*'))) + if args.ref is not None: + ref_paths = sorted(glob.glob(os.path.join(args.ref, '*'))) + + if args.save_file: + sf = open(args.save_file, 'a') + sfwriter = csv.writer(sf) + + avg_score = 0 + test_img_num = len(input_paths) + if metric_name != 'fid': + pbar = tqdm(total=test_img_num, unit='image') + for idx, img_path in enumerate(input_paths): + img_name = os.path.basename(img_path) + if metric_mode == 'FR': + ref_img_path = ref_paths[idx] + else: + ref_img_path = None + + start_time = time() + score = iqa_model(img_path, ref_img_path).cpu().item() + end_time = time() + avg_score += score + pbar.update(1) + pbar.set_description(f'{metric_name} of {img_name}: {score}') + pbar.write(f'{metric_name} of {img_name}: {score}\tTime: {end_time - start_time:.2f}s') + if args.save_file: + sfwriter.writerow([img_path, score]) + + pbar.close() + avg_score /= test_img_num + else: + assert os.path.isdir(args.target), 'input path must be a folder for FID.' + avg_score = iqa_model(args.target, args.ref) + + if args.verbose and torch.cuda.is_available(): + print(torch.cuda.memory_summary()) + + msg = f'Average {metric_name} score of {args.target} with {test_img_num} images is: {avg_score}' + print(msg) + if args.save_file: + sf.close() + + if args.save_file: + print(f'Done! Results are in {args.save_file}.') + else: + print(f'Done!') + + return avg_score + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/models/README.md b/benchmarks/edit/code/FiVE-Bench/models/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7fd135cf838d457abf07d6f7c822d948ca22847b --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/models/README.md @@ -0,0 +1,181 @@ +# FiVE-Bench Video Editing Models + + +This directory contains two state-of-the-art video editing model implementations designed for the FiVE-Bench evaluation framework: + +- **Pyramid-Edit**: A diffusion-based video editing method using the Pyramid-Flow architecture +- **Wan-Edit**: A rectified flow-based video editing approach leveraging the Wan2.1-T2V model + +Both models support fine-grained video editing tasks including object transformations, style changes, background modifications, and temporal consistency preservation across 41-frame sequences. + +rf-editing + +## Environment Setup + +Create and activate the conda environment: + +```bash +conda create -n five-bench python=3.11.10 -y +conda activate five-bench +conda install pytorch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 pytorch-cuda=12.1 -c pytorch -c nvidia +pip install transformers==4.45.2 +pip install -r models/requirements.txt +# Verify flash attention installation +pip install flash-attn==2.7.2.post1 --no-build-isolation +``` + +--- +# Pyramid-Edit + +## Overview + +Pyramid-Edit is a diffusion-based video editing method that leverages the Pyramid-Flow architecture for high-quality, temporally consistent video transformations. + +## Setup: Model Download +```bash +cd models/pyramid-edit +mkdir -p hf +cd hf + +# Download [Pyramid-Flow](https://huggingface.co/rain1011/pyramid-flow-miniflux) model checkpoint +git clone https://huggingface.co/rain1011/pyramid-flow-miniflux +``` + +## Configuration + +Before running Pyramid-Edit, update the configuration file `models/pyramid-edit/config.yaml`: + +```yaml +device: 'cuda' +dtype: 'bf16' +model_name: 'pyramid_flux' # or 'pyramid_mmdit' +model_path: 'models/pyramid-edit/hf/pyramid-flow-miniflux' +resolution: '384p' # or '768p' +max_frames: 41 +``` + +## Running Pyramid-Edit + +### Single Video Editing + +Edit a single video with custom prompts. This processes the bear example video, changing it from brown to purple. + +```bash +# Run single video editing example +bash models/pyramid-edit/scripts/run_single.sh +``` + +### Running on FiVE Dataset + +```bash +bash models/pyramid-edit/scripts/run_FiVE.sh +``` + +--- +# Wan-Edit + +## Overview + +Wan-Edit is a rectified flow-based video editing method built upon the Wan2.1-T2V-1.3B model architecture. This approach provides efficient and high-quality video transformations through: + +- **Rectified flow modeling**: Advanced flow-based generative approach for smoother video transitions +- **Text-to-video capabilities**: Strong text conditioning for precise edit control +- **1.3B parameter efficiency**: Optimized model size balancing performance and resource usage +- **832x480 resolution**: High-definition output suitable for detailed editing tasks + +## Setup: Model Download +```bash +cd models/wan-edit +mkdir hf +# Download [Wan2.1-T2V-1.3B](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B) model checkpoint to `models/wan-edit/hf/` directory +cd hf +git clone https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B +``` + +## Running Wan-Edit on FiVE Dataset + +To run Wan-Edit on the FiVE-Bench dataset: + +```bash +# Run the complete FiVE evaluation script +bash models/wan-edit/scripts/run_FiVE.sh +``` + +This script will: +- Process all editing tasks (edit1 through edit6) in the FiVE-Bench dataset +- Use the Wan2.1-T2V-1.3B model with 832x480 resolution and 41 frames +- Require the model checkpoint in `models/wan-edit/hf/wan13/` +- Save results to `outputs/wan_edit_results/` + +### Manual Execution + +You can also run individual editing tasks manually: + +```bash +sh models/wan-edit/scripts/run_single.sh +``` + +### Custom Parameters + +For advanced usage, you can specify custom parameters: + +```bash +python models/wan-edit/edit.py \ + --task t2v-1.3B \ + --size 832*480 \ + --frame_num 41 \ + --ckpt_dir models/wan-edit/hf/Wan2.1-T2V-1.3B/ \ + --data_dir data \ + --save_dir outputs \ + --FiVE_dataset_json data/edit_prompt/edit5_FiVE.json +``` + +**Parameter Options:** +- `--task`: Model variant (t2v-1.3B) +- `--size`: Output resolution (832*480 recommended) +- `--frame_num`: Number of frames to generate (41 for FiVE-Bench) +- `--ckpt_dir`: Path to model checkpoint directory +- `--data_dir`: Input data directory +- `--save_dir`: Output directory for edited videos +- `--FiVE_dataset_json`: Specific editing task file + +***Note:*** To specify a particular video, use the following arguments: +``` +--video_dir data/examples \ +--video_name blackswan \ +``` + +--- + +# Model Comparison & Selection + +### When to Use Pyramid-Edit +- **High-quality requirements**: Better for applications requiring maximum visual fidelity +- **Flexible resolutions**: When you need both 384p and 768p output options + +### When to Use Wan-Edit +- **Efficiency focused**: Faster inference with 1.3B parameter model +- **Flow-based benefits**: Smoother temporal transitions and more stable generation +- **Text conditioning**: Superior text understanding for complex editing instructions +- **Resource constraints**: Better performance on limited computational resources + +### Performance Characteristics (Wan-Edit > Pyramid-Edit) + +| Aspect | Pyramid-Edit | Wan-Edit | +|--------|--------------|----------| +| **Model Size** | Larger (varies by variant) | 1.3B parameters | +| **Resolution** | 384p/768p | 832x480 | +| **Architecture** | Rectified flow | Rectified flow | +| **Inference Speed** | Slower | Faster | +| **Text Understanding** | Good | Excellent | +| **Memory Usage** | Higher | Lower | + +### Performance Optimization + +**1. GPU Memory Optimization** +- Use `bf16` precision instead of `fp32` +- Reduce `max_frames` if memory limited + +**2. Inference Speed** +- Use single GPU with `CUDA_VISIBLE_DEVICES=0` +- Consider lower resolution for rapid prototyping \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/models/requirements.txt b/benchmarks/edit/code/FiVE-Bench/models/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c554c282afe23bde060e554021eab1f2a971adb --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/models/requirements.txt @@ -0,0 +1,20 @@ +torch>=2.4.0 +torchvision>=0.19.0 +opencv-python>=4.9.0.80 +diffusers>=0.31.0 +transformers>=4.49.0 +tokenizers>=0.20.3 +accelerate>=1.1.1 +flash-attn==2.7.4.post1 +tqdm +imageio +easydict +ftfy +dashscope +imageio-ffmpeg +flash_attn +gradio>=5.0.0 +numpy>=1.23.5,<2 + +IPython +tensorboardX \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/requirements.txt b/benchmarks/edit/code/FiVE-Bench/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..57f610ed94308ff92aa79a12cad25f33ea99f058 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/requirements.txt @@ -0,0 +1,8 @@ +transformers +flash-attn==2.7.4.post1 +Pillow +omegaconf +imageio +einops +torchmetrics +qwen_vl_utils \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit1_FiVE_evaluation_result_frame_stride8_avg.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit1_FiVE_evaluation_result_frame_stride8_avg.csv new file mode 100644 index 0000000000000000000000000000000000000000..d491fcc584893a4f22ad21acbd55d893b7149484 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit1_FiVE_evaluation_result_frame_stride8_avg.csv @@ -0,0 +1,2 @@ +file_id,8_Wan_Edit_iccv|structure_distance,8_Wan_Edit_iccv|psnr_unedit_part,8_Wan_Edit_iccv|lpips_unedit_part,8_Wan_Edit_iccv|mse_unedit_part,8_Wan_Edit_iccv|ssim_unedit_part,8_Wan_Edit_iccv|clip_similarity_source_image,8_Wan_Edit_iccv|clip_similarity_target_image,8_Wan_Edit_iccv|clip_similarity_target_image_edit_part,8_Wan_Edit_iccv|niqe_target_image,8_Wan_Edit_iccv|motion_fidelity_score,8_Wan_Edit_iccv|motion_fidelity_score_edit_part,8_Wan_Edit_iccv|five_acc_yes_no,8_Wan_Edit_iccv|five_acc_multi_choice,8_Wan_Edit_iccv|five_acc_union,8_Wan_Edit_iccv|five_acc_inter,8_Wan_Edit_iccv|five_acc +49.5000,13.5418,24.8160,93.6857,39.6836,82.4478,27.5199,27.4070,21.4084,5.5329,88.3090,84.9133,0.4400,0.6300,0.6300,0.4250,0.5303 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit2_FiVE_evaluation_result_frame_stride8_avg.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit2_FiVE_evaluation_result_frame_stride8_avg.csv new file mode 100644 index 0000000000000000000000000000000000000000..ff46f1eb4f4bd643ce26d4bf0a8d6d6c05f9f145 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit2_FiVE_evaluation_result_frame_stride8_avg.csv @@ -0,0 +1,2 @@ +file_id,8_Wan_Edit_iccv|structure_distance,8_Wan_Edit_iccv|psnr_unedit_part,8_Wan_Edit_iccv|lpips_unedit_part,8_Wan_Edit_iccv|mse_unedit_part,8_Wan_Edit_iccv|ssim_unedit_part,8_Wan_Edit_iccv|clip_similarity_source_image,8_Wan_Edit_iccv|clip_similarity_target_image,8_Wan_Edit_iccv|clip_similarity_target_image_edit_part,8_Wan_Edit_iccv|niqe_target_image,8_Wan_Edit_iccv|motion_fidelity_score,8_Wan_Edit_iccv|motion_fidelity_score_edit_part,8_Wan_Edit_iccv|five_acc_yes_no,8_Wan_Edit_iccv|five_acc_multi_choice,8_Wan_Edit_iccv|five_acc_union,8_Wan_Edit_iccv|five_acc_inter,8_Wan_Edit_iccv|five_acc +49.5000,14.4782,24.5304,96.6331,40.4782,82.2283,27.5199,27.0973,20.0105,5.7286,87.9354,85.6728,0.3500,0.6800,0.6900,0.3400,0.5101 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit3_FiVE_evaluation_result_frame_stride8.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit3_FiVE_evaluation_result_frame_stride8.csv new file mode 100644 index 0000000000000000000000000000000000000000..bd4899f21cc018b28173d977fb2a5ee48a09f64d --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit3_FiVE_evaluation_result_frame_stride8.csv @@ -0,0 +1,101 @@ +file_id,8_Wan_Edit_iccv|structure_distance,8_Wan_Edit_iccv|psnr_unedit_part,8_Wan_Edit_iccv|lpips_unedit_part,8_Wan_Edit_iccv|mse_unedit_part,8_Wan_Edit_iccv|ssim_unedit_part,8_Wan_Edit_iccv|clip_similarity_source_image,8_Wan_Edit_iccv|clip_similarity_target_image,8_Wan_Edit_iccv|clip_similarity_target_image_edit_part,8_Wan_Edit_iccv|niqe_target_image,8_Wan_Edit_iccv|motion_fidelity_score,8_Wan_Edit_iccv|motion_fidelity_score_edit_part,8_Wan_Edit_iccv|five_acc_yes_no,8_Wan_Edit_iccv|five_acc_multi_choice,8_Wan_Edit_iccv|five_acc_union,8_Wan_Edit_iccv|five_acc_inter,8_Wan_Edit_iccv|five_acc +0,0.008863762331505617,27.242191632588703,0.08716761072476704,0.0019048084698927898,0.8566316266854604,24.392577807108562,27.44985357920329,24.589724858601887,5.48927312856355,0.9791669249534607,0.9678874611854553,1,1,1,1,1.0 +1,0.014985848683863878,23.40605068206787,0.10483726859092712,0.00459711622291555,0.7689878344535828,30.66161600748698,31.270147959391277,24.69023895263672,4.569939404133222,0.9840860366821289,0.9711756706237793,1,1,1,1,1.0 +2,0.020522415265440942,25.348332977294923,0.1103984072804451,0.002943013096228242,0.872152316570282,32.15108947753906,30.753874588012696,26.088267517089843,6.4832163347418845,0.8644475936889648,0.8673215508460999,1,1,1,1,1.0 +3,0.015853033401072025,22.909969965616863,0.10375053808093071,0.005186130137493213,0.7968098322550455,27.935168584187824,30.1767479578654,26.03596846262614,4.878341131125089,0.9350965619087219,0.8959293365478516,0,1,1,0,0.5 +4,0.010222014039754868,23.833939870198567,0.1010300728181998,0.0041515432531014085,0.7963367601235708,28.737505276997883,27.15227699279785,20.321300824483234,4.09365485607369,0.5307323932647705,0.5227614045143127,0,0,0,0,0.0 +5,0.0068457409118612604,28.350740432739258,0.12751921763022742,0.0014678924150454502,0.8296490708986918,30.225081125895183,29.57446543375651,19.71474536259969,6.07225939879789,0.9948163628578186,0.9909738898277283,1,1,1,1,1.0 +6,0.02927792693177859,21.02715269724528,0.10841210931539536,0.007981304622565707,0.8208674788475037,24.955354690551758,26.391895294189453,19.165656089782715,5.81018967908174,0.9863970875740051,0.985139787197113,1,1,1,1,1.0 +7,0.008714672876521945,25.09970982869466,0.12453842908143997,0.0031140471498171487,0.8106643656889597,24.226337750752766,26.42649745941162,21.130358695983887,5.178150963291128,0.9170845746994019,0.8730543255805969,1,1,1,1,1.0 +8,0.013994554989039898,24.531094233194988,0.11624655872583389,0.003528409171849489,0.7857620020707449,25.711615244547527,24.001298268636067,21.669422149658203,4.185712161210219,0.9776163101196289,0.934317409992218,0,0,0,0,0.0 +9,0.0037246939803784094,29.752129872639973,0.09227517247200012,0.001063077594153583,0.9201472401618958,28.703993797302246,25.801265080769856,17.558648109436035,6.271216829208544,0.9586907625198364,1,1,1,1,1.0 +10,0.014810778123016158,22.55523745218913,0.1316885525981585,0.0058206622100745635,0.6260571380456289,29.01831817626953,28.967305819193523,22.483672777811687,5.131896497098495,0.9783540964126587,0.8890051245689392,1,1,1,1,1.0 +11,0.031573368391642966,21.686172803243,0.16675454999009767,0.007149383037661512,0.6478840410709381,29.88356653849284,31.232908566792805,23.478565216064453,5.208032420571335,0.9579923152923584,0.9534338116645813,1,1,1,1,1.0 +12,0.011563309157888094,23.729270617167156,0.12896245966355005,0.004252965872486432,0.7012041211128235,29.220608711242676,29.445133209228516,16.206100463867188,4.726436337597938,0.9562647342681885,0.8933427333831787,1,1,1,1,1.0 +13,0.0242981241705517,22.101805051167805,0.129039087643226,0.006332964054308832,0.7212502757708231,27.33162848154704,31.099531809488933,23.0704288482666,5.1718121414322065,0.957238495349884,0.8767493963241577,1,1,1,1,1.0 +14,0.0077372584491968155,23.670730590820312,0.08359453678131104,0.004646620433777571,0.8151728630065918,22.293205642700194,22.48985481262207,18.49806327819824,5.031998314233804,0.9824817180633545,0.935982882976532,1,1,1,1,1.0 +15,0.017139820537219446,20.622181574503582,0.11895813917120297,0.008706394272545973,0.7909459471702576,29.068965276082356,33.72295061747233,28.558852513631184,5.180278136042962,0.9658900499343872,0.9070296883583069,1,1,1,1,1.0 +16,0.011077583767473698,28.01214599609375,0.07390631238619487,0.0017510476851991068,0.9368165532747904,27.39897632598877,29.554242451985676,26.449024200439453,5.601042639034045,0.8917392492294312,0.9046306014060974,1,1,1,1,1.0 +17,0.012387499523659548,27.39865843454997,0.10614390671253204,0.0018225475020396213,0.7752204636732737,28.968124707539875,25.568106333414715,22.46206792195638,5.123786982809581,0.9494721293449402,0.9313268065452576,1,1,1,1,1.0 +18,0.006379944272339344,26.31536293029785,0.08371248965462048,0.002457944598669807,0.8426532447338104,3.0408948858579,1.505237380663554,7.6725233395894366,5.4374315425666895,0.995053231716156,0.9870193004608154,0,0,0,0,0.0 +19,0.015037184736380974,21.94382667541504,0.12126357977588971,0.006402226630598307,0.7146155337492625,30.701362291971844,31.57418664296468,27.99503993988037,4.292205884097666,0.9484382271766663,0.9079626202583313,0,0,0,0,0.0 +20,0.00781143568456173,24.531021499633788,0.08227488994598389,0.003549647377803922,0.8717871189117432,31.37451591491699,32.06961784362793,17.96964454650879,4.733378127316906,0.7104445099830627,0.5832417607307434,1,1,1,1,1.0 +21,0.004993128629090886,28.348488807678223,0.08623648434877396,0.0014671550792021055,0.8371271590391794,30.447711944580078,34.17116928100586,20.0413916905721,5.075849641302404,0.6133549809455872,0.5746639370918274,1,1,1,1,1.0 +22,0.01949926372617483,22.05594253540039,0.11261900514364243,0.006295357675602038,0.7302193840344747,31.082651138305664,30.425357818603516,23.235957145690918,4.986086646015599,0.8104287981987,0.8520113825798035,1,1,1,1,1.0 +23,0.005181873682886362,28.0379425684611,0.06815735871593158,0.0016218571496816974,0.8921942412853241,26.25293477376302,29.774776140848797,24.031861305236816,5.51766083642589,0.9847983717918396,0.9631380438804626,1,1,1,1,1.0 +24,0.014370804652571678,22.132530212402344,0.13005715608596802,0.0061806986729304,0.8317361176013947,7.518662532170613,6.020686229070027,8.36287784576416,5.6077200934084,0.9185180068016052,0.9009989500045776,1,0,1,0,0.5 +25,0.005527257298429807,23.421833038330078,0.0661811102181673,0.004560038136939208,0.867706815401713,1.2621366704503696,1.4600156098604202,9.163902759552002,5.156027854796787,0.4967045783996582,0.598334789276123,0,1,1,0,0.5 +26,0.011959701931724945,22.097095489501953,0.13282755886514983,0.00618890921274821,0.7689104378223419,27.73381773630778,35.28333346048991,24.076462427775066,5.211823214577173,0.9752725958824158,0.9394738674163818,0,0,0,0,0.0 +27,0.0029070377349853516,28.461359977722168,0.08747416237990062,0.001437412342056632,0.876600315173467,26.533513069152832,26.37183157602946,24.995925903320312,6.449441819869722,0.9755066633224487,0.9447429180145264,0,1,1,0,0.5 +28,0.03126057734092077,20.196844418843586,0.17651532838741937,0.00998532601321737,0.6020503143469492,24.916886647542317,26.794891993204754,24.657151222229004,4.812819547008926,0.8896183371543884,0.7518615126609802,0,0,0,0,0.0 +29,0.006094495300203562,22.056484540303547,0.09983412300546964,0.006241751213868459,0.7981200516223907,29.18990675608317,32.3128859202067,20.200106620788574,3.899508938207312,0.3995441198348999,0.37891486287117004,1,1,1,1,1.0 +30,0.009090325329452753,23.837491671244305,0.11923998221755028,0.004135357371220986,0.7267415821552277,29.29452641805013,28.249706268310547,19.6026709874471,4.29230243706724,0.8694116473197937,0.845425546169281,1,1,1,1,1.0 +31,0.011500460095703602,26.01869996388753,0.06684901751577854,0.002528612889970342,0.9193032085895538,31.421629269917805,29.59055010477702,25.523556391398113,7.841255707595216,0.9617377519607544,0.9535399079322815,1,1,1,1,1.0 +32,0.030300589899222057,19.881242116292317,0.16568747411171594,0.010327938478440046,0.6320555508136749,26.57515748341878,25.21391773223877,24.01384512583415,5.060967499933063,0.9415414929389954,0.8395118117332458,1,1,1,1,1.0 +33,0.013931152255584797,23.061490376790363,0.10879974191387494,0.004950466022516291,0.7298567195733389,27.04060935974121,27.363143920898438,27.372808774312336,4.36242521741328,0.98245769739151,0.9647735357284546,0,0,0,0,0.0 +34,0.00809737939077119,26.496832529703777,0.07666208098332088,0.0022755983906487622,0.8989491164684296,30.968846956888836,27.83823521931966,20.35719394683838,6.355633081734802,0.9754848480224609,0.9305881857872009,1,1,1,1,1.0 +35,0.017876124009490013,21.23088264465332,0.10187743231654167,0.007651966297999024,0.7773186465104421,25.228551864624023,23.18557135264079,23.55328114827474,4.047497591588468,0.9839058518409729,0.9655795097351074,1,0,1,0,0.5 +36,0.00426030750774468,29.335322697957356,0.07854844133059184,0.0013598085400493194,0.9593150615692139,32.24213663736979,31.75113836924235,17.25314935048421,7.909506081884896,0.820350170135498,0.8168588876724243,1,1,1,1,1.0 +37,0.01789197496448954,23.0489985148112,0.12361624836921692,0.005124895717017353,0.7718117038408915,28.086151123046875,28.24306011199951,21.543014844258625,5.318547136109905,0.9852244853973389,0.9615675806999207,1,1,1,1,1.0 +38,0.007360621510694425,23.74816131591797,0.0782450878371795,0.004277149603391687,0.8269604444503784,30.519266764322918,30.07240581512451,20.541589101155598,4.453139994054584,0.9785346388816833,0.9780715107917786,0,0,0,0,0.0 +39,0.008430534352858862,26.47765000661214,0.09101444482803345,0.002419938954214255,0.8385024964809418,4.6037605206171675,3.6601544419924417,8.984344244003296,5.608123676543303,0.9814056158065796,0.9640358090400696,1,1,1,1,1.0 +40,0.011435156998534998,24.867025057474773,0.107463122655948,0.0033098204682270684,0.7864600121974945,28.439318974812824,28.539330800374348,21.286439577738445,5.398582529004263,0.9524914026260376,0.9384458661079407,0,1,1,0,0.5 +41,0.009399756323546171,25.192605018615723,0.06680192363758881,0.0030328199888269105,0.8862330317497253,22.742003122965496,21.63046360015869,19.937766075134277,5.641357516584457,0.48836013674736023,0.5616845488548279,0,0,0,0,0.0 +42,0.00639665185008198,26.339874585469563,0.09478864446282387,0.0023950372900192938,0.8224775095780691,26.928987820943195,26.466938018798828,19.064021587371826,5.08154874915528,0.9933294057846069,0.9865040183067322,1,1,1,1,1.0 +43,0.01640929204101364,21.745992024739582,0.13722757995128632,0.007062836084514856,0.7047551472981771,24.006995519002277,24.23998514811198,23.485368092854817,5.07308199990709,0.865090548992157,0.8108181357383728,1,1,1,1,1.0 +44,0.0068381165619939566,27.130933443705242,0.09427825982371967,0.00194989792847385,0.8628991742928823,27.858824412027996,27.664793332417805,21.10363006591797,4.773083628277443,0.6644179224967957,0.6144975423812866,1,1,1,1,1.0 +45,0.014589982883383831,24.351254145304363,0.11938343569636345,0.0037052481590459743,0.7649329602718353,28.864056905110676,23.940778732299805,20.573801676432293,5.081439503738667,0.9477779269218445,0.9638153910636902,0,0,0,0,0.0 +46,0.008840134739875794,25.85515480041504,0.06039526611566544,0.002598364930599928,0.9024637460708618,30.22248077392578,27.646281814575197,26.0933479309082,5.147375583593621,0.511633574962616,0.5359689593315125,0,0,0,0,0.0 +47,0.006439968710765243,24.85166295369466,0.12149710208177567,0.003294357603105406,0.7513461709022522,26.40644709269206,27.04886595408122,23.016517639160156,4.243882573414749,0.9909950494766235,0.9510689973831177,1,1,1,1,1.0 +48,0.012266908151408037,23.87568473815918,0.09498424082994461,0.004174308696140845,0.8801750739415487,27.032498995463055,29.717333793640137,27.76054096221924,6.04997800208384,0.6702553629875183,0.6984960436820984,1,1,1,1,1.0 +49,0.018413945722083252,28.795180956522625,0.09034581109881401,0.0013228499446995556,0.8396509289741516,27.024845759073894,25.648772875467937,17.39916753768921,6.542164836119665,0.9631117582321167,0.958039402961731,1,1,1,1,1.0 +50,0.014715347283830246,26.380004564921062,0.10246034090717633,0.0023310628021135926,0.8704949816068014,29.103871663411457,29.654213587443035,14.669125398000082,6.476998188338279,0.9234800338745117,0.8610273599624634,1,1,1,1,1.0 +51,0.014201891298095385,24.75478394826253,0.1322265019019445,0.0034715142489100495,0.7022332549095154,28.854605356852215,28.835819562276203,25.151236534118652,5.689508810855375,0.9930467009544373,0.9922389984130859,1,0,1,0,0.5 +52,0.01163414865732193,23.815396626790363,0.12290440623958905,0.004203581095983584,0.736370454231898,29.373405774434406,26.290068944295246,21.905941327412922,5.560823956599215,0.9848884344100952,0.967478334903717,1,0,1,0,0.5 +53,0.018228691692153614,21.101582209269207,0.1327777417997519,0.007775505383809407,0.6898466348648071,26.732075373331707,27.676646550496418,20.81358750661214,4.46852184889955,0.9874347448348999,0.9852097630500793,0,0,0,0,0.0 +54,0.01727336955567201,25.584144592285156,0.09047541270653407,0.0027899762305120626,0.8446978231271108,27.7214994430542,27.623308499654133,26.11361249287923,5.361397703063729,0.9451475143432617,0.9247459769248962,0,0,0,0,0.0 +55,0.009730029851198196,25.481332461039226,0.08762322862943013,0.0029646598268300295,0.8852902253468832,24.34856605529785,24.64754295349121,20.784695943196613,5.803067386533176,0.9770873785018921,0.9799769520759583,0,0,0,0,0.0 +56,0.011134346791853508,26.54221185048421,0.11757380266984303,0.0022997377479138472,0.7876871824264526,29.15004762013753,26.133732159932453,24.855818112691242,6.329459875394541,0.9795593023300171,0.9670815467834473,1,1,1,1,1.0 +57,0.008559120974193016,27.19424343109131,0.09020868440469106,0.0019090565425964694,0.866874227921168,28.276838938395183,30.975979169209797,25.486666043599445,5.246375690586425,0.9303715825080872,0.9265558123588562,1,1,1,1,1.0 +58,0.022379426285624504,21.796538988749187,0.1327344812452793,0.007110593297208349,0.7392093340555826,27.07481511433919,27.454990069071453,23.22801907857259,5.51138051199137,0.9458852410316467,0.9493606090545654,1,1,1,1,1.0 +59,0.023533839111526806,25.821789741516113,0.13525382181008658,0.0029450260723630586,0.8101143538951874,26.27460289001465,27.008662859598797,23.80077854792277,5.830997028952983,0.9961020350456238,0.9953836798667908,1,1,1,1,1.0 +60,0.01655312937994798,23.95120334625244,0.1151922419667244,0.004192118610565861,0.7742748359839121,32.586317698160805,32.8624963760376,23.889233589172363,4.875796501703195,0.9835261702537537,0.9189434051513672,1,1,1,1,1.0 +61,0.013843497882286707,24.752488136291504,0.09533997997641563,0.0033596889891972146,0.838021437327067,28.74448045094808,29.570001284281414,25.785582224527996,4.458106842059614,0.9488560557365417,0.8370746970176697,0,0,0,0,0.0 +62,0.017612596818556387,22.076740582784016,0.13995479047298431,0.006388821716730793,0.7628119985262553,27.203686714172363,26.631879806518555,22.01751136779785,5.569368150300882,0.6784185767173767,0.6768729090690613,1,1,1,1,1.0 +63,0.0084435629658401,25.019101715087892,0.07643206715583802,0.003257610648870468,0.7861944675445557,27.78900489807129,25.33927345275879,16.71379280090332,5.525586930333542,0.9399170279502869,0.935804545879364,1,1,1,1,1.0 +64,0.00883598749836286,23.914303461710613,0.08730167771379153,0.004075661301612854,0.8451838294665018,26.372241338094074,27.31495539347331,24.768689791361492,5.135151376481463,0.9269061088562012,0.8062129616737366,1,1,1,1,1.0 +65,0.011434191837906837,29.348992347717285,0.08009189243117969,0.0011872709340726335,0.9186850984891256,27.485953330993652,27.945274988810223,19.412829875946045,7.088823935539019,0.9833784103393555,0.9778482913970947,0,0,0,0,0.0 +66,0.008210604855169853,28.122532844543457,0.0907301592330138,0.001570854588256528,0.8848133186499277,31.831198692321777,31.877997080485027,24.03254763285319,5.960475420585884,0.8750476837158203,0.8525258302688599,1,1,1,1,1.0 +67,0.022190910950303077,28.72708625793457,0.07041625082492828,0.0013419965980574489,0.9201701879501343,27.572897338867186,29.26319465637207,22.917581939697264,6.608908982728755,0.8346788287162781,0.8018936514854431,1,1,1,1,1.0 +68,0.005013105226680636,28.235042572021484,0.09217516208688419,0.0015052836194323997,0.8424923618634542,29.05566469828288,26.799057960510254,19.392601648966473,5.177269934422446,0.9580981135368347,0.933074414730072,1,1,1,1,1.0 +69,0.012844595747689405,23.349530855814617,0.12475643927852313,0.004664977081120014,0.782996674378713,27.930469512939453,30.794464111328125,21.208877881368,5.205006119691141,0.9850793480873108,0.9658352732658386,1,1,1,1,1.0 +70,0.017375843754659098,21.929080963134766,0.13989567508300146,0.006484112469479442,0.7683617174625397,31.10748227437337,29.421685218811035,26.905345280965168,4.995406949608624,0.7784881591796875,0.8601731657981873,1,0,1,0,0.5 +71,0.015330780996009707,22.227619647979736,0.09791448339819908,0.0059930532006546855,0.7442055642604828,31.999398231506348,32.35163640975952,19.620790481567383,4.6500028633624115,0.8382232785224915,0.8504642248153687,0,1,1,0,0.5 +72,0.006935520485664408,24.71207269032796,0.09139794980486234,0.0033850694308057427,0.8514002958933512,26.673309961954754,27.734192848205566,18.597095489501953,5.424196726820543,0.965009331703186,0.9427921772003174,1,1,1,1,1.0 +73,0.015568260569125414,23.30219268798828,0.10738456870118777,0.004687022029732664,0.8038560549418131,29.030211448669434,26.918328285217285,24.62320899963379,4.15618291551757,0.9659486413002014,0.9130391478538513,0,0,0,0,0.0 +74,0.007255812796453635,25.080684343973797,0.04839044560988744,0.0031107263639569283,0.8484437763690948,32.812037785847984,35.28469657897949,27.117706298828125,5.102093707162614,0.9494503736495972,0.9259398579597473,1,1,1,1,1.0 +75,0.006703637540340424,30.075318654378254,0.040702142442266144,0.0010186080471612513,0.9534165759881338,25.356762568155926,25.777723630269367,25.88163725535075,9.26612555448495,0.7295007109642029,0.7713027596473694,0,0,0,0,0.0 +76,0.00997723739904662,29.71405251820882,0.059687680254379906,0.0012077190913259983,0.91804767648379,30.228810628255207,31.709729194641113,22.47644583384196,8.95998184959,0.7510836720466614,0.8086181282997131,1,1,1,1,1.0 +77,0.005727542797103524,32.652612368265785,0.02596285504599412,0.0005456401268020272,0.9636962215105692,29.053016026814777,27.72802480061849,24.127766927083332,7.41200737257578,0.46365347504615784,0.5741716027259827,0,0,0,0,0.0 +78,0.010947276062021652,27.82960033416748,0.06197756715118885,0.0016666789112302165,0.8905684451262156,32.304396311442055,33.216315587361656,26.00407600402832,7.173390932856247,0.8025807738304138,0.8876403570175171,0,1,1,0,0.5 +79,0.007619543699547648,27.29402192433675,0.04930800385773182,0.0018768296965087454,0.9132302502791086,32.37559986114502,31.613368034362793,23.152206420898438,6.492474713397217,0.7497844696044922,0.8590495586395264,1,1,1,1,1.0 +80,0.0120280214274923,25.233873685201008,0.06670869328081608,0.003037448118751248,0.8924416800340017,30.36746311187744,29.494914054870605,21.88509178161621,7.296781271959873,0.9511028528213501,0.8543269038200378,0,0,0,0,0.0 +81,0.006463012347618739,24.171536763509113,0.05153912678360939,0.003830488189123571,0.8428273797035217,29.705933570861816,28.522823651631672,20.50098705291748,4.701446877614403,0.9447121620178223,0.9441908597946167,0,0,0,0,0.0 +82,0.0047371818994482355,28.904327392578125,0.04709241477151712,0.0012924725500245888,0.8933999538421631,27.91925271352132,29.19222132364909,21.43847433725993,6.220751475679292,0.856428861618042,0.7831984758377075,1,1,1,1,1.0 +83,0.009077229847510656,24.07368055979411,0.06621211518843968,0.004011726472526789,0.8615903457005819,29.05754025777181,32.17453130086263,21.419034957885742,6.024328617878871,0.9286339282989502,0.9230349659919739,1,1,1,1,1.0 +84,0.007478215188408892,25.915973663330078,0.04548630925516287,0.0025710390570263066,0.8811169366041819,29.817204475402832,27.84015464782715,17.09959125518799,5.45766748993426,0.536878764629364,0.5646027326583862,1,0,1,0,0.5 +85,0.005641483934596181,25.433529535929363,0.04836257671316465,0.0028874579972277084,0.9143908520539602,28.446220715840656,27.44336986541748,20.137630462646484,5.889611840371256,0.8880037665367126,0.876376748085022,0,0,0,0,0.0 +86,0.005948797411595781,26.06330458323161,0.0398928119490544,0.0025252215176199875,0.8870015740394592,30.81200663248698,31.09135850270589,20.680429458618164,8.029185108259705,0.8904093503952026,0.7018168568611145,0,0,0,0,0.0 +87,0.008175080254053077,25.682332038879395,0.05208245478570461,0.002716855456431707,0.8678895731767019,24.649881680806477,29.321034749348957,26.748883565266926,5.516880282535844,0.889674961566925,0.9005635380744934,1,1,1,1,1.0 +88,0.006081449644019206,27.09944788614909,0.039354764545957245,0.0019785986126710973,0.926688571770986,29.61598300933838,28.98144467671712,21.247800827026367,4.876201553668498,0.8617936968803406,0.8757996559143066,0,0,0,0,0.0 +89,0.009467145738502344,24.62225914001465,0.06520125394066174,0.0038409227272495627,0.8835998276869456,31.196261723836262,29.545438130696613,24.861828168233234,6.788155931585735,0.9829432964324951,0.9425272941589355,0,0,0,0,0.0 +90,0.004181167692877352,27.11971124013265,0.052782388404011726,0.0019979632925242186,0.9008340338865916,29.644922574361164,28.283361434936523,19.66211446126302,6.339577368886569,0.8933062553405762,0.8846214413642883,0,0,0,0,0.0 +91,0.009801171720027924,28.277531623840332,0.04067959822714329,0.0015226280859981973,0.948495477437973,29.28541660308838,30.348828951517742,25.631128629048664,8.740190642806484,0.9311043620109558,0.8364508748054504,0,0,0,0,0.0 +92,0.012831083033233881,30.42771625518799,0.04913473750154177,0.001000646618194878,0.8771771291891733,29.552697499593098,27.599026044209797,25.57474644978841,8.129509009747958,0.9679820537567139,0.9498865604400635,0,0,0,0,0.0 +93,0.006000093029191096,29.12375831604004,0.0383146038899819,0.001224366753983001,0.9069607158501943,27.84822146097819,29.5878807703654,27.71625868479411,6.810769721492046,0.9689080119132996,0.9550468921661377,0,0,0,0,0.0 +94,0.005347435052196185,30.135973294576008,0.023137847582499187,0.0009729100080827872,0.9417470892270406,27.95263735453288,29.49114449818929,29.899800936381023,6.118181914323696,0.9929471015930176,0.9907607436180115,1,1,1,1,1.0 +95,0.007240258622914553,28.354950269063313,0.04583430786927541,0.0014820564538240433,0.9150031606356303,28.41052182515462,28.13699754079183,19.787895838419598,8.2419334844604,0.9229099750518799,0.8673171401023865,1,1,1,1,1.0 +96,0.00415494591773798,25.778567632039387,0.04751480929553509,0.0026543543208390474,0.8736743032932281,25.53180185953776,21.633715947469074,19.090976079305012,4.016586801477874,0.8838784098625183,0.765005350112915,0,0,0,0,0.0 +97,0.005532221480583151,28.234771728515625,0.037463175132870674,0.0015077995291600625,0.9166989823182424,26.79162057240804,27.961151440938313,25.488391876220703,5.319468567367832,0.6076847910881042,0.5727985501289368,0,0,0,0,0.0 +98,0.007436523136372368,25.280262629191082,0.06671673183639844,0.0029691319602231183,0.8329208294550577,32.617099126180015,32.245500246683754,25.971692085266113,6.963601153831193,0.9906388521194458,0.9671503305435181,0,1,1,0,0.5 +99,0.010741045698523521,23.797549883524578,0.06209866267939409,0.0041838487377390265,0.8569163282712301,31.89664363861084,31.337905248006184,24.21193790435791,4.86520607507166,0.9273481965065002,0.9150086045265198,0,0,0,0,0.0 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit3_FiVE_evaluation_result_frame_stride8_avg.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit3_FiVE_evaluation_result_frame_stride8_avg.csv new file mode 100644 index 0000000000000000000000000000000000000000..929edf370f87f2a94ad0bdc8793eecebda2d4759 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit3_FiVE_evaluation_result_frame_stride8_avg.csv @@ -0,0 +1,2 @@ +file_id,8_Wan_Edit_iccv|structure_distance,8_Wan_Edit_iccv|psnr_unedit_part,8_Wan_Edit_iccv|lpips_unedit_part,8_Wan_Edit_iccv|mse_unedit_part,8_Wan_Edit_iccv|ssim_unedit_part,8_Wan_Edit_iccv|clip_similarity_source_image,8_Wan_Edit_iccv|clip_similarity_target_image,8_Wan_Edit_iccv|clip_similarity_target_image_edit_part,8_Wan_Edit_iccv|niqe_target_image,8_Wan_Edit_iccv|motion_fidelity_score,8_Wan_Edit_iccv|motion_fidelity_score_edit_part,8_Wan_Edit_iccv|five_acc_yes_no,8_Wan_Edit_iccv|five_acc_multi_choice,8_Wan_Edit_iccv|five_acc_union,8_Wan_Edit_iccv|five_acc_inter,8_Wan_Edit_iccv|five_acc +49.5000,11.6256,25.3154,90.8494,35.8234,82.9536,27.5199,27.6324,22.0755,5.6553,88.6007,86.6405,0.6100,0.6200,0.6800,0.5500,0.6111 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit4_FiVE_evaluation_result_frame_stride8.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit4_FiVE_evaluation_result_frame_stride8.csv new file mode 100644 index 0000000000000000000000000000000000000000..cba49a713f2fa7d143b58febd3994364568140af --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit4_FiVE_evaluation_result_frame_stride8.csv @@ -0,0 +1,101 @@ +file_id,8_Wan_Edit_iccv|structure_distance,8_Wan_Edit_iccv|psnr_unedit_part,8_Wan_Edit_iccv|lpips_unedit_part,8_Wan_Edit_iccv|mse_unedit_part,8_Wan_Edit_iccv|ssim_unedit_part,8_Wan_Edit_iccv|clip_similarity_source_image,8_Wan_Edit_iccv|clip_similarity_target_image,8_Wan_Edit_iccv|clip_similarity_target_image_edit_part,8_Wan_Edit_iccv|niqe_target_image,8_Wan_Edit_iccv|motion_fidelity_score,8_Wan_Edit_iccv|motion_fidelity_score_edit_part,8_Wan_Edit_iccv|five_acc_yes_no,8_Wan_Edit_iccv|five_acc_multi_choice,8_Wan_Edit_iccv|five_acc_union,8_Wan_Edit_iccv|five_acc_inter,8_Wan_Edit_iccv|five_acc +0,0.009234070312231779,27.20557912190755,0.087762251496315,0.0019116738888745506,0.859298994143804,24.392577807108562,25.09801991780599,20.990111351013184,5.412631991112459,0.9797719717025757,0.9737869501113892,0,0,0,0,0.0 +1,0.0147265267247955,23.899951299031574,0.10025192300478618,0.0041308463939155144,0.775944987932841,30.66161600748698,27.475185712178547,23.69983704884847,4.619168043102744,0.9835245013237,0.9718006253242493,1,1,1,1,1.0 +2,0.014001969434320926,25.436225128173827,0.09728550463914871,0.002865128219127655,0.8734628438949585,32.15108947753906,31.28564567565918,26.96930694580078,6.118921682297523,0.8259152173995972,0.8141031861305237,1,1,1,1,1.0 +3,0.015026690438389778,23.175705591837566,0.1014607014755408,0.004863752944705387,0.8001672923564911,27.935168584187824,31.082658131917317,25.96046193440755,4.905505595266857,0.9425370097160339,0.903436541557312,1,1,1,1,1.0 +4,0.008016970784713825,24.639446258544922,0.09471103549003601,0.0034432246272141733,0.8084881603717804,28.737505276997883,26.124155680338543,22.470960934956867,4.108992119620638,0.5389347076416016,0.5406432747840881,0,0,0,0,0.0 +5,0.006002322227383654,28.42022132873535,0.12507997329036394,0.001444829647274067,0.8331765532493591,30.225081125895183,29.014922459920246,20.70589256286621,6.173826984089356,0.9961042404174805,0.9937044978141785,0,0,0,0,0.0 +6,0.021695442808171112,22.00956662495931,0.11144901812076569,0.006307088537141681,0.8262020746866862,24.955354690551758,26.83862845102946,20.387393951416016,5.8745368454143785,0.9857106804847717,0.9846876263618469,0,0,0,0,0.0 +7,0.009912400894487897,24.55308437347412,0.12919394299387932,0.0035751662217080593,0.8063159982363383,24.226337750752766,25.856436093648274,20.7081462542216,5.167913691961821,0.9173034429550171,0.9154210090637207,0,0,0,0,0.0 +8,0.01508921446899573,24.512745539347332,0.11942453434069951,0.0035432177052522698,0.7797899047533671,25.711615244547527,24.443067868550617,23.522386868794758,4.191629475333607,0.9747851490974426,0.9270278215408325,1,0,1,0,0.5 +9,0.003479416365735233,30.206162134806316,0.09265154227614403,0.0009551227461391439,0.9187588095664978,28.703993797302246,25.353814125061035,14.533433596293131,6.147538933912948,0.9654083847999573,0,0,0,0,0.0 +10,0.010959123106052479,23.752578417460125,0.12493059287468593,0.004306447381774585,0.6775109867254893,29.01831817626953,29.366946856180828,23.868986129760742,5.097816242965764,0.9918071627616882,0.9578754305839539,0,0,0,0,0.0 +11,0.009869079726437727,24.26870123545329,0.12949707607428232,0.00375566065000991,0.7378445267677307,29.88356653849284,29.94364134470622,21.365473747253418,5.021263601865585,0.9787142872810364,0.9726738333702087,0,0,0,0,0.0 +12,0.009694326358536879,23.985336303710938,0.12959938993056616,0.004022925742901862,0.7016014158725739,29.220608711242676,28.283912022908527,17.51332441965739,4.662871180192809,0.9581417441368103,0.8872784972190857,0,0,0,0,0.0 +13,0.02272589908291896,22.814481735229492,0.12555474787950516,0.005402344938678046,0.7429708441098531,27.33162848154704,29.55991840362549,20.3292334874471,5.184691329064045,0.9568833708763123,0.8870145082473755,0,0,0,0,0.0 +14,0.009453296009451152,24.091210174560548,0.08015917539596558,0.004103998886421323,0.8350111246109009,22.293205642700194,25.98193473815918,22.539147567749023,5.147729343884675,0.9757446050643921,0.9216116666793823,0,1,1,0,0.5 +15,0.012661621750642857,21.470452308654785,0.12273424242933591,0.007185777726893623,0.8011015057563782,29.068965276082356,29.464336395263672,25.135164896647137,5.20529902906953,0.9711570143699646,0.9256068468093872,0,0,0,0,0.0 +16,0.00822838512249291,28.52393086751302,0.06354871081809203,0.0015790603259423126,0.9432754715283712,27.39897632598877,28.653714815775555,27.367276509602863,5.496515546459327,0.8590314388275146,0.8931310176849365,0,1,1,0,0.5 +17,0.011429916135966778,26.951901117960613,0.10956587394078572,0.002022004647490879,0.7755731542905172,28.968124707539875,28.424342155456543,23.333316485087078,5.2211806962592435,0.961891770362854,0.9495016932487488,0,0,0,0,0.0 +18,0.006618781868989269,26.666550636291504,0.08600037793318431,0.0022651016091307006,0.8406303028265635,3.0408948858579,1.6908348004023235,6.063183347384135,5.365387184458419,0.996209979057312,0.9904612898826599,1,1,1,1,1.0 +19,0.013086489556978146,21.796807289123535,0.12405642742911975,0.0066207140528907376,0.7203339238961538,30.701362291971844,32.35535589853922,28.710267384847004,4.164803175137703,0.9549497961997986,0.9218171834945679,0,0,0,0,0.0 +20,0.007363593019545078,25.00732536315918,0.07251932621002197,0.0031843242701143025,0.8845732927322387,31.37451591491699,29.964988708496094,17.998725509643556,4.809627583540468,0.7150393128395081,0.5654972791671753,0,0,0,0,0.0 +21,0.005155325362769266,27.781258900960285,0.08661232516169548,0.001718540540120254,0.8345969120661417,30.447711944580078,31.55190626780192,19.73283576965332,5.096342593004354,0.6081074476242065,0.5508615970611572,0,1,1,0,0.5 +22,0.01836680682996909,21.903411865234375,0.115738561997811,0.006511872634291649,0.7319148778915405,31.082651138305664,32.26221593221029,24.9018653233846,5.0583524354609315,0.8012670874595642,0.8428634405136108,1,1,1,1,1.0 +23,0.00499920923418055,28.005899747212727,0.06934737041592598,0.0016243561791876953,0.8884439071019491,26.25293477376302,28.308818499247234,23.698330561319988,5.539762359502525,0.9815117716789246,0.9591104984283447,1,1,1,1,1.0 +24,0.008255186878765622,23.74799410502116,0.10306328659256299,0.004234130494296551,0.8591764767964681,7.518662532170613,6.0975643793741865,6.357088963190715,5.637070516918764,0.9215852618217468,0.9190346002578735,0,1,1,0,0.5 +25,0.005453952277700107,23.810959180196125,0.06389033794403076,0.0041616500820964575,0.8734269340833029,1.2621366704503696,2.978044251600901,9.650790452957153,5.101211276165281,0.49879300594329834,0.6064146161079407,0,0,0,0,0.0 +26,0.01389762278025349,22.017157554626465,0.1438980996608734,0.006296484110256036,0.7565494577089945,27.73381773630778,33.06211026509603,22.855151176452637,5.223457803902309,0.9749087691307068,0.9462347626686096,0,1,1,0,0.5 +27,0.00535028288140893,26.323949495951336,0.09980053330461185,0.002352056559175253,0.8686566253503164,26.533513069152832,28.10823408762614,24.264564514160156,6.542483968307597,0.9748175144195557,0.9397802352905273,1,1,1,1,1.0 +28,0.028661896474659443,20.833114941914875,0.17361667503913245,0.008701815425107876,0.606480598449707,24.916886647542317,24.85560480753581,23.66386381785075,4.866569964079333,0.944190502166748,0.8705335855484009,0,0,0,0,0.0 +29,0.006012713924671213,21.88481871287028,0.10122841596603394,0.006516069717084368,0.7951890726884207,29.18990675608317,28.652164141337078,19.45703109105428,3.9715481816004647,0.4234115779399872,0.383587509393692,0,0,0,0,0.0 +30,0.009273599910860261,23.692264556884766,0.12146121636033058,0.004278050425151984,0.7176644504070282,29.29452641805013,26.141194661458332,19.445902188618977,4.290439178337491,0.8700667023658752,0.8643741607666016,0,0,0,0,0.0 +31,0.00820543640293181,26.359488487243652,0.06605774164199829,0.002361825395685931,0.9184817870457967,31.421629269917805,31.570017496744793,22.510953585306805,7.85388625168243,0.9534119963645935,0.9541358947753906,0,1,1,0,0.5 +32,0.020427493378520012,20.985142707824707,0.154470128317674,0.008070209917301932,0.6639779408772787,26.57515748341878,26.393881797790527,24.452000617980957,4.684383685986201,0.9414650797843933,0.8674611449241638,0,0,0,0,0.0 +33,0.01299341768026352,23.2043244043986,0.10825587436556816,0.004790752427652478,0.7323565483093262,27.04060935974121,28.753019332885742,26.989397366841633,4.338907161370554,0.976705014705658,0.955374002456665,0,0,0,0,0.0 +34,0.008453662740066648,26.70860481262207,0.08364918828010559,0.0022624594857916236,0.8911303480466207,30.968846956888836,28.40161895751953,19.99777348836263,6.430841921363656,0.9714617729187012,0.9125871658325195,0,0,0,0,0.0 +35,0.015018390802045664,21.58274968465169,0.09569474433859189,0.0071104303157577915,0.7871747513612112,25.228551864624023,25.48371473948161,24.413235664367676,3.9640193556618173,0.9836164712905884,0.9660736918449402,0,1,1,0,0.5 +36,0.006266355010059972,29.228576978047688,0.08238878721992175,0.0013952476050083835,0.9582666158676147,32.24213663736979,31.919050216674805,20.473817825317383,7.634047294062907,0.8376369476318359,0.8239975571632385,0,0,0,0,0.0 +37,0.013462412636727095,24.28648630777995,0.10957079256574313,0.0037556110958879194,0.7975576817989349,28.086151123046875,29.33478291829427,21.36242930094401,5.195841970584254,0.972560703754425,0.9724001884460449,0,0,0,0,0.0 +38,0.007923018963386616,24.38404115041097,0.07736631917456786,0.0036769868650784097,0.830930252869924,30.519266764322918,29.75535519917806,25.4824374516805,4.473758086164085,0.9799298644065857,0.979498565196991,1,1,1,1,1.0 +39,0.00675244062828521,25.590832392374676,0.09436426684260368,0.0029313411990491054,0.8276817997296652,4.6037605206171675,4.443393270174663,9.612568855285645,5.635725354247103,0.9845717549324036,0.9722092747688293,1,1,1,1,1.0 +40,0.013808462458352247,24.460601488749187,0.11397473389903705,0.0037149289079631367,0.7855979899565378,28.439318974812824,31.594918251037598,24.391136805216473,5.537637229582571,0.95957350730896,0.9399218559265137,0,1,1,0,0.5 +41,0.015137892682105303,24.438617706298828,0.06953764023880164,0.003636908329402407,0.8796018163363138,22.742003122965496,22.110870997111004,18.88723659515381,5.593852339010745,0.49241238832473755,0.5758287310600281,0,1,1,0,0.5 +42,0.004770809047234555,26.503061294555664,0.09268960232535998,0.0023151777956324318,0.8224306404590607,26.928987820943195,26.14660390218099,19.20643901824951,5.0577745868301704,0.9917213916778564,0.9826622605323792,0,0,0,0,0.0 +43,0.017094210876772802,21.372687021891277,0.13415177166461945,0.007658930883432428,0.7049127916495005,24.006995519002277,25.820027669270832,25.189355214436848,5.067153007882033,0.8706388473510742,0.8502624034881592,0,1,1,0,0.5 +44,0.006640077801421285,26.77146625518799,0.09495843946933746,0.002138153494646152,0.8590313891569773,27.858824412027996,26.90373198191325,21.151230812072754,5.023723696102114,0.6441315412521362,0.5965035557746887,0,1,1,0,0.5 +45,0.013706788886338472,24.44431145985921,0.12313443173964818,0.0036119959161927304,0.7689571777979533,28.864056905110676,30.316065152486164,26.299079259236652,5.032615431673494,0.9518005847930908,0.9645866751670837,0,0,0,0,0.0 +46,0.007855771109461784,25.785842514038087,0.06515770852565765,0.0026403028052300213,0.8993975996971131,30.22248077392578,31.13564338684082,28.631952667236327,5.121060703011714,0.5010387301445007,0.5248832106590271,0,0,0,0,0.0 +47,0.004676880004505317,25.235092480977375,0.11796800668040912,0.003027962055057287,0.7547411322593689,26.40644709269206,25.515843391418457,22.2902733484904,4.3077829561069185,0.9916393160820007,0.9529250264167786,0,0,0,0,0.0 +48,0.009350898675620556,24.828693389892578,0.08480789388219516,0.003447870956733823,0.8916950523853302,27.032498995463055,29.103155453999836,26.99167537689209,6.194460112370019,0.6957312226295471,0.7077033519744873,0,0,0,0,0.0 +49,0.016535239138950903,29.149963061014812,0.08312186474601428,0.0012526373805788655,0.8381699621677399,27.024845759073894,24.296157519022625,16.634888807932537,6.661887032343212,0.955183207988739,0.9554001092910767,0,1,1,0,0.5 +50,0.006789997840921084,28.6437406539917,0.09455976511041324,0.0013777531567029655,0.8840179940064748,29.103871663411457,28.28354326883952,14.891612688700357,6.411129789043457,0.9293071627616882,0.8758198022842407,0,1,1,0,0.5 +51,0.0134819271042943,24.959707260131836,0.1318033238252004,0.003249412674146394,0.7030746440092722,28.854605356852215,29.2678279876709,26.00012715657552,5.798874923151598,0.9916759729385376,0.9916261434555054,0,0,0,0,0.0 +52,0.013783433940261602,23.841631571451824,0.12478533759713173,0.004146266728639603,0.7348156273365021,29.373405774434406,32.95181528727213,22.71240743001302,5.436933690694015,0.9839541912078857,0.9610176682472229,1,1,1,1,1.0 +53,0.015223518013954163,21.921433448791504,0.12789500380555788,0.006444957728187243,0.6953190465768179,26.732075373331707,27.75029404958089,22.920681635538738,4.376142867249552,0.9898788332939148,0.9874348640441895,0,0,0,0,0.0 +54,0.01699778437614441,24.47910753885905,0.0938737125446399,0.0036682888166978955,0.8349126478036245,27.7214994430542,27.001641591389973,26.5724515914917,5.52716804254127,0.9485366940498352,0.9338845014572144,0,0,0,0,0.0 +55,0.011117492647220692,25.441223462422688,0.09028185407320659,0.00296562355166922,0.8789276878039042,24.34856605529785,25.93112786610921,21.9348045984904,6.123227755766209,0.9734946489334106,0.9762636423110962,0,1,1,0,0.5 +56,0.011232655417794982,25.263298352559406,0.12097649276256561,0.0031041839780906835,0.7512262562910715,29.15004762013753,26.821916580200195,25.711631139119465,6.27135347393597,0.975892961025238,0.963795006275177,0,1,1,0,0.5 +57,0.007912904179344574,27.51637585957845,0.08643613134821256,0.0017717426332334678,0.8700674374898275,28.276838938395183,27.817021369934082,23.128493309020996,5.234163060379838,0.9280065298080444,0.94162917137146,1,1,1,1,1.0 +58,0.024645240511745214,21.517133712768555,0.14604501674572626,0.007375614407161872,0.7320098082224528,27.07481511433919,28.15297222137451,24.53378677368164,5.7162445460708575,0.9728093147277832,0.9604049324989319,0,1,1,0,0.5 +59,0.017786880023777485,26.684892654418945,0.11763511473933856,0.002343141551439961,0.833572506904602,26.27460289001465,25.52344258626302,25.777785301208496,5.801537969739289,0.9960053563117981,0.9951255917549133,0,0,0,0,0.0 +60,0.016008221699545782,23.737292607625324,0.11785125608245532,0.004374092017921309,0.7729542156060537,32.586317698160805,33.65428924560547,27.388431231180828,4.97564837016339,0.9818841814994812,0.9104086756706238,0,1,1,0,0.5 +61,0.012967413601775965,25.199766794840496,0.09167693182826042,0.0030257974673683443,0.840056985616684,28.74448045094808,28.540897369384766,26.509280522664387,4.474328824358806,0.9516533613204956,0.854971706867218,0,1,1,0,0.5 +62,0.017130876425653696,22.614142417907715,0.13645035276810327,0.0055386753131945925,0.7699618438879648,27.203686714172363,29.627302169799805,22.65595054626465,5.389747183624717,0.7486696243286133,0.7271943688392639,0,1,1,0,0.5 +63,0.008886809553951025,25.076161193847657,0.07554954588413239,0.0032440694514662026,0.7821781635284424,27.78900489807129,29.045602798461914,21.092380714416503,5.458215933531118,0.9728399515151978,0.9740958213806152,0,1,1,0,0.5 +64,0.005474585496510069,25.50581932067871,0.08478404209017754,0.002823111213122805,0.8568478326002756,26.372241338094074,29.994930903116863,25.20927079518636,4.929053156563602,0.927545964717865,0.7768470644950867,1,1,1,1,1.0 +65,0.013215467023352781,30.126746495564777,0.07608816400170326,0.0010507151891943067,0.9196091989676157,27.485953330993652,28.01364294687907,18.717259565989178,6.642706830980422,0.9804003834724426,0.9743361473083496,0,0,0,0,0.0 +66,0.011779215962936481,27.415451367696125,0.09734997525811195,0.0018847270985133946,0.8709744612375895,31.831198692321777,32.5538543065389,21.983198801676433,5.691802168588603,0.8753983378410339,0.8563582301139832,1,1,1,1,1.0 +67,0.024695876985788345,28.049774169921875,0.07720892876386642,0.001570556336082518,0.9121633529663086,27.572897338867186,26.625384902954103,21.234083557128905,6.625307280595725,0.8207539319992065,0.7843108177185059,0,0,0,0,0.0 +68,0.005095517340426643,28.090750694274902,0.09068844839930534,0.0015675810476144154,0.845676193634669,29.05566469828288,25.02126630147298,19.09133752187093,5.170397524721738,0.9524683356285095,0.9384155869483948,0,1,1,0,0.5 +69,0.014248941714564959,21.682946523030598,0.14334245026111603,0.006831642317896088,0.7673247357209524,27.930469512939453,33.02115726470947,23.13411585489909,5.3074349519148,0.9800478219985962,0.947700023651123,0,1,1,0,0.5 +70,0.014490151467422644,22.253347396850586,0.13605642691254616,0.005987189089258512,0.7735017140706381,31.10748227437337,30.039469718933105,27.206968625386555,4.902377132028135,0.7595545649528503,0.8660576343536377,0,0,0,0,0.0 +71,0.01508466643281281,22.460192680358887,0.0837930254638195,0.005745166330598295,0.7532240748405457,31.999398231506348,33.07064151763916,20.916090726852417,4.559956718239131,0.8653830289840698,0.8439609408378601,0,1,1,0,0.5 +72,0.005268710354963939,25.59296639760335,0.09011672561367352,0.002867177070584148,0.8650412956873575,26.673309961954754,25.863747596740723,19.28213946024577,5.524057330272928,0.9672843217849731,0.9501761198043823,0,0,0,0,0.0 +73,0.014050050638616085,24.008829434712727,0.10347995658715566,0.004035423121725519,0.8108930091063181,29.030211448669434,28.854741096496582,25.728010813395183,4.094201496453009,0.9766008853912354,0.9374105334281921,0,1,1,0,0.5 +74,0.00783627813992401,24.7681827545166,0.049900829792022705,0.0033783643351246915,0.8392511109511057,32.812037785847984,31.110143343607586,22.489163398742676,5.182953116318022,0.9469916820526123,0.9168618321418762,0,0,0,0,0.0 +75,0.006450016129141052,30.10940647125244,0.0410822710643212,0.0010007278081805755,0.9496923188368479,25.356762568155926,26.749314943949383,26.117970784505207,9.393744518088184,0.7542940378189087,0.7519747018814087,0,0,0,0,0.0 +76,0.008130417050172886,29.431172053019207,0.05904868679742018,0.0013970642952093233,0.918046216169993,30.228810628255207,30.829288164774578,24.020400047302246,8.745810536265195,0.8040574789047241,0.8586546778678894,1,1,1,1,1.0 +77,0.004257521863716344,33.99980862935384,0.02473962710549434,0.0003991556780723234,0.9673575659592947,29.053016026814777,28.362703641255695,23.941089312235516,7.296421991672715,0.4738123118877411,0.5883355140686035,0,0,0,0,0.0 +78,0.009326068839679161,28.124506950378418,0.05959932195643584,0.0015609857897895079,0.8929910461107889,32.304396311442055,32.039093653361,24.7210594813029,7.375924105597693,0.8010849952697754,0.888276219367981,0,0,0,0,0.0 +79,0.0073496032661447925,27.076157569885254,0.051463685308893524,0.0019911395696302256,0.9139978388945261,32.37559986114502,30.29143746693929,24.107277234395344,6.582716656056323,0.7349259257316589,0.8404937386512756,0,1,1,0,0.5 +80,0.010044048385073742,25.886157353719074,0.06221022394796213,0.0025921585814406476,0.8979775011539459,30.36746311187744,30.521142323811848,22.323400497436523,7.428281913046042,0.9332404136657715,0.8407424092292786,0,1,1,0,0.5 +81,0.00777520580838124,23.705632209777832,0.053913659105698265,0.004262616702665885,0.8345910509427389,29.705933570861816,29.2476323445638,21.567164421081543,4.718041109911517,0.9408712983131409,0.9402233362197876,0,0,0,0,0.0 +82,0.006298999690140287,28.21508534749349,0.049543570106228195,0.001512785772016893,0.8914440671602885,27.91925271352132,27.235035578409832,19.379929224650066,6.137045886389551,0.8611297011375427,0.7387306094169617,0,1,1,0,0.5 +83,0.011998166174938282,22.47411568959554,0.07388484105467796,0.006075117814665039,0.8171375095844269,29.05754025777181,30.008665402730305,21.299748102823894,5.782937797775241,0.9302934408187866,0.9237462878227234,0,0,0,0,0.0 +84,0.0061711512971669436,26.942494074503582,0.03642764066656431,0.002028885743735979,0.8975917398929596,29.817204475402832,27.26916440327962,18.03117911020915,5.4743418552358,0.5302432179450989,0.5680992603302002,0,0,0,0,0.0 +85,0.006216459286709626,25.177680333455402,0.05242909863591194,0.003052821382880211,0.9081816077232361,28.446220715840656,28.058568000793457,22.256232579549152,5.923585838226223,0.8834556341171265,0.8821125626564026,1,1,1,1,1.0 +86,0.006252991268411279,26.0748504002889,0.03886907920241356,0.002519421298832943,0.8863331079483032,30.81200663248698,29.75868860880534,22.8334321975708,7.9336677568291565,0.9088717103004456,0.8028365969657898,0,0,0,0,0.0 +87,0.008576413228486976,25.216835021972656,0.05171112654109796,0.0030363004577035704,0.8708475331465403,24.649881680806477,27.508617401123047,25.193353017171223,5.581018363541102,0.8991612195968628,0.897735595703125,0,0,0,0,0.0 +88,0.009589354197184244,26.133036295572918,0.043861876552303634,0.002469043441427251,0.921834816535314,29.61598300933838,30.528795560201008,21.98587989807129,5.073064177198728,0.8613206744194031,0.8588335514068604,1,1,1,1,1.0 +89,0.010687420843169093,23.812220255533855,0.07131302605072658,0.005440378988472124,0.8847622474034628,31.196261723836262,32.072313944498696,26.528024673461914,6.843791684560035,0.9713626503944397,0.9263005256652832,0,0,0,0,0.0 +90,0.004098590385789673,27.232465426127117,0.0537555410216252,0.0019107898891282578,0.8979326685269674,29.644922574361164,29.075769424438477,18.727931022644043,6.37080375434133,0.9067329168319702,0.9107099771499634,0,1,1,0,0.5 +91,0.00843545359869798,29.078923225402832,0.04059205173204342,0.001308866689214483,0.9496995111306509,29.28541660308838,30.035982131958008,25.79231834411621,8.899425005493049,0.954840362071991,0.8905925750732422,0,0,0,0,0.0 +92,0.011936525348573923,29.7169672648112,0.046229248866438866,0.0010950138772993039,0.8875506718953451,29.552697499593098,28.642224311828613,25.399852752685547,7.565335681998959,0.9728676080703735,0.955998420715332,0,0,0,0,0.0 +93,0.00589347289254268,29.228224754333496,0.03796292655169964,0.001194894682460775,0.9050152897834778,27.84822146097819,27.490912755330402,25.888235727945965,6.860961033346553,0.9679145216941833,0.9520437717437744,0,0,0,0,0.0 +94,0.004414334272344907,30.621355056762695,0.02313274921228488,0.0008682375482749194,0.9420636196931204,27.95263735453288,27.862493832906086,29.4685853322347,6.035017067214018,0.9931517243385315,0.9915173053741455,0,0,0,0,0.0 +95,0.007174677448347211,27.626184781392414,0.04794046717385451,0.0017873859032988548,0.9099237620830536,28.41052182515462,29.35356839497884,21.423285166422527,8.23280250470877,0.9186415076255798,0.8658653497695923,0,1,1,0,0.5 +96,0.0038322771045689783,25.954545974731445,0.04272268650432428,0.002543303300626576,0.8823663791020712,25.53180185953776,26.8108008702596,22.335044542948406,4.169606858914157,0.8865783214569092,0.7682155966758728,1,0,1,0,0.5 +97,0.005451208679005504,29.19133758544922,0.03761796901623408,0.001207043998874724,0.9188082218170166,26.79162057240804,26.738742510477703,23.27690060933431,5.395108686420716,0.6101022958755493,0.5660444498062134,0,0,0,0,0.0 +98,0.009303838635484377,25.26180076599121,0.06729518560071786,0.0030630630208179355,0.8310192227363586,32.617099126180015,36.88322448730469,28.72382386525472,6.787152712790847,0.9802544713020325,0.9267398118972778,1,1,1,1,1.0 +99,0.010077633584539095,23.944941520690918,0.061140283942222595,0.004043753142468631,0.857090691725413,31.89664363861084,32.42603365580241,23.480634053548176,4.961043354902116,0.9307066798210144,0.9182385206222534,0,0,0,0,0.0 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit4_FiVE_evaluation_result_frame_stride8_avg.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit4_FiVE_evaluation_result_frame_stride8_avg.csv new file mode 100644 index 0000000000000000000000000000000000000000..be3354fb0e43730dde187403bdfee07f5d609f3e --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit4_FiVE_evaluation_result_frame_stride8_avg.csv @@ -0,0 +1,2 @@ +file_id,8_Wan_Edit_iccv|structure_distance,8_Wan_Edit_iccv|psnr_unedit_part,8_Wan_Edit_iccv|lpips_unedit_part,8_Wan_Edit_iccv|mse_unedit_part,8_Wan_Edit_iccv|ssim_unedit_part,8_Wan_Edit_iccv|clip_similarity_source_image,8_Wan_Edit_iccv|clip_similarity_target_image,8_Wan_Edit_iccv|clip_similarity_target_image_edit_part,8_Wan_Edit_iccv|niqe_target_image,8_Wan_Edit_iccv|motion_fidelity_score,8_Wan_Edit_iccv|motion_fidelity_score_edit_part,8_Wan_Edit_iccv|five_acc_yes_no,8_Wan_Edit_iccv|five_acc_multi_choice,8_Wan_Edit_iccv|five_acc_union,8_Wan_Edit_iccv|five_acc_inter,8_Wan_Edit_iccv|five_acc +49.5000,10.6873,25.4580,89.7453,34.2415,83.2181,27.5199,27.7762,22.3881,5.6443,88.8904,86.1335,0.1900,0.4600,0.4800,0.1700,0.3283 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit6_FiVE_evaluation_result_frame_stride8.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit6_FiVE_evaluation_result_frame_stride8.csv new file mode 100644 index 0000000000000000000000000000000000000000..a828bab275c13678ab59bd65489b3ba15716b2d2 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit6_FiVE_evaluation_result_frame_stride8.csv @@ -0,0 +1,11 @@ +file_id,8_Wan_Edit|structure_distance,8_Wan_Edit|psnr_unedit_part,8_Wan_Edit|lpips_unedit_part,8_Wan_Edit|mse_unedit_part,8_Wan_Edit|ssim_unedit_part,8_Wan_Edit|clip_similarity_source_image,8_Wan_Edit|clip_similarity_target_image,8_Wan_Edit|clip_similarity_target_image_edit_part,8_Wan_Edit|niqe_target_image,8_Wan_Edit|motion_fidelity_score,8_Wan_Edit|motion_fidelity_score_edit_part,8_Wan_Edit|five_acc_yes_no,8_Wan_Edit|five_acc_multi_choice,8_Wan_Edit|five_acc_union,8_Wan_Edit|five_acc_inter,8_Wan_Edit|five_acc +0,0.00418276822892949,29.81367842356364,0.07958397269248962,0.0010751441877800971,0.8297213315963745,30.66161600748698,30.01973533630371,24.841994921366375,4.756757213155461,0.9903452396392822,0.9844503402709961,0,0,0,0,0.0 +1,0.0019254906898519646,34.88595008850098,0.04636978295942148,0.0003420070934225805,0.9634365836779276,27.39897632598877,27.464684168497723,24.50825023651123,5.443351397493701,0.8654411435127258,0.8851667046546936,0,0,0,0,0.0 +2,0.0008984126810294887,31.172149022420246,0.06385695872207482,0.0007923756202217191,0.9142926335334778,7.518662532170613,6.8546507358551025,7.630458037058513,5.476224041863287,0.9323528409004211,0.9226940870285034,0,0,0,0,0.0 +3,0.003676262121492376,29.334948857625324,0.082675917694966,0.001252934045623988,0.83408189813296,30.14535903930664,29.439313252766926,25.106491724650066,5.518251177010453,0.9760950207710266,0.9615105390548706,0,0,0,0,0.0 +4,0.0023791458030852177,31.252258618672688,0.042686463644107185,0.0007633661637858798,0.9262453317642212,22.84447447458903,22.212827682495117,17.84633461634318,5.652071180241099,0.5319910645484924,0.6071568727493286,0,0,0,0,0.0 +5,0.00295292337735494,26.7450377146403,0.10638122757275899,0.0021314721864958606,0.7743127644062042,26.40644709269206,26.526074409484863,21.647146860758465,4.407333864645003,0.9939640164375305,0.9670056700706482,0,0,0,0,0.0 +6,0.0014544463144072022,35.04924774169922,0.06943708347777526,0.00031339487759396434,0.9173972606658936,29.103871663411457,28.927610397338867,14.664368311564127,6.502568645379519,0.9462375640869141,0.9095913171768188,0,0,0,0,0.0 +7,0.0020515997894108295,32.84889157613119,0.0664970555032293,0.0005299387266859412,0.8893862962722778,27.7214994430542,25.105921427408855,25.252729415893555,5.53052283327257,0.9664486646652222,0.9579300880432129,0,0,0,0,0.0 +8,0.0007617347776734581,40.053993225097656,0.010720648181935152,9.923924153554253e-05,0.989260176817576,29.053016026814777,27.888821283976238,25.273146629333496,7.829637339140123,0.4845246374607086,0.6589348316192627,0,0,0,0,0.0 +9,0.00208839993380631,31.339603106180828,0.02755398799975713,0.0007680245568432534,0.9290801088015238,24.136377970377605,24.66152572631836,21.481863339742024,5.382945180287419,0.9019994139671326,0.9210590124130249,0,0,0,0,0.0 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit6_FiVE_evaluation_result_frame_stride8_avg.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit6_FiVE_evaluation_result_frame_stride8_avg.csv new file mode 100644 index 0000000000000000000000000000000000000000..782156240d27be8814350a24328f3a36980c93e6 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/edit6_FiVE_evaluation_result_frame_stride8_avg.csv @@ -0,0 +1,2 @@ +file_id,8_Wan_Edit|structure_distance,8_Wan_Edit|psnr_unedit_part,8_Wan_Edit|lpips_unedit_part,8_Wan_Edit|mse_unedit_part,8_Wan_Edit|ssim_unedit_part,8_Wan_Edit|clip_similarity_source_image,8_Wan_Edit|clip_similarity_target_image,8_Wan_Edit|clip_similarity_target_image_edit_part,8_Wan_Edit|niqe_target_image,8_Wan_Edit|motion_fidelity_score,8_Wan_Edit|motion_fidelity_score_edit_part,8_Wan_Edit|five_acc_yes_no,8_Wan_Edit|five_acc_multi_choice,8_Wan_Edit|five_acc_union,8_Wan_Edit|five_acc_inter,8_Wan_Edit|five_acc +4.5000,2.2371,32.2496,59.5763,8.0679,89.6721,25.4990,24.9101,20.8253,5.6500,85.8940,87.7550,0.0000,0.0000,0.0000,0.0000,0.0000 diff --git a/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/final_averaged_results.csv b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/final_averaged_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..6e925c111dba2fb38e50247ac2e34cf3d3c031c3 --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/8_wan_edit/final_averaged_results.csv @@ -0,0 +1,2 @@ +file_id,8_Wan_Edit|structure_distance,8_Wan_Edit|psnr_unedit_part,8_Wan_Edit|lpips_unedit_part,8_Wan_Edit|mse_unedit_part,8_Wan_Edit|ssim_unedit_part,8_Wan_Edit|clip_similarity_source_image,8_Wan_Edit|clip_similarity_target_image,8_Wan_Edit|clip_similarity_target_image_edit_part,8_Wan_Edit|niqe_target_image,8_Wan_Edit|motion_fidelity_score,8_Wan_Edit|motion_fidelity_score_edit_part,8_Wan_Edit|five_acc_yes_no,8_Wan_Edit|five_acc_multi_choice,8_Wan_Edit|five_acc_union,8_Wan_Edit|five_acc_inter,8_Wan_Edit|five_acc +34.4167,12.5987,25.5080,94.9950,42.0091,82.3145,26.7227,26.7140,21.3669,5.5224,88.9996,87.1417,0.4131,0.5280,0.5615,0.3771,0.4688 diff --git a/benchmarks/edit/code/FiVE-Bench/results/avg_metrics_in_csv.py b/benchmarks/edit/code/FiVE-Bench/results/avg_metrics_in_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..3d20372c603efd63f85ce170fd912bf7cafef9ff --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/results/avg_metrics_in_csv.py @@ -0,0 +1,98 @@ +import csv +import os + + +result_avg_files = [] +for i in range(1, 7): + result_path = f"8_wan_edit/edit{i}_FiVE_evaluation_result_frame_stride8.csv" + + if not os.path.exists(result_path): + continue + + # calculate the average of each metric (each column) + with open(result_path, 'r') as f: + reader = list(csv.reader(f)) + header, rows = reader[0], reader[1:] + + avg_row = [] + # Process each column by index to handle rows with different lengths + for col_idx, name in enumerate(header): + print("processing", name) + # Extract column values, handling missing values + col_values = [] + for row in rows: + if col_idx < len(row): + col_values.append(row[col_idx]) + else: + col_values.append("") # Use empty string for missing values + + try: + # Filter out empty strings and convert to float + values = [float(x) for x in col_values if x != "" and x != "nan"] + if values: # Only calculate average if there are valid values + avg = sum(values) / len(values) + if 'structure_distance' in name: + avg *= 1000 + elif 'lpips_' in name: + avg *= 1000 + elif 'mse_' in name: + avg *= 10000 + elif 'ssim_' in name: + avg *= 100 + elif 'motion_fidelity_score' in name: + avg *= 100 + elif name.startswith('five_acc'): + avg *= 100 + avg_row.append(f"{avg:.4f}") + else: + avg_row.append("N/A") + except ValueError: + avg_row.append("N/A") + + + with open(result_path.replace('.csv', '_avg.csv'), 'w', newline='') as f_out: + writer = csv.writer(f_out) + writer.writerow(header) + writer.writerow(avg_row) + + result_avg_files.append(result_path.replace('.csv', '_avg.csv')) + + +# average the results in result_avg_files +if result_avg_files: + all_avg_rows = [] + + # Read all average files + for result_avg_file in result_avg_files: + with open(result_avg_file, 'r') as f: + reader = list(csv.reader(f)) + header, rows = reader[0], reader[1:] + if rows: # Make sure there's data + all_avg_rows.append(rows[0]) # Get the average row + + # Calculate final averages across all files + final_avg_row = [] + for col_idx, name in enumerate(header): + print("final averaging", name) + + # Extract values from all average files for this column + col_values = [] + for avg_row in all_avg_rows: + if col_idx < len(avg_row) and avg_row[col_idx] != "N/A": + try: + col_values.append(float(avg_row[col_idx])) + except ValueError: + pass # Skip non-numeric values + + # Calculate final average + if col_values: + final_avg = sum(col_values) / len(col_values) + final_avg_row.append(f"{final_avg:.4f}") + else: + final_avg_row.append("N/A") + + # Write final averaged results + with open(f"{result_path.split('/')[-2]}/final_averaged_results.csv", 'w', newline='') as f_out: + writer = csv.writer(f_out) + writer.writerow(header) + writer.writerow(final_avg_row) \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/scripts/eval_FiVE.sh b/benchmarks/edit/code/FiVE-Bench/scripts/eval_FiVE.sh new file mode 100644 index 0000000000000000000000000000000000000000..a412a3a004400495eead7b46435bbad573427d2d --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/scripts/eval_FiVE.sh @@ -0,0 +1 @@ +CUDA_VISIBLE_DEVICES=1 python evaluation/evaluate.py \ No newline at end of file diff --git a/benchmarks/edit/code/FiVE-Bench/scripts/eval_FiVE_acc_only.sh b/benchmarks/edit/code/FiVE-Bench/scripts/eval_FiVE_acc_only.sh new file mode 100644 index 0000000000000000000000000000000000000000..9627acb2eab869b20ec78c7ec5d2963a4ecb47ab --- /dev/null +++ b/benchmarks/edit/code/FiVE-Bench/scripts/eval_FiVE_acc_only.sh @@ -0,0 +1,3 @@ +CUDA_VISIBLE_DEVICES=0 python evaluation/evaluate.py \ + --metrics "five_acc" \ + --result_path outputs/evaluation_result_five_acc.csv \ No newline at end of file diff --git a/benchmarks/edit/code/IVEBench/README.md b/benchmarks/edit/code/IVEBench/README.md new file mode 100644 index 0000000000000000000000000000000000000000..31819003271efd4340934a447be7c4dfc3583ff5 --- /dev/null +++ b/benchmarks/edit/code/IVEBench/README.md @@ -0,0 +1,260 @@ +

+ +image + +

+

+ Yinan Chen 1★ + · + Jiangning Zhang 1,2★ + · + Teng Hu 3 + · + Yuxiang Zeng 4 + · + Zhucun Xue 1 + · +
Qingdong He 2 + · + Chengjie Wang 2,3 + · + Yong Liu 1† + · + Xiaobin Hu 2 + · + Shuicheng Yan 5 +

+

+ 1Zhejiang University     + 2YouTu Lab, Tencent     + 3Shanghai Jiao Tong University +
+ 4University of Auckland     + 5National University of Singapore +

+

+ + arXiv PDF + + + + webpage-Web + +

+ + + +# :blush:Continuous Updates + +This repository is a comprehensive collection of resources for **IVEBench**, If you find any work missing or have any suggestions, feel free to pull requests or [contact us](#contact). We will promptly add the missing papers to this repository. + + + +**🔥 More up-to-date instruction-guided video editing methods will continue to be updated.** + + + +**📝 Update:** + +- **[2026-01-27]** IVEBench has been accepted by **ICLR 2026**.🎉🎉🎉 +- **[2025-11-27]** Supports adjusting weights for each dimension. + +- **[2025-11-26]** Update Evaluation Results: [Ditto](https://github.com/EzioBy/Ditto) + +- **[2025-10-23]** Update Evaluation Results: [Lucy-Edit-Dev](https://huggingface.co/decart-ai/Lucy-Edit-Dev), [Omni-Video](https://github.com/SAIS-FUXI/Omni-Video), [ICVE](https://github.com/leoisufa/ICVE) +- **[2025-10-16]** Update Evaluation Results: [InsV2V](https://github.com/amazon-science/instruct-video-to-video), [StableV2V](https://github.com/AlonzoLeeeooo/StableV2V), [AnyV2V](https://github.com/TIGER-AI-Lab/AnyV2V), [VACE](https://github.com/ali-vilab/VACE) + +**🤓 You can view the scores and comparisons of each method at [IVEBench LeaderBoard](https://ryanchenyn.github.io/projects/IVEBench/#leaderboard).** + + + +# ✨ Highlight!!! + + + +Compared with existing video editing benchmarks, our proposed **IVEBench** offers the following key advantages: + +1. **Comprehensive support for IVE methods:** IVEBench is specifically designed to evaluate instruction-guided video editing (IVE) models while remaining compatible with traditional source-target prompt-based methods, ensuring broad applicability across editing paradigms; +2. **Diverse and semantically rich video corpus:** The benchmark contains 600 high-quality source videos spanning seven semantic dimensions and thirty topics, with frame lengths ranging from 32 to 1,024, providing wide coverage of real-world scenarios; +3. **Comprehensive editing taxonomy:** IVEBench includes eight major editing categories and thirty-five subcategories, encompassing diverse editing types such as style, attribute, subject motion, camera motion, and visual effect editing, to fully represent instruction-guided behaviors; +4. **Integration of MLLM-based and traditional metrics:** The evaluation protocol combines conventional objective indicators with multimodal large language model (MLLM)-based assessments across three dimensions (video quality, instruction compliance, and video fidelity) for more human-aligned and holistic evaluation; +5. **Extensive benchmarking of state-of-the-art models:** We conduct a thorough quantitative and qualitative evaluation of leading IVE models—including InsV2V, AnyV2V, StableV2V, as well as the multi-conditional video editing framework VACE, establishing a unified and fair standard for future research. + + + +# :mailbox_with_mail:Summary of Contents + +- [Introduction](#introduction) +- [Highlight](#highlight) +- [Data Pipeline](#movie_camera-data-pipeline) +- [Benchmark Statistics](#benchmark-statistics) +- [Installation](#installation) + - [Install requirements](#1-install-requirements) + - [Install Grounding DINO requirements](#2-install-requirements-for-grounding-dino) + - [Download pretrained checkpoints](#3-downloads-the-checkpoints-used) + - [Download IVEBench Database](#4-downloads-the-ivebench-database) +- [Usage](#usage) +- [Experiments](#experiments) + - [Performance Comparison](#performance-score-of-different-methods) + - [Quantitative Visualization](#quantitative-visualization) + - [Qualitative Visualization](#quanlitative-visualization) +- [Citation](#citation) +- [Contact](#contact) + + + +# :movie_camera: Data Pipeline + + + +**Data acquisition and processing pipeline of IVEBench.** **1)** Curation process to 600 high-quality diverse videos. **2)** Well-designed pipeline for comprehensive editing prompts. + +The playback of the source videos can be viewed on [IVEBench website](https://ryanchenyn.github.io/projects/IVEBench/#results-carousel). + + + +# :sunflower:Benchmark Statistics + + + +Statistical distributions of IVEBench DB + + + +# :hammer:Installation + +### 1. Install requirements + +``` +git clone git@github.com:RyanChenYN/IVEBench.git +cd IVEBench +conda create -n ivebench python=3.12 +conda activate ivebench +pip install -r requirements.txt +``` + +### 2. Install requirements for Grounding DINO + +Grounding DINO requires additional installation steps, which can be found in the Install section of [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) + +### 3. Downloads the checkpoints used + +All checkpoints utilized in this project are listed in `matrics/path.yml`. +Additionally, you may download the following pretrained models as referenced below: + +- [Qwen/Qwen2.5-VL-72B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-72B-Instruct) +- [Koala-36M/Training_Suitability_Assessment](https://huggingface.co/Koala-36M/Training_Suitability_Assessment/tree/main) +- [alibaba-pai/VideoCLIP-XL-v2](https://huggingface.co/alibaba-pai/VideoCLIP-XL-v2/tree/main) +- `baseline_offline.pth` from [facebook/cotracker3](https://huggingface.co/facebook/cotracker3) +- `groundingdino_swinb_cogcoor.pth` from [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha2/groundingdino_swinb_cogcoor.pth) + +After downloading the required checkpoints, you should replace the corresponding loading paths in `matrics/path.yml` with the local directories where the checkpoints are stored. + +### 4. Downloads the IVEBench Database + +This section provides access to the [IVEBench Database](https://huggingface.co/datasets/Coraxor/IVEBench), which contains the complete `.mp4` video data of IVEBench and a `.csv` file (the file provides the original URLs for each video in the [IVEBench Database](https://huggingface.co/datasets/Coraxor/IVEBench), except for those from the OpenHumanVid subset, which do not have corresponding URLs). +🥰You can download [IVEBench DB](https://huggingface.co/datasets/Coraxor/IVEBench) to your local path using the following command: + +``` +huggingface-cli download --repo-type dataset --resume-download Coraxor/IVEBench --local-dir $YOUR_LOCAL_PATH +``` + + + +# :muscle:Usage + +1. You first need to run your own video editing model on the [IVEBench DB](https://huggingface.co/datasets/Coraxor/IVEBench) to generate the corresponding Target Video dataset. + + - For each source video, the associated source prompt, edit prompt, target prompt, target phrase, and target span are stored in the `.json` file provided within the [IVEBench DB](https://huggingface.co/datasets/Coraxor/IVEBench). + + - The filenames of the videos in your generated Target Video dataset must match the corresponding source video names exactly. + + - The metric computation of IVEBench requires both the original and target videos to be in the form of video frame folders. Therefore, you need to convert the `.mp4` videos downloaded from [IVEBench DB](https://huggingface.co/datasets/Coraxor/IVEBench) into video frame folders. Similarly, if the target videos you generate are in `.mp4` format, they also need to be converted. + + ``` + python data_process/mp42frames_batch.py --input_path $INPUT_PATH --output_path $OUTPUT_PATH + ``` + + - The IVEBench DB contains videos ranging from **720P to 8K** resolution, with frame counts between **32 and 1024**. If your method has limitations regarding resolution or frame count, you can use `data_process/resize_batch.py` to perform downscaling and frame sampling on the frame folders converted from the IVEBench DB. This will produce a source video dataset at the maximum resolution and frame count supported by your method, making subsequent editing and evaluation more convenient. + + ``` + python data_process/resize_batch.py --input_path $INPUT_PATH --output_path $OUTPUT_PATH --size $WIDTH $HEIGHT --max_frame $MAX_FRAME + ``` + +2. After you have properly set up the environment, loaded the model weights, prepared the **IVEBench DB**, and generated the **Target Video dataset** using your editing method on IVEBench DB, you can use the evaluation script below to compute the performance scores for each video in your Target Video dataset across all metrics. And the evaluation results will be exported as a **CSV file**. + + ``` + cd metrics + python evaluate.py \ + --output_path $YOUR_TARGET_VIDEOS_DIR \ + --source_videos_path $IVEBENCHDB_SOURCE_VIDEOS_DIR \ + --target_videos_path $YOUR_TARGET_VIDEOS_DIR \ + --info_json_path PROMPT_JSON_PATH \ + --metric $LIST_OF_METRICS_YOU_NEED \ + ``` + +3. After obtaining the evaluation results on each videos, you can use `metrics\get_average_score.py` to get the total score of your method on the IVEBench DB, as well as the average scores across the three dimensions and all individual metrics. + + ``` + python get_average_score.py -i $INPUT_CSV -o $OUTPUT_CSV + ``` + +4. It is important to note that **IVEBench** is divided into two subsets: the **IVEBench DB Short subset** and the **IVEBench DB Long subset**. + The Short subset contains videos with **32–128 frames**, while the Long subset contains videos with **129–1024 frames**, representing a higher level of difficulty. + If you wish to evaluate your method on the **full IVEBench DB**, you need to generate the **Target Video dataset** for both subsets separately and perform evaluation on each subset independently. + + + +# :bar_chart:Experiments + +### **Performance score of different methods** + + + +The continuously updated, sortable table of the latest IVE methods is available on the [IVEBench website](https://ryanchenyn.github.io/projects/IVEBench/#leaderboard) + + + +### **Quantitative Visualization** + + + +**IVEBench Evaluation Results of Video Editing Models.** We visualize the evaluation results of four IVE models in 12 IVEBench metrics. We normalize the results per dimension for clearer comparisons. + + + +### **Quanlitative Visualization** + + + +Comparative demonstrations of the source videos and the target videos generated by different methods can be viewed on [IVEBench website](https://ryanchenyn.github.io/projects/IVEBench/#results-carousel2). + + + +# :black_nib:Citation + +If you If you find [IVEBench](https://ryanchenyn.github.io/projects/IVEBench) useful for your research, please consider giving a star⭐ and citation📝 :) + +``` +@inproceedings{chen2026ivebench, + title={IVEBench: Modern Benchmark Suite for Instruction-Guided Video Editing Assessment}, + author={Chen, Yinan and Zhang, Jiangning and Hu, Teng and Zeng, Yuxiang and Xue, Zhucun and He, Qingdong and Wang, Chengjie and Liu, Yong and Hu, Xiaobin and Yan, Shuicheng}, + booktitle={The Fourteenth International Conference on Learning Representations}, + year={2026} +} +``` + + + + + +# ✉️Contact + +``` +yinanchencs@outlook.com +``` + +``` +186368@zju.edu.cn +``` + diff --git a/benchmarks/edit/code/IVEBench/ivebench.yml b/benchmarks/edit/code/IVEBench/ivebench.yml new file mode 100644 index 0000000000000000000000000000000000000000..ee6cecf1f14c1f59b04bd61c3fe3f5602c071544 --- /dev/null +++ b/benchmarks/edit/code/IVEBench/ivebench.yml @@ -0,0 +1,183 @@ +name: ivebench +channels: + - defaults +dependencies: + - _libgcc_mutex=0.1=main + - _openmp_mutex=5.1=1_gnu + - bzip2=1.0.8=h5eee18b_6 + - ca-certificates=2025.2.25=h06a4308_0 + - expat=2.7.1=h6a678d5_0 + - ld_impl_linux-64=2.40=h12ee557_0 + - libffi=3.4.4=h6a678d5_1 + - libgcc-ng=11.2.0=h1234567_1 + - libgomp=11.2.0=h1234567_1 + - libstdcxx-ng=11.2.0=h1234567_1 + - libuuid=1.41.5=h5eee18b_0 + - ncurses=6.4=h6a678d5_0 + - openssl=3.0.16=h5eee18b_0 + - python=3.12.9=h5148396_0 + - readline=8.2=h5eee18b_0 + - sqlite=3.45.3=h5eee18b_0 + - tk=8.6.14=h39e8969_0 + - wheel=0.45.1=py312h06a4308_0 + - xz=5.6.4=h5eee18b_1 + - zlib=1.2.13=h5eee18b_1 + - pip: + - absl-py==2.2.2 + - accelerate==1.1.0 + - addict==2.4.0 + - aiohappyeyeballs==2.6.1 + - aiohttp==3.11.18 + - aiosignal==1.3.2 + - annotated-types==0.7.0 + - antlr4-python3-runtime==4.9.3 + - anyio==4.9.0 + - asttokens==3.0.0 + - attrs==25.3.0 + - av==15.0.0 + - beautifulsoup4==4.13.4 + - bitsandbytes==0.45.5 + - certifi==2025.8.3 + - cffi==1.17.1 + - cfgv==3.4.0 + - charset-normalizer==3.4.2 + - click==8.2.1 + - clip + - colorama==0.4.6 + - contourpy==1.3.3 + - cryptography==43.0.3 + - cycler==0.12.1 + - datasets==3.6.0 + - decorator==5.2.1 + - decord==0.6.0 + - defusedxml==0.7.1 + - dill==0.3.8 + - distlib==0.3.9 + - einops==0.8.1 + - executing==2.2.0 + - facexlib==0.3.0 + - filelock==3.18.0 + - filterpy==1.4.5 + - fonttools==4.59.0 + - frozenlist==1.6.0 + - fsspec==2025.7.0 + - ftfy==6.3.1 + - future==1.0.0 + - gdown==5.2.0 + - gitdb==4.0.12 + - gitpython==3.1.44 + - groundingdino==0.1.0 + - grpcio==1.71.0 + - h11==0.16.0 + - hf-xet==1.1.7 + - httpcore==1.0.9 + - httpx==0.28.1 + - huggingface-hub==0.34.3 + - icecream==2.1.4 + - identify==2.6.10 + - idna==3.10 + - imageio==2.37.0 + - imageio-ffmpeg==0.6.0 + - iniconfig==2.1.0 + - jinja2==3.1.6 + - kiwisolver==1.4.8 + - lazy-loader==0.4 + - llvmlite==0.44.0 + - lmdb==1.6.2 + - markdown==3.8 + - markupsafe==3.0.2 + - matplotlib==3.10.5 + - moviepy==2.2.1 + - mpmath==1.3.0 + - multidict==6.4.4 + - multiprocess==0.70.16 + - networkx==3.5 + - nodeenv==1.9.1 + - numba==0.61.2 + - numpy==2.2.6 + - nvidia-cublas-cu12==12.8.4.1 + - nvidia-cuda-cupti-cu12==12.8.90 + - nvidia-cuda-nvrtc-cu12==12.8.93 + - nvidia-cuda-runtime-cu12==12.8.90 + - nvidia-cudnn-cu12==9.10.2.21 + - nvidia-cufft-cu12==11.3.3.83 + - nvidia-cufile-cu12==1.13.1.3 + - nvidia-curand-cu12==10.3.9.90 + - nvidia-cusolver-cu12==11.7.3.90 + - nvidia-cusparse-cu12==12.5.8.93 + - nvidia-cusparselt-cu12==0.7.1 + - nvidia-nccl-cu12==2.27.3 + - nvidia-nvjitlink-cu12==12.8.93 + - nvidia-nvtx-cu12==12.8.90 + - omegaconf==2.3.0 + - open-clip-torch==2.32.0 + - openai-clip==1.0.1 + - opencv-python==4.12.0.88 + - opencv-python-headless==4.11.0.86 + - packaging==25.0 + - pandas==2.2.3 + - pillow==11.3.0 + - pip==25.2 + - platformdirs==4.3.8 + - pluggy==1.6.0 + - pre-commit==4.2.0 + - proglog==0.1.12 + - propcache==0.3.1 + - protobuf==6.31.0 + - psutil==7.0.0 + - pyarrow==20.0.0 + - pycocotools==2.0.10 + - pycparser==2.22 + - pydantic==2.11.4 + - pydantic-core==2.33.2 + - pygments==2.19.1 + - pyiqa==0.1.13 + - pyparsing==3.2.3 + - pysocks==1.7.1 + - pytest==8.3.5 + - python-dateutil==2.9.0.post0 + - python-dotenv==1.1.0 + - pytz==2025.2 + - pywavelets==1.8.0 + - pyyaml==6.0.2 + - qwen-vl-utils==0.0.11 + - regex==2025.7.34 + - requests==2.32.4 + - ruff==0.11.10 + - safetensors==0.6.1 + - scikit-image==0.25.2 + - scipy==1.16.1 + - sentencepiece==0.2.0 + - sentry-sdk==2.29.1 + - setproctitle==1.3.6 + - setuptools==80.9.0 + - six==1.17.0 + - sk-video==1.1.10 + - smmap==5.0.2 + - sniffio==1.3.1 + - soupsieve==2.7 + - supervision==0.26.1 + - sympy==1.14.0 + - tensorboard==2.19.0 + - tensorboard-data-server==0.7.2 + - thop==0.1.1-2209072238 + - tifffile==2025.3.30 + - timm==1.0.19 + - tokenizers==0.21.4 + - torch==2.8.0 + - torchvision==0.23.0 + - tqdm==4.67.1 + - transformers==4.55.0 + - triton==3.4.0 + - typing-extensions==4.14.1 + - typing-inspection==0.4.0 + - tzdata==2025.2 + - urllib3==2.5.0 + - virtualenv==20.31.2 + - volcengine-python-sdk==3.0.2 + - wandb==0.20.1 + - wcwidth==0.2.13 + - werkzeug==3.1.3 + - xxhash==3.5.0 + - yapf==0.43.0 + - yarl==1.20.0 diff --git a/benchmarks/edit/code/IVEBench/requirements.txt b/benchmarks/edit/code/IVEBench/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b310d604d8a64c960a88783b10d7d3c7b8b3b2b4 --- /dev/null +++ b/benchmarks/edit/code/IVEBench/requirements.txt @@ -0,0 +1,17 @@ +torch +torchvision +transformers +accelerate +qwen-vl-utils[decord]==0.0.8 +opencv-python +openai-clip +scipy +omegaconf +imageio +tqdm +ftfy +regex +timm +decord +einops +sk-video \ No newline at end of file diff --git a/benchmarks/edit/code/OpenVE-3M/README.md b/benchmarks/edit/code/OpenVE-3M/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a7ba54cbd275ff2019b252e283b68dcf417ed7db --- /dev/null +++ b/benchmarks/edit/code/OpenVE-3M/README.md @@ -0,0 +1,67 @@ +
+ +
+

+ OpenVE-3M: A Large-Scale High-Quality Dataset for Instruction-Guided Video Editing +

+ +
+ +[Haoyang He1*](https://scholar.google.com/citations?hl=zh-CN&user=8NfQv1sAAAAJ), +Jie Wang2*, +[Jiangning Zhang1#](https://zhangzjn.github.io), +[Zhucun Xue1](https://scholar.google.com/citations?user=m3KDreEAAAAJ&hl=en), + +[Xingyuan Bu2](https://scholar.google.com/citations?hl=en&user=cqYaRhUAAAAJ&view_op=list_works), +[Qiangpeng Yang2](https://scholar.google.com/citations?user=vr9z1VQAAAAJ&hl=en&oi=ao), +[Shilei Wen2](https://scholar.google.com/citations?user=zKtYrHYAAAAJ&hl=en&oi=ao), +[Lei Xie1#](https://scholar.google.com/citations?hl=zh-CN&user=7ZZ_-m0AAAAJ), + +1Zhejiang University, 2Bytedance + +\*Equal Contribution. \# Corresponding Author. +
+ +
+   +   +   + +   +   +   +
+ +--- + + + +## 📑 Open-Source Plan +The dataset, code, model, and benchmark are currently under review. Please stay tuned. +- [x] OpenVE-3M Dataset +- [ ] OpenVE-Edit Model +- [x] OpenVE-Bench Benchmark +- [ ] Inference & Multi-gpus Sequence Parallel inference +- [ ] Fine-tuning & Lora-tuning scripts + + + +## 🌍 Introduction +The quality and diversity of instruction-based image editing datasets are continuously increasing, yet large-scale, high-quality datasets for instruction-based video editing remain scarce. To address this gap, we introduce OpenVE-3M, an open-source, large-scale, and high-quality dataset for instruction-based video editing. It comprises two primary categories: spatially-aligned edits (Global Style, Background Change, Local Change, Local Remove, Local Add, and Subtitles Edit) and non-spatially-aligned edits (Camera Multi-Shot Edit and Creative Edit). All edit types are generated via a meticulously designed data pipeline with rigorous quality filtering. OpenVE-3M surpasses existing open-source datasets in terms of scale, diversity of edit types, instruction length, and overall quality. Furthermore, to address the lack of a unified benchmark in the field, we construct OpenVE-Bench, containing 431 video-edit pairs that cover a diverse range of editing tasks with three key metrics highly aligned with human judgment. We present OpenVE-Edit, a 5B model trained on our dataset that demonstrates remarkable efficiency and effectiveness by setting a new state-of-the-art on OpenVE-Bench, outperforming all prior open-source models including a 14B baseline. + +
+demo +

Demonstration of Eight different categories on the same video from the proposed OpenVE-3M dataset.

+
+ + +## 🔗 Citation +If you find OpenVE useful for your research and applications, please cite using this BibTeX: +``` +@article{he2025openve-3m, + title={OpenVE-3M: A Large-Scale High-Quality Dataset for Instruction-Guided Video Editing}, + author={Haoyang He, Jie Wang, Jiangning Zhang, Zhucun Xue, Xingyuan Bu, Qiangpeng Yang, Shilei Wen, Lei Xie}, + journal={arXiv preprint arXiv:2512.07826}, + year={2025} +} +``` diff --git a/benchmarks/edit/code/VE-Bench/.gitignore b/benchmarks/edit/code/VE-Bench/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..09e143424fe9114675d0fba66cf0dbfd85ce5f83 --- /dev/null +++ b/benchmarks/edit/code/VE-Bench/.gitignore @@ -0,0 +1,12 @@ +ckpts +__pycache__ +data +*/__pycache__ +*/*/__pycache__ +*/*/*/__pycache__ +build +dist +*egg-info +.DS_Store +*/.DS_Store +*/*/.DS_Store \ No newline at end of file diff --git a/benchmarks/edit/code/VE-Bench/LICENSE b/benchmarks/edit/code/VE-Bench/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4e7e37894e74e7209176a15c76bfbff50d2622ed --- /dev/null +++ b/benchmarks/edit/code/VE-Bench/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 sunshk1227 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/benchmarks/edit/code/VE-Bench/MANIFEST.in b/benchmarks/edit/code/VE-Bench/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..4dec9f19931773fd7a552f5cf7229b69501c033b --- /dev/null +++ b/benchmarks/edit/code/VE-Bench/MANIFEST.in @@ -0,0 +1,2 @@ +include config/*.yaml +include models/backbone/BLIP_configs diff --git a/benchmarks/edit/code/VE-Bench/README.md b/benchmarks/edit/code/VE-Bench/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e4e6d91624db2bb09aa4c0a4fc7f5f116f663ea0 --- /dev/null +++ b/benchmarks/edit/code/VE-Bench/README.md @@ -0,0 +1,93 @@ +# [\[AAAI 25\] VE-Bench: Subjective-Aligned Benchmark Suite for Text-Driven Video Editing Quality Assessment](https://arxiv.org/abs/2408.11481) + +
+Shangkun Sun, Xiaoyu Liang, Songlin Fan, Wenxu Gao, Wei Gao*
+ +(* Corresponding author)
+ +
+ + + +## 🎦 Introduction +TL;DR: VE-Bench is an evaluation suite for text-driven video editing, consisting of a quality assessment model to provide a human-aligned metric for edited videos, and a database containing rich video-prompt pairs and the corresponding human scores. + +
+ +
+Overview of the VE-Bench Suite +
+ +VE-Bench DB contains a rich collection of source videos, including real-world videos, AIGC videos, and CG videos, covering various aspects such as people, objects, animals, and landscapes. It also includes a variety of editing instructions across different categories, including semantic editing like addition, removal, replacement, etc., as well as structural changes in size, shape, etc., and stylizations such as color, texture, etc. Additionally, it features editing results based on different video editing models. We conducted a subjective experiment involving 24 participants from diverse backgrounds, resulting in 28,080 score samples. We further trained VE-Bench QA model based on this data. The left image below shows the box plot of average scores obtained by each model during the subjective experiment, while the right image illustrates the scores for each model across different types of prompts. + +
+ +
+Left: Average score distributions of 8 editing methods.     Right: Performance on different types of prompts from previous video-editing methods. +
+ +## Easy Use +VE-Bench can be installed with a single ``pip`` command. +``` +pip install vebench +``` +When comparing videos, you can use ``python test.py``, namely: +``` +from vebench import VEBenchModel + +evaluator = VEBenchModel() + +score1 = evaluator.evaluate('A black-haired boy is turning his head', 'assets/src.mp4', 'assets/dst.mp4') +score2 = evaluator.evaluate('A black-haired boy is turning his head', 'assets/src.mp4', 'assets/dst2.mp4') +print(score1, score2) # Score1: 1.3563, Score2: 0.66194 +``` +Since the model employs normalization during training, its output does not represent exactly absolute 1 \~ 10 scores, as demonstrated above. + +## Database +VE-Bench DB is available here. [baidu netdisk](https://pan.baidu.com/s/1D5y6ADXgz8PPHGCxROlNIQ?pwd=sggc) | [google drive](https://drive.google.com/file/d/1SBmXK6XKuyGTaV9LUQXfy5w82bsA3Nve/view?usp=sharing) + + +## Local Inference + +### 💼 Preparation +`` +cd vebench +`` + +You can also download all checkpoints from [google drive](https://drive.google.com/drive/folders/1kD82Ex90VP9A_AqjYV1J5DYvBQW-hkXa?usp=sharing) and put them into ``ckpts``. + +### ✨ Usage +To evaluate one single video: +``` +python -m infer.py --single_test --src_path ${path_to_source_video} --dst_path ${path_to_dst_video} --prompt ${editing_prompt} + +# Run on example videos +# python -m infer.py --single_test --src_path "./data/src/00433tokenflow_baby_gaze.mp4" --dst_path "./data/edited/00433tokenflow_baby_gaze.mp4" --prompt "A black-haired boy is turning his head" +``` + + +To evaluate a set of videos: +``` +python -m infer.py --data_path ${path_to_data_folder} --label_path ${path_to_prompt_txt_file} +``` + +## 🙏 Acknowledgements +Part of the code is developed based on [DOVER](https://github.com/VQAssessment/DOVER) and [BLIP](https://github.com/salesforce/BLIP). We would like to thank the authors for their contributions to the community. + + +## 📭 Contact +If your have any comments or questions, feel free to contact [sunshk@stu.pku.edu.cn](lsunshk@stu.pku.edu.cn). + + + +## 📖 BibTex +```bibtex +@article{sun2024bench, + title={VE-Bench: Subjective-Aligned Benchmark Suite for Text-Driven Video Editing Quality Assessment}, + author={Sun, Shangkun and Liang, Xiaoyu and Fan, Songlin and Gao, Wenxu and Gao, Wei}, + journal={arXiv preprint arXiv:2408.11481}, + year={2024} +} +``` diff --git a/benchmarks/edit/code/VE-Bench/requirements.txt b/benchmarks/edit/code/VE-Bench/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d266debf5ae495d9c9f669b606ccd9f19202f0bc --- /dev/null +++ b/benchmarks/edit/code/VE-Bench/requirements.txt @@ -0,0 +1,7 @@ +decord +einops +fairscale +numpy +timm +transformers +scikit-video diff --git a/benchmarks/edit/code/VE-Bench/setup.py b/benchmarks/edit/code/VE-Bench/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0f18d79d70d14d8d5524d67470b97c967bc5f6ab --- /dev/null +++ b/benchmarks/edit/code/VE-Bench/setup.py @@ -0,0 +1,23 @@ +from setuptools import find_packages, setup + +name = 'vebench' + +long_description='Please refer to https://github.com/littlespray/VE-Bench' + +setup( + name=name, # 包名同工程名,这样导入包的时候更有对应性 + version='1.0.0', + author="Shangkun Sun", + license="MIT Licence", + author_email='sunshk@stu.pku.edu.cn', + description="Evaluator for Text-driven Video Editing", + packages=find_packages(), + python_requires='>=3', + long_description=long_description, + # 设置依赖包 + install_requires=['torch', 'decord', 'einops', 'fairscale', 'numpy', 'timm', 'transformers', 'sk-video'], + include_package_data=True, # 包含额外的非Python文件 + package_data={ + '': ['configs/*.yaml', 'models/backbone/BLIP_configs/*'], # 匹配目录下的所有文件 + }, +) diff --git a/benchmarks/edit/code/VE-Bench/test.py b/benchmarks/edit/code/VE-Bench/test.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe12413b3af70027aedb99245b1c275bcdb6ff8 --- /dev/null +++ b/benchmarks/edit/code/VE-Bench/test.py @@ -0,0 +1,7 @@ +from vebench import VEBenchModel + +evaluator = VEBenchModel() + +score1 = evaluator.evaluate('A black-haired boy is turning his head', 'assets/src.mp4', 'assets/dst.mp4') +score2 = evaluator.evaluate('A black-haired boy is turning his head', 'assets/src.mp4', 'assets/dst2.mp4') +print(score1, score2) \ No newline at end of file diff --git a/benchmarks/edit/code/VEFX-Bench/.gitignore b/benchmarks/edit/code/VEFX-Bench/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..45ef0e8624df197aca98bcd0f2aedea1f1663c2b --- /dev/null +++ b/benchmarks/edit/code/VEFX-Bench/.gitignore @@ -0,0 +1,37 @@ +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +dist/ +build/ +*.egg + +# Environment +.env +*.env + +# IDE +.vscode/ +.idea/ + +# Model weights +*.safetensors +*.pth +*.bin +*.ckpt +*.onnx + +# Data +*.avi +*.mov + +# Keep sample videos for examples +!examples/sample_videos/*.mp4 + +# OS +.DS_Store +Thumbs.db + +# Outputs +merged_model/ +results/ diff --git a/benchmarks/edit/code/VEFX-Bench/LICENSE b/benchmarks/edit/code/VEFX-Bench/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f67df4866303cf355067b17fcab34ddded742791 --- /dev/null +++ b/benchmarks/edit/code/VEFX-Bench/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/benchmarks/edit/code/VEFX-Bench/README.md b/benchmarks/edit/code/VEFX-Bench/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4fb96879e335b407948698bdde1660474158dfb8 --- /dev/null +++ b/benchmarks/edit/code/VEFX-Bench/README.md @@ -0,0 +1,214 @@ +
+ +# VEFX-Bench + +### Benchmarking Generic Video Editing and Visual Effects + +[📄 Paper](https://arxiv.org/abs/2604.16272) • +[💻 Code](https://github.com/Visko-Platform/VEFX-Bench) • +[🤗 Dataset](https://huggingface.co/datasets/xiangbog/VEFX-Bench) • +[🤗 Model (4B)](https://huggingface.co/xiangbog/VEFX-Reward-4B) • +[🏆 Leaderboard](https://vefx-leaderboard.com/) • +[🌐 Project Page](https://xiangbogaobarry.github.io/VEFX-Bench/) + +
+ +**VEFX-Bench** is a comprehensive benchmark for evaluating text-driven video editing and visual effects. It includes **5,049 annotated examples** spanning **9 categories** and **32 subcategories**, evaluated by **VEFX-Reward** — a VLM-based reward model that scores edits across three dimensions on a 1–4 scale: + +| Dimension | What it measures | +|---|---| +| **Instructional Following (IF)** | Does the edit accurately reflect the editing instruction? | +| **Render Quality (RQ)** | Visual clarity, temporal consistency, and physical plausibility | +| **Edit Exclusivity (EE)** | Were only the intended regions modified, without side-effects? | + +--- + +## 🏆 Model Leaderboard + +VEFX-Reward scores on 1–4 scale. Ranked by **GeoAgg** (α=2 for IF, β=1 for RQ, γ=1 for EE). Higher is better. + +> **📅 Updated: May 2, 2026** — For the latest results & submissions, visit the **[live leaderboard →](https://vefx-leaderboard.com/)** + +| Rank | Model | Type | IF ↑ | RQ ↑ | EE ↑ | GeoAgg ↑ | +|:---:|---|---|:---:|:---:|:---:|:---:| +| 🥇 | **Kling o3 Omni** | Commercial | 3.033 | **3.588** | 3.043 | **3.057** | +| 🥈 | **Kling o1** | Commercial | **3.040** | 3.534 | 2.976 | 2.985 | +| 🥉 | **Runway Gen-4.5** | Commercial | 2.817 | 3.319 | 2.923 | 2.912 | +| 4 | Seedance 2.0 | Commercial | 2.811 | 3.421 | 3.088 | 2.766 | +| 5 | Grok Imagine | Commercial | 2.606 | 3.346 | **3.376** | 2.723 | +| 6 | Luma Ray 3 | Commercial | 2.702 | 3.403 | 2.705 | 2.717 | +| 7 | UniVideo | Open-source | 2.294 | 3.266 | 3.091 | 2.516 | +| 8 | Wan 2.6 | Commercial | 2.012 | 3.317 | 2.446 | 2.146 | +| 9 | Luma Ray 2 | Commercial | 2.038 | 2.532 | 1.363 | 1.804 | +| 10 | VACE | Open-source | 2.027 | 3.172 | 1.180 | 1.775 | + +--- + +## 🎬 Demo Videos + +Each demo shows the **original video** (left) alongside the **edited video** (right). + + + + + + + + + + + + + + + + + + +
Attribute Change
"Change the color of the red industrial trailer to a bright yellow while maintaining the texture and appearance of the metal surface."
Object Removal
"Remove the woman with the grey backpack walking on the right side of the frame."
Style Transfer
"Restore the natural, realistic colors to the entire scene, replacing the current black and white style with a full-color rendition."
Camera Motion
"Perform a smooth zoom in on the distant snowy mountain peaks to create a more immersive view."
+ +--- + +## 📊 Benchmark at a Glance + +| | | +|---|---| +| 📝 **5,049** Annotated Examples | 🎬 **1,419** Source Videos | +| 📂 **9 / 32** Categories / Subcategories | 🤖 **10** Editing Systems | +| 📐 **3** Quality Dimensions (IF, RQ, EE) | 🧪 **300** Benchmark Test Pairs | + +--- + +## 🤗 VEFX-Reward Models + +| Model | Backbone | Params | HuggingFace | Status | +|---|---|---|---|---| +| **VEFX-Reward-4B** | Qwen3-VL-4B-Instruct | 4B | [xiangbog/VEFX-Reward-4B](https://huggingface.co/xiangbog/VEFX-Reward-4B) | ✅ Available | +| VEFX-Reward-32B | Qwen3-VL-32B-Instruct | 32B | TBD | 🔜 Coming soon | + +--- + +## 🚀 Quick Start + +### Installation + +```bash +conda create -n vefx-bench python=3.10 -y +conda activate vefx-bench + +# Install PyTorch first (match your CUDA version) +# See https://pytorch.org/get-started/locally/ for the right command +pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124 + +# Install remaining dependencies +pip install -r requirements.txt + +# Install the package +pip install -e . +``` + +> **Requirements:** Python ≥ 3.10, CUDA GPU, ~10 GB VRAM (bfloat16). Make sure your PyTorch CUDA version matches your driver. + +### Score a Video Edit (Python API) + +```python +from vefx_reward import VEFXReward + +model = VEFXReward("xiangbog/VEFX-Reward-4B", device="cuda") + +scores = model.score( + original_video="examples/sample_videos/object_removal_original.mp4", + edited_video="examples/sample_videos/object_removal_edited.mp4", + instruction="Remove the woman with the grey backpack walking on the right side of the frame.", +) +print(scores) +# {'IF': 2.34, 'RQ': 1.93, 'EE': 1.82, 'Overall': 6.09} +``` + +### CLI Usage + +```bash +python examples/quick_start.py \ + --original examples/sample_videos/object_removal_original.mp4 \ + --edited examples/sample_videos/object_removal_edited.mp4 \ + --instruction "Remove the woman with the grey backpack walking on the right side of the frame." +``` + +### Score All Included Samples + +The repo includes 4 sample video pairs with prompts. Score them all: + +```python +import json +from vefx_reward import VEFXReward + +model = VEFXReward("xiangbog/VEFX-Reward-4B", device="cuda") + +with open("examples/sample_videos/prompts.json") as f: + samples = json.load(f) + +for sample in samples: + scores = model.score( + original_video=f"examples/sample_videos/{sample['original']}", + edited_video=f"examples/sample_videos/{sample['edited']}", + instruction=sample["instruction"], + ) + print(f"[{sample['category']}] IF={scores['IF']:.2f} RQ={scores['RQ']:.2f} EE={scores['EE']:.2f}") +``` + +### Batch Scoring + +Prepare a CSV with columns `original_video`, `edited_video`, `instruction`: + +```bash +python examples/batch_scoring.py --csv edits.csv --output results.csv +``` + +### Multi-GPU Scoring + +For large-scale evaluation across multiple GPUs: + +```bash +python examples/multi_gpu_scoring.py --csv edits.csv --num_gpus 4 --output results.csv +``` + +--- + +## 📖 API Reference + +### `VEFXReward` + +```python +VEFXReward( + model_path="xiangbog/VEFX-Reward-4B", # HuggingFace ID or local path + device="cuda", # "cuda", "cuda:0", "cpu" + dtype=torch.bfloat16, # torch.bfloat16 or torch.float16 + fps=4.0, # Video sampling rate + max_frame_pixels=399360, # Max pixels per frame +) +``` + +#### `model.score(original_video, edited_video, instruction) → dict` + +Score a single video edit. Returns `{'IF': float, 'RQ': float, 'EE': float, 'Overall': float}`. + +#### `model.score_batch(original_videos, edited_videos, instructions) → list[dict]` + +Score multiple edits sequentially. Each sample is processed independently to avoid OOM. + +--- + +## 📝 Citation + +```bibtex +@article{gao2025vefxbench, + title={VEFX-Bench: Benchmarking Generic Video Editing and Visual Effects}, + author={Xiangbo Gao and Sicong Jiang and Bangya Liu and Xinghao Chen and Minglai Yang and Siyuan Yang and Mingyang Wu and Jiongze Yu and Qi Zheng and Haozhi Wang and Jiayi Zhang and Jared Yang and Jie Yang and Zihan Wang and Qing Yin and Zhengzhong Tu}, + journal={arXiv preprint arXiv:2604.16272}, + year={2026} +} +``` + +## License + +This project is licensed under the Apache License 2.0. See [LICENSE](LICENSE) for details. diff --git a/benchmarks/edit/code/VEFX-Bench/requirements.txt b/benchmarks/edit/code/VEFX-Bench/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..c019bda19a08ebbefb093b729d861bf82e3a00b5 --- /dev/null +++ b/benchmarks/edit/code/VEFX-Bench/requirements.txt @@ -0,0 +1,11 @@ +torch>=2.1.0 +torchvision>=0.16.0 +transformers>=4.51.0,<5.0.0 +accelerate>=0.30.0 +safetensors>=0.4.0 +huggingface_hub>=0.20.0 +Pillow>=10.0.0 +numpy>=1.24.0 +requests +packaging +decord>=0.6.0 diff --git a/benchmarks/edit/code/VEFX-Bench/setup.py b/benchmarks/edit/code/VEFX-Bench/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a56ec57b94581c6fc0956535c3dd07f804ccee --- /dev/null +++ b/benchmarks/edit/code/VEFX-Bench/setup.py @@ -0,0 +1,30 @@ +from setuptools import setup, find_packages + +setup( + name="vefx-reward", + version="0.1.0", + description="VEFX-Reward: A reward model for video editing quality assessment", + long_description=open("README.md").read(), + long_description_content_type="text/markdown", + url="https://github.com/taco-group/VEFX-Bench", + packages=find_packages(), + python_requires=">=3.10", + install_requires=[ + "torch>=2.1.0", + "torchvision>=0.16.0", + "transformers>=4.51.0", + "accelerate>=0.30.0", + "safetensors>=0.4.0", + "huggingface_hub>=0.20.0", + "Pillow>=10.0.0", + "numpy>=1.24.0", + "requests", + "packaging", + "decord>=0.6.0", + ], + classifiers=[ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + ], +) diff --git a/benchmarks/edit/pdf/EDITREWARD-BENCH.md b/benchmarks/edit/pdf/EDITREWARD-BENCH.md new file mode 100644 index 0000000000000000000000000000000000000000..d1941d44ce534ae23bff8d10e1a57e0b8e7013ad --- /dev/null +++ b/benchmarks/edit/pdf/EDITREWARD-BENCH.md @@ -0,0 +1,201 @@ +# EDITREWARD 详细总结 + +![EDITREWARD 首页与总览图](./assets/editreward-page1.png) + +## 1. 基本信息 + +| 项目 | 内容 | +| --- | --- | +| 论文名 | EDITREWARD: A Human-Aligned Reward Model for Instruction-Guided Image Editing | +| 作者 | Keming Wu, Sicong Jiang, Max Ku, Ping Nie, Minghao Liu, Wenhu Chen | +| 单位 | University of Waterloo、Tsinghua University、2077AI、McGill University、Independent | +| 时间 | 2026-02-28(ICLR 2026) | +| 论文链接 | [arXiv:2509.26346](https://arxiv.org/abs/2509.26346) | +| 项目页 | https://tiger-ai-lab.github.io/EditReward | +| 本地 PDF | [EDITREWARD- A HUMAN-ALIGNED REWARD MODEL FOR INSTRUCTION-GUIDED IMAGE EDITING.pdf](<./EDITREWARD- A HUMAN-ALIGNED REWARD MODEL FOR INSTRUCTION-GUIDED IMAGE EDITING.pdf>) | + +## 2. 这篇论文在做什么 + +虽然它是 **图像编辑** 论文,不是视频编辑 benchmark,但它和视频编辑评测很相关,因为它提供了一个完整的“人类对齐 reward model”范式。 + +论文主要提出 3 个资源: + +1. **EDITREWARD-DATA**:约 200K 人工偏好对数据。 +2. **EDITREWARD**:面向 instruction-guided image editing 的 reward model。 +3. **EDITREWARD-BENCH**:更难的多路偏好 benchmark。 + +## 3. 评估维度 + +EDITREWARD 把图像编辑质量拆成 2 个核心维度: + +1. **Instruction Following, IF** +2. **Visual Quality, VQ** + +这两个维度一起决定“一个编辑结果到底好不好”。 + +作者特别强调:单一总分会掩盖这两种质量之间的矛盾,例如: + +1. 图像很漂亮,但没按指令改对。 +2. 指令改对了,但画面非常假。 + +## 4. 数据来源 + +### 4.1 EDITREWARD-DATA 规模 + +| 项目 | 数量 | +| --- | --- | +| instruction-image 对 | 9,557 | +| 候选编辑图像/样本池 | 每条指令 12 张候选 | +| 人工偏好对 | 约 200K | +| 数据来源数 | 6 个基准源 + 1 个内部难例源 | + +### 4.2 指令来源 + +作者从以下已有人类校验 benchmark / 数据源收集原始 instruction-image 对: + +1. GEdit-Bench +2. ImgEdit-Bench +3. MagicBrush +4. AnyEdit +5. EmuEdit +6. internal challenging set + +### 4.3 候选编辑结果来源 + +每条指令用 6 个 SOTA 模型生成 12 张候选图: + +1. Step1X-Edit +2. Flux-Kontext +3. Qwen-Image-Edit +4. BAGEL +5. Ovis-U1 +6. OmniGen2 + +## 5. 数据处理方法 + +### 5.1 候选生成 + +1. 对每个 source pair 生成 12 张候选图。 +2. 使用多个随机种子,避免单模型偏置。 +3. 从中随机采样 7 张进入人工评估。 + +### 5.2 人工标注 + +1. 每张图按 4 分制对 IF 和 VQ 分别打分。 +2. IF 看语义是否正确、完整、有没有不该改的地方。 +3. VQ 看真实感、无伪影、审美质量。 + +### 5.3 Benchmark 构建 + +EDITREWARD-BENCH 从候选池里精选 500 组高质量 group: + +1. 覆盖 7 个编辑类别。 +2. 每组由 3 个独立专家交叉标注。 +3. 除 pairwise 外,还构造 3-way 和 4-way preference ranking。 +4. 优先保留“候选之间差距很小”的难例,提高区分能力。 + +## 6. 任务类型 + +论文没有像视频 benchmark 那样列完整任务树,但数据覆盖了 instruction-guided image editing 的多种场景,包括: + +1. object insertion / removal +2. style transfer +3. text change +4. 属性和语义编辑 +5. 复杂多候选排序判断 + +## 7. 评估指标与每个指标怎么做 + +### 7.1 人工维度 + +| 指标 | 怎么做 | +| --- | --- | +| IF | 判断编辑结果是否准确、完整地执行了文本指令,并避免额外无关修改。 | +| VQ | 判断图像是否真实、自然、无明显伪影,同时具有良好审美。 | + +### 7.2 Reward model 的输出方式 + +EDITREWARD 不直接输出一个普通标量,而是对每个维度预测一个高斯分布: + +`si,d ~ N(μi,d, σ²i,d)` + +也就是: + +1. 对 IF 预测一个均值和不确定性。 +2. 对 VQ 预测一个均值和不确定性。 + +### 7.3 总分聚合方式 + +作者测试了 3 种聚合策略: + +1. Pessimistic Minimum:取两个维度的较小值。 +2. Balanced Average:取两个维度平均。 +3. Direct Summation:直接相加。 + +最终实验表明多头 + balanced mean 效果最好。 + +### 7.4 排序损失怎么做 + +作者的核心训练目标是 **Multi-Dimensional Uncertainty-Aware Ranking Loss**: + +1. 先把两个维度的预测聚合成一个有效分数。 +2. 再根据两个候选的分数分布,计算偏好概率 `P(Ih > Il)`。 +3. 用负对数似然训练。 + +此外还做了: + +1. pointwise aggregated score regression 对比实验 +2. tie disentanglement,把“总体打平但两个维度各有优劣”的样本拆成两条相反偏好监督 + +### 7.5 EDITREWARD-BENCH 的评价方式 + +| 指标 | 怎么做 | +| --- | --- | +| K=2 | 普通 pairwise preference accuracy | +| K=3 | ternary ranking,要求同时判断三者所有 pair 的偏好关系 | +| K=4 | quaternary ranking,要求同时判断四者所有 pair 的偏好关系 | +| Overall | 综合 K=2/3/4 的多路偏好表现 | + +这里的关键点是:**不是只判断 A 是否优于 B,而是判断整个候选组排序逻辑是否一致。** + +### 7.6 外部 benchmark 上的验证指标 + +作者在不同 benchmark 上使用不同统计标准: + +1. GenAI-Bench:pairwise accuracy +2. AURORA-Bench:pairwise accuracy +3. ImagenHub:Spearman correlation +4. EDITREWARD-BENCH:multi-way preference accuracy + +## 8. 结果中的关键信息 + +1. EDITREWARD (MiMo-VL-7B) 在 GenAI-Bench 达到 65.72。 +2. 在 AURORA-Bench 达到 63.62。 +3. 在 EDITREWARD-BENCH Overall 达到 38.42,为文中最好。 +4. 用它从 46K ShareGPT-4o-Image 中筛 Top 20K,再微调 Step1X-Edit,GEdit-Bench Overall 从 6.780 提升到 7.086。 + +## 9. 特点 + +### 9.1 作为 reward benchmark 的特点 + +1. 大规模人工高质量偏好数据,不是纯合成标签。 +2. 多维评价,不是单标量。 +3. 多路偏好 benchmark,比单纯 pairwise 更难。 +4. 不只评 judge,还验证了 reward model 在数据筛选上的实用价值。 + +### 9.2 对视频编辑研究的启发 + +虽然这是图像编辑论文,但对视频编辑 benchmark 很有借鉴意义: + +1. 多维 label 比单分数更有信息量。 +2. reward model 应同时看 source、instruction、edited output。 +3. “只改该改的地方”应被单独建模,而不是藏进总分里。 + +### 9.3 局限 + +1. 场景是图像编辑,不是视频。 +2. 作者也承认模型有亮度偏好、背景过编辑等失败模式。 + +## 10. 一句话评价 + +EDITREWARD 的价值在于把“人类对齐编辑评估”做成了一个完整闭环:**数据集、reward model、难例 benchmark、下游数据筛选应用** 全都补上了。 diff --git a/benchmarks/edit/pdf/FIVE-BENCH.md b/benchmarks/edit/pdf/FIVE-BENCH.md new file mode 100644 index 0000000000000000000000000000000000000000..4b54056c0c8dea71e204d8165e5bec9c356350e7 --- /dev/null +++ b/benchmarks/edit/pdf/FIVE-BENCH.md @@ -0,0 +1,177 @@ +# FiVE 详细总结 + +![FiVE 首页与总览图](./assets/five-page1.png) + +## 1. 基本信息 + +| 项目 | 内容 | +| --- | --- | +| 论文名 | FiVE: A Fine-grained Video Editing Benchmark for Evaluating Emerging Diffusion and Rectified Flow Models | +| 作者 | Minghan Li, Chenxi Xie, Yichen Wu, Lei Zhang, Mengyu Wang | +| 单位 | Harvard AI and Robotics Lab, Harvard University;Broad Institute;Hong Kong Polytechnic University;Harvard SEAS;City University of Hong Kong;Kempner Institute | +| 时间 | 2025-07-21(arXiv v2) | +| 论文链接 | [arXiv:2503.13684](https://arxiv.org/abs/2503.13684) | +| 项目页 | https://sites.google.com/view/five-benchmark | +| 本地 PDF | [FiVE - A Fine-grained Video Editing Benchmark for Evaluating Emerging Diffusion and Rectified Flow Models.pdf](<./FiVE - A Fine-grained Video Editing Benchmark for Evaluating Emerging Diffusion and Rectified Flow Models.pdf>) | + +## 2. 这篇论文在做什么 + +FiVE 的定位非常明确:它不是做“通用视频编辑 benchmark”,而是专门做 **细粒度对象级视频编辑** 评测。 + +它关注的问题是: + +1. 模型能不能精确修改目标对象。 +2. 修改对象后,背景和时间一致性能不能保住。 +3. 现有指标是否真的能衡量“编辑是否成功”。 + +因此 FiVE 提出了: + +1. **FiVE Benchmark**:100 个视频、420 条对象级编辑 prompt、配套 mask。 +2. **FiVE-Acc**:一个 VLM 驱动的“编辑成功率”指标。 + +## 3. 评估维度 + +FiVE 的评测可以分成两层: + +1. 传统客观指标层:结构、背景保留、文本一致性、图像质量、时间一致性、运行时间。 +2. 细粒度成功率层:FiVE-Acc。 + +## 4. 数据来源 + +### 4.1 数据规模 + +| 项目 | 数量 | +| --- | --- | +| 视频总数 | 100 | +| 真实视频 | 74 | +| 合成视频 | 26 | +| 编辑任务 | 6 | +| prompt 对 | 420 | +| 每视频帧数范围 | 35-126 | +| 掩码 | 提供 | + +### 4.2 视频来源 + +1. 74 个真实视频来自 DAVIS。 +2. 26 个高真实感合成视频由 T2V 模型生成。 + +### 4.3 数据来源特点 + +1. 既有真实视频,也有生成视频,方便比较两类输入下的编辑性能。 +2. 明确提供 source object words、edited object words、instruction、mask。 +3. 非常强调对象级精细修改。 + +## 5. 数据处理方法 + +### 5.1 视频描述构建 + +1. 对 DAVIS 视频每隔 8 帧抽样。 +2. 用 GPT-4o 为视频生成结构化 caption。 +3. caption 包含对象类别、动作、背景、镜头运动等。 +4. 标注是否存在 non-rigid deformation,方便区分任务难度。 + +### 5.2 任务与 prompt 构建 + +1. 对 4 类核心对象编辑任务,用 GPT-4o 为每个视频生成 4 组 source-target prompt。 +2. 额外选 10 个视频做 add,10 个视频做 remove。 +3. 为兼容不同编辑模型,再生成 instruction prompt。 +4. 用 SAM2 生成编辑区域 mask,用于背景保留指标。 + +## 6. 任务类型 + +FiVE 的 6 类细粒度视频编辑任务是: + +1. Object substitution without non-rigid deformation +2. Object substitution with non-rigid deformation +3. Color alteration +4. Material modification +5. Object addition +6. Object removal + +这 6 类任务里,前 4 类都是对象级微操作,明显比一般 benchmark 更细。 + +## 7. 评估指标与每个指标怎么做 + +FiVE 总共使用 15 个指标:10 个传统指标 + 5 个 FiVE-Acc 指标。 + +### 7.1 传统指标 + +| 指标组 | 指标 | 怎么做 | +| --- | --- | --- | +| Structure | Structure Distance | 衡量编辑结果与源视频在结构上的差异,越小越好。 | +| Background Preservation | PSNR | 在编辑 mask 之外计算背景保真。 | +| Background Preservation | LPIPS | 在编辑区域外看感知差异,越小越好。 | +| Background Preservation | MSE | 在编辑区域外看像素误差。 | +| Background Preservation | SSIM | 在编辑区域外看结构相似性。 | +| Text Alignment | CLIPSIM | 对整张图/整帧计算文本-图像一致性。 | +| Text Alignment | CLIPS.edit | 只在编辑区域看文本-图像一致性。 | +| IQA | NIQE | 无参考图像质量指标,越低越好。 | +| Temporal Consistency | Motion Fidelity Score | 评估时间一致性和动作保持。 | +| Efficiency | Time / per-frame runtime | 评估编辑效率。 | + +### 7.2 FiVE-Acc:细粒度编辑成功率 + +FiVE-Acc 是这篇论文最有辨识度的部分。 + +#### 7.2.1 基础流程 + +1. 给编辑后视频提问。 +2. 由 Qwen2.5-VL-7B 回答。 +3. 根据回答是否正确,计算对象编辑成功率。 + +#### 7.2.2 四个子指标 + +| 指标 | 怎么做 | +| --- | --- | +| FiVE-YN-Acc | 问两个 Yes/No 问题:源对象还在不在、目标对象在不在。只有“源对象不存在 + 目标对象存在”才算成功。 | +| FiVE-MC-Acc | 提一个多选题,让 VLM 在“源对象/目标对象”之间识别编辑后视频中的正确对象。 | +| FiVE-∪-Acc | 只要 FiVE-YN 或 FiVE-MC 其中之一成立,就算通过,反映整体成功率。 | +| FiVE-∩-Acc | 要求 FiVE-YN 和 FiVE-MC 同时成立,反映高质量成功率。 | +| FiVE-Acc | 最终综合准确率,按各编辑类型分别计算后再平均。 | + +### 7.3 为什么 FiVE-Acc 重要 + +作者指出,仅看 CLIP 分数不够,因为: + +1. CLIP 高,不等于对象真的改对。 +2. 对象替换、材质修改、删除等任务需要“对象级正确性”。 +3. FiVE-Acc 更像“编辑成功率”,更接近人类直观判断。 + +论文还拿 Qwen2.5-VL 与 Human 做对比,FiVE-Acc 上二者整体接近,说明 VLM judge 在这个任务上具备一定可信度。 + +## 8. 特点 + +### 8.1 作为 Benchmark 的特点 + +1. 是明显偏 **fine-grained object-level editing** 的 benchmark。 +2. 数据不算最大,但标注结构最适合“对象编辑成功/失败”分析。 +3. 提供 mask,使背景保留指标更可信。 +4. 提出 FiVE-Acc,弥补传统 CLIP 类指标不足。 + +### 8.2 核心维度拆解 + +1. 目标对象是否改对。 +2. 原背景是否保住。 +3. 运动/时间一致性是否保住。 +4. 运行成本是否可接受。 + +### 8.3 论文给出的任务难度结论 + +作者总结的难度从易到难大致是: + +1. color change 最容易 +2. rigid object replacement 和 object addition 相对较容易 +3. non-rigid transformation、material change 中等偏难 +4. object removal 最难 + +## 9. 适合怎么使用 + +FiVE 特别适合: + +1. 评估对象替换、加物体、删物体这类精细编辑。 +2. 比较不同方法在目标对象层面的成功率。 +3. 研究“传统指标高,但对象其实没改对”的失败模式。 + +## 10. 一句话评价 + +FiVE 的核心贡献不是“更大”,而是“更准”地评细粒度对象编辑,尤其是用 **FiVE-Acc** 把“对象到底改没改对”从隐含问题变成了显式指标。 diff --git a/benchmarks/edit/pdf/IVE-BENCH.md b/benchmarks/edit/pdf/IVE-BENCH.md new file mode 100644 index 0000000000000000000000000000000000000000..17675bde233deb313f9a4a9013d394942c9737df --- /dev/null +++ b/benchmarks/edit/pdf/IVE-BENCH.md @@ -0,0 +1,191 @@ +# IVEBench 详细总结 + +![IVEBench 首页与总览图](./assets/ive-bench-page1.png) + +## 1. 基本信息 + +| 项目 | 内容 | +| --- | --- | +| 论文名 | IVEBENCH: Modern Benchmark Suite for Instruction-Guided Video Editing Assessment | +| 作者 | Yinan Chen, Jiangning Zhang, Teng Hu, Yuxiang Zeng, Zhucun Xue, Qingdong He, Chengjie Wang, Yong Liu, Xiaobin Hu, Shuicheng Yan | +| 单位 | 浙江大学、Tencent Youtu Lab、上海交通大学、University of Auckland、National University of Singapore | +| 时间 | 2025-10-13 | +| 论文链接 | [arXiv:2510.11647](https://arxiv.org/abs/2510.11647) | +| 代码 | https://github.com/RyanChenYN/IVEBench | +| 数据 | https://huggingface.co/datasets/Coraxor/IVEBench | +| 项目页 | https://ryanchenyn.github.io/projects/IVEBench | +| 本地 PDF | [IVEBENCH- Modern Benchmark Suite for Instruction-Guided Video Editing Assessment.pdf](<./IVEBENCH- Modern Benchmark Suite for Instruction-Guided Video Editing Assessment.pdf>) | + +## 2. 这篇论文在做什么 + +IVEBench 是一套专门面向 **Instruction-Guided Video Editing, IVE** 的现代评测基准。它不仅给出数据,还系统设计了任务、提示词、短视频/长视频划分,以及一套三大维度、12 个指标的综合评测协议。 + +它解决的是已有视频编辑 benchmark 的三类问题: + +1. 源视频不够多样。 +2. 编辑任务覆盖不全,尤其缺少真正面向“指令式编辑”的任务。 +3. 评测指标过于单薄,难以兼顾画质、指令遵循、内容保真。 + +## 3. 评估维度 + +IVEBench 的评测框架分为 3 大维度、12 个细粒度指标: + +1. 视频质量(Video Quality) +2. 指令遵循(Instruction Compliance) +3. 视频保真度(Video Fidelity) + +更细的 12 个指标如下: + +| 大维度 | 子指标 | 含义 | +| --- | --- | --- | +| 视频质量 | SC | Subject Consistency,主体跨帧一致性 | +| 视频质量 | BC | Background Consistency,背景跨帧一致性 | +| 视频质量 | TF | Temporal Flickering,时序闪烁 | +| 视频质量 | MS | Motion Smoothness,运动平滑度 | +| 视频质量 | VTSS | Video Training Suitability Score,综合视频质量 | +| 指令遵循 | OSC | Overall Semantic Consistency,全局语义一致性 | +| 指令遵循 | PSC | Phrase Semantic Consistency,短语级语义一致性 | +| 指令遵循 | IS | Instruction Satisfaction,指令满足度 | +| 指令遵循 | QA | Quantity Accuracy,数量准确度 | +| 视频保真度 | SF | Semantic Fidelity,语义保真度 | +| 视频保真度 | MF | Motion Fidelity,运动保真度 | +| 视频保真度 | CF | Content Fidelity,内容保真度 | + +## 4. 数据来源 + +### 4.1 视频来源 + +作者从以下来源收集高质量源视频: + +1. Pexels +2. Mixkit +3. UltraVideo +4. OpenHumanVid + +### 4.2 数据规模 + +| 项目 | 数量 | +| --- | --- | +| 源视频 | 600 | +| 短视频子集 | 400(32-128 帧) | +| 长视频子集 | 200(129-1024 帧) | +| 语义维度 | 7 | +| 细粒度主题 | 30 | +| 编辑大类 | 8 | +| 编辑子类 | 35 | + +### 4.3 数据来源特点 + +1. 视频分辨率要求较高,主要收集 2K 及以上素材。 +2. 同时覆盖短视频和长视频,避免 benchmark 只适合短片编辑。 +3. 专门补充 OpenHumanVid 来增强人类主体视频的数量和多样性。 + +## 5. 数据处理方法 + +IVEBench 的数据构建流程比较完整,分为“视频筛选”和“提示生成”两大段。 + +### 5.1 源视频处理 + +1. 先按 7 个语义维度和 30 个细粒度主题定义采样目标。 +2. 自动预处理去除黑边、字幕、低质量内容。 +3. 再进行人工筛选,保证视频确实适合编辑,且难度从简单到复杂都有覆盖。 +4. 用 Qwen2.5-VL-72B 为每个源视频生成结构化 caption,覆盖主体、背景、动作、情绪、风格、视角、镜头运动等要素。 + +### 5.2 编辑提示生成 + +1. 先定义 8 个大类、35 个子类的编辑任务空间。 +2. 基于源视频 caption,用大语言模型生成 edit prompt。 +3. 人工再次修订 prompt,保证任务可执行、语义明确、粒度足够细。 +4. 同时生成 target prompt、target phrase、target span,便于后续不同层级的评测。 + +## 6. 任务类型 + +IVEBench 支持 8 大类 IVE 任务: + +1. Style Editing +2. Subject Editing +3. Attribute Editing +4. Quantity Editing +5. Subject Motion Editing +6. Visual Effect Editing +7. Camera Motion Editing +8. Camera Angle Editing + +这些任务覆盖了传统 source-target prompt benchmark 很少覆盖的“视频专属编辑能力”,尤其是: + +1. 主体运动修改 +2. 镜头运动修改 +3. 镜头角度修改 +4. 数量控制 + +## 7. 评估指标与每个指标怎么做 + +### 7.1 视频质量维度 + +| 指标 | 怎么做 | +| --- | --- | +| SC 主体一致性 | 对视频中主体做跨帧特征比较,使用 DINO 特征计算主体在时间维上的一致性,衡量主体身份和外观是否稳定。 | +| BC 背景一致性 | 用 CLIP 特征比较背景跨帧相似度,衡量背景场景是否稳定。 | +| TF 时序闪烁 | 对采样帧之间计算平均绝对差异,量化画面闪烁问题;差异越异常,闪烁越严重。 | +| MS 运动平滑度 | 利用视频插帧模型的 motion prior 来评估运动连续性,看是否存在抖动、突变、不自然加速度。 | +| VTSS | 使用在人类标注数据上训练的监督式视频质量模型,综合考察构图、审美、锐度、色彩饱和度、自然性与运动稳定性。 | + +### 7.2 指令遵循维度 + +| 指标 | 怎么做 | +| --- | --- | +| OSC 全局语义一致性 | 用 VideoCLIP-XL2 计算目标视频与 target prompt 的语义相似度,关注整段视频是否整体符合指令。 | +| PSC 短语语义一致性 | 用 VideoCLIP-XL2 计算目标视频与 target phrase 的相似度,重点检查被编辑对象或局部语义是否命中。 | +| IS 指令满足度 | 将 edit prompt 与目标视频一起输入 Qwen2.5-VL,由 MLLM 按预定义等级标准打分,适合传统指标难覆盖的主体运动、相机运动、机位编辑。 | +| QA 数量准确度 | 将 target span 输入 Grounding DINO,比较检测框数量和指令中要求的数量是否一致;正确记 1,错误记 0。 | + +### 7.3 视频保真度维度 + +| 指标 | 怎么做 | +| --- | --- | +| SF 语义保真度 | 用 VideoCLIP-XL2 计算源视频和目标视频之间的特征相似度,衡量未编辑语义是否被保留下来。 | +| MF 运动保真度 | 用 CoTracker3 提取源/目标视频中的运动轨迹,再做轨迹匹配与相似度计算,关注编辑前后动作轨迹是否保真。 | +| CF 内容保真度 | 对相机运动、机位、转场等传统匹配困难任务,借助 Qwen2.5-VL 判断目标视频是否仍保留源视频关键内容。 | + +### 7.4 汇总方式 + +作者还设计了统一加权方式: + +1. 12 个指标先分别算分。 +2. 三个大维度再聚合成总分。 +3. 权重来自人工重要性评分。 +4. 文中说明 VTSS 权重最高,IS 和 CF 次之,其余指标权重较低但仍保留。 + +## 8. 特点 + +### 8.1 作为 Benchmark 的特点 + +1. 是专门为 **指令引导视频编辑** 设计的,不再依赖 source-target prompt 作为唯一接口。 +2. 同时覆盖短视频和长视频。 +3. 任务空间完整,8 类 35 子类已经很接近真实编辑需求。 +4. 评测协议明显比旧 benchmark 更系统,不只看 text alignment。 + +### 8.2 核心维度拆解 + +1. 视频质量:画面稳不稳、顺不顺、像不像真实视频。 +2. 指令遵循:模型有没有真正把用户说的编辑做出来。 +3. 视频保真度:除了该改的地方,原视频该保留的内容有没有保住。 + +### 8.3 和已有 benchmark 的差异 + +1. 比 VE-Bench、EditBoard 更偏向 instruction-guided setting。 +2. 比 FiVE 更强调“通用 IVE 全面评测”,而不是“细粒度对象编辑”。 +3. 引入多模态大模型参与评价,覆盖传统指标做不好的运动/机位类任务。 + +## 9. 适合怎么使用 + +如果你的研究目标是下面这些方向,IVEBench 很适合: + +1. 通用 instruction-based video editing 模型。 +2. 长视频编辑模型。 +3. 相机运动、相机角度、数量编辑等复杂任务。 +4. 需要比较系统、细粒度、接近人工感知的自动评测。 + +## 10. 一句话评价 + +IVEBench 的价值在于:它不是只扩充数据量,而是把 **数据、任务、指标、MLLM 评审、长短视频划分** 一次性补齐了,属于当前非常完整的一套 IVE benchmark。 diff --git a/benchmarks/edit/pdf/SST-EM-BANCH.md b/benchmarks/edit/pdf/SST-EM-BANCH.md new file mode 100644 index 0000000000000000000000000000000000000000..f52754c16c7cba2214560c8086d4aac53110e1bc --- /dev/null +++ b/benchmarks/edit/pdf/SST-EM-BANCH.md @@ -0,0 +1,171 @@ +# SST-EM 详细总结 + +![SST-EM 首页与总览图](./assets/sst-em-page1.png) + +## 1. 基本信息 + +| 项目 | 内容 | +| --- | --- | +| 论文名 | SST-EM: Advanced Metrics for Evaluating Semantic, Spatial and Temporal Aspects in Video Editing | +| 作者 | Varun Biyyala, Bharat Chanderprakash Kathuria, Jialu Li, Youshan Zhang | +| 单位 | Yeshiva University, Katz School of Science and Health, Graduate Computer Science and Engineering Department | +| 时间 | 2025-01-13 | +| 论文链接 | [arXiv:2501.07554](https://arxiv.org/abs/2501.07554) | +| 本地 PDF | [SST-EM- Advanced Metrics for Evaluating Semantic, Spatial and Temporal Aspects in Video Editing .pdf](<./SST-EM- Advanced Metrics for Evaluating Semantic, Spatial and Temporal Aspects in Video Editing .pdf>) | + +## 2. 这篇论文在做什么 + +SST-EM 不是传统意义上的 benchmark 数据集论文,更像一个 **视频编辑自动评测框架/复合指标**。 + +它的目标是补足传统 CLIP 类指标的不足: + +1. 只看文本相似度,难捕捉复杂语义。 +2. 只看图像相似度,看不到时间一致性。 +3. 缺少对“目标对象是否真的被改对了”的显式检测。 + +因此作者设计了一个 4 阶段 pipeline,并把结果合成为 SST-EM 总分。 + +## 3. 评估维度 + +SST-EM 名字里的三个维度分别是: + +1. Semantic +2. Spatial +3. Temporal + +在实现上,SST-EM 实际主要落地为 3 个可量化子分数: + +1. Context Similarity Score +2. Object Detection Score +3. Temporal Consistency Score + +然后再做加权融合得到最终 SST-EM 分数。 + +## 4. 数据来源 + +### 4.1 数据来源 + +论文主数据来自: + +1. Enhanced End-to-End Video Editing dataset + +并补充了额外的多动作、多颜色、可编程 zoom 场景数据,用于验证公式鲁棒性。 + +### 4.2 数据规模 + +| 项目 | 数量 | +| --- | --- | +| 视频对 | 40(用于权重优化) | +| frame-prompt 对 | 640(优化集) | +| 视频对 | 40(用于验证/评估) | +| frame-prompt 对 | 900(验证集) | + +### 4.3 涉及的编辑模型来源 + +文中提到的数据覆盖多种编辑模型生成结果,例如: + +1. MotionDirector +2. Trailblazer +3. Tune-A-Video +4. Text2LIVE + +而在最终比较中,还评估了: + +1. VideoP2P +2. TokenFlow +3. Control-A-Video +4. FateZero + +## 5. 数据处理方法 + +1. 将编辑后视频拆成逐帧图像。 +2. 每一帧和对应 editing prompt 配对。 +3. 构建两个子集: + - 权重优化集:用于拟合 SST-EM 公式中的权重。 + - 验证集:用于检查模型对人工评价的复现能力。 +4. 人工评价作为监督信号,综合考虑语义准确性、空间一致性、时间一致性。 + +## 6. 任务类型 + +SST-EM 不是围绕任务树设计的 benchmark,因此文中没有像 IVEBench/FiVE 那样给出完整任务 taxonomy。它更强调“评测公式怎么设计”。 + +从数据描述看,它希望覆盖: + +1. motion manipulation +2. visual style transfer +3. object manipulation +4. zoom / trajectory 类场景 + +## 7. 评估指标与每个指标怎么做 + +### 7.1 Stage 1: Context Similarity Score + +| 指标 | 怎么做 | +| --- | --- | +| Context Similarity Score | 用 PaliGemma 为每一帧生成 caption,再与 editing prompt 计算余弦相似度,衡量视频内容在语义上是否符合指令。 | + +### 7.2 Stage 2: Object Detection Score + +| 指标 | 怎么做 | +| --- | --- | +| Object Detection Score | 用 Grounding DINO 做 text-conditioned object detection,检测 prompt 中主对象是否在各帧中被正确识别;对各帧置信度取平均。 | + +作者还引入了: + +1. **Mistral-7B-Instruct-v0.3** 作为 LLM agent,用来帮助聚焦“主对象”。 + +也就是说,这一步不是泛泛地检测所有物体,而是尽量让检测模型盯住“编辑指令的核心对象”。 + +### 7.3 Stage 3: Temporal Consistency Score + +| 指标 | 怎么做 | +| --- | --- | +| Temporal Consistency Score | 用 Vision Transformer 提取相邻帧 embedding,计算连续帧之间的余弦相似度并取平均,衡量过渡是否平滑连贯。 | + +### 7.4 Stage 4: Final SST-EM Score + +最终分数公式为: + +`Sfinal = w1 * Ssimilarity + w2 * Sobject_detection + w3 * (1 - Stemporal)` + +文中说明: + +1. `w1, w2, w3` 不是手工拍脑袋设的。 +2. 它们通过线性回归,用人工评价分数拟合得到。 +3. 权重优化在 optimization set 上做,泛化验证在 validation set 上做。 + +## 8. 验证指标 + +作者用下列统计量验证 SST-EM 与人工打分的一致性: + +1. Pearson correlation +2. Spearman correlation +3. Kendall correlation +4. R1 score + +文中声称 SST-EM 的 Pearson 相关性最高,达到 0.962,高于其他比较指标。 + +## 9. 特点 + +### 9.1 作为评测框架的特点 + +1. 不是只算一个 CLIP 分,而是把语义、对象、时间三个方面拼起来。 +2. 引入 Object Detection,使“对象有没有改对”成为显式维度。 +3. 用人类评价回归出权重,而不是完全手工定权。 + +### 9.2 核心维度拆解 + +1. 语义:改的内容是否符合文本。 +2. 空间/对象:关键对象是否真的出现/消失/替换。 +3. 时间:跨帧是否稳定自然。 + +### 9.3 局限 + +1. 数据规模不大。 +2. 评测管线较重,包含 VLM、Grounding DINO、LLM agent、ViT,多模型串联成本高。 +3. 最终是线性加权公式,表达能力有限。 +4. 论文更偏“工程式复合 metric”,不是一个成熟社区 benchmark。 + +## 10. 一句话评价 + +SST-EM 的价值不在于提供大规模 benchmark,而在于提出了一种 **“语义 + 对象 + 时序”三合一的视频编辑评测思路**,适合当作复合自动指标参考。 diff --git a/benchmarks/edit/pdf/VE-BENCH.md b/benchmarks/edit/pdf/VE-BENCH.md new file mode 100644 index 0000000000000000000000000000000000000000..161540015d220936c9195354ca096975832ded37 --- /dev/null +++ b/benchmarks/edit/pdf/VE-BENCH.md @@ -0,0 +1,192 @@ +# VE-Bench 详细总结 + +![VE-Bench 首页与总览图](./assets/ve-bench-page1.png) + +## 1. 基本信息 + +| 项目 | 内容 | +| --- | --- | +| 论文名 | VE-Bench: Subjective-Aligned Benchmark Suite for Text-Driven Video Editing Quality Assessment | +| 作者 | Shangkun Sun, Xiaoyu Liang, Songlin Fan, Wenxu Gao, Wei Gao | +| 单位 | 北京大学 SECE、鹏城实验室 | +| 时间 | 2024-12-18(arXiv v2) | +| 论文链接 | [arXiv:2408.11481](https://arxiv.org/abs/2408.11481) | +| 本地 PDF | [VE-Bench- Subjective-Aligned Benchmark Suite for Text-Driven Video Editing Quality Assessment.pdf](<./VE-Bench- Subjective-Aligned Benchmark Suite for Text-Driven Video Editing Quality Assessment.pdf>) | + +## 2. 这篇论文在做什么 + +VE-Bench 想解决两个问题: + +1. 现有视频编辑指标和人的主观感受不够一致。 +2. 视频编辑缺少带有主观分数的人类标注数据集。 + +因此它提出了两部分内容: + +1. **VE-Bench DB**:一个面向视频编辑质量评估的数据库。 +2. **VE-Bench QA**:一个面向视频编辑的主观一致性自动评估网络。 + +它的重点不是“任务更全”,而是 **主观对齐**,也就是让自动分数更接近人类打分。 + +## 3. 评估维度 + +VE-Bench 的核心评估思想可以拆成 3 个维度: + +1. 编辑结果与文本指令的对齐程度。 +2. 编辑结果与源视频之间的关联/保真程度。 +3. 编辑后视频本身的画质,包括审美和技术失真。 + +人工主观实验中,参与者也正是围绕这三点打分: + +1. Text-video consistency +2. Source-target fidelity +3. Edited video quality + +## 4. 数据来源 + +### 4.1 视频来源 + +VE-Bench DB 的源视频来自三大类: + +1. Real-world videos +2. CG-rendered videos +3. AIGC videos + +同时覆盖: + +1. 人、动物、物体、风景等主体 +2. 不同动作与职业/年龄/性别 +3. ego-motion 和 exo-motion 等不同运动模式 + +### 4.2 数据规模 + +| 项目 | 数量 | +| --- | --- | +| 源视频 | 169 | +| 编辑模型 | 8 | +| 编辑结果 | 1,170(人工筛选后) | +| 人类标注者 | 24 | + +### 4.3 数据来源特点 + +1. 是文中声称的首个面向 text-driven video editing 的 VQA 数据库。 +2. 不是只收真实视频,也包含 CG 和 AIGC 视频。 +3. 明确保留了人类 MOS 分数,便于训练和验证自动评估器。 + +## 5. 数据处理方法 + +VE-Bench DB 的构建流程有 4 个阶段: + +1. Source video collection +2. Prompt composition +3. Editing model selection and execution +4. Subjective experiments + +### 5.1 视频收集 + +1. 从公开视频和互联网素材中收集多样化视频。 +2. 保证动作、主体、场景、运动模式都足够多样。 + +### 5.2 Prompt 设计 + +作者将编辑 prompt 分成 3 大类: + +1. Style editing:颜色、纹理、整体氛围等风格修改。 +2. Semantic editing:增加、删除、替换对象,修改背景等。 +3. Structural editing:大小、姿态、运动等结构性变化。 + +这些 prompt 由人工设计,以保证具体且有区分度。 + +### 5.3 主观标注 + +1. 24 位受试者参与评分。 +2. 对每个结果视频按 1-10 分打分。 +3. 打分时综合考虑文本一致性、源目标保真、视频质量。 +4. 原始 MOS 用 Z-score 做归一化,去掉不同受试者的个人尺度差异。 + +## 6. 任务类型 + +VE-Bench 本身不是按超细任务树展开,而是用 3 类 prompt 覆盖主要视频编辑场景: + +1. 风格编辑 +2. 语义编辑 +3. 结构编辑 + +从论文例子和描述看,实际覆盖的具体操作包括: + +1. Addition +2. Removal +3. Replacement +4. Color / Texture / Atmosphere change +5. Size / Shape / Pose / Motion change +6. Background editing + +## 7. 评估指标与每个指标怎么做 + +VE-Bench 的“指标”分两层理解: + +1. **数据库层**:人类给出的 MOS,是最终监督信号。 +2. **自动评估层**:VE-Bench QA 网络,用多分支结构预测与人类主观评分对齐的质量分数。 + +### 7.1 VE-Bench QA 的三个核心评分分支 + +| 分支 | 作用 | 怎么做 | +| --- | --- | --- | +| Text-video alignment | 看结果是否符合 prompt | 采用 BLIP 视觉编码器和文本编码器,并加 temporal adapter,把视频和文本做跨模态交互后得到对齐分数。 | +| Source-target relationship | 看编辑前后是否保持合理关联 | 分别编码 source video 和 edited video 的时空特征,再做拼接和前馈网络建模两者关系。 | +| Visual quality | 看结果视频本身好不好 | 借鉴 DOVER 的思路,拆成美学分支和技术失真分支。 | + +### 7.2 Visual quality 分支内部怎么做 + +| 子分支 | 怎么做 | +| --- | --- | +| Aesthetic | 用 inflated ConvNext,预训练于 AVA,评估审美质量。 | +| Technical distortion | 用 VideoSwin-Tiny,结合 GRPB 预训练,评估技术失真、伪影、清晰度等。 | + +### 7.3 最终自动指标 + +VE-Bench QA 最终输出一个与人类主观偏好对齐的综合分数。它不是简单拼几个现成指标,而是一个针对视频编辑任务训练出来的评估器。 + +### 7.4 论文中用于验证评估器的统计指标 + +作者用以下统计量验证 VE-Bench QA 和 MOS 的一致程度: + +| 指标 | 含义 | +| --- | --- | +| SROCC | Spearman 秩相关,衡量排序一致性 | +| PLCC | Pearson 线性相关,衡量线性拟合程度 | +| KRCC | Kendall 秩相关,衡量排序相关性 | +| RMSE | 均方根误差,衡量预测误差 | + +这四个不是视频编辑任务指标本身,而是“评估器好不好”的验证指标。 + +## 8. 特点 + +### 8.1 作为 Benchmark 的特点 + +1. 强调与人类主观评分对齐。 +2. 同时提供数据集和自动评估器,而不是只给数据或只给指标。 +3. 把 source-target 关系显式纳入自动评估,而不是只看编辑后视频单独质量。 + +### 8.2 核心维度拆解 + +1. Prompt adherence:有没有按文字改。 +2. Source-target relevance:有没有在保留原视频基础上改。 +3. Quality itself:改出来的视频像不像高质量视频。 + +### 8.3 相比后续 benchmark 的局限 + +1. 任务类别覆盖还不算特别广。 +2. 更像“主观一致性质量基准”,不是“全任务覆盖型 benchmark”。 +3. 最终质量分数是单标量,不如后来的多维显式解耦 benchmark 丰富。 + +## 9. 适合怎么使用 + +VE-Bench 特别适合: + +1. 训练或验证自动视频编辑评估器。 +2. 希望用 MOS 对齐的方式比较模型。 +3. 研究“编辑结果是否更符合人类偏好”而不是只追求单项客观指标。 + +## 10. 一句话评价 + +VE-Bench 的最大贡献是把“视频编辑评估”从散乱的 CLIP/LPIPS/FVD 拼接,推进到 **带 MOS 数据库 + 主观对齐评估网络** 的阶段。 diff --git a/benchmarks/edit/pdf/VEDIT-BENCH.md b/benchmarks/edit/pdf/VEDIT-BENCH.md new file mode 100644 index 0000000000000000000000000000000000000000..3693b7e7b42172c3bf4130191a91c97d89a7a5ef --- /dev/null +++ b/benchmarks/edit/pdf/VEDIT-BENCH.md @@ -0,0 +1,182 @@ +# VEditBench 详细总结 + +![VEditBench 首页与总览图](./assets/vedit-bench-page1.png) + +## 1. 基本信息 + +| 项目 | 内容 | +| --- | --- | +| 论文名 | VEDITBENCH: HOLISTIC BENCHMARK FOR TEXT-GUIDED VIDEO EDITING | +| 作者 | 匿名作者(双盲投稿版本) | +| 单位 | 未披露 | +| 发表状态 | ICLR 2025 双盲投稿稿件 | +| 论文链接 | 文中未给出公开 arXiv/项目页 | +| 本地 PDF | [VEDITBENCH- HOLISTIC BENCHMARK FOR TEXT-GUIDED VIDEO EDITING.pdf](<./VEDITBENCH- HOLISTIC BENCHMARK FOR TEXT-GUIDED VIDEO EDITING.pdf>) | + +## 2. 这篇论文在做什么 + +VEditBench 是一个面向 **Text-Guided Video Editing, TGVE** 的综合 benchmark。它的设计目标是:在统一框架下,比较不同视频编辑模型在真实世界视频上的表现。 + +论文强调 3 个核心贡献: + +1. 更大的真实视频集。 +2. 更广的编辑任务覆盖。 +3. 更完整的多维评价体系。 + +## 3. 评估维度 + +VEditBench 从两大视角看模型: + +1. **Semantic Fidelity**:编辑是否真正遵循了用户意图,同时是否合理保留源视频信息。 +2. **Visual Quality**:不管编辑指令是什么,最终视频本身的视觉质量是否足够好。 + +这两大视角继续细分为 9 个评价维度: + +| 大类 | 指标 | +| --- | --- | +| Semantic Fidelity | Spatial Alignment | +| Semantic Fidelity | Spatio-Temporal Alignment | +| Semantic Fidelity | Structural Similarity | +| Semantic Fidelity | Motion Similarity | +| Visual Quality | Image Quality | +| Visual Quality | Image Aesthetic | +| Visual Quality | Motion Smoothness | +| Visual Quality | Temporal Quality | +| Visual Quality | Video Quality | + +## 4. 数据来源 + +### 4.1 视频来源 + +主要数据来源: + +1. YouTube +2. Videvo + +检索时还使用 GPT-4o 生成关键词,并借助 Panda-70M / YouTube 检索素材。 + +### 4.2 数据规模 + +| 项目 | 数量 | +| --- | --- | +| 视频总数 | 420 | +| 短视频 | 300(2-4 秒) | +| 长视频 | 120(10-40 秒) | +| 类别 | 6 | +| 编辑任务 | 6 | +| 编辑 prompt | 2520(420 × 6) | + +### 4.3 视频类别 + +1. Animals +2. Food +3. Scenery +4. Sports Activity +5. Technology +6. Vehicles + +## 5. 数据处理方法 + +### 5.1 视频收集与清洗 + +1. 先用 GPT-4o 为每个类别生成检索关键词。 +2. 从 YouTube / Videvo 中搜索相关视频。 +3. 人工筛掉模糊、抖动、鬼影等低质量内容。 +4. 为视频生成 caption,并由人工修订,避免漏检或幻觉对象。 + +### 5.2 Prompt 生成 + +1. 给 GPT-4o 输入采样帧网格和视频 caption。 +2. 生成 edit instruction 和 target prompt。 +3. 人工复核并修正,保证多样性和准确性。 + +## 6. 任务类型 + +VEditBench 定义了 6 类真实世界常见编辑任务: + +1. Object Addition +2. Object Removal +3. Object Swap +4. Scene Replacement +5. Motion Change +6. Style Translation + +这些任务比早期 benchmark 更接近真实编辑需求,特别是加入了 motion change 和 scene replacement。 + +## 7. 评估指标与每个指标怎么做 + +### 7.1 Semantic Fidelity + +| 指标 | 怎么做 | +| --- | --- | +| Spatial Alignment | 用 CLIP 计算生成帧与 target prompt 的特征相似度,衡量单帧内容是否与目标文本对齐。 | +| Spatio-Temporal Alignment | 用 ViCLIP 计算整段编辑视频与 target prompt 的对齐度,显式纳入时间动态。 | +| Structural Similarity | 计算源视频与目标视频对应帧的 SSIM,衡量原始结构是否被合理保留。 | +| Motion Similarity | 先用 CoTracker 提取源视频和目标视频轨迹,再构造位置+方向联合代价矩阵,用 Hungarian matching 匹配轨迹,最后得到运动相似度。 | + +### 7.2 Visual Quality + +| 指标 | 怎么做 | +| --- | --- | +| Image Quality | 使用 Q-Align 的图像质量评分器,对帧级清晰度与失真做评价。 | +| Image Aesthetic | 使用 Q-Align 中基于 AVA 训练的审美评分器,评估视觉美感。 | +| Motion Smoothness | 参考 VBench,使用视频插帧模型的 motion prior 评估动作连续性。 | +| Temporal Quality | 使用 Content-Debiased FVD,采用 VideoMAE-v2 特征,降低传统 FVD 偏向逐帧质量的问题。 | +| Video Quality | 使用 Q-Align 的视频质量打分器,联合考虑空间和时间因素。 | + +### 7.3 指标解释上的重点 + +这个 benchmark 的特点是: + +1. 文本对齐不只看单帧,还看整段视频。 +2. 源视频保真不只看结构,还专门看运动。 +3. 画质评价既看单帧,也看时间稳定性,还看整段视频整体质量。 + +## 8. 实验设置 + +### 8.1 评测模型 + +短视频集上共评测 10 个 TGVE 模型,包括: + +1. Tune-A-Video +2. MotionDirector +3. VidToMe +4. Pix2Video +5. TokenFlow +6. Flatten +7. DMT +8. RAVE +9. Text2Video-Zero +10. InsV2V + +长视频集上只评测能处理长视频的 4 个模型: + +1. Pix2Video +2. VidToMe +3. Text2Video-Zero +4. InsV2V + +## 9. 特点 + +### 9.1 作为 Benchmark 的特点 + +1. 420 个真实世界视频,规模明显大于更早的 TGVE benchmark。 +2. 同时覆盖短视频和长视频。 +3. 任务集合不再局限于风格/前景/背景修改。 +4. 明确把“语义保真”和“视觉质量”解耦为 9 个细粒度维度。 + +### 9.2 核心维度拆解 + +1. Text alignment:有没有把用户说的内容改出来。 +2. Video alignment:改的时候有没有保住原视频结构和运动。 +3. Visual quality:最终画面是否自然、清晰、连贯。 + +### 9.3 局限 + +1. 作者匿名,公开资源状态不明。 +2. 没有引入显式人工打分数据,偏向“指标驱动 benchmark”。 +3. 任务维度虽多,但对 instruction-following 的语义深度理解仍主要依赖 CLIP/ViCLIP 体系。 + +## 10. 一句话评价 + +VEditBench 更像是一个 **“经典客观指标体系下的全面 TGVE benchmark”**:数据够大、任务够全、指标分得细,但它不像 VE-Bench 或 VEFX-Bench 那样把“人类主观偏好”放在中心位置。 diff --git a/benchmarks/edit/pdf/VEFX-BENCH.md b/benchmarks/edit/pdf/VEFX-BENCH.md new file mode 100644 index 0000000000000000000000000000000000000000..90496bd066ce95cce7db63785fe1e91c11522ae3 --- /dev/null +++ b/benchmarks/edit/pdf/VEFX-BENCH.md @@ -0,0 +1,208 @@ +# VEFX-Bench 详细总结 + +![VEFX-Bench 首页与总览图](./assets/vefx-bench-page1.png) + +## 1. 基本信息 + +| 项目 | 内容 | +| --- | --- | +| 论文名 | VEFX-Bench: A Holistic Benchmark for Generic Video Editing and Visual Effects | +| 作者 | Xiangbo Gao, Sicong Jiang, Bangya Liu, Xinghao Chen, Minglai Yang, Siyuan Yang, Mingyang Wu, Jiongze Yu, Qi Zheng, Haozhi Wang, Jiayi Zhang, Jie Yang, Zihan Wang, Qing Yin, Zhengzhong Tu | +| 单位 | Texas A&M University、Visko Platform、Abaka AI | +| 时间 | 2026-04-20(arXiv v2) | +| 论文链接 | [arXiv:2604.16272](https://arxiv.org/abs/2604.16272) | +| 项目页 | https://xiangbogaobarry.github.io/VEFX-Bench/ | +| 本地 PDF | [VEFX-Bench- A Holistic Benchmark for Generic Video Editing and Visual Effects.pdf](<./VEFX-Bench- A Holistic Benchmark for Generic Video Editing and Visual Effects.pdf>) | + +## 2. 这篇论文在做什么 + +VEFX-Bench 不是单纯一个 benchmark,而是一整套资源: + +1. **VEFX-Dataset**:带人工多维标签的视频编辑数据集。 +2. **VEFX-Reward**:专门用于视频编辑质量评估的 reward model。 +3. **VEFX-Bench**:300 条标准化 benchmark item,用来统一比较系统。 + +它解决的核心问题是:以前的视频编辑 benchmark 要么没有 edited outputs,要么没有人工质量标签,要么把复杂质量压成一个单分数。 + +## 3. 评估维度 + +VEFX 的核心设计是把视频编辑质量拆成 3 个 **解耦** 维度: + +1. **Instruction Following, IF** +2. **Rendering Quality, RQ** +3. **Edit Exclusivity, EE** + +这三个维度分别回答: + +1. 有没有按指令编辑。 +2. 画面质量是否自然稳定。 +3. 有没有只改该改的地方,而不是顺手把无关区域也改掉。 + +## 4. 数据来源 + +### 4.1 数据规模 + +| 项目 | 数量 | +| --- | --- | +| 源视频数 | 1,419 | +| 编辑样本数 | 5,049 | +| 训练集 | 4,200 | +| 测试集 | 849 | +| Benchmark items | 300 | +| 主任务类别 | 9 | +| 子类别 | 32 | +| 场景类别 | 10 | + +### 4.2 视频来源 + +1. Open-Sora +2. OpenVid-1M +3. 私有补充素材 + +### 4.3 编辑结果来源 + +作者明确从多种系统生成 edited video: + +1. 商业系统 +2. 开源模型 +3. agentic editing pipeline + +这样做的目的是让 reward model 见到更多失败模式,而不是只学某个模型家族的输出风格。 + +## 5. 数据处理方法 + +### 5.1 源视频处理 + +1. 过滤分辨率、时长、时间连续性不达标的视频。 +2. 去除 NSFW 内容。 +3. 按场景类别和内容类型采样,控制数据多样性。 + +### 5.2 指令生成 + +1. 为 9 个主类别、32 个子类别定义任务空间。 +2. 使用 Gemini 3 Flash 分析视频内容。 +3. 自动为视频匹配合适的编辑类别并生成 prompt。 +4. 丢弃低置信度分配,保证 task-video compatibility。 + +### 5.3 编辑样本生成 + +对每个 `(source video, instruction)`,从多来源系统生成 edited video。附录还说明了不同类别的专用 pipeline,例如: + +1. 实例删除:SAM2 + ROSE/PISCO +2. 实例插入:NanoBanana-Pro + SAM2 + PISCO +3. 实例位移/缩放:VLM 解析指令 + SAM2 + PISCO +4. 相机运动/角度:Gemini-2.0-Flash 映射成 camera parameters,再由 ReCamMaster / LightX 执行 +5. 风格/创意/视觉特效/属性编辑:NanoBanana-Pro 首帧编辑,再由 VACE/UniVideo 做时序传播 + +### 5.4 人工标注 + +所有样本按 4 分制对 3 个维度独立打分: + +1. IF +2. RQ +3. EE + +额外做了 550 样本交叉复标,验证标注一致性。 + +## 6. 任务类型 + +VEFX-Dataset 的 9 个主任务类别是: + +1. Camera Angle +2. Quantity +3. Attribute +4. Style +5. Camera Motion +6. Instance Motion +7. Instance +8. Visual Effect +9. Creative Edit + +文中还说明: + +1. Camera Angle 是最难的 IF 类别。 +2. Quantity 在 IF 上也比较难。 +3. Style 的 IF 最容易,但 EE 较低,说明全局风格变化容易破坏 locality。 + +## 7. 评估指标与每个指标怎么做 + +### 7.1 人工标注维度 + +| 指标 | 怎么做 | +| --- | --- | +| IF | 看是否正确完成指令语义。4 分表示全部完成且正确,1 分表示失败、矛盾或基本无关。 | +| RQ | 看画质、自然性、清晰度、时间稳定性,以及是否有闪烁、鬼影、模糊、扭曲等伪影。 | +| EE | 看是否只改了目标区域。4 分表示没有明显非目标改动,1 分表示全局或广泛过编辑。 | + +### 7.2 4 分制 rubric 的细化 + +| 分数 | IF | RQ | EE | +| --- | --- | --- | --- | +| 4 | 所有请求编辑都正确完成 | 清晰、稳定、几乎无伪影 | 没有明显非目标改动 | +| 3 | 核心编辑完成,但有轻微偏差 | 有轻微但可接受的质量下降 | 只有一处明显非目标改动 | +| 2 | 只完成部分编辑,且偏差较大 | 存在明显质量问题/反复伪影 | 2-3 处非目标改动,或一次较大误改 | +| 1 | 完全失败/矛盾/无关 | 严重崩坏 | 全局过编辑 | + +### 7.3 VEFX-Reward 自动指标 + +VEFX-Reward 不是直接回归一个总分,而是对 IF/RQ/EE 三个维度分别做 **ordinal regression**,输出 1-4 的软预测。 + +| 指标 | 怎么做 | +| --- | --- | +| IF 预测 | 模型同时输入 source video、editing instruction、edited video,判断语义是否执行到位。 | +| RQ 预测 | 同样三元输入,但重点看视觉质量与时间稳定性。 | +| EE 预测 | 利用 source vs edited 的对比能力,判断是否出现非目标区域改动。 | + +### 7.4 Overall 汇总分数 + +论文给出两个汇总指标: + +| 指标 | 怎么做 | +| --- | --- | +| Overall (Mean) | 直接对 IF、RQ、EE 取算术平均。 | +| Overall (GeoAgg) | 先把 IF/RQ/EE 归一化到 `[0,1]`,再做加权几何聚合;作者设 `(α, β, γ) = (2,1,1)`,即 IF 权重更高,从而更严厉惩罚“看起来还行但没按指令改”的结果。 | + +### 7.5 评估 reward model 本身时用的统计指标 + +作者还用以下指标验证 VEFX-Reward 是否和人工更一致: + +1. SRCC +2. KRCC +3. PLCC +4. RMSE +5. Pairwise Accuracy + +这些是“评估评估器”的统计指标,不是编辑任务内容指标。 + +## 8. 特点 + +### 8.1 作为 Benchmark 的特点 + +1. 同时包含 edited outputs、人工分数、多维质量标签。 +2. 首次把 **Edit Exclusivity** 作为显式主维度提出来,非常适合衡量 over-editing。 +3. 不再把视频编辑质量压成一个 MOS 单分数。 + +### 8.2 核心维度拆解 + +1. IF:编辑语义是否真的做对。 +2. RQ:视频看起来是否稳定自然。 +3. EE:模型是否克制,没有误改无关内容。 + +### 8.3 相对前作的进步 + +1. 比 VE-Bench 更细,因为 VE-Bench 最终主要是单标量质量。 +2. 比 FiVE、IVEBench 更偏“有 edited outputs + 人工标注 + reward model”。 +3. 更适合后续做 reward learning、ranking、自动 judge。 + +## 9. 适合怎么使用 + +VEFX-Bench 特别适合: + +1. 比较商业与开源视频编辑模型。 +2. 训练或评估视频编辑 reward model。 +3. 研究 instruction following 和 edit locality 之间的张力。 +4. 做自动评估替代人工评分。 + +## 10. 一句话评价 + +VEFX-Bench 的最大价值是把视频编辑评测从“单一好坏分数”升级成 **IF / RQ / EE 三轴评价体系**,尤其把“只改该改的地方”正式做成了 benchmark 主指标。 diff --git a/benchmarks/edit/pdf/_extracted/editreward.meta.txt b/benchmarks/edit/pdf/_extracted/editreward.meta.txt new file mode 100644 index 0000000000000000000000000000000000000000..7b94f7db029a114ae7d45168f9edd3e8dd67b742 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/editreward.meta.txt @@ -0,0 +1,3 @@ +title=EditReward: A Human-Aligned Reward Model for Instruction-Guided Image Editing +author=Keming Wu; Sicong Jiang; Max Ku; Ping Nie; Minghao Liu; Wenhu Chen +pages=32 diff --git a/benchmarks/edit/pdf/_extracted/editreward.txt b/benchmarks/edit/pdf/_extracted/editreward.txt new file mode 100644 index 0000000000000000000000000000000000000000..635298a84d2cd72967453aeefa2a1079f818928c --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/editreward.txt @@ -0,0 +1,1367 @@ +FILE: EDITREWARD- A HUMAN-ALIGNED REWARD MODEL FOR INSTRUCTION-GUIDED IMAGE EDITING.pdf +PAGES: 32 + + +===== PAGE 1 ===== +arXiv:2509.26346v2 [cs.CV] 28 Feb 2026 +Published as a conference paper at ICLR 2026 +EDITREWARD: A HUMAN-ALIGNED REWARD MODEL +FOR INSTRUCTION-GUIDED IMAGE EDITING +†Keming Wu1,2∗, Sicong Jiang3,4∗, Max Ku1, Ping Nie5, Minghao Liu3 +, +†Wenhu Chen1 +1University of Waterloo, 2Tsinghua Univerisity, 32077AI, 4McGill University, 5Independent +{wukeming0608@gmail.com, wenhuchen@uwaterloo.ca} +https://tiger-ai-lab.github.io/EditReward +ABSTRACT +Recently, we have witnessed great progress in image editing with natural lan- +guage instructions. Several closed-source models like GPT-Image-1, Seedream, +and Google-Nano-Banana have shown highly promising progress. However, the +open-source models are still lagging. The main bottleneck is the lack of a reli- +able reward model to scale up high-quality synthetic training data. To address +this critical bottleneck, we built EDITREWARD, trained with our new large-scale +human preference dataset, meticulously annotated by trained experts following a +rigorous protocol containing over 200K preference pairs. EDITREWARD demon- +strates superior alignment with human preferences in instruction-guided image +editing tasks. Experiments show that EDITREWARD achieves state-of-the-art hu- +man correlation on established benchmarks such as GenAI-Bench, AURORA- +Bench, ImagenHub, and our new EDITREWARD-BENCH, outperforming a wide +range of VLM-as-judge models. Furthermore, we use EDITREWARD to select a +high-quality subset from the existing noisy ShareGPT-4o-Image dataset. We train +Step1X-Edit on the selected subset, which shows significant improvement over +training on the full set. This demonstrates EDITREWARD’s ability to serve as a +reward model to scale up high-quality training data for image editing. EDITRE- +WARD with its training dataset will be released to help the community build more +high-quality image editing training datasets to catch up with the frontier ones. +1 INTRODUCTION +Instruction-guided image editing is an important task to enable intuitive and fine-grained image mod- +ifications through natural language instructions (Brooks et al., 2023; Zhang et al., 2024a; Zhao et al., +2024; Wei et al., 2024). Closed-source models like GPT-Image-1 (OpenAI, 2025), Seedream (Gao +et al., 2025), and Google’s Nano Banana (Google DeepMind, 2025) have made marvelous strides on +this task. The progress is driven partially by their high-quality in-house private training dataset. Ex- +isting open-source image editing datasets like ImgEdit (Ye et al., 2025), HQ-Edit (Hui et al., 2024), +GPT-Image-Edit-1.5M (Wang et al., 2025d), UltraEdit (Zhao et al., 2024), and OmniEdit (Wei et al., +2024) are all produced with automatic data synthesis pipelines and filtered with different rewards. +Commonly used rewards are mainly divided into three categories: (1) Perceptual scores like +LPIPS (Zhang et al., 2018) fail to capture semantic alignment with user instructions, (2) Feature +scores like CLIP (Hessel et al., 2021) fail to capture editing semantics, (3) VLM-as-a-judge like +VIEScore (Ku et al., 2023; Jiang et al., 2024; Wang et al., 2025b) uses general-purpose Vision- +Language Models (VLM), which are not optimized for rewarding image editing tasks. Therefore, +these ad-hoc rewards show weak alignment with human preference in the image editing task. To +build more aligned rewards, a line of work proposes to fine-tune general-purpose VLMs (for in- +stance Qwen2.5-VL) to reward models. However, some of them rely on noisy, crowd-sourced pref- +erence annotations (Lin et al., 2024; Xu et al., 2024), which are often plagued by inconsistency, low +inter-annotator agreement. The others adopt pseudo-labels generated by proprietary, closed-source +models (Wei et al., 2024; Wu et al., 2025c), creating highly noisy and biased labels. These trained +∗These authors contributed equally. +1 + +===== PAGE 2 ===== +Published as a conference paper at ICLR 2026 +reward models still fall short in providing enough reward signals to scale up high-quality image +editing datasets. A high quality image editing dataset is desired to build a good reward model. +In this paper, we introduce EDITREWARD, a human-aligned reward model powered by a high- +quality dataset for instruction-guided image editing. We first construct EDITREWARD-DATA, a +large-scale, high-fidelity preference dataset for instruction-guided image editing. It comprises over +200K manually annotated preference pairs, covering a diverse range of edits produced by seven state- +of-the-art models across twelve distinct sources. Every preference annotation in EDITREWARD- +DATA was curated by trained annotators following a rigorous and standardized protocol, ensuring +high alignment with considered human judgment and minimizing label noise. Using this dataset, we +train the reward model EDITREWARD to score instruction-guided image edits. To rigorously assess +EDITREWARD and future models, we also introduce EDITREWARD-BENCH, a new benchmark built +upon our high-quality annotations, which includes more difficult multi-way preference prediction. +Experimental results show that EDITREWARD achieves state-of-the-art performance on several +benchmarks. On GenAI-Bench (Jiang et al., 2024), our model obtains a score of 65.72, signifi- +cantly outperforming other leading VLM judges such as GPT-5 (59.61). Similarly, on AURORA- +Bench (Krojer et al., 2024), EDITREWARD scores 63.62, showing a substantial gain over OpenAI- +GPT-4o (50.81). While demonstrating competitive performance on ImagenHub (Ku et al., 2024) +with a score of 35.20, it is on our proposed EDITREWARD-BENCH where the fine-grained capabil- +ities of top models are most clearly discerned. This not only validates the superiority of our model +but also demonstrates that EDITREWARD-BENCH provides a more reliable and challenging evalu- +ation. We further study the potential of EDITREWARD to select the high-quality subset from noisy +candidates, which can be used to train next-generation image editing models. Specifically, we adopt +EDITREWARD to select the top 20K subset from ShareGPT-4o-Image (Chen et al., 2025a) and use +the subset to fine-tune Step1X-Edit (Liu et al., 2025b). We observe significant improvement by +training on the subset over training on the full set. On GEdit-Bench, the overall score increases from +6.7/10 (full-set) to 7.1/10 (subset), making it on par with Doubao-Edit (Wang et al., 2025c). This +experiment demonstrates its high potential to work as a reward model for future research. +In summary, our primary contributions are: (1) We construct and release EDITREWARD-DATA, a +large-scale (200K) preference dataset for image editing, distinguished by its high-quality manual +annotations and diversity of sources. (2) We train and release EDITREWARD, a VLM-based reward +model trained on EDITREWARD-DATA that demonstrates superior alignment with human prefer- +ences. (3) We propose EDITREWARD-BENCH, a new benchmark featuring a more challenging +multi-way preference ranking task that provides a more robust evaluation of reward models. +2 EDITREWARD-DATA +2.1 THE EDITREWARD-DATA CONSTRUCTION +EDITREWARD-DATA contains 9557 instruction–image pairs collected from six established editing +benchmarks: GEdit-Bench (606) (Liu et al., 2025b), ImgEdit-Bench (737) (Ye et al., 2025), Mag- +icBrush (1,053) (Zhang et al., 2024a), AnyEdit (1,250) (Yu et al., 2025), EmuEdit (5,611) (Sheynin +et al., 2024), and an internal set (300). This aggregation ensures broad coverage of semantically +grounded and executable editing instructions. For each instruction, we generated 12 candidate im- +ages using six state-of-the-art models: Step1X-Edit (Liu et al., 2025b), Flux-Kontext (BlackForest- +Labs et al., 2025), Qwen-Image-Edit (Wu et al., 2025a), BAGEL (Deng et al., 2025), Ovis-U1 (Wang +et al., 2025a), and OmniGen2 (Wu et al., 2025b), with multiple random seeds to avoid model bias. +Seven candidates were randomly sampled for human evaluation. Annotators scored each image on +a 4-point Likert scale (1 = Poor and 4 = Excellent) along two dimensions: Instruction Following +(semantic accuracy, completeness, and no unprompted changes) and Visual Quality (plausibility, +artifact-free rendering, and aesthetics). This rubric yields more informative labels than single-score +schemes. Details of the annotation protocol and quality-control process are provided in the Appendix +A.2. Comprehensive statistics of the dataset are provided in Table 1 and Figure 2. EDITREWARD- +DATA is unique in combining large-scale, expert human annotation and a multi-dimensional scoring +rubric, making it a strong foundation for training editing reward models. More representative exam- +ples from EDITREWARD-DATA are shown in the Appendix A.10. The IAA results in Table 9 pro- +vide a critical quantitative assessment of our expert annotation quality (Fleiss, 1971). We highlight +2 + +===== PAGE 3 ===== +Published as a conference paper at ICLR 2026 +Figure 1: An overview of our framework, illustrating the construction of the EDITREWARD- +DATA and the subsequent training of our reward model, EDITREWARD. Top: The data pipeline, +where we generate a diverse candidate pool from multiple state-of-the-art models and collect multi- +dimensional human preference annotations. Bottom: The model pipeline, where EDITREWARD +is optimized on EDITREWARD-DATA using our proposed Multi-Dimensional Uncertainty-Aware +Ranking Loss for training, followed by its use in inference. +the values derived from Krippendorff’s Alpha (α) (Krippendorff, 2011), which is the most appropri- +ate metric as it correctly models the ordinal nature of our 4-point Likert scale. The αscores of 0.668 +for Instruction Following (IF) and 0.597 for Visual Quality (VQ) establish a strong, quantified base- +line for human consistency. Crucially, the observed difference (IAAIF >IAAVQ) provides empirical +validation for our core contribution: it confirms that the VQ dimension is inherently more subjective +than IF. This validates our design choice to use a multi-dimensional rubric and a multi-head reward +model, as a single holistic score would obscure this critical difference in human variance. +Table 1: The comparison of different generative preference datasets and benchmarks. +Dataset Scale Task Focus Annotation Eval. Dims. Limitation / Caveat +ImageRewardDB(Xu et al., 2024)∼137K Visual Generation Human Single Noise, limited diversity +VisionPrefer(Wu et al., 2025c)∼1.2M Visual Generation Model Multiple Model bias, synthetic prefs +GenAI-Bench(Jiang et al., 2024)∼1.6K Generation / Editing Human Single Small scale +HIVE(Zhang et al., 2024b)∼3.6K Instructional Editing Human Single Small reward set +ADIEE(Chen et al., 2025b)∼100K Instructional Editing Model Single Synthetic labels, model bias +HPSv3(Ma et al., 2025)∼1.17M Visual Generation Human Single Generalization limits +EDITREWARD-DATA ∼200K Instructional Editing Human Multiple Fine-grained supervision +Benchmark Scale Annotation Eval. Dims. Multi-Way Preference Pair-Wise Point-Wise +GenAI-Bench-Edit(Jiang et al., 2024)∼900 Human Multiple 2-way ✓– +AURORA-Bench-Edit(Krojer et al., 2024)∼1.6K Human Single 2-way ✓ ✓ +ImagenHub-Edit(Ku et al., 2024)∼1.4K Human Multiple – – ✓ +EDITREWARD-BENCH ∼1.5K Human Cross-check Multiple 2/3/4-way ✓ ✓ +Table 2: Inter-Annotator Agreement (IAA) Metrics for Expert Annotations. The robust Krippendorff +Alpha (α) values confirm the high reliability of our multi-dimensional expert scoring. +Dataset Fleiss’ Kappa (IF) Fleiss’ Kappa (VQ) Krippendorff Alpha (IF) Krippendorff Alpha (VQ) +EDITREWARD-DATA 0.4157 0.3203 0.6762 0.5720 +EDITREWARD-BENCH 0.3962 0.3157 0.6623 0.6114 +All data 0.3994 0.3111 0.6685 0.5972 +3 + +===== PAGE 4 ===== +Published as a conference paper at ICLR 2026 +(a) Category Data Distribution (b) Dataset Source Distribution +(c) Model Contribution Distribution +Instruction Following +Visual Quality +Overall +33.19 +36.28 +42.75 +38.28 +32.83 +20.68 +28.53 +30.89 +36.57 +Model 1 Win +Tie +Model 2 Win +0 25 50 75 100 +Win Rate Percentage (%) +(d) Words Distribution in Dataset Instruction +(e) Human Preference Distribution +Figure 2: Statistics of our EDITREWARD-DATA and EDITREWARD-BENCH. +2.2 THE EDITREWARD-BENCH CONSTRUCTION +EDITREWARD-BENCH is designed to provide a more robust evaluation of image editing reward +models than existing suites. We curated 500 high-quality groups from the EDITREWARD-DATA +candidate pool, covering diverse editing categories. Each group was annotated by three independent +experts using the same two-dimensional rubric (instruction following and visual quality) described in +Section 2.1. We prioritized challenging cases where competing edits had small score differences to +increase the discriminative power of the benchmark. The key innovation of EDITREWARD-BENCH +is a multi-way preference comparison protocol that extends beyond pairwise judgments. Evalu- +ation units include ternary (A, B, C) and quaternary (A, B, C, D) tuples, with correctness defined +by simultaneously predicting all pairwise relations within the tuple. This strict criterion provides a +more comprehensive and reliable test of ranking consistency than traditional pairwise accuracy. We +benchmark a wide range of models on EDITREWARD-BENCH, and results are reported in Section 4. +More Details of the construction of EDITREWARD-BENCH are provided in the Appendix A.3. +3 EDITREWARD +3.1 ARCHITECTURE +Inspired by the success of VLMs as powerful feature extractors, we leverage a VLM as the backbone +for our reward model. The task of image editing evaluation is inherently tri-modal, requiring joint +reasoning over a source image (Is), a textual prompt (P), and an edited image (Ie). Our model is +trained on human preference data, which consists of pairs of edited images, (Ie,1,Ie,2), generated +from the same (Is,P) context. +Our reward model consists of two components: a multimodal backbone, Hψ (either Qwen2.5- +VL (Bai et al., 2023) or Mimo-VL (Yue et al., 2025)), which computes a latent representation of +the edit’s quality; and an MLP reward head, Rω, which projects this representation to a scalar score. +The score si for an edited image Ie,i is thus given by: +si = Rω(Hψ(Is,P,Ie,i)). (1) +Here Hψ represents the VLM backbone with parameters ψ, and Rω is the MLP reward head with +parameters ω. For a preference pair, the scores s1 and s2 are computed using Eq. 1 and are subse- +quently used in a preference loss function to jointly optimize the parameters ψand ω. +4 + +===== PAGE 5 ===== +Published as a conference paper at ICLR 2026 +3.2 MULTI-DIMENSIONAL UNCERTAINTY-AWARE RANKING +Prior reward models for generative tasks often fail to account for inconsistencies in human annota- +tions, treating each preference label with equal certainty. This can introduce bias, particularly when +judging ambiguous or challenging cases. The HPSv3 framework (Sun et al., 2025) made significant +progress in text-to-image evaluation by addressing this issue. Instead of predicting a deterministic +score s, HPSv3 models the score as a Gaussian distribution s ∼N(µ,σ2), thereby capturing the +uncertainty inherent in the data. The preference probability P(Ie,1 ≻Ie,2) is then computed by +integrating over the two reward distributions, leading to a more robust, probabilistic ranking. +Inspired by this, we adapt and extend this uncertainty-aware paradigm for the more complex domain +of instruction-guided image editing. Image editing quality is multi-faceted; an edit can be faithful to +the instruction but visually unrealistic, or vice versa. To capture this complexity, our EDITREWARD- +DATA provides disentangled scores across two distinct dimensions: (1) Instruction Following and +(2) Visual Quality. A single, holistic uncertainty distribution as in HPSv3 is insufficient to model +this rich, multi-dimensional feedback. +To this end, we adapt the reward head, Rω, using a Multi-Task Learning (MTL) (Crawshaw, 2020) +approach. For a single edited image sample (Is,P,Ie), the reward head no longer outputs a single +distribution, but rather a separate Gaussian distribution for each evaluation dimension. Let d ∈ +{1,2}represent the two dimensions. The output for a single sample iis a pair of distributions as +formulated in Eq. 2: +si,d ∼N(µi,d,σ2 +i,d), for d= 1,2. (2) +This is achieved by having the final layers of the MLP in Rω predict a set of parameters +(µi,1,σi,1,µi,2,σi,2) for each input. We explore both separate and shared-parameter heads for the +task. To train our model with this multi-dimensional output, we explore two distinct loss: +Multi-Dimensional Uncertainty-Aware Ranking Loss. This approach extends the probabilistic +ranking framework of HPSv3 (Sun et al., 2025) to our multi-dimensional task. To do so, we must +first aggregate the two predicted dimensional mean scores (µi,1,µi,2) for each candidate image iinto +a single, effective mean score, µagg +i . We propose and investigate three distinct aggregation strategies, +which can be compactly formulated as Eq. 3: +µagg +i = +   +min(µi,1,µi,2) (Pessimistic Minimum) +1 +2 (µi,1 + µi,2) (Balanced Average) +(3) +µi,1 + µi,2 (Direct Summation) +The resulting aggregated means for a pair of images, along with their predicted uncertainties (σ2), +are then used to compute the final preference probability P(Ih ≻Il) following the probabilistic +method from HPSv3. The model is trained by minimizing the negative log-likelihood of the ground- +truth preference as in Eq. 4: +Lrank =−log(P(Ih ≻Il)). (4) +Aggregated Score Regression. Alternatively, we frame the training as a direct regression task. +This approach leverages the pointwise scores available in our EDITREWARD-DATA dataset by first +aggregating the predicted distributions. Given that the sum of two independent Gaussians is also a +Gaussian, the aggregated score distribution for a sample iis si,agg ∼N(µi,1 + µi,2,σ2 +i,1 + σ2 +i,2). +The model is then optimized by minimizing the Mean Squared Error (MSE) between the mean of +this aggregated distribution and a transformed sum of the ground-truth scores,˜ +zagg = T(z1 + z2): +Lreg = E(Is ,P,Ie ,z1 ,z2 )∼D ∥(µi,1 + µi,2)− +˜ +zagg∥2 +. (5) +This multi-dimensional uncertainty-aware approach allows our model to learn a more nuanced and +disentangled representation of edit quality, leveraging the rich supervisory signal in our dataset. +Ablation study comparing the loss functions and aggregation strategies is presented in Section 4.6. +3.3 DISENTANGLING TIES VIA DIMENSIONAL PREFERENCE. +While standard models like Bradley-Terry model with ties (BTT) treat tied pairs as a single out- +come (Liu et al., 2025a), we propose a novel data augmentation strategy to extract a richer supervi- +sory signal from these ambiguous cases. Our key insight is that a tie in overall quality often masks +5 + +===== PAGE 6 ===== +Published as a conference paper at ICLR 2026 +Figure 3: Representative examples of our reward model aligning with human judgments. +complementary dimensional strengths. For instance, one image may excel in Instruction Follow- +ing while the other has superior Visual Quality. We leverage this by decomposing each qualifying +tie pair (IA,IB)tie into two new training samples with opposing preference labels, (IA ≻IB) and +(IB ≻IA), based on their respective dimensional advantages (Eq. 6). Let zi,d be the ground-truth +score for image ion dimension d. A tie pair where one image is preferred on the first dimension and +the other is preferred on the second (e.g., zA,1 >zB,1 and zB,2 >zA,2) is duplicated and relabeled +as follows: +The pair (IA,IB)tie = ⇒ Sample 1 with label: IA ≻IB +Sample 2 with label: IB ≻IA +(6) +This strategy forces the model to reconcile seemingly contradictory signals for the same input pair, +pushing it to develop a more granular understanding of nuanced trade-offs. This not only doubles +the utility of our annotated tie data but also leads to a more stable training dynamic. As illustrated in +Appendix A.7, our tie-disentanglement method results in a smoother training loss curve and more +consistent performance gains on the validation set. Figure 3 shows some examples of our reward +model giving rewards that are aligned with humans. More failure mode anaylysis of EDITREWARD +is shown in th Appendix A.13. +4 EXPERIMENTS +4.1 IMPLEMENTATION DETAILS +We train our reward model, EDITREWARD, using 200K high-quality pairwise preference samples +from our dataset. For our main experimental results, we report performance using two powerful +vision-language models as backbones: Qwen2.5-VL-7B and MiMo-VL-7B. To ensure a controlled +comparison, all ablation studies are conducted consistently using the Qwen2.5-VL-7B backbone. +During training, all parameters of the backbone are unfrozen and set as trainable. The training is +performed for 2 epochs on a cluster of 8 NVIDIA A800 GPUs. We follow the hyperparameter +configuration to HPSv3, using a learning rate of 2 ×10−6 with a cosine learning rate schedule and +a warm-up ratio of 0.05. With a per-GPU batch size of 2, the total effective batch size is 16. For +preprocessing, all training images are resized to 448 ×448 pixels while preserving their original +aspect ratios. Additional training details are provided in Appendix A.4. +4.2 BENCHMARKS AND BASELINES +We evaluate our approach on a suite of three established public benchmarks and our newly proposed +benchmark, designed to provide a more comprehensive assessment of image editing quality. +Existing Benchmarks. We utilize ImagenHub (Ku et al., 2024), GenAI-Bench (Jiang et al., 2024), +and AURORA-Bench (Krojer et al., 2024). We explicitly confirm that we verified no overlap exists +between our EDITREWARD-DATA training set and these evaluation benchmarks. They serve as fully +6 + +===== PAGE 7 ===== +Published as a conference paper at ICLR 2026 +Table 3: Comprehensive results on public benchmarks and our proposed EDITREWARD-BENCH. +Under the EDITREWARD-BENCH results, K denotes the number of candidates in the multi-way +preference ranking task. Bold marks the best performance, and underline marks the second best. +Method GenAI- AURORA- Imagen EDITREWARD-BENCH +Bench Bench Hub K=2 K=3 K=4 Overall +Random 25.90 33.43 – Human-to-Human – – 41.84 25.81 11.33 1.35 13.84 +– – – – +Proprietary Models +53.54 50.81 38.21 59.61 47.27 40.85 GPT-4o GPT-5 Gemini-2.0-Flash 53.32 44.31 23.69 Gemini-2.5-Flash 57.01 47.63 41.62 45.69 27.33 7.31 28.31 +57.53 38.51 12.84 37.81 +52.43 33.33 13.51 33.47 +58.61 39.86 12.16 38.02 +Open-Source VLMs +Qwen2.5-VL-3B-Inst 42.76 30.69 -2.54 Qwen2.5-VL-7B-Inst 40.48 38.62 18.59 Qwen2.5-VL-32B-Inst 39.28 37.06 26.87 MiMo-VL-7B-SFT-2508 57.89 30.43 22.14 ADIEE 59.96 55.56 34.50 51.07 20.27 2.71 26.86 +52.69 24.67 3.38 29.75 +50.54 25.27 4.05 28.72 +49.46 30.41 9.46 31.19 +– – – – +Reward Models (Ours) +EDITREWARD (on Qwen2.5-VL-7B) 63.97 59.50 36.18 EDITREWARD (on MiMo-VL-7B-SFT) 65.72 63.62 35.20 56.99 36.00 10.81 36.78 +56.45 42.67 11.49 38.42 +independent, held-out testbeds, ensuring a fair and unbiased evaluation of EDITREWARD’s gener- +alization. For benchmarks with point-wise annotations like ImagenHub, we measure the Spearman +rank correlation to assess alignment with human scores. For ImagenHub, which includes three rat- +ings per sample, we also compute the Human-to-Human correlation as a practical upper bound (Ku +et al., 2023). For benchmarks with paired comparisons like GenAI-Bench and the pair-wise split +of AURORA-Bench, we report the prediction accuracy. Additional details of the evaluation across +different methods are provided in Appendix A.5. +EDITREWARD-BENCH. Derived from the held-out test split of our EDITREWARD-DATA dataset, +this benchmark provides pair-wise preference labels. We report performance on EDITREWARD- +BENCH using overall preference accuracy (pair-wise). We evaluated a wide range of leading models +on EDITREWARD-BENCH to establish its utility. This included proprietary models such as GPT-4o, +GPT-5, Gemini-2.0-Flash (Hassabis et al., 2024), and Gemini-2.5-Flash (Comanici et al., 2025), as +well as prominent open-source VLMs like the Qwen2.5-VL series and MiMo-VL-7B. The experi- +mental results, detailed in Section 4, demonstrate that EDITREWARD-BENCH effectively differenti- +ates between models of varying capabilities and reveals challenges, such as reasoning over multiple +candidates, that are not apparent in simpler pairwise benchmarks. +4.3 EXPERIMENTAL RESULTS: ALIGNMENT WITH HUMANS +The main results presented in Table 3 establish EDITREWARD as a new state-of-the-art reward model +for instruction-guided image editing. Our best model, EDITREWARD (on MiMo-VL-7B), achieves +top scores on the primary public benchmarks, obtaining an accuracy of 65.72% on GenAI-Bench +and 63.62% on AURORA-Bench. This performance surpasses strong proprietary models like GPT-5 +(59.61) and the leading open-source method ADIEE (59.96). On the point-wise ImagenHub bench- +mark, our model remains highly competitive with the best systems available, the Qwen2.5-VL-7B +variant achieves a second-best Spearman correlation of 36.18, closely following GPT-4o. +Crucially, our results highlight the profound impact of our training paradigm itself. By applying our +methodology to the base Qwen2.5-VL-7B model, we observe a massive performance uplift of over +23 points on GenAI-Bench (from 40.48% to 63.97%), demonstrating that our framework dramati- +cally enhances a VLM’s alignment with human judgments. This capability is further validated on +our challenging EDITREWARD-BENCH, where EDITREWARD (on MiMo-VL-7B) again achieves +the highest score of 38.42%, outperforming specialized models like Gemini-2.5-Flash (38.02) and +GPT-5 (37.81). The strong performance of EDITREWARD on both Qwen and MiMo-VL backbones +also confirms that our framework is robust and effectively scales with more powerful base models. +7 + +===== PAGE 8 ===== +Published as a conference paper at ICLR 2026 +4.4 APPLICATION: EDITREWARD AS A REWARD +To demonstrate EDITREWARD’s practical utility as a data supervisor, we conducted a data curation +experiment designed to improve a state-of-the-art editing model. We employed our reward model +to score the 46,000 examples in the ShareGPT-4o-Image dataset (Chen et al., 2025a), from which +we selected high-quality subsets (Top 10K, 20K, and 30K) for comparative analysis. This curated +dataset was then used to fine-tune the powerful Step1X-Edit model (Liu et al., 2025b). The com- +putational cost for scoring the samples in this pool was minimal, requiring only average 2.61 GPU +hours, demonstrating high efficiency (0.25 seconds/sample). +Table 4: Comprehensive comparison of state-of-the-art models on both the English and Chinese ver- +sions of the GEdit-Bench benchmark, across intersection and full test sets. Our model, significantly +improve the base model Step1X-Edit, including sensitivity analysis for the EDITREWARD-curated +subsets (Top 10K, 20K, and 30K). ↑indicates higher the better. *-I means intersection set. +Model GEdit-Bench-EN-I ↑ GEdit-Bench-EN ↑ GEdit-Bench-CN-I ↑ GEdit-Bench-CN ↑ +G SC G PQ G O G SC G PQ G O G SC G PQ G O G SC G PQ G O +AnyEdit (Yu et al., 2025) 3.122 5.865 2.919 3.053 5.882 2.854 3.098 5.840 2.899 3.011 5.849 2.817 +OmniGen (Wu et al., 2025b) 6.037 5.856 5.154 5.879 5.871 5.005 6.015 5.830 5.122 5.850 5.845 4.976 +Gemini-2.0 (Hassabis et al., 2024) 6.816 7.408 6.483 6.866 7.436 6.509 6.790 7.385 6.450 6.821 7.402 6.473 +Doubao (Wang et al., 2025c) 7.396 7.899 7.137 7.222 7.885 6.983 7.370 7.870 7.105 7.195 7.851 6.942 +GPT-Image-1 (OpenAI, 2025) 7.867 8.097 7.590 7.743 8.133 7.494 7.840 8.075 7.560 7.708 8.095 7.451 +Step1X-Edit 7.289 6.962 6.618 7.131 6.998 6.444 7.464 7.076 6.779 7.647 7.398 6.983 +Step1X-Edit + ShareGPT-4o-Image 7.411 6.838 6.803 7.349 6.893 6.780 7.126 6.855 6.595 7.116 6.807 6.583 +Ours (EDITREWARD as reward) (Top-K Sensitivity) +Step1X-Edit + Ours (Top 10K) 7.762 6.811 6.957 7.690 6.866 6.938 7.591 7.064 7.000 7.591 7.047 6.987 +Step1X-Edit + Ours (Top 30K) 7.641 6.957 7.007 7.632 6.890 6.962 7.524 7.068 6.938 7.456 7.098 6.888 +Step1X-Edit + Ours (Top 20K) 7.895 6.946 7.131 7.854 6.931 7.086 7.757 7.024 7.074 7.658 6.995 7.001 +Evaluation Protocol. To measure the impact of this curation, we evaluate the resulting model on +the comprehensive GEdit-Bench. This benchmark features both English (EN) and Chinese (CN) +instructions, as well as a challenging ”Intersection” subset containing prompts that all models could +process. We compare our fine-tuned model against a diverse range of baselines, including the orig- +inal Step1X-Edit, the same model fine-tuned on the full unfiltered dataset, and other leading open- +source and proprietary models like Doubao and GPT-Image-1. Following established practices Ku +et al. (2023), performance is judged by GPT-4o on three metrics (0-10 scale): Semantic Consis- +tency (G SC) for instruction fidelity, Perceptual Quality (G PQ) for visual realism, and an Overall +Score (G O) for overall quality. +Results and Analysis. As detailed in Table 4, this reward-driven filtering yields significant per- +formance gains. The results show a clear trade-off between data quality and volume, confirming +that our EDITREWARD-filtered 20K subset represents the optimal balance for fine-tuning. Our best- +performing model, trained on the Top 20K subset, achieves an English G O score of 7.086. This +substantially outperforms the original Step1X-Edit baseline (6.444) and the model trained on the +full, noisy 46K dataset (6.780). Furthermore, our sensitivity analysis confirms that while the Top +10K subset (representing the highest signal-to-noise ratio) also outperforms the full set (G O: 6.938), +it is marginally inferior to the Top 20K subset, indicating the 20K size is necessary for robust gener- +alization and avoiding underfitting. Crucially, the Top 30K subset (G O: 6.962) yields diminishing +returns compared to the Top 20K, confirming that including lower-quality data dilutes the training +signal. This finding is crucial, as it confirms that data quality, as judged by our reward model, is more +impactful than sheer data quantity. EDITREWARD successfully prunes noisy examples that would +otherwise degrade performance during fine-tuning. This uplift elevates the open-source Step1X-Edit +to be competitive with top-tier editors like Doubao, validating our model’s potential as an essential +tool for training next-generation generative models. +4.5 OUT-OF-DISTRIBUTION GENERALIZATION ANALYSIS +To evaluate robustness outside the training pool, we conducted a targeted experiment on two chal- +lenging Out-of-Distribution (OOD) categories: Text-in-Image (OCR) and Style Transfer. +8 + +===== PAGE 9 ===== +Published as a conference paper at ICLR 2026 +Table 5: Accuracy comparison on OOD tasks (Text & Style) sourced from Open Images. EDITRE- +WARD achieves performance comparable to GPT-4o while being open-source and cost-effective. +Model Text Category Style Category Overall +GPT-4o 45.50 35.79 41.69 +EDITREWARD (on MiMo-VL-7B-SFT) 47.83 45.41 46.80 +Experimental Setup. We constructed a specialized OOD set sourced from Open Images (distinct +from training sources), comprising 253 Text pairs and 185 Style pairs with expert annotations. We +compare EDITREWARD (on MiMo-VL-7B-SFT) against the commercial SOTA, GPT-4o. +Results. Table 5 shows EDITREWARD achieves performance comparable to GPT-4o on these tasks, +maintaining competitive alignment despite inherent VLM difficulties with OCR. Crucially, EDITRE- +WARD offers significant advantages as a cost-effective, open-source alternative with faster inference +speeds. +4.6 ABLATION STUDIES +Table 6: Ablation study on key design choices for our reward model. We compare a point-wise +regression loss (variant I) against our pair-wise uncertainty loss (variant II, III, IV, V), and further +investigate the impact of the reward head architecture (Shared vs. Multiple) and different score +aggregation strategies. +Variants Model Configuration Benchmark Performance +Loss Type Head Type Aggregation GenAI-Bench AURORA-Bench ImagenHub EditReward +I Point-wise N/A N/A 49.62 42.38 13.40 22.73 +II Pair-wise Shared Mean 60.17 56.75 32.65 36.78 +III Pair-wise Multiple Min 59.96 57.25 30.25 36.57 +IV Pair-wise Multiple Sum 59.63 55.19 32.93 37.60 +V Pair-wise Multiple Mean 63.97 59.50 36.18 36.78 +Ablation on Model Design. We analyze our model’s key architectural choices in Table 6. +Loss Type. Comparing loss functions (Variant I vs. V), our pair-wise uncertainty model (63.97 on +GenAI-Bench) significantly outperforms the point-wise regression baseline (49.62). This confirms +that modeling relative preferences is more effective than regressing on absolute scores for this task. +Head Type. For the reward head (Variant II vs. V), using multiple independent heads (63.97) pro- +vides a clear improvement over a shared architecture (60.17 on GenAI-Bench), suggesting that spe- +cialized heads better capture our disentangled evaluation dimensions. +Aggregation Strategy. Finally, we compare three score aggregation strategies (Variants III-V), find- +ing that the balanced mean provides the most consistent and highest performance (63.97 on GenAI- +Bench and 59.50 on AURORA-Bench). We therefore adopt the Pair-wise model with Multiple +heads and Mean aggregation as our final configuration. +Table 7: Ablation study on different model parameter sizes and different model backbones. +Backbone GenAI-Bench AURORA-Bench ImagenHub EDITREWARD-BENCH +Qwen2.5-VL-3B-Inst 62.79 57.37 32.34 37.40 +Qwen2.5-VL-7B-Inst 63.97 59.50 36.18 36.78 +MiMo-VL-7B-SFT-2508 65.72 63.62 35.20 38.42 +Ablation on Model Backbone. To verify our framework’s generalizability, we train EDITREWARD +on three backbones of varying scale and architecture, confirming that our method consistently bene- +fits from stronger foundation models (Table 7). Performance increases when scaling from Qwen2.5- +VL-3B to 7B, and improves further at the 7B scale when using the more advanced MiMo-VL-7B +9 + +===== PAGE 10 ===== +Published as a conference paper at ICLR 2026 +architecture, which achieves state-of-the-art scores of 65.72% on GenAI-Bench and 63.62% on +AURORA-Bench. This demonstrates that our framework is backbone-agnostic and effectively lever- +ages the capabilities of more powerful models. +5 RELATED WORKS +Evolution of Instruction-Guided Image Editing. Instruction-guided image editing has rapidly +evolved from early trajectory-based methods. Diffusion models (Song et al., 2020; Dhariwal & +Nichol, 2021; Rombach et al., 2022; Podell et al., 2023) first enabled editing via dual-prompt for- +mulations that relied on cross-attention manipulation or inversion (Hertz et al., 2022; Mokady et al., +2023; Wallace et al., 2023). The paradigm then shifted to more user-friendly single-instruction edit- +ing, pioneered by InstructPix2Pix (Brooks et al., 2023) and refined by works like MagicBrush and +Emu-Edit (Zhang et al., 2024a;b; Sheynin et al., 2024) that focused on curating high-quality datasets. +This trajectory-based family has been further advanced by flow-matching models (BlackForestLabs +et al., 2025), which improve training and sampling efficiency. In parallel, sequential generative mod- +els, including autoregressive approaches (Yu et al., 2022; Tian et al., 2024), enhance compositional +reasoning. The most recent advances feature hybrid multimodal architectures like OmniGen2 (Wu +et al., 2025b) and BAGEL (Deng et al., 2025), which integrate large vision–language backbones +with generative decoders to enable more context-aware, conversational editing. +Evaluating Instruction-Guided Image Editing. Early evaluation of image editing relied on per- +ceptual metrics like LPIPS (Zhang et al., 2018), but these require reference images and fail to assess +semantic alignment. CLIP-based metrics (Hessel et al., 2021) were introduced for text–image con- +sistency but also show limited correlation with human judgment (Ku et al., 2024). The advent of +large vision–language models (VLMs) enabled zero-shot evaluation, with proprietary models (Ku +et al., 2023; Wang et al., 2025b) demonstrating promising human correlation while open-source +counterparts (Liu et al., 2023; Laurenc¸on et al., 2024) have lagged (Jiang et al., 2024). Conse- +quently, recent work has focused on improving open-source evaluators via fine-tuning. One strategy +distills supervision from proprietary models (Wei et al., 2024; Gu et al., 2024; Wu et al., 2024), +which risks inheriting model biases. The other collects direct human annotations (Xu et al., 2024; +Liang et al., 2024; Wu et al., 2023; Sani et al., 2026), offering higher-quality signals but typically at +a smaller scale. Our work contributes a large-scale, expert-annotated dataset, enabling more reliable +and robust reward modeling for image editing. +6 CONCLUSION +In this paper, we addressed the critical bottleneck hindering the advancement of open-source +instruction-guided image editing: the lack of a reliable, human-aligned reward model for scaling +up high-quality training data. To this end, we introduced a three-part solution: (1) EDITREWARD- +DATA, a new large-scale (200K) preference dataset curated with rigorous expert annotation to +minimize the noise and bias prevalent in existing resources; (2) EDITREWARD, a dedicated re- +ward model trained on this high-fidelity data to specialize in the image editing domain; and (3) +EDITREWARD-BENCH, a challenging new benchmark featuring multi-way preference tasks to en- +able more robust evaluation. Our experimental results validate the effectiveness of our approach. +EDITREWARD establishes a new state of the art, demonstrating superior correlation with human +judgment by outperforming strong VLM judges like GPT-5 and GPT-4o on public benchmarks. +More importantly, we demonstrated its practical utility in a downstream data curation task: fine- +tuning Step1X-Edit on a 20K subset of data filtered by EDITREWARD yielded significantly better +performance than training on the full 46K noisy dataset (7.1 vs. 6.7 overall score on GEdit-Bench). +This confirms that a high-quality reward signal is a key ingredient for training powerful, next- +generation editing models. Ultimately, this work provides both a methodology and a set of open +resources to help bridge the gap between open-source and proprietary image editing models. To +empower the community and facilitate future research, we will publicly release our EDITREWARD- +DATA dataset, the trained EDITREWARD model, and the EDITREWARD-BENCH benchmark. +10 + +===== PAGE 11 ===== +Published as a conference paper at ICLR 2026 +ETHICS STATEMENT +The development of advanced instruction-guided image editing models, which our work aims to +evaluate and improve, carries significant ethical implications. While these technologies enable pow- +erful creative expression, they can also be misused to generate deceptive or harmful content, such +as deepfakes, misinformation, or fraudulent documents, lowering the barrier for malicious actors. +Our work, by creating a more effective reward model, could inadvertently contribute to acceler- +ating these capabilities. We acknowledge this dual-use potential and have taken steps to mitigate +risks. Specifically, the EDITREWARD-DATA dataset was constructed from publicly available, non- +sensitive benchmarks, and automated and manual filtering was applied to remove any personally +identifiable information (PII) or sensitive content. Our reward model, EDITREWARD, is trained to +align with constructive and high-quality edits, as defined by our multi-dimensional rubric, and does +not follow harmful or malicious instructions. Additionally, all generated data and model outputs +will be released under a CC-BY-NC-SA 4.0 license, explicitly prohibiting commercial use, which +mitigates potential misuse such as the creation of deepfakes or other harmful applications. By pub- +licly releasing our dataset, model, and code, we aim to promote transparency and enable the research +community to further study the safety, biases, and alignment of such models. Finally, we encourage +the community to adopt similar safeguards, including watermarking, provenance tracking, and care- +ful curation of training data, when deploying or extending instruction-guided image editing models. +REPRODUCIBILITY STATEMENT +To ensure the reproducibility of our work, we provide the following details. All of our reward +models were trained on 8 NVIDIA A800 GPUs. The evaluation of baseline models was conducted +using their official public codebases and recommended configurations. For proprietary models (e.g., +GPT-4o, Gemini series), we accessed their APIs between April and June 2025; given the evolving +nature of these models, we have archived their specific outputs for consistency. Our new dataset, +EDITREWARD-DATA, was constructed following the detailed protocol described in Section 2.1, and +both the dataset and our evaluation benchmark, EDITREWARD-BENCH, will be publicly released. +The complete codebase for training and evaluating our EDITREWARD, along with the final model +weights for both the Qwen2.5-VL and MiMo-VL backbones, will be made available on GitHub and +Hugging Face. Further details are provided in Appendix A.4 and A.5. +REFERENCES +Jinze Bai, Shuai Bai, Shusheng Yang, Shijie Wang, Sinan Tan, Peng Wang, Junyang Lin, Chang +Zhou, and Jingren Zhou. Qwen-vl: A versatile vision-language model for understanding, local- +ization, text reading, and beyond. arXiv preprint arXiv:2308.12966, 2023. +BlackForestLabs, Stephen Batifol, Andreas Blattmann, Frederic Boesel, Saksham Consul, Cyril +Diagne, Tim Dockhorn, Jack English, Zion English, Patrick Esser, Sumith Kulal, Kyle Lacey, +Yam Levi, Cheng Li, Dominik Lorenz, Jonas M¨ uller, Dustin Podell, Robin Rombach, Harry Saini, +Axel Sauer, and Luke Smith. Flux.1 kontext: Flow matching for in-context image generation and +editing in latent space, 2025. URL https://arxiv.org/abs/2506.15742. +Tim Brooks, Aleksander Holynski, and Alexei A Efros. Instructpix2pix: Learning to follow image +editing instructions. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern +Recognition, pp. 18392–18402, 2023. +Junying Chen, Zhenyang Cai, Pengcheng Chen, Shunian Chen, Ke Ji, Xidong Wang, Yunjin Yang, +and Benyou Wang. Sharegpt-4o-image: Aligning multimodal models with gpt-4o-level image +generation. arXiv preprint arXiv:2506.18095, 2025a. +Sherry X Chen, Yi Wei, Luowei Zhou, and Suren Kumar. Adiee: Automatic dataset creation and +scorer for instruction-guided image editing evaluation. arXiv preprint arXiv:2507.07317, 2025b. +Gheorghe Comanici, Eric Bieber, Mike Schaekermann, Ice Pasupat, Noveen Sachdeva, Inderjit +Dhillon, Marcel Blistein, Ori Ram, Dan Zhang, Evan Rosen, et al. Gemini 2.5: Pushing the +frontier with advanced reasoning, multimodality, long context, and next generation agentic capa- +bilities. arXiv preprint arXiv:2507.06261, 2025. +11 + +===== PAGE 12 ===== +Published as a conference paper at ICLR 2026 +Michael Crawshaw. Multi-task learning with deep neural networks: A survey. arXiv preprint +arXiv:2009.09796, 2020. +Chaorui Deng, Deyao Zhu, Kunchang Li, Chenhui Gou, Feng Li, Zeyu Wang, Shu Zhong, Wei- +hao Yu, Xiaonan Nie, Ziang Song, Guang Shi, and Haoqi Fan. Emerging properties in unified +multimodal pretraining. arXiv preprint arXiv:2505.14683, 2025. +Prafulla Dhariwal and Alexander Nichol. NeurIPS, 34:8780–8794, 2021. +Diffusion models beat GANs on image synthesis. +Joseph L Fleiss. Measuring nominal scale agreement among many raters. Psychological bulletin, +76(5):378, 1971. +Yu Gao, Lixue Gong, Qiushan Guo, Xiaoxia Hou, Zhichao Lai, Fanshi Li, Liang Li, Xiaochen +Lian, Chao Liao, Liyang Liu, Wei Liu, Yichun Shi, Shiqi Sun, Yu Tian, Zhi Tian, Peng Wang, +Rui Wang, Xuanda Wang, Xun Wang, Ye Wang, Guofeng Wu, Jie Wu, Xin Xia, Xuefeng Xiao, +Zhonghua Zhai, Xinyu Zhang, Qi Zhang, Yuwei Zhang, Shijia Zhao, Jianchao Yang, and Weilin +Huang. Seedream 3.0 technical report. arXiv preprint arXiv:2504.11346, 2025. URL https: +//arxiv.org/abs/2504.11346. +Google DeepMind. Gemini 2.5 flash image (nano banana). https://ai.google.dev/ +gemini-api/docs/image-generation, 2025. Google’s AI image generation and edit- +ing model, officially Gemini 2.5 Flash Image, known by its nickname “Nano Banana”. Accessed +September 2025. +Xin Gu, Ming Li, Libo Zhang, Fan Chen, Longyin Wen, Tiejian Luo, and Sijie Zhu. Multi-reward +as condition for instruction-based image editing. arXiv preprint arXiv:2411.04713, 2024. +Demis Hassabis, Koray Kavukcuoglu, and Gemini Team. Introducing gemini 2.0: our new ai +model for the agentic era. https://blog.google/technology/google-deepmind/ +google-gemini-ai-update-december-2024/, 2024. Google DeepMind blog an- +nouncement, December 2024. +Amir Hertz, Ron Mokady, Jay Tenenbaum, Kfir Aberman, Yael Pritch, and Daniel Cohen-Or. +Prompt-to-Prompt image editing with cross attention control. arXiv preprint arXiv:2208.01626, +2022. +Jack Hessel, Ari Holtzman, Maxwell Forbes, Ronan Le Bras, and Yejin Choi. Clipscore: A +reference-free evaluation metric for image captioning. arXiv preprint arXiv:2104.08718, 2021. +Mude Hui, Siwei Yang, Bingchen Zhao, Yichun Shi, Heng Wang, Peng Wang, Yuyin Zhou, and +Cihang Xie. HQ-Edit: A high-quality dataset for instruction-based image editing. arXiv preprint +arXiv:2404.09990, 2024. +Dongfu Jiang, Max Ku, Tianle Li, Yuansheng Ni, Shizhuo Sun, Rongqi Fan, and Wenhu Chen. Genai +arena: An open evaluation platform for generative models. arXiv preprint arXiv:2406.04485, +2024. +Klaus Krippendorff. Computing krippendorff’s alpha-reliability. 2011. +Benno Krojer, Dheeraj Vattikonda, Luis Lara, Varun Jampani, Eva Portelance, Christopher Pal, and +Siva Reddy. Learning Action and Reasoning-Centric Image Editing from Videos and Simulations. +In NeurIPS, 2024. URL https://arxiv.org/abs/2407.03471. Spotlight Paper. +Max Ku, Dongfu Jiang, Cong Wei, Xiang Yue, and Wenhu Chen. Viescore: Towards explainable +metrics for conditional image synthesis evaluation. arXiv preprint arXiv:2312.14867, 2023. +Max Ku, Tianle Li, Kai Zhang, Yujie Lu, Xingyu Fu, Wenwen Zhuang, and Wenhu Chen. Ima- +genhub: Standardizing the evaluation of conditional image generation models. In The Twelfth +International Conference on Learning Representations, 2024. URL https://openreview. +net/forum?id=OuV9ZrkQlc. +12 + +===== PAGE 13 ===== +Published as a conference paper at ICLR 2026 +Hugo Laurenc¸on, L´ eo Tronchon, and Victor Sanh. Introducing idefics2: A powerful 8b vision- +language model for the community. Hugging Face Blog, April 2024. URL https:// +huggingface.co/blog/idefics2. +Youwei Liang, Junfeng He, Gang Li, Peizhao Li, Arseniy Klimovskiy, Nicholas Carolan, Jiao +Sun, Jordi Pont-Tuset, Sarah Young, Feng Yang, Junjie Ke, Krishnamurthy Dj Dvijotham, Katie +Collins, Yiwen Luo, Yang Li, Kai J Kohlhoff, Deepak Ramachandran, and Vidhya Navalpakkam. +Rich human feedback for text-to-image generation. In Proceedings of the IEEE/CVF Conference +on Computer Vision and Pattern Recognition, 2024. +Zhiqiu Lin, Deepak Pathak, Baiqi Li, Jiayao Li, Xide Xia, Graham Neubig, Pengchuan Zhang, and +Deva Ramanan. Evaluating text-to-visual generation with image-to-text generation. In European +Conference on Computer Vision, pp. 366–384. Springer, 2024. +Haotian Liu, Chunyuan Li, Qingyang Wu, and Yong Jae Lee. Visual instruction tuning. In NeurIPS, +2023. +Jie Liu, Gongye Liu, Jiajun Liang, Ziyang Yuan, Xiaokun Liu, Mingwu Zheng, Xiele Wu, Qiulin +Wang, Wenyu Qin, Menghan Xia, et al. Improving video generation with human feedback. arXiv +preprint arXiv:2501.13918, 2025a. +Shiyu Liu, Yucheng Han, Peng Xing, Fukun Yin, Rui Wang, Wei Cheng, Jiaqi Liao, Yingming +Wang, Honghao Fu, Chunrui Han, et al. Step1x-edit: A practical framework for general image +editing. arXiv preprint arXiv:2504.17761, 2025b. +Yuhang Ma, Xiaoshi Wu, Keqiang Sun, and Hongsheng Li. Hpsv3: Towards wide-spectrum human +preference score. arXiv preprint arXiv:2508.03789, 2025. +Ron Mokady, Amir Hertz, Kfir Aberman, Yael Pritch, and Daniel Cohen-Or. Null-text Inversion for +editing real images using guided diffusion models. In CVPR, pp. 6038–6047, 2023. +OpenAI. Gpt-image-1. https://platform.openai.com/docs/guides/ +image-generation?image-generation-model=gpt-image-1, 2025. OpenAI’s +image generation model. Accessed September 2025. +Dustin Podell, Zion English, Kyle Lacey, Andreas Blattmann, Tim Dockhorn, Jonas M¨ uller, Joe +Penna, and Robin Rombach. SDXL: Improving latent diffusion models for high-resolution image +synthesis. arXiv preprint arXiv:2307.01952, 2023. +Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Bj¨ orn Ommer. High- +resolution image synthesis with latent diffusion models. In CVPR, pp. 10684–10695, 2022. +Samin Mahdizadeh Sani, Max Ku, Nima Jamali, Matina Mahdizadeh Sani, Paria Khoshtab, Wei- +Chieh Sun, Parnian Fazel, Zhi Rui Tam, Thomas Chong, Edisy Kin Wai Chan, Donald Wai Tong +Tsang, Chiao-Wei Hsu, Lam Ting Wai, Ho Yin Sam Ng, Chiafeng Chu, Chak-Wing Mak, Kem- +ing Wu, Hiu Tung Wong, Yik Chun Ho, Chi Ruan, Zhuofeng Li, I-Sheng Fang, Shih-Ying Yeh, +Ho Kei Cheng, Ping Nie, and Wenhu Chen. Imagenworld: Stress-testing image generation models +with explainable human evaluation on open-ended real-world tasks. In The Fourteenth Interna- +tional Conference on Learning Representations, 2026. URL https://openreview.net/ +forum?id=bld9g6jFh9. +Shelly Sheynin, Adam Polyak, Uriel Singer, Yuval Kirstain, Amit Zohar, Oron Ashual, Devi Parikh, +and Yaniv Taigman. Emu edit: Precise image editing via recognition and generation tasks. In Pro- +ceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 8871– +8879, 2024. +Jiaming Song, Chenlin Meng, and Stefano Ermon. Denoising diffusion implicit models. arXiv +preprint arXiv:2010.02502, 2020. +Wangtao Sun, Xiang Cheng, Xing Yu, Haotian Xu, Zhao Yang, Shizhu He, Jun Zhao, and Kang +Liu. Probabilistic uncertain reward model, 2025. URL https://arxiv.org/abs/2503. +22480. +13 + +===== PAGE 14 ===== +Published as a conference paper at ICLR 2026 +Keyu Tian, Yi Jiang, Zehuan Yuan, Bingyue Peng, and Liwei Wang. Visual autoregressive modeling: +Scalable image generation via next-scale prediction. Advances in neural information processing +systems, 37:84839–84865, 2024. +Bram Wallace, Akash Gokul, and Nikhil Naik. EDICT: Exact diffusion inversion via coupled trans- +formations. In CVPR, pp. 22532–22541, 2023. +Guo-Hua Wang, Shanshan Zhao, Xinjie Zhang, Liangfu Cao, Pengxin Zhan, Lunhao Duan, Shiyin +Lu, Minghao Fu, Jianshan Zhao, Yang Li, and Qing-Guo Chen. Ovis-u1 technical report. arXiv +preprint arXiv:2506.23044, 2025a. +Jifang Wang, Xue Yang, Longyue Wang, Zhenran Xu, Yiyu Wang, Yaowei Wang, Weihua Luo, +Kaifu Zhang, Baotian Hu, and Min Zhang. A unified agentic framework for evaluating conditional +image generation, 2025b. URL https://arxiv.org/abs/2504.07046. +Peng Wang, Yichun Shi, Xiaochen Lian, Zhonghua Zhai, Xin Xia, Xuefeng Xiao, Weilin Huang, +and Jianchao Yang. Seededit 3.0: Fast and high-quality generative image editing. arXiv preprint +arXiv:2506.05083, 2025c. +Yuhan Wang, Siwei Yang, Bingchen Zhao, Letian Zhang, Qing Liu, Yuyin Zhou, and Cihang Xie. +Gpt-image-edit-1.5m: A million-scale, gpt-generated image dataset, 2025d. URL https:// +arxiv.org/abs/2507.21033. +Cong Wei, Zheyang Xiong, Weiming Ren, Xinrun Du, Ge Zhang, and Wenhu Chen. Om- +niedit: Building image editing generalist models through specialist supervision. arXiv preprint +arXiv:2411.07199, 2024. +Chenfei Wu, Jiahao Li, Jingren Zhou, Junyang Lin, Kaiyuan Gao, Kun Yan, Sheng ming Yin, Shuai +Bai, Xiao Xu, Yilei Chen, Yuxiang Chen, Zecheng Tang, Zekai Zhang, Zhengyi Wang, An Yang, +Bowen Yu, Chen Cheng, Dayiheng Liu, Deqing Li, Hang Zhang, Hao Meng, Hu Wei, Jingyuan +Ni, Kai Chen, Kuan Cao, Liang Peng, Lin Qu, Minggang Wu, Peng Wang, Shuting Yu, Tingkun +Wen, Wensen Feng, Xiaoxiao Xu, Yi Wang, Yichang Zhang, Yongqiang Zhu, Yujia Wu, Yuxuan +Cai, and Zenan Liu. Qwen-image technical report, 2025a. URL https://arxiv.org/abs/ +2508.02324. +Chenyuan Wu, Pengfei Zheng, Ruiran Yan, Shitao Xiao, Xin Luo, Yueze Wang, Wanli Li, Xiyan +Jiang, Yexin Liu, Junjie Zhou, Ze Liu, Ziyi Xia, Chaofan Li, Haoge Deng, Jiahao Wang, Kun +Luo, Bo Zhang, Defu Lian, Xinlong Wang, Zhongyuan Wang, Tiejun Huang, and Zheng Liu. +Omnigen2: Exploration to advanced multimodal generation. arXiv preprint arXiv:2506.18871, +2025b. +Xiaoshi Wu, Keqiang Sun, Feng Zhu, Rui Zhao, and Hongsheng Li. Human preference score: +Better aligning text-to-image models with human preference. In Proceedings of the IEEE/CVF +International Conference on Computer Vision, pp. 2096–2105, 2023. +Xun Wu, Shaohan Huang, Guolong Wang, Jing Xiong, and Furu Wei. Multimodal large language +models make text-to-image generative models align better. Advances in Neural Information Pro- +cessing Systems, 37:81287–81323, 2024. +Xun Wu, Shaohan Huang, Guolong Wang, Jing Xiong, and Furu Wei. Multimodal large language +models make text-to-image generative models align better. Advances in Neural Information Pro- +cessing Systems, 37:81287–81323, 2025c. +Jiazheng Xu, Xiao Liu, Yuchen Wu, Yuxuan Tong, Qinkai Li, Ming Ding, Jie Tang, and Yuxiao +Dong. Imagereward: Learning and evaluating human preferences for text-to-image generation. +Advances in Neural Information Processing Systems, 36, 2024. +Yang Ye, Xianyi He, Zongjian Li, Bin Lin, Shenghai Yuan, Zhiyuan Yan, Bohan Hou, and Li Yuan. +Imgedit: A unified image editing dataset and benchmark, 2025. URL https://arxiv.org/ +abs/2505.20275. +Jiahui Yu, Yuanzhong Xu, Jing Yu Koh, Thang Luong, Gunjan Baid, Zirui Wang, Vijay Vasudevan, +Alexander Ku, Yinfei Yang, Burcu Karagol Ayan, et al. Scaling autoregressive models for content- +rich text-to-image generation. arXiv preprint arXiv:2206.10789, 2(3):5, 2022. +14 + +===== PAGE 15 ===== +Published as a conference paper at ICLR 2026 +Qifan Yu, Wei Chow, Zhongqi Yue, Kaihang Pan, Yang Wu, Xiaoyang Wan, Juncheng Li, Siliang +Tang, Hanwang Zhang, and Yueting Zhuang. Anyedit: Mastering unified high-quality image +editing for any idea. In Proceedings of the Computer Vision and Pattern Recognition Conference, +pp. 26125–26135, 2025. +Xiaomi LLM-Core Team: Zihao Yue, Zhenru Lin, Yifan Song, Weikun Wang, Shuhuai Ren, Shuhao +Gu, Shicheng Li, Peidian Li, Liang Zhao, Lei Li, Kainan Bao, Hao Tian, Hailin Zhang, Gang +Wang, Dawei Zhu, Cici, Chenhong He, Bowen Ye, Bowen Shen, Zihan Zhang, Zihan Jiang, +Zhixian Zheng, Zhichao Song, Zhenbo Luo, Yue Yu, Yudong Wang, Yuanyuan Tian, Yu Tu, +Yihan Yan, Yi Huang, Xu Wang, Xinzhe Xu, Xingchen Song, Xing Zhang, Xing Yong, Xin +Zhang, Xiangwei Deng, Wenyu Yang, Wenhan Ma, Weiwei Lv, Weiji Zhuang, Wei Liu, Sirui +Deng, Shuo Liu, Shimao Chen, Shihua Yu, Shaohui Liu, Shande Wang, Rui Ma, Qiantong Wang, +Peng Wang, Nuo Chen, Menghang Zhu, Kangyang Zhou, Kang Zhou, Kai Fang, Jun Shi, Jinhao +Dong, Jiebao Xiao, Jiaming Xu, Huaqiu Liu, Hongshen Xu, Heng Qu, Haochen Zhao, Hanglong +Lv, Guoan Wang, Duo Zhang, Dong Zhang, Di Zhang, Chong Ma, Chang Liu, Can Cai, and +Bingquan Xia. Mimo-vl technical report. arXiv preprint arXiv:2506.03569, 2025. URL https: +//arxiv.org/abs/2506.03569. 32 pages. +Kai Zhang, Lingbo Mo, Wenhu Chen, Huan Sun, and Yu Su. Magicbrush: A manually annotated +dataset for instruction-guided image editing. Advances in Neural Information Processing Systems, +36, 2024a. +Richard Zhang, Phillip Isola, Alexei A Efros, Eli Shechtman, and Oliver Wang. The unreasonable +effectiveness of deep features as a perceptual metric. In Proceedings of the IEEE conference on +computer vision and pattern recognition, pp. 586–595, 2018. +Shu Zhang, Xinyi Yang, Yihao Feng, Can Qin, Chia-Chih Chen, Ning Yu, Zeyuan Chen, Huan +Wang, Silvio Savarese, Stefano Ermon, et al. Hive: Harnessing human feedback for instructional +visual editing. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern +Recognition, pp. 9026–9036, 2024b. +Haozhe Zhao, Xiaojian Ma, Liang Chen, Shuzheng Si, Rujie Wu, Kaikai An, Peiyu Yu, Minjia +Zhang, Qing Li, and Baobao Chang. UltraEdit: Instruction-based fine-grained image editing at +scale. arXiv preprint arXiv:2407.05282, 2024. +15 + +===== PAGE 16 ===== +Published as a conference paper at ICLR 2026 +A APPENDIX +A.1 USE OF LLM +Large Language Models (LLMs) were used exclusively for minor grammar correction and stylistic +refinement of the manuscript. Their role was purely auxiliary, and all major scientific contributions +were made by the authors. The authors bear full responsibility for the content of this work. +A.2 DETAILS OF EDITREWARD-DATA CONSTRUCTION +Our dataset construction was centered on three principles: ecological validity, by sourcing in- +structions from human-vetted benchmarks; diversity, by generating candidates from state-of-the-art +models; and reliability, through a rigorous multi-dimensional annotation pipeline. +Source Data Collection. To ensure ecological validity, we collected 9,557 unique instruction-image +pairs from six established, human-vetted sources: GEdit-Bench (606), ImgEdit-Bench (737), Mag- +icBrush (1,053), AnyEdit (1,250), EmuEdit (5,611), and a challenging internal set (300). This ag- +gregation provides a comprehensive foundation of semantically grounded and executable edit in- +structions across a wide spectrum of tasks and styles. +Candidate Generation. For each of the 9,557 source pairs, we generated a diverse pool of +12 candidate images using six state-of-the-art models: Step1X-Edit (Liu et al., 2025b), Flux- +Kontext (BlackForestLabs et al., 2025), Qwen-Image-Edit (Wu et al., 2025a), BAGEL (Deng et al., +2025), Ovis-U1 (Wang et al., 2025a), and OmniGen2 (Wu et al., 2025b). To ensure a broad qual- +ity spectrum and mitigate model-specific biases, we utilized multiple random seeds, preventing any +single model from dominating the candidate pool. +Table 8: The detailed comparison of different generative preference datasets and benchmarks. +Dataset Venue Scale Task Focus Annotation Eval. Dims. Limitation / Caveat +ImageRewardDB NeurIPS’23∼137K Visual Generation Human Single Expert comparisons with limited variety +VisionPrefer NeurIPS’24 1.2M Generation Model Multiple Multi-aspect but model-derived bias risks +GenAI-Bench NeurIPS’24∼1.6K Generation / Editing Human Multiple High quality but very small scale +HIVE CVPR’24∼3.6K Instructional Editing Human Single Task-specific, limited comparison set size +ADIEE ICCV’25 >100K Instructional Editing Model Single Synthetic labels; possible model bias +HPDv3 ICCV’25 >1.17M Visual Generation Human Single Wide-spectrum; generalizability limits +EDITREWARD-DATA ∼200K Instructional Editing Human Multiple Large scale and fine-grained supervision +Benchmark Venue Scale Annotation Eval. Dims. Multi-Way Preference Pair-Wise Point-Wise +GenAI-Bench NeurIPS’24∼900 Human Multiple 2-way ✓— +AURORA-Bench NeurIPS’24∼1.6K Human Multiple 2-way ✓ ✓ +ImagenHub ICLR’24∼1.4K Human + Model Single 2-way — ✓ +EDITREWARD-BENCH 500 Groups (∼1.5K) 3 Human (Cross-check) Multiple 2/3/4-way ✓ ✓ +Multi-Dimensional Annotation. From the pool of 12 candidates, 7 were randomly sampled for +human evaluation. Annotators provided two separate scores for each candidate on a 4-point Lik- +ert scale (1=Poor to 4=Excellent), corresponding to our two evaluation dimensions: (1) Instruc- +tion Following, which assesses semantic accuracy, completeness, and the avoidance of unprompted +changes; and (2) Visual Quality, which evaluates physical plausibility, absence of artifacts, and +overall aesthetic appeal. This multi-dimensional rubric provides a more granular assessment than a +single holistic score. Detailed interface of the annotations is in Figure 4. We also provide detailed +annotation guidance below. +Annotation Guidelines: +16 + +===== PAGE 17 ===== +Published as a conference paper at ICLR 2026 +Instruction Following +This dimension focuses on how accurately, completely, and exclusively the model executed the +text instruction. +Key Criteria: +• Semantic Accuracy: Correctly interpreting the core meaning. +• Completeness: Fulfilling all parts of the instruction. +• Exclusivity: Avoiding unprompted changes to the rest of the image. +Negative Indicators: +• A key part of the instruction is ignored (e.g., color changed but not the object). +• A major misinterpretation (e.g., ”orange” yields a grapefruit). +• The image is unchanged or a random, unrelated image is generated. +Scoring Rubric (1-4 Scale): +• 4 (Very Good): Perfectly executes all aspects of the instruction. Edit is surgical and +flawless. +• 3 (Relatively Good): Achieves the main goal but with minor deviations or omissions (e.g., +misses a small detail). +• 2 (Relatively Poor): Significantly misunderstands or only partially executes the instruc- +tion. Unedited areas may be noticeably altered. +• 1 (Very Poor): Completely fails the instruction. The result is unrelated, or the image is +corrupted. +Visual Quality +This dimension focuses on the physical plausibility, technical flawlessness, and overall aes- +thetic appeal of the edited image. +Key Criteria: +• Plausibility: Consistency with real-world physics (lighting, shadows). +• Artifact-Free: Absence of visual flaws (blur, distortion, seams). +• Aesthetic Quality: The overall harmony, naturalness, and visual appeal. +Negative Indicators: +• Obvious physical errors (e.g., an object casts no shadow). +• Noticeable and distracting artifacts (e.g., a blurry halo around the edit). +• The final image is jarring, ugly, or unbalanced. +Scoring Rubric (1-4 Scale): +• 4 (Very Good): Perfectly realistic and visually flawless. The edit is undetectable and +appealing. +• 3 (Relatively Good): High quality overall, but close inspection may reveal minor imper- +fections (e.g., shadow is slightly off). +• 2 (Relatively Poor): The edit is obvious and looks unnatural, with clear visual flaws that +detract from its quality. +• 1 (Very Poor): A visual failure, full of severe errors and artifacts, making it unusable. +Quality Control. The reliability of our annotations is ensured through a multi-stage process. The +process includes: (1) initial pilot studies to refine the annotation guidelines and rubric; (2) a formal +training and calibration phase for all annotators to align their judgments; and (3) continuous ran- +dom sampling and cross-checking of annotations during the formal labeling process to maintain a +17 + +===== PAGE 18 ===== +Published as a conference paper at ICLR 2026 +Figure 4: Annotation Interface +Table 9: Inter-Annotator Agreement (IAA) Metrics for Expert Annotations. The robust Krippendorff +Alpha (α) values confirm the high reliability of our multi-dimensional expert scoring. +Dataset Fleiss’ Kappa (IF) Fleiss’ Kappa (VQ) Krippendorff Alpha (IF) Krippendorff Alpha (VQ) +EDITREWARD-DATA 0.4157 0.3203 0.6762 0.5720 +EDITREWARD-BENCH 0.3962 0.3157 0.6623 0.6114 +All data 0.3994 0.3111 0.6685 0.5972 +high inter-annotator agreement (IAA). More representative examples from EDITREWARD-DATA are +shown in the Appendix A.10. The IAA results in Table 9 provide a critical quantitative assessment +of our expert annotation quality (Fleiss, 1971). We highlight the values derived from Krippendorff’s +Alpha (α) (Krippendorff, 2011), which is the most appropriate metric as it correctly models the +ordinal nature of our 4-point Likert scale. The α scores of 0.668 for Instruction Following (IF) +and 0.597 for Visual Quality (VQ) establish a strong, quantified baseline for human consistency. +Crucially, the observed difference (IAAIF >IAAVQ) provides empirical validation for our core con- +tribution: it confirms that the VQ dimension is inherently more subjective than IF. This validates our +design choice to use a multi-dimensional rubric and a multi-head reward model, as a single holistic +score would obscure this critical difference in human variance. +18 + +===== PAGE 19 ===== +Published as a conference paper at ICLR 2026 +A.3 DETAILS OF EDITREWARD-BENCH CONSTRUCTION +To provide a more robust and discerning evaluation of image editing reward models, we introduce +EDITREWARD-BENCH. The design of this new benchmark is motivated by several limitations iden- +tified in existing evaluation suites. For instance, ImagenHub utilizes a simple 3-point rating scale +[0, 0.5, 1]. While user-friendly, this coarse granularity can fail to capture the nuanced quality differ- +ences across the broad spectrum of semantic consistency and perceptual quality (Ku et al., 2023). +The editing tasks in AURORA-Bench are primarily focused on action-centric and reasoning-centric +instructions, which may not represent the full diversity of common editing requests. +To address these challenges, we constructed EDITREWARD-BENCH through a meticulous pipeline. +The foundation of our benchmark is a curated subset of 500 high-quality groups sampled from +our EDITREWARD-DATA candidate pool, spanning 7 distinct editing categories. To establish a +reliable ground truth, we engaged three independent groups of trained expert annotators. Following +the multi-dimensional rubric detailed in Section 2.1, each annotator assigned scores on a 4-point +Likert scale [1, 2, 3, 4] for both instruction fidelity and visual quality. This process ensures the +robustness and accuracy of our ground-truth labels. To increase the benchmark’s difficulty and test +the fine-grained discriminative power of models, we prioritized the inclusion of samples where the +competing edits have small differences in their average human scores. +The primary innovation of EDITREWARD-BENCH is its introduction of a multi-way preference +comparison protocol, moving beyond simple pairwise judgments. We construct more complex +evaluation units, including ternary tuples (A, B, C) and quaternary tuples (A, B, C, D), based +on our reliable human scores. For a model’s evaluation of a tuple to be considered correct, it must +correctly predict the preference relationship for all constituent pairs within that tuple (e.g., A>B, +A>C, and B>C for a ternary tuple where A is the best and C is the worst). This strict, all-or- +nothing criterion provides a much more comprehensive and robust measure of a reward model’s +ranking consistency and reasoning capabilities than traditional pairwise accuracy. We evaluated a +wide range of leading models on EDITREWARD-BENCH to establish its utility. The experimental +results are detailed in Section 4. +Dataset Details We provide additional details regarding our annotation protocol. All annotators +followed a standardized rubric with clear dimension-specific guidelines, covering Instruction Fol- +lowing (IF) and Visual Quality (VQ). To ensure high consistency, each annotator underwent training +sessions with reference examples before formal labeling. +For EDITREWARD-DATA, each edited image is scored by a single expert annotator on a 4-point +scale (1–4) across the two dimensions (IF, VQ). This provides large-scale but fine-grained supervi- +sion. +For EDITREWARD-BENCH, every group is annotated by three independent experts, again along +the two dimensions (IF, VQ). Annotators must jointly determine the ranking consistency among +multiple candidates. When disagreements occur, a cross-check protocol ensures consistency across +annotators, with the final label derived from majority agreement. +This protocol guarantees both the scale and quality of the training data and the strict reliability of +the benchmark. +A.4 MORE DETAILS AND IMPLEMENTATION OF TRAINING +Reward Model Architecture. Our reward model, EDITREWARD, is built upon a powerful pre- +trained Vision-Language Model (VLM) backbone, which is fully fine-tuned during training. Our +main results use two backbones: Qwen2.5-VL-7B and MiMo-VL-7B. The VLM backbone is fol- +lowed by a Multi-Layer Perceptron (MLP) reward head. Based on our ablation studies, we use a +Multiple Head architecture, where separate MLP heads predict the parameters (µ,σ2) for each of +the two quality dimensions independently. +19 + +===== PAGE 20 ===== +Published as a conference paper at ICLR 2026 +(a) Loss curve and Valid set Acc without using Disentangling Ties via Dimensional Preference training +(b) Loss curve and Valid set Acc by using Disentangling Ties via Dimensional Preference training +Figure 5: Loss curve and Valid set Acc by using or not using Disentangling Ties via Dimensional +Preference during model training. +A.5 MORE DETAILS ABOUT EVALUATION +We present the main experimental results in Table 3. The findings clearly demonstrate that our +reward model, EDITREWARD, sets a new state of the art in aligning with human preferences for +instruction-guided image editing. +State-of-the-Art Performance. Our best model, EDITREWARD (on MiMo-VL-7B), achieves +the highest performance on three out of four benchmarks. It obtains a state-of-the-art accuracy +of 65.72% on GenAI-Bench, significantly surpassing the strongest proprietary competitor, GPT-5 +(59.61), and the best open-source VLM, ADIEE (59.96). Similarly, on AURORA-Bench, our model +scores 63.62%, demonstrating a substantial margin over the next-best models, EDITREWARD (on +Qwen2.5-VL-7B) at 59.50% and ADIEE at 55.56%. On ImagenHub, our models remain highly +competitive with the top proprietary systems, with EDITREWARD (on Qwen2.5-VL-7B) achieving +a Spearman correlation of 36.18, second only to GPT-4o. +Effectiveness of Reward Modeling. A key insight from our results is the profound impact of our +reward modeling framework itself. By comparing the base open-source VLMs to our EDITREWARD +trained on them, we can quantify the performance uplift. For instance, the base Qwen2.5-VL-7B- +Inst scores 40.48% on GenAI-Bench. After being trained with our multi-dimensional, uncertainty- +aware methodology, the resulting EDITREWARD (on Qwen2.5-VL-7B) skyrockets to 63.97%—a +massive +23.5 point improvement. This demonstrates that our contribution is not merely the appli- +cation of a strong backbone, but a highly effective training paradigm that dramatically enhances a +model’s alignment with human judgments. +Performance on EDITREWARD-BENCH and Backbone Generalization. Our proposed bench- +mark, EDITREWARD-BENCH, proves to be a more challenging and discerning testbed. Here, our +20 + +===== PAGE 21 ===== +Published as a conference paper at ICLR 2026 +EDITREWARD (on MiMo-VL-7B) again achieves the top score of 38.42%, narrowly outperform- +ing Gemini-2.5-Flash (38.02) and GPT-5 (37.81). Notably, GPT-4o, the best-performing model on +ImagenHub, scores significantly lower at 28.31, confirming that EDITREWARD-BENCH effectively +identifies limitations in models that other benchmarks may miss. Finally, the strong performance of +EDITREWARD on both Qwen2.5-VL and the more powerful MiMo-VL backbone confirms that our +reward modeling framework is robust and can effectively leverage the capabilities of stronger base +models to push the state of the art even further. +A.6 MORE DETAILS ABOUT APPLICATION +Beyond direct evaluation, a key application for a powerful reward model is to improve downstream +generative models through data curation. To demonstrate the practical utility of EDITREWARD, we +conducted an experiment to see if it could filter a large, noisy dataset to create a high-quality subset +for fine-tuning a state-of-the-art image editing model. +Experimental Setup. Our experiment uses the open-source Step1X-Edit (Liu et al., 2025b) as the +base model for fine-tuning. The training data is derived from ShareGPT-4o-Image (Chen et al., +2025a), a large dataset containing approximately 46,000 instruction-image pairs. We first employed +EDITREWARD to score every example in this dataset. We then curated a high-quality subset by +selecting only the top-scoring 20,000 examples. The goal is to evaluate if fine-tuning Step1X-Edit +on this smaller, curated subset yields better performance than training on the full, noisy dataset. +Evaluation Metrics and Baselines. We evaluate all models on GEdit-Bench, a comprehensive +benchmark with English (EN) and Chinese (CN) versions, each containing a full set and a more +challenging intersection (-I) split. Performance is measured across three axes: Semantic Con- +sistency (G SC), which evaluates how well the edit follows the instruction; Perceptual Quality +(G PQ), which assesses visual realism and aesthetics; and a holistic General Overall (G O) score. +For all metrics, higher is better. +We compare our final model against two critical baselines to measure the impact of our data curation: +• Step1X-Edit: The original model without any additional fine-tuning. +• Step1X-Edit + ShareGPT-4o-Image: The baseline model fine-tuned on the full, unfiltered +ShareGPT-4o-Image dataset. +This setup allows us to directly isolate the benefit of filtering with EDITREWARD. We also compare +against other leading editing models like Doubao and GPT-Image-1 to contextualize our perfor- +mance. +Results and Analysis. As shown in Table 4, fine-tuning Step1X-Edit on our EDITREWARD-curated +subset yields substantial improvements across all benchmarks and metrics. On the GEdit-Bench-EN +Overall score (G O), our model achieves 7.086, a significant gain over both the original Step1X-Edit +(6.444) and the model trained on the full, noisy dataset (6.780). +This result is crucial: it demonstrates that training on a smaller, higher-quality dataset curated by our +reward model is more effective than training on the entire noisy dataset. EDITREWARD successfully +identifies and filters out low-quality or misaligned examples that can harm the fine-tuning process. +Furthermore, this improvement elevates the performance of the open-source Step1X-Edit to be on +par with, or even superior to, strong competitors like Doubao (6.983). This experiment validates +the high potential of EDITREWARD as an essential tool for data curation in the training pipelines of +next-generation image editing models. In Figure x, we show how our reward model is used to score +some image editing examples. +A.7 MORE ABLATION EXPERIMENTS RESULTS +Ablation on Data Scale and Tie Disentanglement. Next, we investigate the combined effect +of increasing our training data from 130k to 200k samples while also applying our proposed tie- +disentanglement strategy. The results of this significant upgrade are presented in Table 10. Compar- +ing our baseline model (Variant I) against our final model which incorporates both changes (Variant +21 + +===== PAGE 22 ===== +Published as a conference paper at ICLR 2026 +Table 10: Ablation study on dataset size and our tie-disentanglement strategy. +Variants Ablation Setting Benchmark Performance +Dataset Size Disentangling Ties GenAI-Bench AURORA-Bench (Pair) ImagenHub EDITREWARD-BENCH +Direct ablation on the full dataset +I 130k 62.24 51.36 32.45 37.81 +II 200k ✓ 63.97 53.33 36.18 36.78 +II), we observe consistent performance gains across all public benchmarks. The improvement is +most pronounced on ImagenHub, where the score increases substantially from 32.45 to 36.18. We +also see notable gains on GenAI-Bench (62.24 →63.97) and AURORA-Bench (51.36 →53.33). +Interestingly, we note a slight performance decrease on our proposed EDITREWARD-BENCH, sug- +gesting it may have different sensitivities to the data distribution. Overall, these results confirm the +significant benefit of our full data strategy, which combines a larger, high-quality dataset with our +novel technique for leveraging ambiguous tie pairs. +Table 11: Bias sensitivity analysis of Gemini 2.0 Flash under left/right bias conditions on GenAI- +Bench. +Condition Accuracy (%) +Left Bias 55.28 +Right Bias 50.16 +Bias Sensitivity (Gap) 5.11 +A.8 POSITIONAL BIAS +In the course of our evaluation on GenAI-Bench, we identified a notable case of bias sensitivity +in the Gemini 2.0 Flash model when subjected to systematic position bias. Specifically, when we +artificially manipulated the ground-truth labels to favor either left-side (A>B) or right-side (B>A) +preferences—while correspondingly swapping the image positions to maintain correctness—we ob- +served a consistent performance discrepancy. As shown in Table 11, the model achieved 55.28% +accuracy under the left-bias condition but only 50.16% under the right-bias condition, yielding a +5.11% gap. This systematic difference indicates that the model exhibits a positional preference for +left-side comparisons, which could distort evaluation outcomes if left unaddressed. To prevent such +bias from affecting comparative results, GenAI-Bench adopts a randomized positioning strategy +that shuffles the order of candidate images (A and B) for each comparison task. This ensures that +evaluation outcomes are driven by genuine quality judgments rather than positional artifacts, thereby +preserving fairness, robustness, and reliability across diverse model architectures. +22 + +===== PAGE 23 ===== +Published as a conference paper at ICLR 2026 +A.9 INPUT TEMPLATE FOR REWARD MODEL +This section provides the exact input prompt template used in all experiments to guide our reward +model, EDITREWARD, in scoring the quality of an image edit. +INSTRUCTION EDIT FOLLOWING TEMPLATE +[IMAGE] You are tasked with evaluating an edited image **in comparison with the original source +image** based on **Visual Quality & Realism**, and assigning a score from 1 to 4, with 1 being the +worst and 4 being the best. This dimension focuses on how realistic, artifact-free, and aesthetically +appealing the edited image is, while remaining consistent with the source image. +**Inputs Provided:** +- Source Image (before editing) +- Edited Image (after applying the instruction) +- Text Instruction +**Sub-Dimensions to Evaluate:** +- **Semantic Accuracy:** Assess whether the edited content accurately captures the semantics of +the instruction. The edited result should precisely match the intended meaning. For example, if the +instruction is ”replace apples with oranges,” the object must clearly be oranges, not other fruits. +- **Completeness of Editing:** Check whether **all parts** of the instruction are fully executed. For +multi-step edits (e.g., ”replace a red car with a blue bicycle”), both the color change and the object +replacement must be done without omissions. +- **Exclusivity of Edit (No Over-Editing):** Ensure that only the requested parts are changed. The +rest of the image (as seen in the source) should remain unaltered. For example, if the instruction +only involves replacing an object, the background, lighting, and unrelated objects should not be +unnecessarily modified. +**Scoring Criteria:** +- **4 (Very Good):** Perfectly accurate, complete, and exclusive execution of the instruction. +- **3 (Relatively Good):** Largely correct, but with minor omissions or slight over-editing. +- **2 (Relatively Poor):** Major misinterpretation, incomplete edits, or noticeable unintended +changes. +- **1 (Very Poor):** Instruction ignored or completely wrong execution. +Text instruction – {text_prompt} +23 + +===== PAGE 24 ===== +Published as a conference paper at ICLR 2026 +INSTRUCTION EDIT QUALITY TEMPLATE +[IMAGE] You are tasked with evaluating an edited image **in comparison with the original source +image** based on **Visual Quality & Realism**, and assigning a score from 1 to 4, with 1 being the +worst and 4 being the best. This dimension focuses on how realistic, artifact-free, and aesthetically +appealing the edited image is, while remaining consistent with the source image. +**Inputs Provided:** +- Source Image (before editing) +- Edited Image (after applying the instruction) +- Text Instruction +**Sub-Dimensions to Evaluate:** +- **Plausibility & Physical Consistency:** Check whether the edit aligns with the laws of physics +and the scene context. Lighting, shadows, reflections, perspective, size, and interactions with the +environment should all appear natural compared to the source image. +- **Artifact-Free Quality:** Look for technical flaws such as blur, distortions, pixel misalignment, +unnatural textures, or seams around edited regions. High-quality results should be free from such +visible artifacts. +- **Aesthetic Quality:** Evaluate the overall harmony and visual appeal. The image should look +natural, balanced, and pleasant. Colors, composition, and atmosphere should enhance the image +rather than degrade it. +**Scoring Criteria:** +- **4 (Very Good):** Perfectly realistic, artifact-free, seamless, and aesthetically pleasing. +- **3 (Relatively Good):** Mostly realistic and clean, with only minor flaws that do not significantly +distract. +- **2 (Relatively Poor):** Noticeable physical inconsistencies or visible artifacts that make the edit +unnatural. +- **1 (Very Poor):** Severe artifacts, incoherent composition, or visually unusable result. +Text instruction – {text_prompt} +24 + +===== PAGE 25 ===== +Published as a conference paper at ICLR 2026 +Full Input Template +[IMAGE] You are tasked with evaluating an edited image **in comparison with the original source +image**, and assigning a score from 1 to 8, with 1 being the worst and 8 being the best. This score +should reflect **both how accurately the instruction was followed and the visual quality of the edited +image**. +**Inputs Provided:** +- Source Image (before editing) +- Edited Image (after applying the instruction) +- Text Instruction +**Dimension 1: Instruction Following & Semantic Fidelity** +Evaluate how well the edited image follows the given instruction. Consider the following sub- +dimensions: +- **Semantic Accuracy:** Check if the edited content accurately captures the intended meaning of the +instruction. For example, if the instruction is ”replace apples with oranges,” the object must clearly be +oranges, not other fruits. +- **Completeness of Editing:** Verify that all aspects of the instruction are fully executed. Multi-step +edits should be completely applied without omissions. +- **Exclusivity of Edit (No Over-Editing):** Ensure that only the requested changes are applied; +the rest of the image should remain consistent with the source image without unintended modifications. +**Dimension 2: Visual Quality & Realism** +Evaluate the realism, technical quality, and aesthetic appeal of the edited image. Consider the +following sub-dimensions: +- **Plausibility & Physical Consistency:** Check whether the edit aligns with natural laws and scene +context (lighting, shadows, reflections, perspective, and object interactions). +- **Artifact-Free Quality:** Assess for technical flaws such as blur, distortions, pixel misalignment, +unnatural textures, or seams around edited regions. +- **Aesthetic Quality:** Consider overall harmony and visual appeal. Colors, composition, atmo- +sphere, and balance should enhance the image without degrading realism. +**Scoring Criteria (1–8):** +- **8 (Very Good):** Perfect instruction following and flawless visual quality; edits are accurate, +complete, exclusive, and visually seamless. +- **7 (Relatively Good):** Very good instruction following and high visual quality; minor, non- +distracting flaws. +- **6 (Good):** Good instruction following or mostly good visual quality; minor omissions or slight +artifacts. +- **5 (Moderate):** Partially correct edits or moderate visual issues; noticeable flaws but understand- +able. +- **4 (Relatively Poor):** Significant misinterpretation, incomplete edits, or noticeable visual +artifacts. +- **3 (Poor):** Major errors in instruction following and/or poor visual quality; hard to fully +understand. +- **2 (Very Poor):** Very poor edits with large semantic errors and strong visual artifacts. +- **1 (Failed):** Completely wrong edits or visually unusable result. +Text instruction – {text_prompt} +A.10 REPRESENTATIVE RESULTS OF EDITREWARD-DATA +The following examples provide additional qualitative illustrations of EDITREWARD-DATA. They +highlight a broad spectrum of real editing behaviors, including appearance manipulation, object in- +sertion/removal, style transfer and text change. Each example includes the source image, the edited +result, and the associated annotations—such as instruction-following and visual quality. These sam- +ples complement the main paper by demonstrating the dataset’s diversity, annotation fidelity, and +coverage across both everyday and challenging editing scenarios. +25 + +===== PAGE 26 ===== +Published as a conference paper at ICLR 2026 +source ovis_u1 +IF: 3 | QA: 4 +omnigen2 +IF: 3 | QA: 4 +bagel_think +IF: 2 | QA: 4 +step1x_v2n +IF: 3 | QA: 4 +step1x_v2n_random2 +IF: 3 | QA: 4 +flux_kontext +IF: 4 | QA: 4 +Instruction: Replace the text 'NIPS' with 'CVPR' +(a) Example 1 from EDITREWARD-DATA. +qwen_edit +IF: 3 | QA: 4 +source step1x +IF: 4 | QA: 4 +flux_kontext +IF: 4 | QA: 4 +bagel +IF: 4 | QA: 3 +ovis_u1 +IF: 4 | QA: 4 +step1x_v2n +ovis_u1_random2 +IF: 2 | QA: 4 +IF: 4 | QA: 4 +Instruction: Make the image appear as if it's a woodblock print by Hokusai. +omnigen2 +IF: 2 | QA: 3 +(b) Example 2 from EDITREWARD-DATA. +Figure 6: Representative examples from EDITREWARD-DATA, complementing Fig. 2. +A.11 QUALITATIVE EXAMPLES OF EDITREWARD-BASED FILTERING +To provide additional intuition about the preferences learned by EDITREWARD-DATA ’s reward +model, we visualize samples from the ShareGPT-4o-Image dataset (Chen et al., 2025a) that are +either retained or filtered out after ranking with EditReward scores. The selected examples highlight +the characteristic patterns captured by the reward model. +High-Quality Retained Data. Samples with high EditReward scores generally demonstrate ac- +curate instruction following, clean and localized modifications, and visually coherent integration +with the surrounding context. These images exhibit minimal artifacts and adhere closely to both the +semantic intent and spatial constraints of the edit. +26 + +===== PAGE 27 ===== +Published as a conference paper at ICLR 2026 +source qwen_edit +IF: 3 | QA: 2 +qwen_edit_random2 +IF: 3 | QA: 1 +ovis_u1 +IF: 3 | QA: 1 +ovis_u1_random2 +IF: 3 | QA: 1 +bagel_think +IF: 2 | QA: 1 +step1x +IF: 2 | QA: 1 +Instruction: change the season to autumn +step1x_v2n +IF: 4 | QA: 3 +(a) Example 3 from EDITREWARD-DATA. +source step1x_v2n +IF: 4 | QA: 3 +ovis_u1 +IF: 3 | QA: 3 +bagel_think +IF: 3 | QA: 1 +step1x_v2n_random2 +IF: 3 | QA: 4 +flux_kontext +bagel +IF: 2 | QA: 1 +IF: 4 | QA: 3 +Instruction: Remove the dog from the image and replace with a full image cat. +omnigen2 +IF: 2 | QA: 1 +(b) Example 4 from EDITREWARD-DATA. +Figure 7: Representative examples from EDITREWARD-DATA, complementing Fig. 2. +Low-Quality Filtered Data. Samples with low scores often contain undesirable visual artifacts, +incorrect or incompletely executed edits, spatial misalignment, or hallucinated content. These fail- +ure patterns reflect typical challenges in image editing that violate instruction-following or degrade +overall image quality. +Together, these qualitative examples illustrate the types of editing behaviors favored or penalized by +EditReward, offering a clear and interpretable view of the model’s learned preferences during data +filtering. +27 + +===== PAGE 28 ===== +Published as a conference paper at ICLR 2026 +source bagel +IF: 3 | QA: 4 +flux_kontext +IF: 4 | QA: 3 +qwen_edit +IF: 3 | QA: 4 +bagel_think +IF: 4 | QA: 2 +step1x +qwen_edit _random2 +IF: 4 | QA: 3 +IF: 3 | QA: 3 +Instruction: Add green water to the toilet bowl. +(a) Example 5 from EDITREWARD-DATA. +ovis_u1 +IF: 3 | QA: 2 +source bagel_think +IF: 2 | QA: 2 +ovis_u1 +IF: 3 | QA: 1 +omnigen2 +IF: 1 | QA: 1 +bagel +IF: 1 | QA: 2 +ovis_u1_random2 +IF: 3 | QA: 1 +step1x +IF: 4 | QA: 2 +Instruction: Make the spots on the closest giraffe blue. +step1x_v2n +IF: 1 | QA: 1 +(b) Example 6 from EDITREWARD-DATA. +Figure 8: Representative examples from EDITREWARD-DATA, complementing Fig. 2. +A.12 QUALITATIVE COMPARISON: BEFORE VS. AFTER EDITREWARD FILTERING +To further illustrate the qualitative improvements enabled by EditReward-based data curation, we +present side-by-side comparisons of image editing results produced by the same Step1X-Edit archi- +tecture trained on two datasets: (i) the original unfiltered dataset, and (ii) the EditReward-filtered +high-quality subset. +For each example, we show the source image, the output from the model trained on unfiltered +data (Before Filter), and the output from the model trained on EditReward-curated data (After +Filter). These examples cover a range of editing types, including background replacement, object +insertion/removal, style and material changes, and human-centric edits. +28 + +===== PAGE 29 ===== +Published as a conference paper at ICLR 2026 +(a) Example List 1 of high-quality image editing samples. +(b) Example List 2 of high-quality image editing samples. +Figure 9: Examples of high-quality image editing samples that were retained after filtering based on +EditReward scores. +Qualitatively, the “After Filter” results exhibit more accurate instruction following, cleaner local +modifications, fewer visual artifacts, and more coherent global integration. In contrast, models +trained on unfiltered data tend to produce incomplete edits, spatial inconsistencies, or hallucinated +structures. These comparisons highlight the alignment benefits of EditReward-guided data selection +and validate its effectiveness in improving generation quality. +A.13 FAILURE MODE ANALYSIS OF EDITREWARD +The following analysis moves beyond generic VLM weaknesses and focuses on specific, action- +able biases exhibited by EDITREWARD when its judgment significantly deviates from the human +consensus. We found two persistent failure modes: +1. Visual Quality Bias (Color/Brightness): We observed that EDITREWARD occasionally ex- +hibits a perceptual bias toward vividness, likely inherited from its VLM pre-training. The +model tends to conflate high overall visual quality with excessive brightness or high color sat- +uration, resulting in inflated scores for edits that human judges deem over-processed or visually +jarring. +29 + +===== PAGE 30 ===== +Published as a conference paper at ICLR 2026 +(a) Example List 1 of low-quality image editing samples. +(b) Example List 2 of low-quality image editing samples. +Figure 10: Examples of low-quality image editing samples that were filtered out based on EditRe- +ward scores. +2. Global Consistency Failure (Background Over-Editing): Despite our explicit training on the +”Exclusivity” criterion, the model sometimes gives high scores to edits where the background +or unedited regions were substantially and unnecessarily altered. This suggests a specific +weakness in balancing local edit success against the preservation mandate. +30 + +===== PAGE 31 ===== +Published as a conference paper at ICLR 2026 +(a) Example 1: Comparison of edits produced before and after EditReward filtering. +(b) Example 2: Another comparison of Step1X-Edit results trained with and without EditReward filtering. +Figure 11: Qualitative comparison of Step1X-Edit models trained on unfiltered data (Before Filter) +and EditReward-curated data (After Filter). Each example shows the source image, the output before +filtering, and the output after filtering. Results demonstrate that training on EditReward-filtered data +produces more accurate, stable, and faithful edits. +31 + +===== PAGE 32 ===== +Published as a conference paper at ICLR 2026 +(a) Failure Mode 1: Brightness Bias. This image received a high score from EDITREWARD (e.g., Score 3.8/4.0) +due to its vivid colors, even though human experts rated it lower (e.g., Score 2.0) for being over-saturated and +visually implausible. This illustrates the model’s tendency to reward excessive brightness. +(b) Failure Mode Examplex 2: Exclusivity/Background Failure. The edit (e.g., ”Change the object”) was +successful locally, yet the model gave it a high reward (e.g., Score 3.5/4.0) despite the background being +severely altered and distorted—a clear violation of the ”no unprompted changes” rule. +Figure 12: Qualitative Taxonomy of EDITREWARD’s Reward Biases. These examples illustrate +specific cases where EDITREWARD’s high scores deviate from human consensus, demonstrating +the model’s inherited bias toward high color vividness and its difficulty in penalizing subtle global +inconsistencies. +32 diff --git a/benchmarks/edit/pdf/_extracted/five.meta.txt b/benchmarks/edit/pdf/_extracted/five.meta.txt new file mode 100644 index 0000000000000000000000000000000000000000..df16c52965d1da04fd797cfcc19d2ebef19deb41 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/five.meta.txt @@ -0,0 +1,3 @@ +title=FiVE: A Fine-grained Video Editing Benchmark for Evaluating Emerging Diffusion and Rectified Flow Models +author=Minghan Li; Chenxi Xie; Yichen Wu; Lei Zhang; Mengyu Wang +pages=26 diff --git a/benchmarks/edit/pdf/_extracted/five.txt b/benchmarks/edit/pdf/_extracted/five.txt new file mode 100644 index 0000000000000000000000000000000000000000..76b7b9597bf12ebdb5617606b0d0292c50dfc790 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/five.txt @@ -0,0 +1,1992 @@ +FILE: FiVE - A Fine-grained Video Editing Benchmark for Evaluating Emerging Diffusion and Rectified Flow Models.pdf +PAGES: 26 + + +===== PAGE 1 ===== +arXiv:2503.13684v2 [cs.CV] 21 Jul 2025 +FiVE : A Fine-grained Video Editing Benchmark for Evaluating +Emerging Diffusion and Rectified Flow Models +Minghan Li1,2* , Chenxi Xie3∗, Yichen Wu4,5, Lei Zhang3 and Mengyu Wang1,2,6† +1Harvard AI and Robotics Lab, Harvard University, 2Broad Institute, 3Hong Kong Polytechnic University +4School of Engineering and Applied Sciences, Harvard University, 5City University of Hong Kong +6Kempner Institute for the Study of Natural and Artificial Intelligence, Harvard University +mili4@meei.harvard.edu, chenxi.xie@connect.polyu.hk, yichen@seas.harvard.edu +cslzhang@comp.polyu.edu.hk, mengyu wang@meei.harvard.edu +FiVE-Dataset Wan-Edit Results and FiVE-Evaluation +Object (w/o non-rigid deform): A rhinoceros … Material: A stone elephant … +Source Video +Caption: An elephantis walking across a rocky enclosure in a zoo… +Prompt1: A rhinoceros is walking across… +Instruct1: Change the elephant to rhinoceros +Prompt2: A jeep is moving across … +Instruct2: Change the elephant to jeep +Prompt3: A blue elephant is walking … +Instruct3: Make the elephant blue. +Prompt4: A stone elephant is walking … +Instruct4: Make the elephant stone. +Prompt5: An elephant wearing a hat … +Instruct5: Add a hat to the elephant. +Prompt6: No elephant in a zoo … +Instruct6: Remove the elephant +Masks: FiVE-Bench +FiVE-Acc:[1,1,1,1]à 1 +Human: +Object (w non-rigid deform): A jeep … CLIP Score:0.57 +FiVE-Acc:[0,0,0,0] à 0 +Human: +Add: An elephant wearing a hat … +CLIP Score:0.89 +FiVE-Acc:[1,1,1,1]à 1 +Human: +Color: A blue elephant … CLIP Score:0.72 +FiVE-Acc:[1,1,1,1] à 1 +Remove: An elephant … +Human: +CLIP Score:0.84 +FiVE-Acc:[1,0,1,0]à 0.5 +Human: +CLIP Score:0.90 +FiVE-Acc:[0,0,0,0] à 0 +Human: +CLIP Score:0.46 +Figure 1. The introduced FiVE Benchmark and corresponding editing results of the proposed Wan-Edit method. +Abstract +Numerous text-to-video (T2V) editing methods have +emerged recently, but the lack of a standardized benchmark +for fair evaluation has led to inconsistent claims and an in- +ability to assess model sensitivity to hyperparameters. Fine- +grained video editing is crucial for enabling precise, object- +level modifications while maintaining context and temporal +consistency. To address this, we introduce FiVE, a Fine- +grained Video Editing Benchmark for evaluating emerg- +ing diffusion and rectified flow models. Our benchmark in- +cludes 74 real-world videos and 26 generated videos, fea- +turing 6 fine-grained editing types, 420 object-level edit- +ing prompt pairs, and their corresponding masks. Addi- +*Equal contribution, †Corresponding author. +tionally, we adapt the latest rectified flow (RF) T2V gen- +eration models—Pyramid-Flow [15] and Wan2.1 [43]—by +introducing FlowEdit [19], resulting in training-free and +inversion-free video editing models Pyramid-Edit and Wan- +Edit. We evaluate five diffusion-based and two RF-based +editing methods on our FiVE benchmark using 15 met- +rics, covering background preservation, text-video similar- +ity, temporal consistency, video quality, and runtime. To fur- +ther enhance object-level evaluation, we introduce FiVE- +Acc, a novel metric leveraging Vision-Language Models +(VLMs) to assess the success of fine-grained video edit- +ing. Experimental results demonstrate that RF-based edit- +ing significantly outperforms diffusion-based methods, with +Wan-Edit achieving the best overall performance and ex- +hibiting the least sensitivity to hyperparameters. More +video demo available on the anonymous website: https: +1 + +===== PAGE 2 ===== +//sites.google.com/view/five-benchmark +1. Introduction +Recent advancements in text-to-image (T2I) and text-to- +video (T2V) generation [1, 15, 25, 27, 32, 37, 43] have +led to the emergence of numerous image and video editing +methods [4, 9, 10, 49], enabling users to create and modify +video content with unprecedented flexibility. These meth- +ods leverage powerful generative models, such as diffusion +models [6, 11, 12, 36] and Rectified Flow (RF) [8, 24] mod- +els, to synthesize and edit videos based on textual prompts. +However, despite significant progress in these fields, the +lack of a standardized benchmark for fair and comprehen- +sive evaluation has still become a major bottleneck hin- +dering further development. Currently, the video editing +field has only one publicly available dataset, TGVE [50] +/TGVE+ [35] (see Fig.(1)), which includes 76 videos and 6 +editing types, such as style transfer, background replace- +ment, single-object and multi-object transformations, as +well as object addition and removal. While TGVE+ aims +to cover as many editing types as possible, its evaluation +within each editing type is not comprehensive, particularly +in supporting fine-grained video editing. Fine-grained video +editing requires precise object-level modifications while +preserving the overall context and temporal consistency of +the video, posing higher demands on model performance. +Due to the lack of a standardized benchmark and uni- +fied evaluation framework for fine-grained video editing, +existing methods [9, 22, 29, 53] often rely on self-collected +small-scale video datasets to validate their effectiveness. +This approach not only makes it difficult to objectively com- +pare the performance of different methods but also fails to +comprehensively assess model robustness to hyperparam- +eters or determine their suitability for real-world applica- +tions. Therefore, building a comprehensive and challenging +benchmark for fine-grained video editing has become an ur- +gent need to advance the field. +To address these challenges, we introduce FiVE (Fine- +grained Video Editing Benchmark), a comprehensive +benchmark designed to evaluate emerging diffusion and +rectified flow models for fine-grained video editing. FiVE +includes 74 real-world videos and 26 generated videos, cov- +ering a diverse range of scenes and editing scenarios. It +features 6 fine-grained editing types, 420 object-level edit- +ing prompt pairs, and their corresponding masks, provid- +ing a rich and challenging testbed for evaluating video edit- +ing methods. Additionally, we propose FiVE-Acc, a novel +evaluation metric that leverages Vision-Language Models +(VLMs) to assess the successful accuracy of fine-grained +object-level editing. Specifically, FiVE-Acc complements +traditional metrics by providing a more nuanced under- +standing of editing quality, particularly in terms of semantic +alignment, contextual preservation and motion awareness. +Recently, many image editing methods [5, 19, 33, 44] +based on the latest rectified flow T2I generation model +Flux [20] have achieved state-of-the-art editing results and +fidelity, such as RF-Inversion [33], RF-Solver [44], and +FlowEdit [19]. However, to the best of our knowledge, +there are no video editing methods based on RF T2V gen- +eration models, primarily due to the relatively slow devel- +opment of T2V generation models. Fortunately, the re- +cent release of two state-of-the-art RF-based T2V gener- +ation models—Pyramid-Flow [15] and Wan2.1 [43]—has +opened new possibilities for RF video editing. +Building on the latest advancements, we adapt Pyramid- +Flow [15] and Wan2.1 [43] by introducing FlowEdit [19]. +This adaptation facilitates training-free and inversion-free +video editing models, Pyramid-Edit and Wan-Edit, which +leverage the strong temporal consistency inherent in video +generation models without requiring additional attention +mechanisms. Specifically, Pyramid-Flow employs a multi- +resolution and temporally autoregressive model architec- +ture across time steps. To adapt to this unique design, +we modified FlowEdit to support multi-resolution process- +ing, enabling seamless integration with the Pyramid-Flow +framework, leading to Pyramid-Edit. On the other hand, +Wan2.1 utilizes the DiT architecture, which unfolds tem- +poral frames into sequences and processes them via self- +attention. Since its design is fundamentally similar to im- +age generation models, Wan2.1 can directly adopt FlowEdit +without any additional modifications, giving rise to Wan- +Edit. +To show the effectiveness of the proposed two RF-based +editing methods, we compare them with five diffusion- +based editing methods on the built FiVE benchmark, evalu- +ating them across 14 metrics, including background preser- +vation, edited text-video similarity, temporal consistency, +and generated video quality. Our experiments demon- +strate that RF-based editing methods significantly outper- +form diffusion-based methods across multiple metrics. No- +tably, Wan-Edit achieves the best overall performance, ex- +hibiting superior editing quality and the least sensitivity to +hyperparameters. These findings highlight the potential of +RF-based models for fine-grained video editing and provide +valuable insights for future research in this area. +In summary, this work makes four key contributions: +• We introduce FiVE, a comprehensive benchmark for fine- +grained video editing, featuring diverse videos, editing +types, and evaluation metrics. +• We propose FiVE-Acc, a novel metric leveraging VLMs +to assess the success of fine-grained editing. +• We adapt RF-based T2V models Pyramid-Flow and +Wan2.1 using FlowEdit, resulting in efficient and effec- +tive video editing methods Pyramid-Edit and Wan-Edit. +• We evaluate seven video editing methods across 15 met- +2 + +===== PAGE 3 ===== +rics, showing that RF-based editing consistently outper- +forms diffusion-based approaches. +2. Related Work +2.1. Diffusion and RF Inversion +Diffusion inversion. Diffusion models (DMs) drive ad- +vances in inversion techniques for better control over gen- +erated samples. DDIM [36] accelerates sampling but strug- +gles with fine-grained reconstructions due to nonlinearities +and score estimation errors. To improve accuracy, fine- +tuning and optimization-based methods [7, 16, 26, 42, 48] +have been proposed. While these advancements signifi- +cantly enhance the fidelity and accuracy of DDIM inversion, +the associated computational costs and resource demands +remain substantial limiting factors. Although diffusion- +based methods have achieved outstanding performance, re- +cent studies [8, 15, 20, 33] suggest that Rectified Flow mod- +els (RFs) hold significant potential to surpass DMs in cer- +tain applications. Notably, the inversion and editing capa- +bilities of RF models have been explored in image edit- +ing [5, 19, 33, 44, 51], demonstrating their efficiency and +effectiveness. Building on these strengths, this work extend +their potential in video editing. +2.2. Video Editing +Video editing can generally be categorized into three +types based on their training: training-free methods, +one/few-shot finetuned methods, and massive data fine- +tuned methods. Training-free models [14, 18, 22, 29, +53], enable task execution without retraining. Token- +Flow [9] uses pre-trained models for efficient video syn- +thesis, while DMT [54] transfers motion via diffusion. +Other models like Pixel2Video [3], Render-A-Video [52], +and Text2Video-zero [17] enhance accessibility for real- +time video editing. One/few-shot fine-tuned models adapt +pre-trained models for video editing with minimal fine- +tuning. Methods like Tune-A-Video [49], MotionDirec- +tor [60], DreamVideo [46], and MotionEditor [39] achieve +strong results using limited annotated samples, balancing +customization and efficiency for task-specific editing. +Massive data fine-tuned models undergo extensive train- +ing on large datasets for high-quality, versatile video edit- +ing [14, 30, 38]. InstructVid2Vid [30] enables complex ed- +its via natural language instructions, while EffiVED [58] +refines broad datasets into high-quality subsets for efficient +editing. SF-V [59] introduces adversarial training for video +synthesis. Despite their precision and adaptability, these +methods are computationally expensive, limiting practical- +ity in resource-constrained settings. These methods focus +on learning video motion, which may compromise back- +ground preservation. Recently, VideoGrain [53] has em- +phasized multi-granularity video editing rather than fine- +grained edits, aiming to retain background details while +modifying target objects. This work aims to address this +issue and advance the field. +Recent unified architectures [14, 38, 55] have also in- +corporated video editing into their multi-functional frame- +works. VACE [14] enables users to perform video gen- +eration, editing, and personalization in an integrated man- +ner. Such architectures typically concatenate reference and +target tokens as input to the model, allowing for a unified +processing pipeline. +3. FiVE Benchmark and FiVE-Acc +In this section, we present the FiVE benchmark, which +includes the FiVE video dataset, six fine-grained editing +tasks, and the proposed VLM-based FiVE-Acc metric to +evaluate editing accuracy. +3.1. FiVE Benchmark +Videos in FiVE Benchmark. We meticulously curate 74 +real-world videos suitable for fine-grained editing from the +DAVIS [28] dataset. Consecutive frames are extracted at +every 8-frame interval, and the GPT-4o [13] is employed to +generate formatted captions for these videos. These cap- +tions encompass details pertaining to object category, ac- +tion, background, and camera movement. Additionally, dur- +ing the annotation process, we document instances of object +deformation (such as limb movements in humans or ani- +mals), which aids in differentiating the complexity of edit- +ing tasks during evaluation. To further enhance the diversity +of our benchmark, we generate 26 highly realistic synthetic +videos using the T2V model [43]. These synthetic videos +not only expand the range of video categories but also en- +able a comparative analysis of editing performance across +real and synthetic videos. More details on the selection of +text prompts for video generation are in the Appendix. +Six Fine-grained Video Editing Tasks. FiVE com- +prises six fine-grained video editing tasks, totaling 420 +high-quality editing prompt pairs. It primarily includes +four object-targeted editing tasks of increasing complex- +ity: color alteration, material modification, object substi- +tution without non-rigid deformation, and object substitu- +tion with non-rigid deformation. For each task, we use +GPT-4o [13] to generate four source-target prompt pairs +per video in the benchmark, resulting in 400 high-quality +editing pairs. To further enhance the diversity of editing +types within the benchmark, we select 10 videos each for +the add and remove tasks and design corresponding source- +target prompt pairs. Additionally, we explicitly provide +both object-related source words and edited words in the +source and edited text prompts, respectively, denoted as +‘src. obj. words’ and ‘edit obj. words’ in Table 1. To ac- +commodate different editing methods, we use GPT-4o [13] +to generate instruction prompts (‘Obj. Instr.’ in Table 1) for +3 + +===== PAGE 4 ===== +Table 1. Statistics of existing video editing datasets and benchmarks. +Dataset Usage Num. Num. Frames Num. Gen. Src. obj. Edit obj. Obj. Src. obj. Type of Edited Prompts +Images Videos Per Video Prompts Videos Words Words Instruct. Masks +VIVID-10M Train 672K 73.7K 30 10M ✗ ✗ ✗ ✓ ✓ object, add, remove +Se˜ norita-2M Train 0 388.9K 33∼64 2M ✗ ✗ ✗ ✓ ✗ style, object, multiple, color, add, remove, motion +TGVE Eval 0 76 32 304 ✗ ✗ ✗ ✗ ✗ style, object, bg, multiple +TGVE+ Eval 0 76 32 1417 ✗ ✗ ✗ ✗ ✗ style, object, bg, multiple, color, add, remove +VIVID-10M Eval 0 64 33∼64 852 ✗ ✗ ✗ ✓ ✓ object, add, remove +FiVE (Ours) Eval 0 100 35∼126 420 ✓ ✓ ✓ ✓ ✓ object (w&w/o non-rigid), color, material, add, remove +Source video +Target video +Yes/No questions +Src-Q: Is a black swan +drifting in the video? +Tgt-Q: Is a flamingo +drifting in the video? +VLM +(Qwen- +2.5-VL) +Src-A Tgt-A FiVE-YN-Acc +No Yes 1.0 +No No 0.0 +Yes Yes 0.0 +Yes No 0.0 +Video +Editing +Model +Source prompt +A black swan drifting ... +Multi -choice question +Q: What is the object +drifting in the video? +Options: +A) a black swan +B) a flamingo +VLM +(Qwen- +2.5-VL) +Answer FiVE-MC-Acc +A) +B) +0.0 +1.0 +Target prompt +A flamingo drifting… +a) Video Editing +b) FiVE accuracy evaluation +FiVE-∪-Acc & FiVE-∩-Acc +Figure 2. The VLM-based FiVE accuracy (FiVE-Acc) evaluation. +each source-target pair, ensuring compatibility with mod- +els like InstructPix2Pix [2]. For each video, we employ +SAM2 [21, 31] to generate masks of the edited regions, en- +abling the evaluation of background preservation metrics. +Additional details can be found in the Appendix. +3.2. FiVE-Acc Evaluation +To evaluate the accuracy of fine-grained video editing, we +propose FiVE accuracy evaluation, a framework assessing +how precisely video editing models modify the target ob- +ject. Fig. 2 presents the FiVE pipeline, comprising video +editing and accuracy evaluation. +Video editing. Given a source video, a video editing +model is prompted with a source prompt, describing the ini- +tial scene, and a target prompt, specifying the desired mod- +ification. The model generates a target video, where the +intended transformation is applied. +FiVE accuracy evaluation. To quantitatively evaluate +the fidelity of video editing, we employ a Vision-Language +Model (VLM) (e.g., Qwen-2.5-VL) to analyze the edited +video. The evaluation includes two types of questions: +• Yes/No Questions: The model is asked whether the +source and target objects are present in the target video. +Editing succeeds only if the model answers ‘No’ for the +source object and ‘Yes’ for the target, leading to the cal- +culation of FiVE-YN-Acc. The source object question en- +sures the model both removes the source and adds the tar- +get, refining accuracy evaluation. +• Multi-choice Question: It evaluates whether the VLM +recognizes the target (e.g., flamingo in Fig. 2) or source +object (e.g., black swan in Fig. 2) in the edited video. The +model selects between the two objects to compute FiVE- +MC-Acc, measuring its recognition accuracy. +Based on the two obtained accuracies, we further calcu- +late the union and intersection accuracies to derive FiVE- +∪-Acc and FiVE-∩-Acc. These offer a more detailed eval- +uation: the former reflects the model’s overall editing suc- +cess accuracy, while the latter highlights the model’s high- +quality editing success accuracy. In summary, FiVE-Acc +combines the accuracies of four components, using the +VLM’s recognition ability to evaluate the alignment be- +tween the edited object and its real data distribution. To the +best of our knowledge, we are the first to introduce accuracy +evaluation in fine-grained video editing. +4. Methods +In this section, we first provide a brief review of recti- +fied flow (RF) and the RF-based image editing method, +FlowEdit. We then introduce two RF-based video editing +methods, PyramidEdit and WanEdit. +4.1. Preliminary +Rectified Flow (RF) Models [23, 24] . Let q0 denote the +source distribution (i.e., standard Gaussian N(0,I)), p0 re- +fer to the target distribution (i.e., the distribution over im- +ages), and vt(·) is the time-varying vector field. RF mod- +els [23, 24] aim to transform q0 progressively into p0 by +4 + +===== PAGE 5 ===== +(a) Pyramid-Edit (b) Wan-Edit +Figure 3. Two RF-based inversion-free video editing models: Pyramid-Edit and Wan-Edit. Pyramid-Edit is a multi-resolution temporal +autoregressive architecture, while Wan-Edit (DiT architecture) treats temporal frames as a sequence and processing them simultaneously. +solving the following ordinary differential equation (ODE): +dXt = vt(Xt)dt, t∈[0,1]. (1) +Here, the vector field vt(Xt) = f(Xt,c,1−t; φ), where +f(·) is a neural network parameterized by φ and c is the +guided text. Given the ODE in Eq. (1), we start with +X0 ∼ q0 from the source distribution and integrate over +t : 0 →1 to reach the endpoint X1 ∼p0, which is sam- +pled from the target distribution. the forward process of +RF assumes the linear path between the two states: Xt = +(1−t)X0 +tX1, then we can derive the vector field of vt(·): +ut(Xt) = X1−X0. Then, vt(Xt) is used to approximate +the network f(Xt,c,t; φ) by minimizing the loss function +Lφ = Et∼U[0,1],Yt [∥vt(Xt)−f(Xt,c,t; φ)∥2 +2].RF ensures +that their sampling paths are relatively straight, enabling the +use of a small number of discretization steps. +RF-based Image Editing FlowEdit [19]. Image edit- +ing involves taking a source image Xsrc +1 and a source text +prompt csrc, and allowing the user to provide a target text +prompt ctgt for targeted fine-grained editing to ultimately +yield the edited image Xtgt +1 . For example, the source text +prompt might be ‘A black swan is swimming,’ while the +target text prompt could be ‘A flamingo is swimming.’ To +simplify notation, we denote the vector fields correspond- +ing to the source and target text prompt as vt(Xsrc +t ) and +vt(Xtgt +t ), respectively. Their sampling process in RF fol- +lows: dXsrc +t = vt(Xsrc +t )dt, dXtgt +t = vt(Xtgt +t )dt. +FlowEdit operates inversion-free, mapping source +modes to the nearest target modes, as shown in the right +of Fig. 3. It assumes target images follow straight trajecto- +ries, allowing latent interpolation between image and noise: +Xsrc +t = (1−t)X0 +tXsrc +1 , where X0 is randomly sampled +from Gaussian noise. Thus, the nearest target mode Xedit +t in +timestep tis derived by subtracting the source image from +the difference between the source and target latents: +Xedit +t = Xsrc +1 + Xtgt +t−Xsrc +t. (2) +Note that Xedit +t remains within the clean image latent space +without incorporating any noise, following: Xedit +t = Xsrc +1 , +if t →0; Xedit +t = Xtgt +t , if t →1. A more straightfor- +ward explanation is: Xedit +t evolves within the target distri- +bution, continuously transitioning through the clean latent +space across all timesteps, (i.e. Xedit +t gradually transforms +from a black swan to a flamingo as the timestep progresses +in Fig. 3). Therefore, we can obtain Xtgt +t simply by solv- +ing for Xedit +t , t →1. By substituting Eq. (2), we derive: +Xtgt +t = Xedit +t +Xsrc +t−Xsrc +1 . Since Xedit +t is unknown at the +current timestep, we approximate it using Xedit +t−1 , yielding: +Xtgt +t ≈ˆ +Xtgt +t = Xedit +t−1 +Xsrc +t−Xsrc +1. (3) +Finally, the editing process can be formulated as: +Xedit +t = Xedit +t−1 + dXtgt +t−dXsrc +t +≈Xedit +ˆ +t−1 + E[vt( +Xtgt +t )−vt(Xsrc +t )|Xsrc +1 ]dt +≜ Xedit +t−1 + E[v∆ +ˆ +t ( +Xtgt +t ,Xsrc +t )|Xsrc +1 ]dt (4) +To obtain the edited image, Xedit +t is iteratively updated +from ϵto 1, where ϵ ∈[0,1) represents skipped timesteps. +5 + +===== PAGE 6 ===== +The edited latent Xedit +ϵ is initialized as Xsrc +1 . The source +latent Xsrc +t is obtained via interpolation between random +noise and the source image, while Xtgt +t is computed using +Eq. (3). Finally, Xedit +t is updated following Eq. (4). +4.2. RF-based Video Editing +This section introduces Pyramid-Edit, followed by a discus- +sion of Wan-Edit, highlighting key features and differences. +4.2.1. Pyramid-Edit +Pyramid-Flow [15] employs a multi-resolution scheme +across timesteps and a temporally autoregressive architec- +ture to effectively handle the spatial-temporal complex- +ity in video generative modeling. It decomposes the flow +into segments over K timestep windows within the in- +terval [0,1]. Each window interpolates between successive +resolutions, reducing redundant computations in the ear- +lier steps. For example, in the sampling process, within +the k-th window [sk,ek], it defines the rescaled timestep +tk =(t−sk )/(ek−sk ) and the corresponding flow is +Xtk = (1−tk)¯ +xsk + tk +¯ +xek , +¯ +xsk = (1−sk)X0 + skUp(Down(X1,2k+1)), +¯ +xek = (1−ek)X0 + ekDown(X1,2k), +(5) +where Down(· +,·) and Up(·) represent the down-sampling +and up-sampling, respectively. Meanwhile, the vector field +in the k-th window is defined as vtk (Xtk ) = ¯ +¯ +xek− +xsk . To +maintain continuity in the probability path within the pyra- +mid structure, corrective noise is added at transition points +between stages, as follows: +Xsk−1 += +sk−1 +ek +Up(Xek )+αn +′,s.t.nk−1 ∼N(0,Σ′), (6) +where the rescaling coefficient sk−1/ek aligns the means of +these distributions, the corrective noise n′ +k−1 weighted by α +aligns their covariance matrices, and the covariance matrix +Σ′is related to the upsampling function. +Pyramid-Edit. The autoregressive architecture allows +Pyramid-Edit to process frames sequentially, where pre- +vious frames serve as conditional information. However, +the multi-resolution scheme across timesteps hinders direct +use of FlowEdit. To address this, Pyramid-Edit integrates +FlowEdit (Eq. (4)) into each window as follows: +Xedit +tk += Xedit +tk−1 + E[v∆ +ˆ +tk ( +Xtgt +tk ,Xsrc +tk )|¯ +xsrc +ek ]dt, (7) +whereˆ +Xtgt += Xedit +tk +tk−1 +Xsrc +¯ +− +xsrc +tk +ek , and the target distri- +bution is the end point of each window¯ +xsrc +ek , instead of the +clean latent Xsrc +1 in FlowEdit. +The workflow proceeds as illustrated in Fig. 3 (a) and +is structured as follows: starting from noise and the lowest- +resolution latent, Xedit +t0 is initialized as¯ +xsrc +e0 , Eq. (7) is used +to reconstruct and edit low-frequency information. At the +end of the first stage, the reconstructed latent and the edited +latent are upsampled to a higher resolution and passed +through corrective noise as described in Eq. (6) to obtain the +starting point for the next stage, Xedit +s1 and Xsrc +s1 . However, +FlowEdit operates within the target distribution, meaning +we require the end point for this stage, Xedit +e1 and Xsrc +e1 . The +latter, Xsrc +e1 , can be obtained through interpolation between +X0 and Xsrc +1 , i.e. (Xsrc +¯ +src += +x +e1 +e1 ). To estimate the edited +endpoint Xedit +e1 , we first compute the difference between the +start and end points of the source prompt in this stage. This +difference is then added to the edited start latent variable, +providing an estimate of Xedit +e1 : +¯ +xsrc +e1 +Xedit +e1 += Xsrc +s1 + (¯ +xsrc +e1 += Xedit +s1 + (¯ +xsrc +e1 +−Xsrc +s1 ), (8) +−Xsrc +s1 ). (9) +This step ensures that the edited and reconstructed latents +remain aligned with the source image distribution while +incorporating the desired modifications, preserving the in- +tegrity of the generated features. This is key to the success +of FlowEdit under the pyramid structure. +Another key point is that, starting from the second +frame, Pyramid-Edit respectively incorporates the source +and edited historical information from previous frames +(e.g., the (i−1)-th frame) as a conditioning factor within its +noise-estimation network. This allows the model to lever- +age temporal dependencies from both the source and edited +frames, enhancing the temporal consistency. The source +and edited sampling processes can be simplified as follows: +...→Down(Xsrc,i− 2 +1 ,2k+1 ) →Down(Xsrc,i− 1 +1 ,2k ) +Source History condition +...→Down(Xedit,i− 2 +1 ,2k+1 ) →Down(Xedit,i− 1 +1 ,2k ) +Edited History condition +→Xsrc,i +tk , +→Xedit,i +tk. +For generating subsequent frames, simply introduce the su- +perscripts ias indices for the historical latents in Eq. (7). +4.2.2. Wan-Edit +Wan2.1 [43] is a state-of-the-art video generative model +built on the mainstream Video Diffusion DiT frame- +work [27], achieving significant advancements through in- +novations such as a novel 3D VAE, scalable training strate- +gies, large-scale data curation. These contributions en- +able Wan2.1 to generate high-quality, temporally consistent +videos with improved efficiency and scalability. However, +since the technical report has not yet been publicly released, +we focus on adapting its core framework for video edit- +ing tasks, leveraging its strengths in temporal modeling and +high-fidelity generation. +Compared to Pyramid-Flow, Wan2.1 adopts a much sim- +pler architecture. It consists of 30 WanAttentionBlock +layers, each integrating vision self-attention, text-to-vision +cross-attention, and feed-forward mechanisms. Multi- +frame video inputs are encoded into a 3D vision latent by +the 3D VAE encoder. These 3D vision latents are then +6 + +===== PAGE 7 ===== +Table 2. Comparison of diffusion- and flow-based video editing methods on our proposed FiVE benchmark.∗and †denote methods that +require optimization and depth/segmentation maps, respectively. +Methods Structure Time (s) +Background Preservation Text Alignment IQA Motion Dist.×103 ↓PSNR↑LPIPS×103 ↓MSE×104 ↓SSIM×102 ↑CLIPS.↑CLIPS.edit ↑NIQE↓Fidelity S.×102 ↑Per Frame↓ +Source Videos 0.00 ∞ 0.00 0.00 100.00 24.59 19.87 6.33 93.76 - +DMs +TokenFlow [9] DMT∗[54] VidToMe [22] AnyV2V [18] VideoGrain†[53] 35.62 85.95 22.37 71.36 12.40 19.06 263.61 138.65 72.51 14.71 404.60 372.78 51.64 21.15 263.91 88.75 70.69 15.90 348.59 342.97 50.77 27.05 185.21 25.10 79.13 26.46 21.15 26.66 21.44 26.84 21.05 24.89 19.72 25.69 20.31 4.01 5.24 4.68 5.04 4.08 89.00 82.30 90.06 60.36 88.57 8.04 +25.98 +3.25 +6.11 +27.12 +RFs +(Ours) +Pyramid-Edit Wan-Edit 28.65 12.53 20.84 276.59 95.63 71.72 25.57 94.61 41.84 82.55 26.82 20.20 26.39 21.23 5.48 6.54 80.59 89.43 1.44 +3.07 +Table 3. Comparison of diffusion- and flow-based video editing +methods on the FiVE benchmark using FiVE-Acc metrics. +Method FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +TokenFlow [9] DMT∗[54] VidToMe [22] AnyV2V [18] VideoGrain†[53] 19.36 35.51 36.68 18.18 34.78 62.06 62.98 33.86 20.03 33.50 36.20 17.34 30.62 45.42 48.96 27.09 30.50 43.97 44.30 30.17 27.43 +48.42 +26.77 +38.02 +37.23 +Pyramid-Edit Wan-Edit 33.67 54.01 56.36 31.31 41.41 52.53 55.72 38.22 43.84 +46.97 +flattened into a sequence and fed into the self-attention +layers to encode temporal consistency. Finally, the se- +quence interacts with text tokens through cross-attention +to achieve text-guided video generation. The self-attention +mechanism captures intra-frame dependencies, while the +cross-attention module integrates text tokens to enable text- +guided video generation. This joint modeling of visual +and textual information ensures high-quality, semantically +aligned video outputs. +Wan-Edit. This elegant and streamlined architecture +closely resembles that of image generation models, en- +abling FlowEdit to be directly integrated without significant +modifications. For multi-frame inputs from i1 to i2, denote +as Xsrc +1 = [Xsrc,i1 +1 ,···,Xsrc,i2 +1 ], the editing process, as +shown in Fig. 3 (b), handles all frames simultaneously by +extending FlowEdit to the entire sequence, ensuring tempo- +ral consistency and efficient processing. The editing process +follows the same formulation as Eq. (4) and is defined as: +Xedit +t = Xedit +t−1 +E[v∆ +ˆ +t ( +Xtgt +t ,Xsrc +t )|Xsrc +1 ]dt, (10) +whereˆ +Xtgt +t ≈Xedit +t−1 +Xsrc +t−Xsrc +1 . This allows for smooth +and coherent edits across all frames, preserving the tempo- +ral dynamics of the video. +5. Experiments +5.1. Experimental Settings +Baseline methods. We compare our two RF-based editing +methods with five diffusion-based models: TokenFlow [9], +DMT [54], VidToMe [22], AnyV2V [18], and VideoGrain +[53]. Diffusion-based models require inversion before edit- +ing, while our RF-based methods are inversion-free. DMT +relies on feature optimization of spatial marginal mean +(SMM) during editing, and VideoGrain uses depth maps +and object masks to assist editing. +Evaluation metrics. We conduct a fair evaluation of +all models on our FiVE benchmark using 15 metrics. The +ten commonly used metrics in Table 2 cover six aspects: +structure distance [40], background preservation (PSNR, +LPIPS [56], MSE, and SSIM [45] outside the editing +mask), edit prompt-image consistency (CLIPSIM [47] for +the full image and masked regions), image quality assess- +ment (NIQE [34]), temporal consistency (motion fidelity +score [54]) and running time. Additionally, our proposed +FiVE-Acc introduces five metrics in Table. 3 to evaluate +the accuracy of successful object editing. +Implementation details. Pyramid-Edit utilizes the 384P +Pyramid-Flow model, while Wan-Edit is based on the +Wan2.1 1.3B model. Pyramid-Edit processes the first frame +with 20 timesteps and subsequent frames with 10 timesteps +per stage, across a total of three stages, whereas Wan-Edit +operates with 50 timesteps throughout. For video editing, +we follow the FlowEdit setting, where approximately the +initial one-third of timesteps are skipped to achieve better +results. Specifically, Pyramid-Edit skips all timesteps in the +first stage, while Wan-Edit skips the first 15 timesteps. The +source and target classifier-free guidance (CFG) are set to +7/5 (first/subsequent frames) and 10 in Pyramid-Edit, and 5 +and 12 in Wan-Edit. Due to space constraints, the imple- +mentation details of the comparison methods are provided +in the Supplementary Materials. Considering the differ- +ences in the number of video frames each method can pro- +cess, all DM-based methods except AnyV2V handle only +7 + +===== PAGE 8 ===== +the first 40 frames, while AnyV2V processes only the first +32 frames. RF-based methods process the first 41 frames +due to the requirements of Video/3D VAE. All experiments +were conducted on a single H100 GPU. +Please refer to the Supplementary Materials for details +on baseline models, evaluation metrics, and implementation +of the comparison methods. +5.2. Quantitative Comparison +Tables 2 and 3 present the comparison results averaged +across six editing types, covering both commonly used met- +rics and our proposed FiVE-Acc metrics. The results for +each individual editing type are provided in the Supple- +mentary Materials. To improve evaluation efficiency, all +metrics except Image Quality Assessment (IQA) and Mo- +tion Fidelity Score are calculated by sampling one frame +every eight frames. The final score is obtained by averaging +the per-frame scores. This sampling method significantly +reduces computational cost while maintaining a compre- +hensive evaluation to a certain extent. +5.2.1. Comparison on Common Metrics +In terms of background preservation, VideoGrain and Wan- +Edit rank as the top two, exhibiting comparable perfor- +mance across all metrics. Specifically, VideoGrain achieves +the best results in Structure Distance (12.40) and two Back- +ground Preservation metrics (PSNR: 27.05, MSE: 25.10). +Meanwhile, Wan-Edit, our proposed method, outperforms +in the other two Background Preservation metrics (LPIPS: +94.61, SSIM: 82.55). For text-video similarity, VidToMe +and DMT achieve the best results for both global (CLIPS.: +26.84) and edited-region text-video similarity (CLIPS.edit: +21.44). Our proposed Pyramid-Edit and Wan-Edit follow +closely, securing the second-best results with 26.82 and +21.23, respectively. For image quality assessment (IQA), +the top three methods are TokenFlow, VideoGrain, and Vid- +ToMe, all of which are based on Stable Diffusion (SD) for +image generation. This can be attributed to the inherent ca- +pability of SD models to generate high-quality images. +For temporal consistency, VidToMe and TokenFlow rank +first and third in Motion Fidelity Score by propagating sim- +ilarity between temporal tokens. Our proposed method, +Wan-Edit, also maintains strong temporal consistency, se- +curing second place. Finally, RF-based methods are signif- +icantly faster than diffusion-based models, with Pyramid- +Edit and Wan-Edit achieving 1.44s and 3.07s per frame, +compared to 25.98s and 27.12s for DMT and VideoGrain. +This is mainly due to RF-based approaches leveraging +Video/3D VAE, which enables higher temporal compres- +sion in the latent space, reducing the number of processed +frames. For instance, Pyramid-Edit and Wan-Edit adopt +temporal downsampling rates of 8× and 4×, respectively. +Moreover, unlike diffusion-based methods, the inversion- +free Pyramid-Edit and Wan-Edit bypass the inversion pro- +cess, halving the runtime. Additionally, they require no ex- +tra conditions, such as depth maps or masks, further accel- +erating the editing process. +Overall, diffusion-based VideoGrain and our RF-based +Wan-Edit perform similarly. However, VideoGrain relies on +depth maps and object masks for editing and is significantly +slower (27.12s per frame), whereas the inversion-free Wan- +Edit achieves the highest efficiency with the lowest time +(3.07s per frame). These findings clarify each method’s +strengths and trade-offs, guiding selection for specific ap- +plications and advancing video editing. +5.2.2. Comparison on FiVE-Acc Metrics +Notably, the text-video similarity scores in Table 2 for all +methods show only minor variations, with global CLIP +scores (CLIPS.) clustering around 26 and edited-region +CLIP scores (CLIPS.edit) around 21. This narrow gap sug- +gests that CLIP score may lack the sensitivity needed to +comprehensively evaluate fine-grained text-video alignment +in editing tasks. To overcome this limitation, our pro- +posed VLM-based FiVE-Acc metrics, presented in Table 3, +leverage vision-language models to better capture seman- +tic changes in target objects, revealing key insights and en- +abling a more fine-grained evaluation. +Table 3 presents the accuracy results averaged across six +editing types. Overall, the FiVE-Acc metrics yield con- +clusions similar to the CLIP score, indicating that DMT, +Wan-Edit, and Pyramid-Edit outperform other methods. +However, the variance among FiVE-Acc metrics is no- +tably higher. For instance, while TokenFlow and VidToMe +achieve scores close to DMT in CLIP score evaluation, their +FiVE-Acc accuracy is only about half of DMT’s—27.43% +and 26.77% compared to 48.42%. This discrepancy arises +because both TokenFlow and VidToMe rely on feature clus- +tering to propagate similar tokens across frames, making +them ineffective for non-rigid transformations. For exam- +ple, in Fig. 6, when editing a woman into a lion, these meth- +ods retain the rigid structure of human being while altering +only attributes like texture and color to resemble a lion. +A detailed comparison and analysis of the FiVE-Acc +metrics is provided. For Yes/No questions (FiVE-YN), our +Wan-Edit and the diffusion-based DMT with optimization +rank the highest, achieving 41.41% and 34.78%, respec- +tively. In multi-choice questions (FiVE-MC), DMT and our +Pyramid-Edit perform best, with accuracy rates of 62.06% +and 54.01%, respectively. FiVE-∪represents cases where +at least one of FiVE-YN or FiVE-MC holds true. The +highest accuracy is again achieved by DMT (62.98%) and +our Pyramid-Edit (56.36%), indicating consistency between +FiVE-YN and FiVE-MC evaluations. Conversely, FiVE-∩ +requires both FiVE-YN and FiVE-MC to hold simultane- +ously. Here, our Wan-Edit and DMT obtain the highest +accuracy, reaching 38.22% and 33.86%, respectively. The +strong performance of Wan-Edit in FiVE-∩suggests that +8 + +===== PAGE 9 ===== +Top1 only (%) +Top1 & Top2 (%) +Figure 4. Human evaluation example using Netlify. Left: An example illustrating human verification of FiVE-Acc metric, conducted on +WanEdit results. Central: A human preference study where annotators select the top-2 preferred results. Right: preference statistics. +First frame +Input: Bear Edit1: Panda Edit2: Dinosaur +Table 4. Human vs. VLM model evaluation on FiVE-Acc metrics. +Evaluator FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +Qwen-2.5-VL Human 41.41 52.53 55.72 38.22 46.97 +44.37 50.31 51.98 42.70 47.34 +Mask +Edit3: Purple bear Edit4: Bronze bear Edit5: Bear with a hat +Figure 5. Human validation of mask quality. +it excels in specific target edits while maintaining minimal +deviation from real-world object distributions. Finally, for +the overall FiVE-Acc metric, which averages the four afore- +mentioned metrics, DMT and Wan-Edit achieve the top two +results, with accuracy rates of 48.42% and 46.97%, respec- +tively. However, DMT is an optimization-based method that +requires per-prompt optimization for each video, whereas +Wan-Edit operates without any additional requirements. +Overall, our proposed VLM-based FiVE-Acc evaluation +is essential for assessing semantic fidelity, especially in +fine-grained editing. It can effectively capture subtle se- +mantic changes in target objects that traditional metrics like +CLIP score may overlook. +5.2.3. Comparison on All Metrics +Overall, as shown in Tables 2 and 3, RF-based video edit- +ing methods achieve comparable or superior background +preservation, text-video similarity, editing accuracy, and +motion consistency compared to diffusion-based methods, +while being 10–15 times faster than diffusion-based models, +such as VideoGrain. In terms of IQA metrics, since fine- +grained video editing focuses on modifying only the tar- +get object while preserving the background, our RF-based +methods, Pyramid-Edit and Wan-Edit, maintain IQA scores +nearly identical to those of the source video, rather than arti- +ficially enhancing the edited frames’ quality as seen in other +methods. This suggests that our approach ensures minimal +distortion to the original video while achieving precise and +semantically aligned edits. +Moreover, our results indicate that diffusion-based meth- +ods often require additional guidance, such as depth maps +or masks, to ensure accurate editing, whereas our RF-based +methods, particularly Pyramid-Edit and Wan-Edit, operate +efficiently without such dependencies. The efficiency of +RF-based approaches is further attributed to the inversion- +free pipeline and Video/3D VAE, which enable higher tem- +poral compression in the latent space, significantly reducing +computational costs while maintaining high-quality edits. +5.3. Human Validation +To ensure the reliability and perceptual alignment of our +evaluation protocol, we conduct comprehensive human val- +idation on the proposed FiVE-Acc metric, the compared +editing methods, and the quality of segmentation masks. +Human validation of FiVE-Acc metrics. In Fig. 4 +(left), we conducted a human study on 16 randomly sam- +pled videos with 64 prompts. Table 4 shows that hu- +man scores closely match Qwen-2.5-VL’s results (47.34 vs. +46.97), confirming FiVE-Acc aligns well with human per- +ception and offers consistent evaluation. +Human validation across compared methods. In Fig. +4 (central), we randomly sample 11 videos, resulting in 45 +source–target prompt pairs. All seven methods from main +Table 2 (methods a–g) are evaluated. To reduce bias, the +order of methods is randomized. Annotators are asked to +select their top-2 preferred results per prompt, and the ag- +gregated votes are used to compute preference statistics in +Fig. 4 (right). The results indicate that Method g (our Wan- +Edit) significantly outperforms the others, receiving 66.2% +top-1 votes and 41.9% top-1&2 combined votes. +9 + +===== PAGE 10 ===== +Edit1 Object (w/o non-rigid deform): Woman → Man +Edit2 Object (w non-rigid deform): Woman → Lion +Edit3 Color: black dress → red dress +Edit4 Material: A woman → A porcelain woman +Source video VideoGrain Wan-Edit +TokenFlow +DMT +VidToMe +Pyramid-Edit +Edit5 Add: A woman → A woman followed closely by a dog Edit6 Remove: A cat is pouncing playfully without a toy +VideoGrain Wan-Edit Pyramid-Edit +Pyramid-Edit +Source video VideoGrain Wan-Edit +10 +Figure 6. Editing results across six editing types and five comparison methods. + +===== PAGE 11 ===== +Human validation of mask quality. The segmentation +masks in FiVE are initially generated by the SAM model +to provide object-level supervision. To ensure accuracy and +alignment with the intended target regions, each mask is +manually reviewed and corrected if necessary by human an- +notators (see Fig. 5). This process guarantees high-quality +annotations that support reliable evaluation and training. +5.4. Qualitative Comparison +Fig. 6 compares the editing results of all methods across +six editing types. More visual comparisons can be found +in the appendix or on our project page.1 Analyzing by +editing type, object edits without non-rigid transformations +(Edit1) and color changes (Edit3) are the easiest, success- +fully handled by nearly all methods. In contrast, object edits +with non-rigid transformations (Edit2) and material changes +(Edit4) are only effectively performed by the optimization- +based DMT and our Wan-Edit. Object addition (Edit5) is +successfully achieved only by Wan-Edit, while object re- +moval (Edit6) fails across all methods—only Pyramid-Edit +manages partial removal, but with suboptimal results. +From the perspective of background preservation in +fine-grained video editing, DMT and VidToME introduce +significant alterations, while TokenFlow, VideoGrain, and +the RF-based Pyramid-Edit and Wan-Edit largely retain +the original background information. Notably, the two +diffusion-based methods enhance background quality, ben- +efiting from Stable Diffusion’s high-quality image genera- +tion model. For foreground object editing, TokenFlow, Vid- +ToME, and VideoGrain fail to handle non-rigid structural +changes. Pyramid-Edit, due to its multi-resolution process- +ing along timesteps and autoregressive temporal architec- +ture, suffers from noise intensity discrepancies and accumu- +lated temporal errors. This results in overlapping or blur- +ring between the source and target objects, making it less +suitable for video editing tasks. Both DMT and Wan-Edit +achieve strong target object editing, but Wan-Edit preserves +object detail and pose consistency more effectively. +The qualitative analysis further supports the quantitative +results: DMT excels in object editing but distorts the back- +ground, whereas VideoGrain and Wan-Edit achieve the best +balance between foreground and background preservation. +More quantitative and qualitative comparison on each fine- +grained editing type can be found in the Supplementary +Materials. +5.5. Limitations and Future Work. +This work adapts image editing techniques 4 to video edit- +ing, demonstrating strong performance on the Wan2.1 T2V +model, which shares the same architecture as I2V meth- +ods. However, it is less suited for the pyramid structure of +Pyramid-Flow T2V model, leaving room for improvement +1https://sites.google.com/view/five-benchmark +in editing quality. In future work, we aim to further refine +RF-based video editing models to ensure broader applica- +bility across different architectures. Additionally, address- +ing challenging cases in benchmark tests—such as large +motions, object removal, and long videos—will be a key +focus for improvement. +6. Conclusion +We introduce FiVE, a benchmark for fine-grained video +editing, and propose the VLM-based FiVE-Acc metric, +which evaluates the accuracy of object-level editing suc- +cess. Additionally, we adapt two RF-based video edit- +ing methods, Pyramid-Edit and Wan-Edit. To the best of +our knowledge, this is the first comprehensive quantitative +and qualitative comparison of emerging diffusion-based and +flow-based models in the video editing community. FiVE +and FiVE-Acc provide a standardized framework for evalu- +ating fine-grained video editing models, guiding future ad- +vancements in efficient and high-fidelity video editing so- +lutions. We hope this benchmark drives innovation in both +research and real-world applications. +References +[1] Andreas Blattmann, Tim Dockhorn, Sumith Kulal, Daniel +Mendelevitch, Maciej Kilian, Dominik Lorenz, Yam Levi, +Zion English, Vikram Voleti, Adam Letts, et al. Stable video +diffusion: Scaling latent video diffusion models to large +datasets. arXiv preprint arXiv:2311.15127, 2023. 2 +[2] Tim Brooks, Aleksander Holynski, and Alexei A Efros. In- +structpix2pix: Learning to follow image editing instructions. +In Proceedings of the IEEE/CVF conference on computer vi- +sion and pattern recognition, pages 18392–18402, 2023. 4, +15, 16 +[3] Duygu Ceylan, Chun-Hao P Huang, and Niloy J Mitra. +Pix2video: Video editing using image diffusion. In Proceed- +ings of the IEEE/CVF International Conference on Com- +puter Vision, pages 23206–23217, 2023. 3 +[4] Weifeng Chen, Jie Wu, Pan Xie, Hefeng Wu, Jiashi Li, +Xin Xia, Xuefeng Xiao, and Liang Lin. Control-a-video: +Controllable text-to-video generation with diffusion models. +arXiv preprint arXiv:2305.13840, 2023. 2 +[5] Yingying Deng, Xiangyu He, Changwang Mei, Peisong +Wang, and Fan Tang. Fireflow: Fast inversion of rec- +tified flow for image semantic editing. arXiv preprint +arXiv:2412.07517, 2024. 2, 3 +[6] Prafulla Dhariwal and Alexander Nichol. Diffusion models +beat gans on image synthesis. Advances in Neural Informa- +tion Processing Systems, 34:8780–8794, 2021. 2 +[7] Wenkai Dong, Song Xue, Xiaoyue Duan, and Shumin Han. +Prompt tuning inversion for text-driven image editing using +diffusion models. In Proceedings of the IEEE/CVF Inter- +national Conference on Computer Vision, pages 7430–7440, +2023. 3 +[8] Patrick Esser, Sumith Kulal, Andreas Blattmann, Rahim +Entezari, Jonas M¨ uller, Harry Saini, Yam Levi, Dominik +11 + +===== PAGE 12 ===== +Lorenz, Axel Sauer, Frederic Boesel, et al. Scaling recti- +fied flow transformers for high-resolution image synthesis. +In Forty-first International Conference on Machine Learn- +ing, 2024. 2, 3 +[9] Michal Geyer, Omer Bar-Tal, Shai Bagon, and Tali Dekel. +Tokenflow: Consistent diffusion features for consistent video +editing. In The Twelfth International Conference on Learn- +ing Representations, 2024. 2, 3, 7, 15, 20, 21, 22 +[10] Yuwei Guo, Ceyuan Yang, Anyi Rao, Yaohui Wang, Yu +Qiao, Dahua Lin, and Bo Dai. Animatediff: Animate your +personalized text-to-image diffusion models without specific +tuning. arXiv preprint arXiv:2307.04725, 2023. 2 +[11] Jonathan Ho, Ajay Jain, and Pieter Abbeel. Denoising dif- +fusion probabilistic models. Advances in neural information +processing systems, 33:6840–6851, 2020. 2 +[12] Jonathan Ho, William Chan, Chitwan Saharia, Jay Whang, +Ruiqi Gao, Alexey Gritsenko, Diederik P Kingma, Ben +Poole, Mohammad Norouzi, David J Fleet, et al. Imagen +video: High definition video generation with diffusion mod- +els. arXiv preprint arXiv:2210.02303, 2022. 2 +[13] Aaron Hurst, Adam Lerer, Adam P Goucher, Adam Perel- +man, Aditya Ramesh, Aidan Clark, AJ Ostrow, Akila Weli- +hinda, Alan Hayes, Alec Radford, et al. Gpt-4o system card. +arXiv preprint arXiv:2410.21276, 2024. 3, 17 +[14] Zeyinzi Jiang, Zhen Han, Chaojie Mao, Jingfeng Zhang, +Yulin Pan, and Yu Liu. Vace: All-in-one video creation and +editing. arXiv preprint arXiv:2503.07598, 2025. 3 +[15] Yang Jin, Zhicheng Sun, Ningyuan Li, Kun Xu, Hao Jiang, +Nan Zhuang, Quzhe Huang, Yang Song, Yadong Mu, and +Zhouchen Lin. Pyramidal flow matching for efficient video +generative modeling. arXiv preprint arXiv:2410.05954, +2024. 1, 2, 3, 6, 16 +[16] Xuan Ju, Ailing Zeng, Yuxuan Bian, Shaoteng Liu, and +Qiang Xu. Pnp inversion: Boosting diffusion-based editing +with 3 lines of code. International Conference on Learning +Representations (ICLR), 2024. 3 +[17] Levon Khachatryan, Andranik Movsisyan, Vahram Tade- +vosyan, Roberto Henschel, Zhangyang Wang, Shant +Navasardyan, and Humphrey Shi. Text2video-zero: Text-to- +image diffusion models are zero-shot video generators. arXiv +preprint arXiv:2303.13439, 2023. 3 +[18] Max Ku, Cong Wei, Weiming Ren, Harry Yang, and Wenhu +Chen. Anyv2v: A tuning-free framework for any video-to- +video editing tasks. arXiv preprint arXiv:2403.14468, 2024. +3, 7, 15, 20, 21, 22 +[19] Vladimir Kulikov, Matan Kleiner, Inbar Huberman- +Spiegelglas, and Tomer Michaeli. Flowedit: Inversion-free +text-based editing using pre-trained flow models. arXiv +preprint arXiv:2412.08629, 2024. 1, 2, 3, 5, 16 +[20] Black Forest Labs. Flux. https://github.com/ +black-forest-labs/flux. 2, 3 +[21] Minghan Li, Shuai Li, Xindong Zhang, and Lei Zhang. +Univs: Unified and universal video segmentation with +prompts as queries. In Proceedings of the IEEE/CVF con- +ference on computer vision and pattern recognition, pages +3227–3238, 2024. 4 +[22] Xirui Li, Chao Ma, Xiaokang Yang, and Ming-Hsuan Yang. +Vidtome: Video token merging for zero-shot video editing. +In Proceedings of the IEEE/CVF Conference on Computer +Vision and Pattern Recognition, pages 7486–7495, 2024. 2, +3, 7, 15, 20, 21, 22 +[23] Yaron Lipman, Ricky TQ Chen, Heli Ben-Hamu, Maxim- +ilian Nickel, and Matthew Le. Flow matching for genera- +tive modeling. In The Eleventh International Conference on +Learning Representations, 2023. 4 +[24] Xingchao Liu, Chengyue Gong, et al. Flow straight and fast: +Learning to generate and transfer data with rectified flow. In +The Eleventh International Conference on Learning Repre- +sentations, 2023. 2, 4 +[25] Guoqing Ma, Haoyang Huang, Kun Yan, Liangyu Chen, Nan +Duan, Shengming Yin, Changyi Wan, Ranchen Ming, Xi- +aoniu Song, Xing Chen, et al. Step-video-t2v technical re- +port: The practice, challenges, and future of video founda- +tion model. arXiv preprint arXiv:2502.10248, 2025. 2 +[26] Ron Mokady, Amir Hertz, Kfir Aberman, Yael Pritch, and +Daniel Cohen-Or. Null-text inversion for editing real im- +ages using guided diffusion models. In Proceedings of +the IEEE/CVF Conference on Computer Vision and Pattern +Recognition, pages 6038–6047, 2023. 3 +[27] OpenAI. Video generation models as world simulators, +2024. 2, 6 +[28] Federico Perazzi, Jordi Pont-Tuset, Brian McWilliams, Luc +Van Gool, Markus Gross, and Alexander Sorkine-Hornung. +A benchmark dataset and evaluation methodology for video +object segmentation. In Proceedings of the IEEE conference +on computer vision and pattern recognition, pages 724–732, +2016. 3, 17 +[29] Chenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, +Xintao Wang, Ying Shan, and Qifeng Chen. Fatezero: Fus- +ing attentions for zero-shot text-based video editing. arXiv +preprint arXiv:2303.09535, 2023. 2, 3 +[30] Bosheng Qin, Juncheng Li, Siliang Tang, Tat-Seng Chua, +and Yueting Zhuang. Instructvid2vid: Controllable video +editing with natural language instructions. In 2024 IEEE +International Conference on Multimedia and Expo (ICME), +pages 1–6. IEEE, 2024. 3 +[31] Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu, Ronghang +Hu, Chaitanya Ryali, Tengyu Ma, Haitham Khedr, Roman +R¨ adle, Chloe Rolland, Laura Gustafson, Eric Mintun, Junt- +ing Pan, Kalyan Vasudev Alwala, Nicolas Carion, Chao- +Yuan Wu, Ross Girshick, Piotr Doll´ ar, and Christoph Feicht- +enhofer. Sam 2: Segment anything in images and videos, +2024. 4 +[32] Robin Rombach, Andreas Blattmann, Dominik Lorenz, +Patrick Esser, and Bj¨ orn Ommer. High-resolution image +synthesis with latent diffusion models. In Proceedings of +the IEEE/CVF conference on computer vision and pattern +recognition, pages 10684–10695, 2022. 2, 16 +[33] Litu Rout, Yujia Chen, Nataniel Ruiz, Constantine Carama- +nis, Sanjay Shakkottai, and Wen-Sheng Chu. Semantic im- +age inversion and editing using rectified stochastic differen- +tial equations. arXiv preprint arXiv:2410.10792, 2024. 2, +3 +[34] Michele A Saad and Alan C Bovik. Blind quality assess- +ment of videos using a model of natural scene statistics and +12 + +===== PAGE 13 ===== +motion coherency. In 2012 Conference Record of the Forty +Sixth Asilomar Conference on Signals, Systems and Comput- +ers (ASILOMAR), pages 332–336. IEEE, 2012. 7 +[35] Uriel Singer, Amit Zohar, Yuval Kirstain, Shelly Sheynin, +Adam Polyak, Devi Parikh, and Yaniv Taigman. Video edit- +ing via factorized diffusion distillation. In European Con- +ference on Computer Vision, pages 450–466. Springer, 2024. +2 +[36] Jiaming Song, Chenlin Meng, and Stefano Ermon. Denois- +ing diffusion implicit models. In International Conference +on Learning Representations, 2021. 2, 3, 16 +[37] Spencer Sterling. Zeroscope. https://huggingface. +co/cerspense/zeroscope_v2_576w, 2023. 2, 16 +[38] Zhiyu Tan, Hao Yang, Luozheng Qin, Jia Gong, Meng- +ping Yang, and Hao Li. Omni-video: Democratizing uni- +fied video understanding and generation. arXiv preprint +arXiv:2507.06119, 2025. 3 +[39] Shuyuan Tu, Qi Dai, Zhi-Qi Cheng, Han Hu, Xintong Han, +Zuxuan Wu, and Yu-Gang Jiang. Motioneditor: Editing +video motion via content-aware diffusion. In Proceedings of +the IEEE/CVF Conference on Computer Vision and Pattern +Recognition, pages 7882–7891, 2024. 3 +[40] Narek Tumanyan, Omer Bar-Tal, Shai Bagon, and Tali +Dekel. Splicing vit features for semantic appearance trans- +fer. In Proceedings of the IEEE/CVF Conference on Com- +puter Vision and Pattern Recognition (CVPR), pages 10748– +10757, 2022. 7 +[41] Narek Tumanyan, Michal Geyer, Shai Bagon, and Tali +Dekel. Plug-and-play diffusion features for text-driven +image-to-image translation. In Proceedings of the IEEE/CVF +Conference on Computer Vision and Pattern Recognition, +pages 1921–1930, 2023. 16 +[42] Bram Wallace, Akash Gokul, and Nikhil Naik. Edict: Exact +diffusion inversion via coupled transformations. In Proceed- +ings of the IEEE/CVF Conference on Computer Vision and +Pattern Recognition, pages 22532–22541, 2023. 3 +[43] Team Wan, Ang Wang, Baole Ai, Bin Wen, Chaojie Mao, +Chen-Wei Xie, Di Chen, Feiwu Yu, Haiming Zhao, Jianxiao +Yang, et al. Wan: Open and advanced large-scale video gen- +erative models. arXiv preprint arXiv:2503.20314, 2025. 1, +2, 3, 6, 16 +[44] Jiangshan Wang, Junfu Pu, Zhongang Qi, Jiayi Guo, Yue Ma, +Nisha Huang, Yuxin Chen, Xiu Li, and Ying Shan. Tam- +ing rectified flow for inversion and editing. arXiv preprint +arXiv:2411.04746, 2024. 2, 3 +[45] Zhou Wang, Alan C Bovik, Hamid R Sheikh, and Eero P Si- +moncelli. Image quality assessment: from error visibility to +structural similarity. IEEE Transactions on Image Process- +ing, 13(4):600–612, 2004. 7 +[46] Yujie Wei, Shiwei Zhang, Zhiwu Qing, Hangjie Yuan, Zhi- +heng Liu, Yu Liu, Yingya Zhang, Jingren Zhou, and Hong- +ming Shan. Dreamvideo: Composing your dream videos +with customized subject and motion. In Proceedings of +the IEEE/CVF Conference on Computer Vision and Pattern +Recognition, pages 6537–6549, 2024. 3 +[47] Chenfei Wu, Lun Huang, Qianxi Zhang, Binyang Li, Lei Ji, +Fan Yang, Guillermo Sapiro, and Nan Duan. GODIVA: Gen- +erating open-domain videos from natural descriptions. arXiv +preprint arXiv:2104.14806, 2021. 7 +[48] Chen Henry Wu and Fernando De la Torre. A latent space +of stochastic diffusion models for zero-shot image editing +and guidance. In Proceedings of the IEEE/CVF International +Conference on Computer Vision, pages 7378–7387, 2023. 3 +[49] Jay Zhangjie Wu, Yixiao Ge, Xintao Wang, Stan Weixian +Lei, Yuchao Gu, Yufei Shi, Wynne Hsu, Ying Shan, Xiaohu +Qie, and Mike Zheng Shou. Tune-a-video: One-shot tuning +of image diffusion models for text-to-video generation. In +Proceedings of the IEEE/CVF International Conference on +Computer Vision, pages 7623–7633, 2023. 2, 3 +[50] Jay Zhangjie Wu, Xiuyu Li, Difei Gao, Zhen Dong, Jin- +bin Bai, Aishani Singh, Xiaoyu Xiang, Youzeng Li, Zuwei +Huang, Yuanxi Sun, et al. Cvpr 2023 text guided video edit- +ing competition. arXiv preprint arXiv:2310.16003, 2023. 2 +[51] Chenxi Xie, Minghan Li, Shuai Li, Yuhui Wu, Qiaosi Yi, and +Lei Zhang. Dnaedit: Direct noise alignment for text-guided +rectified flow editing. arXiv preprint arXiv:2506.01430, +2025. 3 +[52] Shuai Yang, Yifan Zhou, Ziwei Liu, and Chen Change +Loy. Rerender a video: Zero-shot text-guided video-to-video +translation. In SIGGRAPH Asia 2023 Conference Papers, +pages 1–11, 2023. 3 +[53] Xiangpeng Yang, Linchao Zhu, Hehe Fan, and Yi Yang. +Videograin: Modulating space-time attention for multi- +grained video editing. arXiv preprint arXiv:2502.17258, +2025. 2, 3, 7, 15, 20, 21, 22 +[54] Danah Yatim, Rafail Fridman, Omer Bar-Tal, Yoni Kasten, +and Tali Dekel. Space-time diffusion features for zero-shot +text-driven motion transfer. In Proceedings of the IEEE/CVF +Conference on Computer Vision and Pattern Recognition, +pages 8466–8476, 2024. 3, 7, 15, 20, 21, 22 +[55] Zixuan Ye, Xuanhua He, Quande Liu, Qiulin Wang, Xintao +Wang, Pengfei Wan, Di Zhang, Kun Gai, Qifeng Chen, and +Wenhan Luo. Unic: Unified in-context video editing. arXiv +preprint arXiv:2506.04216, 2025. 3 +[56] Richard Zhang, Phillip Isola, Alexei A Efros, Eli Shecht- +man, and Oliver Wang. The unreasonable effectiveness of +deep features as a perceptual metric. In Proceedings of +the IEEE/CVF Conference on Computer Vision and Pattern +Recognition (CVPR), pages 586–595, 2018. 7 +[57] Shiwei Zhang, Jiayu Wang, Yingya Zhang, Kang Zhao, +Hangjie Yuan, Zhiwu Qin, Xiang Wang, Deli Zhao, and +Jingren Zhou. I2vgen-xl: High-quality image-to-video +synthesis via cascaded diffusion models. arXiv preprint +arXiv:2311.04145, 2023. 16 +[58] Zhenghao Zhang, Zuozhuo Dai, Long Qin, and Weizhi +Wang. Effived: Efficient video editing via text-instruction +diffusion models. arXiv preprint arXiv:2403.11568, 2024. 3 +[59] Zhixing Zhang, Yanyu Li, Yushu Wu, Yanwu Xu, Anil Kag, +Ivan Skorokhodov, Willi Menapace, Aliaksandr Siarohin, +Junli Cao, Dimitris Metaxas, et al. Sf-v: Single forward +video generation model. arXiv preprint arXiv:2406.04324, +2024. 3 +[60] Rui Zhao, Yuchao Gu, Jay Zhangjie Wu, David Jun- +hao Zhang, Jia-Wei Liu, Weijia Wu, Jussi Keppo, and +13 + +===== PAGE 14 ===== +Mike Zheng Shou. Motiondirector: Motion customization +of text-to-video diffusion models. In European Conference +on Computer Vision, pages 273–290. Springer, 2025. 3 +14 + +===== PAGE 15 ===== +Supplementary Materials +FiVE-Dataset Wan-Edit Results and FiVE-Evaluation +Object (w/o non-rigid deform): A rhinoceros … Material: A stone elephant … +Source Video +Caption: An elephantis walking across a rocky enclosure in a zoo… +Prompt1: A rhinoceros is walking across… +Instruct1: Change the elephant to rhinoceros +Prompt2: A jeep is moving across … +Instruct2: Change the elephant to jeep +Prompt3: A blue elephant is walking … +Instruct3: Make the elephant blue. +Prompt4: A stone elephant is walking … +Instruct4: Make the elephant stone. +Prompt5: An elephant wearing a hat … +Instruct5: Add a hat to the elephant. +Prompt6: No elephant in a zoo … +Instruct6: Remove the elephant +Masks: FiVE-Bench +FiVE-Acc:[1,1,1,1]à 1 +Human: +Object (w non-rigid deform): A jeep … CLIP Score:0.57 +FiVE-Acc:[0,0,0,0] à 0 +Human: +Add: An elephant wearing a hat … +CLIP Score:0.89 +FiVE-Acc:[1,1,1,1]à 1 +Human: +Color: A blue elephant … CLIP Score:0.72 +FiVE-Acc:[1,1,1,1] à 1 +Remove: An elephant … +Human: +CLIP Score:0.84 +FiVE-Acc:[1,0,1,0]à 0.5 +Human: +CLIP Score:0.90 +FiVE-Acc:[0,0,0,0] à 0 +Human: +CLIP Score:0.46 +Figure 7. The introduced FiVE Benchmark and corresponding editing results of the proposed Wan-Edit method. +In this supplementary file, we provide the following ma- +terials: +• More details on the baseline methods +• More details on implementation details +• More details on FiVE Dataset +• GPU memory and speed comparison +• More quantitative results and analysis +• More qualitative results and analysis +A. Baseline Methods +• TokenFlow [9] is a training-free framework for consistent +video editing that leverages diffusion features by enforc- +ing cross-frame semantic token alignment in latent space +to preserve spatiotemporal coherence. By propagating +consistent appearance and motion patterns through op- +timized token interactions in a pre-trained text-to-image +model, it achieves temporally stable edits without requir- +ing additional fine-tuning or annotated data. +• DMT [54] is a zero-shot framework for text-driven dif- +fusion motion transfer that leverages spatiotemporal dif- +fusion features to align source motion patterns with tar- +get textual descriptions in a unified latent space. By in- +tegrating cross-modal attention mechanisms and tempo- +ral coherence constraints within a pre-trained diffusion +model, it enables realistic motion synthesis without re- +quiring task-specific training or paired data, ensuring both +semantic fidelity and dynamic consistency. +• VidToME [22] is a zero-shot video editing framework +that enhances spatiotemporal consistency by adaptively +merging redundant tokens across frames within a pre- +trained diffusion model. This token-efficient strategy pre- +serves critical motion and appearance features while re- +ducing computational overhead, enabling coherent video +edits without task-specific training or temporal-aware +fine-tuning. +• AnyV2V [18] is a tuning-free framework designed for +universal video editing tasks, leveraging spatiotemporally +consistent diffusion features through cross-frame latent +propagation to maintain coherence across diverse editing +operations. By dynamically aligning semantic and mo- +tion patterns in pre-trained diffusion models without task- +specific tuning, it enables flexible video-to-video trans- +formations while preserving temporal stability and vi- +sual fidelity. For prompt-based editing, it uses Instruct- +Pix2Pix [2] to edit the first frame first. +• VideoGrain [53] is a video editing framework that en- +ables multi-grained control through hierarchical space- +time attention modulation, dynamically adjusting spa- +tial and temporal feature interactions in diffusion mod- +els to achieve precise edits across varying granularities. +By decomposing and recombining cross-frame attention +patterns at different resolution scales, it maintains tem- +poral coherence and visual fidelity while supporting di- +verse editing tasks without requiring architectural modi- +15 + +===== PAGE 16 ===== +Table 5. Comparison of different video editing methods for DM and RF models under default settings. +Methods Publication Inv. Attn Base T2I/V Inv.-free Resolution Timesteps Type Injection Model Inv.+Edit +Conditions +DMs +TokenFlow DMT Vidtome AnyV2V VideoGrain ICCV23 DDIM [36] ✓ SD2.1 [32] ✗ (512, 512) 500 + 50 ✗ +CVPR24 DDIM [36] ✗ ZeroScope [37] ✗ (576, 320) 1000 + 50 CVPR24 PnP [41] ✓ SD1.5 [32] ✗ (512, 512) 50 + 50 ✗ +TMLR24 PnP [41] ✓ I2VGen-XL [57] ✗ (512, 512) 500 + 50 ICLR25 DDIM [36] ✓ SD1.5 [32] ✗ (512, 512) 50 + 50 Optimization +InstrctPix2Pix [2] +Depth + Mask +RFs Pyramid-Edit Wan-Edit Ours FlowEdit [19] ✗ Pyramid-Flow [15] ✓ (640, 384) 40 ✗ +Ours FlowEdit [19] ✗ Wan2.1 [43] ✓ (832, 480) 50 ✗ +Real-world Videos +… +FiVE-Dataset +Generated Videos +… +An elephant is walking slowly across a rocky enclosure in a zoo, with +dust rising around its feet. The camera +Caption +GPT-4o +remains fixed, capturing the elephant's steady movement against the backdrop of trees and a building. +Generate +New Prompts Edit Prompts +Human +Generation +Justification +Generation +A bicycle is rolling steadily along a cobblestone street, with +historic buildings and flower boxes lining the road. The camera +Wan2.1 +remains fixed, capturing the bicycle's smooth motion. +Object +w/o non-rigid +Object +w non-rigid +Color +Material +Add +Remove +fications or task-specific fine-tuning. +B. Implementation Details +All experiments were conducted using the official GitHub +repository and environment, with default settings. For +training-free methods, the editing results are highly depen- +dent on hyperparameters, such as in PNP [41]. To minimize +the impact of hyperparameters, we randomly selected six +videos from our benchmark and performed a search within +an appropriate parameter range to find the best hyperparam- +eters. These were then fixed for all subsequent data in the +benchmark. All experiments were run on a single H100 +GPU. Table 5 lists the parameter settings for the compared +methods and our proposed approach. +For VLM-based FiVE-Acc evaluation, QWen2.5-VL-7B +is selected as the evaluation model. We sample one frame +Figure 8. FiVE-Dataset construction pipeline. +every 8 frames from the edited video, selecting a total of 5 +evenly spaced frames from a 40-frame video, which are then +fed into the vision encoder of QWen2.5-VL. The text input +consists of Yes/No questions or multiple-choice questions, +as illustrated in Fig. 2 of the main paper. Considering the +varying number of videos across different editing types, we +compute the FiVE-Acc metric separately for each type. The +final FiVE benchmark score is obtained by averaging the +scores across all six editing types, as presented in Table 3. +C. More Details on FiVE Dataset +The construction of the FiVE-Dataset involves the collec- +tion of real-world videos, the generation of captions for +these videos, the creation of synthetic video-caption pairs, +and the generation of editing prompts. The overall pipeline +is illustrated in Fig. 8. +16 + +===== PAGE 17 ===== +User: Create English captions for video +generation with the following guideline: +Guideline: +1.Content: Object + Action + Environment + +Camera Movement. +2.Objects: 1-2 objects (animals, people, +buildings, vehicles). No groups. +3.Actions: Simple (e.g., vehicle moving) or +complex (e.g., person running, animal +jumping). +4.Camera: Static, slow movement, or fast +movement. +GPT-4o: +A bicycle is rolling steadily along a +cobblestone street, with historic buildings +and flower boxes lining the road. The +camera remains fixed, capturing the +bicycle's smooth motion. +…… +A bicycle is rolling steadily along a cobblestone street, with historic buildings and flower +boxes lining the road. The camera remains fixed, capturing the bicycle's smooth motion. +A dog is wagging its tail excitedly while sitting on a sandy beach with waves crashing in +the background. The camera remains fixed, focusing on the dog's joyful expression. +A cyclist is pedaling vigorously along a tree-lined path in a city park. The camera follows +the cyclist at a steady pace. +Figure 9. Example of generated caption-video pairs. +System: +Please generate a new prompt by modifying the content related to the target object based on the provided information. +Guidelines: +- The modification should result in a significant difference between the original and changed objects. For example, change a bird to an airplane, a vehicle to a +spaceship/UFO/rocket/animal, etc. Use your imagination to make creative changes. +- For the action description, adjust it accordingly to fit the modified object. +- Do not modify the background description. +- Do not simply add adjective words like ”robotic“ to the changed object, for example ”rhinoceros“ to "robotic rhinoceros", change the object it self. +User: +"caption": "A bicycle is rolling steadily along a cobblestone street, with historic buildings and flower boxes lining the road. The camera remains fixed, +capturing the bicycle's smooth motion.", +"id": "0075_A_bicycle", +"target": "A bicycle", +"camera": "fixed", +"action": false +GPT-4o: +"video_name": "0075_A_bicycle", +"source_prompt": "A bicycle is rolling steadily along a cobblestone street, with historic buildings and flower boxes lining the road. The camera remains fixed, +capturing the bicycle's smooth motion.", +"target_prompt": "A skateboard is gliding steadily along a cobblestone street, with historic buildings and flower boxes lining the road. The camera remains +fixed, capturing the skateboard's smooth motion.", +"instruction": "Change the bicycle to a skateboard.” +…… +Figure 10. Example of editing prompt generation. +C.1. Video-description Pair Construction. +We begin by selecting real-world videos from the DAVIS +dataset [28] that are well-suited for fine-grained video edit- +ing. For each chosen video, we use GPT-4o [13] to gen- +erate detailed annotations every 8th frame, capturing key +elements such as subject actions, background details, and +camera movements. Next, we create new annotations in the +style of real video descriptions, which are then used to guide +a text-to-video model in generating new videos. The full +process and examples of generated pairs are shown in Fig. 9. +In this process, human justification is involved in assessing +the quality of both the videos and their descriptions to en- +sure the generation of high-quality video-description pairs. +C.2. Editing Prompt Generation +For the constructed video-caption pairs, we design special- +ized prompts to generate target editing instructions for six +editing types. GPT-4o is employed to create new video cap- +tions by modifying the original captions based on the target +object, serving as the target prompts for the editing process. +17 + +===== PAGE 18 ===== +System prompt: +Given the source and target prompts, along with the source and target objects, generate a question about the edited object +that reflects its transformation from the source to the target. +User example: (customized for each editing type) +Source prompt: ‘A black swan swimming in the river.’ +Target prompt: ‘A flamingo swimming in the river.’ +Source object: ‘A black swan’ +Target object: ‘A flamingo’ +Yes/No Questions: ‘Is that a black swan in the river?’ \n ‘Is that a flamingo in the river?’\n\n +Multi-choice Question: ‘What is the object in the river? Options: A) Black swan B) Flamingo’ +GPT-4o: +Source prompt: ‘{source prompt}’\n +Target prompt: ‘{target prompt}’\n +Source object: ‘{source object}’\n +Target object: ‘{target object}\n’ +Yes/No Questions: +Multi-choice Question: +Figure 11. Example of Yes/No and Multi-choice question generation for FiVE-Acc evaluation. +Fig. 10 provides an example of the prompt and its corre- +sponding output for generating an editing type instruction. +C.3. FiVE-Acc Question Generation +The FiVE benchmark provides both the source object (the +object in the original video) and the target object (the object +after editing). Based on this information, we utilize GPT-4o +to generate Yes/No questions and Multiple-choice questions +to assess the accuracy of the edits, as shown in Fig. 11. The +user prompt is customized for each editing type, and the +generated questions are manually reviewed for quality as- +surance. These generated questions enable an automated +evaluation of editing success based on the FiVE-Acc met- +ric. +D. GPU Memory and Speed +As shown in Fig. 12, TokenFlow, VidToMe, AnyV2V, and +our proposed Wan-Edit are all positioned in the lower-left +corner, indicating a well-balanced trade-off between editing +time and peak memory usage. However, Wan-Edit signifi- +cantly outperforms the other three in terms of editing qual- +ity, further demonstrating its effectiveness. Compared to +the highly competitive VideoGrain, Pyramid-Edit and Wan- +Edit drastically reduces editing time and memory consump- +tion, proving their efficiency. +The speed differences among these methods stem from +their architectural choices and computational requirements. +Pyramid-Edit is the fastest, benefiting from its multi- +resolution design and the high spatiotemporal compres- +sion rate of VideoVAE (8×8×8), which significantly reduces +the processing burden. However, this aggressive compres- +sion can lead to background collapse, particularly when the +Per-Video Edit Time (s) +25 +TokenFlow +DMT +20 +VidToMe +AnyV2V +15 +VideoGrain +Pyramid-Edit +10 +Wan-Edit +5 +0 +10 20 30 40 50 +Max Memory Allocated (GB) +Figure 12. Comparison of editing efficiency, including GPU +memory usage and per-frame running time. All test on a single +NVIDIA H100. +background exhibits fast motion. Wan-Edit, on the other +hand, adopts a more moderate compression rate (4×8×8), +which balances efficiency and quality, ensuring better back- +ground preservation while maintaining competitive speed. +In contrast, VideoGrain is significantly slower due to its de- +pendence on segmentation and depth models. These ad- +ditional processing steps, which involve extracting object +masks and depth maps to guide the editing process, in- +troduce substantial computational overhead. This makes +VideoGrain less suitable for real-time or high-speed appli- +cations despite its strong editing accuracy. +18 + +===== PAGE 19 ===== +E. More Quantitative Results and Analysis +In this section, we present additional experimental results +and provide a comprehensive analysis of the performance +of all baseline methods on our proposed FiVE benchmark. +For clarity, we define six editing types, referred to as Edit +1–6: rigid transformation (e.g., car to bus), non-rigid trans- +formation (e.g., car to elephant), color change (e.g., black +to red), attribute change (e.g., car to a wooden texture), ob- +ject addition, and object removal. We conduct a compara- +tive analysis of various video editing methods across these +categories using multiple metrics. Additionally, we evalu- +ate diffusion- and flow-based approaches on the proposed +FiVE benchmark and FiVE-Acc metric. +Tables 6 and 8 present the results for Edit1: Object re- +placement without non-rigid transformations (e.g., replac- +ing a car with a bus). Our proposed Wan-Edit achieves +background preservation and text alignment comparable +to VideoGrain, while exhibiting superior motion fidelity. +Since Wan-Edit better retains the original video back- +ground, its IQA scores remain consistent with those of the +source video. Regarding the FiVE-Acc metrics, which as- +sess the accuracy of successful edits, the most competitive +method is DMT, which optimizes editing based on the input +text. The training-free Wan-Edit and VideoGrain achieve +similar results, slightly trailing DMT but significantly out- +performing other methods. Overall, DMT offers the best +text-vision alignment but requires optimization, whereas +VideoGrain and Wan-Edit strike a strong balance across var- +ious fine-grained video editing metrics. Notably, Wan-Edit +stands out for its superior efficiency, delivering faster and +more stable results compared to VideoGrain. +Tables 7 and 9 present the results of all compared meth- +ods on Edit2: Object Replacement with Non-Rigid Trans- +formations, revealing similar conclusions to Edit1: Object +Replacement with Rigid Transformations. However, Edit2 +is more challenging than Edit1 due to the complexity of +non-rigid transformations. This increased difficulty results +in a noticeable drop in text-vision alignment, motion fi- +delity scores, and the editing success rate (FiVE-Acc) met- +rics compared to Edit1. In terms of the editing success +rate (FiVE-Acc), DMT and Wan-Edit achieve 67.86% and +52.02%, respectively, on Edit1, with DMT outperforming +Wan-Edit by approximately 15%. However, on Edit2, DMT +drops significantly to 53.72%, while Wan-Edit remains sta- +ble. This indicates Wan-Edit’s robustness in handling non- +rigid transformations, maintaining consistent performance +even in more challenging editing scenarios. +Similarly, consistent trends are observed across other +editing types, Edit3 (color changes) and Edit4 (object ma- +terial changes) as shown in Tables 10 - 13, further reinforc- +ing our conclusions. Regarding the FiVE-Acc metric, color +changes (Edit3) achieve the highest editing success rate +among all types, with VideoGrain reaching 86% and Wan- +Edit at 63%. In contrast, object material changes (Edit4) +are significantly more challenging, with AnyV2V achiev- +ing the highest success rate at 43%, followed by Pyramid- +Edit at 36%. This difficulty arises because object material +changes often require modifying mid- and low-frequency +noise, making training-free methods highly sensitive to pa- +rameters, which leads to lower success rates. +Tables 14 - 17 compare the results of Edit5 (object +addition) and Edit6 (object removal). For object addi- +tion (Edit5), VideoGrain and Wan-Edit achieve the high- +est scores in background preservation and motion fidelity, +while TokenFlow performs best in text-vision alignment +and IQA. In terms of FiVE-Acc, the RF-based methods +Pyramid-Edit and Wan-Edit achieve success rates of 83% +and 72%, respectively, whereas the highest-performing +diffusion-based method, DMT, reaches only 61%, high- +lighting the advantage of RF-based approaches in this task. +For Edit6 (object removal), nearly all methods perform the +worst among all editing types, with FiVE-Acc scores drop- +ping below 20%, indicating that object removal is one of +the most challenging fine-grained editing tasks. This diffi- +culty arises because removing an object requires precisely +inpainting the occluded background while maintaining tem- +poral coherence, which is particularly challenging for exist- +ing editing models. The visualizations in Fig. 4 of the main +paper further confirm these findings. +In conclusion, our analysis ranks the difficulty of fine- +grained video editing tasks, with color changes (Edit3) be- +ing the easiest and object removal (Edit6) the most chal- +lenging. Rigid object replacement (Edit1) and object addi- +tion (Edit5) are relatively simple, while non-rigid transfor- +mations (Edit2) and material changes (Edit4) pose moder- +ate challenges. The particularly low success rate of object +removal highlights its complexity, requiring precise inpaint- +ing and temporal consistency. +F. More Qualitative Results and Analysis +We present the editing results across various editing types +and comparison methods in Figs. 13 - 15 and Fig. 16. +Figs. 13 - 15 compare the results of diffusion-based and +RF-based editing methods across six editing types. These +comparisons highlight the strengths and weaknesses of +each method while also demonstrating the superiority of +VideoGrain and our Wan-Edit. The videos shown in Fig. +16 are generated examples and represent a particularly chal- +lenging editing case. Editing becomes difficult when the +object occupies a significant portion of the video frame, as +it requires modifying low-frequency noise while maintain- +ing spatial and temporal consistency. This results in fail- +ure even for the best-performing Wan-Edit. To better show- +case the dynamic consistency in video editing, more video +demos are available on the anonymous website: https: +//sites.google.com/view/five-benchmark. +19 + +===== PAGE 20 ===== +Table 6. Edit1: Comparison of diffusion- and flow-based video editing methods for object replacement without non-rigid transformations +on the FiVE benchmark. +Methods Structure Dist.×103 ↓ Background Preservation PSNR↑ LPIPS×103 ↓ MSE×104 ↓ SSIM×102 ↑ Text Alignment CLIPS.↑ CLIPS.edit ↑ IQA NIQE↓ Temp. Consis. +Motion Fidelity S.×102 ↑ +Source Videos 0.00 ∞ 0.00 0.00 100.00 23.97 18.75 6.33 93.76 +DMs +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 36.24 85.35 23.81 71.19 11.71 19.12 257.32 137.12 72.63 14.35 410.83 402.43 51.61 21.32 261.19 88.47 71.50 15.85 345.77 350.37 50.91 26.92 184.08 26.82 79.06 27.04 21.23 27.26 21.52 27.75 21.19 25.41 19.96 27.43 21.40 4.05 5.25 4.68 4.64 4.10 88.23 +81.93 +90.65 +61.63 +88.29 +RFs +(Ours) +Pyramid-Edit Wan-Edit 28.27 13.50 20.87 276.18 96.15 72.56 24.81 93.67 39.67 82.54 27.43 20.11 27.19 21.38 5.47 6.59 81.52 +89.37 +Table 7. Edit2: Comparison of diffusion- and flow-based video editing methods for object replacement with non-rigid transformations on +the FiVE benchmark. +Methods Structure Background Preservation Text Alignment IQA Temp. Consis. +Dist.×103 ↓ PSNR↑ LPIPS×103 ↓ MSE×104 ↓ SSIM×102 ↑ CLIPS.↑ CLIPS.edit ↑ NIQE↓ Motion Fidelity S.×102 ↑ +Source Videos 0.00 ∞ 0.00 0.00 100.00 22.13 17.33 6.33 93.76 +DMs +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 38.88 91.04 27.95 70.14 11.24 19.08 246.65 138.69 72.99 14.26 413.98 412.38 50.37 20.80 264.37 95.43 70.98 16.01 350.89 325.25 49.66 27.23 180.61 26.13 79.56 26.30 19.70 26.86 20.38 26.95 19.94 23.87 18.46 25.46 19.35 4.21 5.22 4.82 4.62 4.12 88.19 +80.23 +88.97 +60.44 +87.38 +RFs +(Ours) +Pyramid-Edit Wan-Edit 30.00 14.33 20.65 279.11 101.41 71.74 24.54 96.53 40.36 82.33 26.86 18.97 26.85 19.98 5.52 6.63 79.55 +87.94 +Table 8. Edit1: Comparison of diffusion- and flow-based video edit- +ing methods for object replacement without non-rigid transforma- +tions on the FiVE benchmark using FiVE-Acc metrics. +Table 9. Edit2: Comparison of diffusion- and flow-based video edit- +ing methods for object replacement with non-rigid transformations +on the FiVE benchmark using FiVE-Acc metrics. +Method FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +Method FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 30.30 48.48 49.49 29.29 55.95 79.76 79.76 55.95 25.25 47.47 47.47 25.25 27.27 42.42 44.44 25.25 40.00 62.00 62.00 40.00 39.39 +67.86 +36.36 +34.85 +51.00 +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 18.18 37.37 38.38 17.17 41.49 65.96 68.09 39.36 23.23 41.41 43.43 21.21 13.13 26.26 30.30 9.09 12.24 26.53 26.53 12.24 27.78 +53.72 +32.32 +19.70 +19.39 +Pyramid-Edit Wan-Edit 27.27 53.54 55.56 25.25 41.41 62.63 62.63 41.41 40.40 +52.02 +Pyramid-Edit Wan-Edit 30.30 60.61 60.61 30.30 36.36 67.68 68.69 35.35 45.45 +52.02 +Table 10. Edit3: Comparison of diffusion- and flow-based video editing methods for object color changes on the FiVE benchmark. +Methods Structure Background Preservation Text Alignment IQA Temp. Consis. +Dist.×103 ↓ PSNR↑ LPIPS×103 ↓ MSE×104 ↓ SSIM×102 ↑ CLIPS.↑ CLIPS.edit ↑ NIQE↓ Motion Fidelity S.×102 ↑ +Source Videos 0.00 ∞ 0.00 0.00 100.00 26.12 20.64 6.33 93.76 +DMs +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 35.03 85.75 21.90 79.16 14.20 19.07 262.05 138.21 72.71 14.23 413.08 413.91 50.68 21.17 261.94 89.81 72.20 14.37 411.83 455.53 46.82 27.08 185.38 25.95 79.37 27.72 21.68 28.18 22.10 28.45 22.16 26.58 20.59 28.44 22.23 4.02 5.20 4.68 4.65 4.09 88.37 +81.71 +89.26 +61.13 +87.41 +RFs +(Ours) +Pyramid-Edit Wan-Edit 29.37 11.63 20.85 278.17 96.16 72.11 25.32 90.82 35.77 83.04 28.10 21.13 27.39 22.04 5.49 6.58 78.80 +88.59 +20 + +===== PAGE 21 ===== +Table 11. Edit4: Comparison of diffusion- and flow-based video editing methods for object material changes on the FiVE benchmark. +Methods Structure Dist.×103 ↓ Background Preservation PSNR↑ LPIPS×103 ↓ MSE×104 ↓ SSIM×102 ↑ Text Alignment CLIPS.↑ CLIPS.edit ↑ IQA NIQE↓ Temp. Consis. +Motion Fidelity S.×102 ↑ +Source Videos 0.00 ∞ 0.00 0.00 100.00 26.89 21.85 6.33 93.76 +DMs +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 35.22 84.34 23.19 71.97 10.34 19.22 258.53 133.83 73.06 14.15 408.88 417.24 50.24 20.71 273.64 98.70 69.49 15.53 354.39 382.99 50.33 27.21 185.78 25.61 79.13 27.67 22.19 27.33 22.28 27.82 21.91 26.42 20.99 27.44 21.15 4.10 5.14 4.70 4.60 4.02 88.34 +80.47 +89.24 +62.14 +87.55 +RFs +(Ours) +Pyramid-Edit Wan-Edit 28.39 10.66 20.74 277.73 98.54 72.04 25.45 89.72 34.19 83.31 28.07 21.48 27.55 22.35 5.44 6.57 78.27 +88.83 +Table 12. Edit3: Comparison of diffusion- and flow-based video +editing methods for object color changes on the FiVE benchmark +using FiVE-Acc metrics. +Table 13. Edit4: Comparison of diffusion- and flow-based video +editing methods for object material changes on the FiVE benchmark +using FiVE-Acc metrics. +Method FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +Method FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 34.34 46.46 48.48 32.32 55.06 61.80 64.04 52.81 36.36 42.42 43.43 35.35 54.55 64.65 67.68 51.52 82.00 90.00 92.00 80.00 40.40 +58.43 +39.39 +59.60 +86.00 +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 11.11 26.26 29.29 8.08 11.76 47.06 48.24 10.59 13.13 36.36 38.38 11.11 23.23 63.64 64.65 22.22 26.53 40.82 40.82 26.53 18.69 +29.41 +24.75 +43.43 +33.67 +Pyramid-Edit Wan-Edit 59.60 57.58 66.67 50.51 62.63 63.64 68.69 57.58 58.59 +63.13 +Pyramid-Edit Wan-Edit 18.18 54.55 57.58 15.15 19.19 43.43 45.45 17.17 36.36 +31.31 +Table 14. Edit5: Comparison of diffusion- and flow-based video editing methods for object addition on the FiVE benchmark. +Methods Structure Dist.×103 ↓ Background Preservation PSNR↑ LPIPS×103 ↓ MSE×104 ↓ SSIM×102 ↑ Text Alignment CLIPS.↑ CLIPS.edit ↑ IQA NIQE↓ Temp. Consis. +Motion Fidelity S.×102 ↑ +Source Videos 0.00 ∞ 0.00 0.00 100.00 23.52 19.58 5.58 97.86 +DMs +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 36.76 93.29 22.31 55.00 18.03 18.55 295.59 152.12 67.04 15.82 413.62 275.22 47.90 20.55 275.19 93.10 64.19 16.68 328.01 249.76 48.49 26.42 208.18 27.36 74.44 25.32 21.07 25.14 20.85 24.38 19.73 25.01 20.40 22.30 18.52 3.25 5.14 4.31 4.10 4.10 96.71 +91.70 +97.13 +62.76 +98.36 +RFs +(Ours) +Pyramid-Edit Wan-Edit 29.24 23.04 20.33 293.97 100.99 65.23 20.70 139.79 93.43 73.55 24.83 20.25 25.09 21.32 5.39 5.84 89.90 +97.38 +Table 15. Edit6: Comparison of diffusion- and flow-based video editing methods for object removal on the FiVE benchmark. +Methods Structure Dist.×103 ↓ Background Preservation PSNR↑ LPIPS×103 ↓ MSE×104 ↓ SSIM×102 ↑ Text Alignment CLIPS.↑ CLIPS.edit ↑ IQA NIQE↓ Temp. Consis. +Motion Fidelity S.×102 ↑ +Source Videos 0.00 ∞ 0.00 0.00 100.00 24.91 21.06 6.79 92.63 +DMs +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 31.61 75.91 15.03 80.71 8.86 19.33 261.55 131.90 76.63 15.43 367.21 315.51 59.05 22.35 247.12 66.99 75.80 16.97 300.65 293.93 58.38 27.46 167.21 18.76 83.23 24.70 21.02 25.22 21.53 25.67 21.34 22.06 17.93 23.05 19.22 4.42 5.49 4.91 4.93 4.06 84.15 +77.76 +85.12 +54.07 +82.46 +RFs +(Ours) +Pyramid-Edit Wan-Edit 26.63 2.02 21.58 254.41 80.54 76.65 32.62 57.12 7.63 90.52 25.60 19.26 24.29 20.31 5.55 7.02 75.52 +84.50 +21 + +===== PAGE 22 ===== +Table 16. Edit5: Comparison of diffusion- and flow-based video +editing methods for object addition on the FiVE benchmark using +FiVE-Acc metrics. +Table 17. Edit6: Comparison of diffusion- and flow-based video +editing methods object removal on the FiVE benchmark using +FiVE-Acc metrics. +Method FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +Method FiVE-YN FiVE-MC FiVE-∪ FiVE-∩ FiVE-Acc↑ +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 22.22 44.44 44.44 22.22 44.44 77.78 77.78 44.44 22.22 33.33 44.44 11.11 55.56 55.56 66.67 44.44 22.22 33.33 33.33 22.22 33.33 +61.11 +27.78 +55.56 +27.78 +TokenFlow [9] DMT [54] VidToMe [22] AnyV2V [18] VideoGrain [53] 0.00 10.00 10.00 0.00 0.00 40.00 40.00 0.00 0.00 0.00 0.00 0.00 10.00 20.00 20.00 10.00 0.00 11.11 11.11 0.00 5.00 +20.00 +0.00 +15.00 +5.56 +Pyramid-Edit Wan-Edit 66.67 77.78 77.78 66.67 88.89 77.78 88.89 77.78 72.22 +83.33 +Pyramid-Edit Wan-Edit 0.00 20.00 20.00 0.00 0.00 0.00 0.00 0.00 10.00 +0.00 +22 + +===== PAGE 23 ===== +Edit1 Object (w/o non-rigid deform): Dog → Rabbit +Edit2 Object (w non-rigid deform): A young girl → A young alien +Edit3 Color: A gray dog → A pink dog +Edit4 Material: A wheelchair → A wooden wheelchair +Edit6 Remove: A young girl …, not accompanied by a gray dog walking alongside her. +Source video DMT VidToMe VideoGrain Pyramid-Edit Wan-Edit +TokenFlow +Figure 13. Editing results across five editing types and six high-performance comparison methods. +23 + +===== PAGE 24 ===== +Edit1 Object (w/o non-rigid deform): Bear → Panda +Edit2 Object (w non-rigid deform): Bear → Dinosaur +Edit3 Color: A bear → A purple bear +Edit4 Material: A bear → A bronze bear +Edit5 Add: A bear → A bear with cap +Source video DMT VidToMe VideoGrain Pyramid-Edit Wan-Edit +TokenFlow +Figure 14. Editing results across five editing types and six high-performance comparison methods. Wan-Edit is the only method that +succeeds in the object addition editing type. +24 + +===== PAGE 25 ===== +Edit1 Object (w/o non-rigid deform): A tennis player → A ultraman +Edit2 Object (w non-rigid deform): A tennis player → A robot +Edit3 Color: White shorts → Black shorts +Edit4 Material: A tennis player → A clay tennis player +Edit5 Add: A tennis player wearing a bright yellow fedora +TokenFlow +Source video DMT VidToMe VideoGrain Pyramid-Edit Wan-Edit +Figure 15. Editing results across five editing types and six high-performance comparison methods. +25 + +===== PAGE 26 ===== +Generated video: +A cyclist wearing a +helmet is pedaling +vigorously … +Edit1: +A skateboarder +Edit2: +A rollerblader +cyclist +Edit3: +Cardboard cyclist +Edit4: +A maroon cyclist +Edit6: +Not wearing a +helmet +Figure 16. A generated video (first row) along with Wan-Edit’s editing results across five editing types (rows 2-6). +26 diff --git a/benchmarks/edit/pdf/_extracted/ive-bench.meta.txt b/benchmarks/edit/pdf/_extracted/ive-bench.meta.txt new file mode 100644 index 0000000000000000000000000000000000000000..975339854269398125625c3ea8e4ace4acf5193b --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/ive-bench.meta.txt @@ -0,0 +1,3 @@ +title=IVEBench: Modern Benchmark Suite for Instruction-Guided Video Editing Assessment +author=Yinan Chen; Jiangning Zhang; Teng Hu; Yuxiang Zeng; Zhucun Xue; Qingdong He; Chengjie Wang; Yong Liu; Xiaobin Hu; Shuicheng Yan +pages=21 diff --git a/benchmarks/edit/pdf/_extracted/ive-bench.txt b/benchmarks/edit/pdf/_extracted/ive-bench.txt new file mode 100644 index 0000000000000000000000000000000000000000..82983b34939714d9beac7ba88b9a7677a93bec01 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/ive-bench.txt @@ -0,0 +1,1200 @@ +FILE: IVEBENCH- Modern Benchmark Suite for Instruction-Guided Video Editing Assessment.pdf +PAGES: 21 + + +===== PAGE 1 ===== +IVEBench +IVEBENCH: Modern Benchmark Suite for +Instruction-Guided Video Editing Assessment +Yinan Chen1 Jiangning Zhang1,2 Teng Hu3 Yuxiang Zeng4 Zhucun Xue1 +Qingdong He2 Chengjie Wang2,3 Yong Liu1 Xiaobin Hu2 Shuicheng Yan5 +1Zhejiang University 2Tencent Youtu Lab 3Shanghai Jiao Tong University +4University of Auckland 5National University of Singapore +arXiv:2510.11647v1 [cs.CV] 13 Oct 2025 +Instruction-guided video editing has emerged as a rapidly advancing research direction, offering new opportu- +nities for intuitive content transformation while also posing significant challenges for systematic evaluation. +Existing video editing benchmarks fail to support the evaluation of instruction-guided video editing adequately +and further suffer from limited source diversity, narrow task coverage and incomplete evaluation metrics. To +address the above limitations, we introduce IVEBench, a modern benchmark suite specifically designed for +instruction-guided video editing assessment. IVEBench comprises a diverse database of 600 high-quality +source videos, spanning seven semantic dimensions, and covering video lengths ranging from 32 to 1,024 +frames. It further includes 8 categories of editing tasks with 35 subcategories, whose prompts are generated and +refined through large language models and expert review. Crucially, IVEBench establishes a three-dimensional +evaluation protocol encompassing video quality, instruction compliance and video fidelity, integrating both +traditional metrics and multimodal large language model-based assessments. Extensive experiments demon- +strate the effectiveness of IVEBench in benchmarking state-of-the-art instruction-guided video editing methods, +showing its ability to provide comprehensive and human-aligned evaluation outcomes. +Date: October 13, 2025 +Correspondence: yinan.chen@zju.edu.cn +Code: https://github.com/RyanChenYN/IVEBench +Data: https://huggingface.co/datasets/Coraxor/IVEBench +Project: https://ryanchenyn.github.io/projects/IVEBench +1 Introduction +Video editing, which aims to transform source videos to satisfy user-specified editing requirements, has emerged as +a crucial capability in both creative industries and practical applications. As the field of generative modeling and +multimodal understanding advances [1, 2], Instruction-guided Video Editing (abbreviated as IVE that edits are directed +by natural language instruction) has attracted significant research interest [3]. This paradigm promises intuitive and fine- +grained control over video content, unlocking new possibilities for content creation, entertainment, and human-computer +interaction. +Despite rapid progress, current video editing benchmarks still present notable limitations. Existing benchmarks [4] suffer +from three major challenges: i) Insufficient diversity in video sources: The coverage of semantic categories, scenes, +and editing instructions remains limited, constraining the generalizability of evaluation results [5, 6]. ii) Restricted +editing prompts: Editing instructions are often narrowly defined or lack granularity, failing to reflect the diverse +and complex requirements of real-world editing scenarios [7]. iii) Fragile evaluation metrics: Current evaluation +protocols are frequently restricted to basic quality or alignment measures, lacking a comprehensive, multidimensional +assessment, especially those leveraging advances in Multimodal Large Language Models (MLLMs) for semantic +understanding [4, 5]. Besides, existing benchmarks are primarily designed for video editing methods based on source- +target prompts. However, due to their poor user-friendliness and unclear editing requirements, mainstream video editing +1 + +===== PAGE 2 ===== +IVEBench +IVEBench Database +IVE Models +Subject +Theme +VE-Bench EditBoard +IVEBench (Ours) +Style Editing +Subject Editing +Attribute Editing +Quantity Editing +Motion +Perspective +Time +Subject Motion +Editing +Visual Effect +Editing +Emotion +600Videos +Scene +Camera Motion +Camera Angle +Editing +Editing +7Dimensions 8Editing Tasks +600Prompts +Source +Video +Edit Prompt +Target +Video +IVEBench Metrics +Video Quality +5 Metrics +Instruction +Compliance +4 Metrics +Video Fidelity +3 Metrics +Figure 1. Overview of our proposed IVEBench. 1) We construct a diverse video corpus consisting of 600 high-quality source +videos systematically organized across 7 semantic dimensions. 2) For source videos, we design carefully crafted edit prompts, +covering 8 major editing task categories with 35 subcategories. 3) We establish a comprehensive three-dimensional evaluation +protocol comprising 12 metrics, enabling human-aligned benchmarking of state-of-the-art IVE methods. +methods have now shifted toward instruction-guided approaches [3], mirroring a similar trend in image editing [8]. +Therefore, there is an urgent need for a comprehensive benchmark that fully supports IVE. +In this paper, we propose a modern benchmark suite termed IVEBench for IVE assessment, which tackles the +aforementioned challenges through three key innovations: 1) Diverse video corpus: We construct a highly diverse +dataset of 600 source videos, systematically collected and filtered to cover a wide range of topics across 7 semantic +dimensions (see Fig. 1). 2) Comprehensive editing prompts: Editing tasks are designed to cover 8 categories, with +prompts generated and refined via Large Language Models (LLMs) and expert review. 3) Robust evaluation metrics: +We introduce a three-dimensional evaluation protocol encompassing video quality, instruction compliance, and video +fidelity, incorporating both traditional metrics and MLLM-based assessments for richer, more objective evaluation. +We systematically demonstrate that our evaluation suite exhibits a high degree of alignment with human perception +across all metrics. Through both qualitative and quantitative analyses of mainstream IVE methods, we provide valuable +insights for the field of video editing. We will open-source the code, release the dataset, and keep track of the latest IVE +methods. +2 Related Work +Instruction-guided video editing. In recent years, the rapid advancement of image editing technologies has laid +a solid foundation for video editing tasks. As the demand for understanding and generating higher-dimensional +content increases, research focus has gradually shifted from static image editing to dynamic video editing [9]. Early +video editing methods are initially influenced by inversion techniques in the image editing domain (mainly DDIM +Inversion [10]), leading to the development of numerous source-target prompt-based editing approaches [11, 12, 13]. +Although these approaches can accurately preserve object locations and poses during the inversion process [14, 15, 16], +they are inherently limited when it comes to editing tasks involving subject movement or camera motion [17, 18]. +Furthermore, rather than providing detailed target prompts, users tend to express their editing requirements through +instructions [3]. Given these limitations, IVE methods have gained burgeoning attention in the industry due to their +greater user-friendliness and adaptability to diverse editing needs [3]. Mainstream approaches typically combine +InstructPix2Pix [8] for first-frame editing and then leverage generative models to propagate the modifications across +the entire video [19, 20, 21]. In contrast to these paradigms, InsV2V [3] retrains the model on synthetic triplets of +input video, editing instruction, and target video, enabling direct learning of instruction-driven video modification for +2 + +===== PAGE 3 ===== +IVEBench +consistent long video editing. Building on this, InsViE-1M [22] further adopts multi-stage training on CogVideoX-2B [1] +and supports static video editing tasks involving camera motion. +Video editing benchmarks. With the introduction of benchmarks such as VBench [23] and T2V-CompBench [24], +the evaluation systems in the field of video generation have become increasingly comprehensive. Concurrently, video +editing has also garnered significant attention, leading to the recent emergence of dedicated benchmarks for text-driven +video editing. Among them, VE-Bench [4] and EditBoard [5] introduce dedicated datasets and evaluation systems +for text-driven video editing, partially covering editing tasks of subject, style and attribute editing. Building on these +foundations, FiVE [6] and TDVE-Assessor [7] further push evaluation by proposing MLLM-based metrics that enhance +the objectivity of evaluation. However, a significant limitation of these existing benchmarks is that they are designed to +support source-target prompt-based editing methods, while offering no or only partial support for IVE methods [4, 5]. +Furthermore, these benchmarks are constrained by limited dataset sizes, narrow content coverage, and include only a +small subset of editing task types [6, 7]. To address these issues, we propose IVEBench, a thorough benchmark suite +specifically designed for IVE methods. +3 IVEBENCH Database +3.1 Diverse Video Collection for IVE +Video data source. To ensure the comprehensiveness of our benchmark for video editing evaluation, we first expand +the semantic coverage of source videos. Specifically, we define seven semantic dimensions and further subdivide each +dimension into multiple fine-grained topics, resulting in a total of 30 topics. These subdivisions form a diverse set of +semantic requirements for source videos, as illustrated in Fig. 3 (b). Based on these requirements, we manually collect +high-quality video samples (≥2K) on Pexels [25] and Mixkit [26], as well as some from open-source UltraVideo [27]. +In addition, we incorporate a subset from OpenHumanVid [28] dataset to further enhance the quantity and diversity of +human-centric videos (see Fig. 2). +Hybrid automated and manual filtering. All candidate videos undergo a two-stage processing pipeline. In the +automatic preprocessing stage, black borders, subtitles, and low-quality content are removed. Subsequently, during the +manual screening stage, we further ensure that the video content is suitable for editing and capable of covering a wide +spectrum of tasks ranging from simple to complex. Ultimately, we construct a source video dataset comprising 600 +videos with comprehensive semantic coverage, high resolution, and varied frame lengths. The dataset is organized into +two subsets according to frame count: i) the short subset contains 400 videos ranging from 32 to 128 frames. ii) the +long subset includes 200 videos ranging from 129 to 1,024 frames, representing a higher standard for long-sequence +evaluation. +Structural video caption. After obtaining the high-quality source videos, we employ Qwen2.5-VL-72B [2] to generate +captions of appropriate length for each video, capturing key aspects such as subjects, backgrounds, subject actions, +emotional atmosphere, visual styles, as well as camera perspectives and movements. These annotated attributes +are designed to form a structured vocabulary of editable elements, establishing a robust foundation for subsequent +user-driven modification requests. +3.2 Comprehensive IVE Prompt Generation +Diversified editing objectives. To ensure comprehensive coverage of task types in our benchmark for video editing +evaluation, we categorize the editing prompts into eight major classes. Each of these main categories is further +subdivided into more fine-grained subcategories, resulting in a total of 35 subcategories, as illustrated in Fig. 3 (a). +3 + +===== PAGE 4 ===== +IVEBench +Part Ⅰ Diverse Video Collection +Dimensions +Subject +Scene +Emotion +Motion +Theme +Perspective +Time +Manual filtering +720P +High Quality Video Source +Pexels +4K/2K +Mixkit +4K/2K +UltraVideo +8K/4K +OpenHumanVid +Source Videos…… +The video showcases the majestic Arch of Peace in Milan, Italy, +under a clear blue sky. The arch is a grand structure with intricate +carvings and statues, surrounded by a well-maintained green lawn. +The scene is … +High Quality Video Caption (Source Prompts) MLLM +Part Ⅱ Comprehensive Editing Prompt +Source Videos +Source Prompts +Diversified Editing Tasks LLM +Manual correction +Style Editing +Subject Editing +Attribute Editing +Quantity Editing +Subject Motion +Editing +Visual Effect +Editing +Camera Motion +Editing +Camera Angle +Editing +Edit prompt: Add a flock of birds flying above the +Arch of Peace +Target prompt: The video showcases the +majestic Arch of Peace in Milan, Italy, under a +clear blue sky. The arch is a grand structure with +intricate carvings and statues, surrounded by a +well-maintained green lawn. There is a flock of +birds flying above the arch. The scene is… +Target phrase +Target span +Figure 2. Data acquisition and processing pipeline of IVEBench includes: 1) Curation process to 600 high-quality diverse videos. 2) +Well-designed pipeline for comprehensive editing prompts. +Together, these eight categories encompass the full range of current requirements for IVE tasks and effectively address +the limitations of existing benchmarks in terms of task coverage. +LLM-assisted prompt generation and selection. For each source video, we employ Doubao-1.5-pro [29], together +with previously obtained detailed captions, to automatically select the most suitable editing category and generate a +corresponding editing prompt. In addition, the system simultaneously produces the associated target prompt and target +phrase, which serve as references for subsequent evaluation metrics. This design ensures that our benchmark can also +accommodate text-driven video editing methods. All editing categories and prompts are further manually reviewed and +refined to guarantee balanced category distribution as well as clear and reasonable prompts. +4 Comprehensive Metrics of IVEBENCH +In the context of IVE tasks, we define a video editing instance as comprising three data elements: the source video, the +edit prompt (i.e., the editing instruction expressed in natural language), and the target video. Based on the relationships +among these elements, we evaluate the target video along three dimensions: 1) Video Quality focuses on the quality of +the target video itself; 2) Instruction Compliance focuses on the alignment between the edit prompt and the target +video; 3) Fidelity focuses on the consistency between the source video and the target video. Notably, the dimensions of +Video Quality and Instruction Compliance are also applicable as evaluation criteria in video generation tasks, whereas +Fidelity is a dimension specific to video editing. +4.1 Video Quality +Since a video is essentially composed of a sequence of image frames arranged in chronological order, video quality can +be subdivided into two aspects: temporal quality and spatial quality. Temporal quality focuses on the consistency and +continuity between consecutive video frames, while spatial quality emphasizes aspects such as aesthetic value, image +sharpness and the naturalness of the content. +Subject Consistency (SC). For the subjects in a video, we assess whether their appearance remains consistent +throughout the sequence by computing the cross-frame similarity of DINO [30] feature, which serves to evaluate +different models’ capability in maintaining subject consistency. +Background Consistency (BC). For the video’s overall background, we evaluate the temporal consistency of the +background scene by computing the cross-frame similarity of the CLIP [31] feature. +4 + +===== PAGE 5 ===== +IVEBench +(a) Edit Prompt Distribution +17 +Short +8K +4K +2K +720P +Long +8 +8K +e +4K +2K +720P +32 +128 +(c) Video Frames Distribution +(d) Video Resolution Distribution +(b) Video Topic Distribution (e) Edit Prompt Word Length +Figure 3. Statistical distributions of IVEBench. +(f) Edit Prompt Word Cloud +Temporal Flickering (TF). We observe that videos produced by many editing models exhibit temporal flickering. +Accordingly, we quantify temporal flicker by sampling frames and computing the mean absolute difference across +frames. +Motion Smoothness (MS). Motion smoothness is utilized to evaluate the continuity and naturalness of subject or camera +movements. Under normal circumstances, a video should be free from jitter and unnatural acceleration variations. We +adopt the motion priors from the video frame interpolation model [32] to assess the smoothness of motion in the edited +videos. +Video Training Suitability Score (VTSS) [33] is the output of a supervised model trained on human-annotated data. +It integrates indicators such as compositional coherence, aesthetic quality, image sharpness, color saturation, content +naturalness, and motion stability, thereby enabling a comprehensive assessment of a video’s spatial quality. +4.2 Instruction Compliance +Instruction compliance is used to evaluate whether the generated target video correctly fulfills the requirements specified +in the editing prompt, and whether it is semantically aligned with the target prompt. In addition to general metrics and +task-specific criteria for different editing tasks, we further employ MLLM to assist in assessing the semantic consistency +between the video content and the editing instructions, thereby enhancing the comprehensiveness and objectivity of the +evaluation. +Overall Semantic Consistency (OSC). Global semantic consistency is used to holistically evaluate the semantic +correspondence between the target video’s content and the instruction’s intent, with an emphasis on the overall scene. +Therefore, we employ VideoCLIP-XL2 [34] to compute the semantic similarity between the target video and the target +prompt. +5 + +===== PAGE 6 ===== +IVEBench +Phrase Semantic Consistency (PSC). Phrase-level editing adherence is used to assess whether the specific phrases or +operations in the instruction are accurately reflected in the target video, with greater emphasis on the edited subject. +Accordingly, we employ VideoCLIP-XL2 [34] to compute the semantic similarity between the target video and the +target phrase. +Instruction Satisfaction (IS). Since tasks such as subject motion editing, camera motion editing and camera angle +editing are difficult to evaluate accurately using traditional methods, we employ Qwen2.5-VL [2] to assist in determining +whether the target video has faithfully executed the edit prompt. Specifically, we input both the edit prompt and the +target video into the model, instructing it to assign a score on a five-point scale to indicate the accuracy of execution. +Furthermore, we provide detailed descriptions for each score level to ensure that the model maintains consistent +evaluation criteria across multiple rounds of assessment. +Quantity Accuracy (QA). Quantity correctness is a metric specifically designed for quality editing tasks. This metric +uses the target span as input to Grounding DINO [35], compares the number of detected bounding boxes with the +quantity specified in the edit prompt, and assigns a score of 1 for correctness and 0 for incorrectness. +4.3 Video Fidelity +Fidelity is utilized to assess whether the target video retains the unedited portions of the source video, thereby ensuring +that the editing process does not introduce irrelevant alterations. In addition to devising conventional metrics from the +perspectives of motion and semantics, we further leverage MLLM to assess the content fidelity of the target video, +enhancing the robustness of the metric on more challenging tasks. +Semantic Fidelity (SF). To quantify the degree of semantic preservation in the target video, we employ VideoCLIP-XL2 [34] +to compute the feature similarity between the source and target videos. +Motion Fidelity (MF). Existing video motion detection often relies on optical flow, but it struggles with occlusions. +Therefore, we employ Cotracker3 [36], which is capable of handling occlusions, for extracting reliable motion +trajectories. The details of the trajectory similarity computation are provided in Sec. B. +Content Fidelity (CF). For tasks such as camera movement editing, camera angle editing and transition editing, the +same subject may display different orientations due to variations in perspective, which makes it difficult for traditional +metrics to adequately capture content preservation. To address this limitation, we use Qwen2.5-VL [2] to assist in +evaluating whether the target video correctly retains those elements that should remain unedited. Specifically, we input +the source prompt, the edit prompt, and the target video into the model, instructing it to assign a score on a five-point +scale reflecting the fidelity of the unedited content. In addition, we provide detailed descriptions for each score level to +ensure that the model adheres to consistent evaluation standards across multiple rounds of assessment. +4.4 Human Alignment for Benchmark Validation +We select three video editing models {A, B, C}and provide ten source videos with corresponding editing instructions. +For a given source video vi and its editing instruction pi, each selected video editing model produces an edited video, +resulting in a set Gi = {V i,A, V i,B, V i,C }. Within each set, the generated videos are compared in pairs, yielding C2 +3 = 3 +pairwise comparisons. For each evaluation dimension, we prepare detailed guidelines and illustrative examples, and +participants receive prior training to ensure a clear understanding of the dimension definitions. In every pairwise +comparison, human annotators are instructed to evaluate the videos exclusively with respect to the specified metric +(see Fig. 4), and to subjectively judge which video performs better in that dimension, or to mark the pair as "hard to +distinguish." We recruit 30 participants to conduct the human annotation. The conclusions of this experiment will be +6 + +===== PAGE 7 ===== +IVEBench +Table 1. Attributes comparison with open-source video editing benchmarks. Our proposed IVEBench boasts distinct advantages +across various key dimensions. +Method Video Collection Prompt Type Evaluation Metrics Year +Video +Count +Prompt +Count +Quantity +Editing +Subject Motion +Camera Editing +Editing +(Motion and Angle) +Visual Effect +Editing +Instruction +Compliance +Video +Fidelity MLLM +VE-Bench 169 148 ✘ ✘ ✘ ✘ ✔ ✔ ✘ 2025 +EditBoard 40 80 ✘ ✘ ✘ ✘ ✔ ✔ ✘ 2025 +VACE-Benchmark 240 480 ✘ ✔ ✘ ✘ ✔ ✔ ✘ 2025 +FiVE 100 420 ✘ ✘ ✘ ✘ ✔ ✔ ✔ 2025 +TDVE-Assessor 180 340 ✘ ✔ ✘ ✘ ✔ ✔ ✔ 2025 +IVEBench 600 600 ✔ ✔ ✔ ✔ ✔ ✔ ✔ 2025 +presented in Sec. 6.2, with further details provided in Sec. F. +4.5 Unified Scoring for Benchmark Assessment +Each evaluation dimension comprises multiple metrics. To assess their relative importance, trained annotators rate the +contribution of each metric and dimension. The average ratings are rounded to the nearest integer and used as weights +in the scoring formulas. Detailed formulas for dimensions and total score are provided in Sec. C. +5 Discussion with Recent Video Editing Benchmarks +Existing video editing benchmarks are primarily designed for source-target prompt-based methods, and they either fail +to support or can only minimally accommodate IVE methods [6]. As summarized in Tab. 1, these benchmarks exhibit +clear limitations in dataset scale and coverage. More critically, their prompt design largely remains confined to image +editing types (subject editing, attribute editing, or style editing) without dedicated task formulations that address the +temporal nature of video. In contrast, IVEBench provides a comprehensive and instruction-centered evaluation suite that +introduces three substantial advances: 1) A large-scale dataset of 600 videos, covering 35 topics across 7 dimensions, +with lengths ranging from 32 to 1024 frames, organized into short and long subsets to enhance source diversity and +semantic coverage. 2) Full coverage of eight major categories and thirty-five subcategories of editing tasks, including +those that explicitly leverage the unique properties of video, spanning different levels of granularity as well as tasks +involving both single and multiple subjects. 3) MLLM-based metrics specifically designed for Instruction Compliance +and Video Fidelity, coupled with human-annotated weightings and dimensions scoring formulas. These innovations +enable IVEBench to surpass existing benchmarks in video collection, task coverage, and evaluation methodology, +thereby establishing a systematic and practically relevant standard for IVE. +6 Benchmarking Video Editing Method in IVEBench +6.1 Experimental Setup +We evaluate state-of-the-art IVE models InsV2V [3], AnyV2V [20] and StableV2V [21], as well as the multi-conditional +video editing model VACE [37] using IVEBench, all employed with their official implementations and pretrained +weights. Evaluations are conducted on the IVEBench Database. Model-specific configurations, hardware requirements, +treatment of failure cases, and evaluation details are described in Sec. D. +7 + +===== PAGE 8 ===== +IVEBench +Table 2. Performance comparison of different video editing methods on our benchmark.Higher values indicate better +performance. † denotes that certain high-frame videos fail during inference due to out-of-memory issues. ‡ denotes that the method +has a fixed maximum frame number, which is lower than the maximum length of the source videos. +Dimension Performance Metric Performance +Database Method +Total +Score +Video +Quality +Instruction +Compliance +Video +Fidelity SC BC TF MS VTSS OSC PSC IS QA SF MF CF +Short +InsV2V AnyV2V 0.89 StableV2V VACE‡ 0.67 0.80 0.39 0.82 0.58 0.73 0.42 0.59 0.51 0.69 0.43 0.41 0.63 0.80 0.25 0.83 0.94 0.96 0.97 0.97 0.045 0.24 0.23 3.10 0.30 0.95 0.86 4.05 +0.89 0.94 0.97 0.97 0.026 0.22 0.24 3.33 0.30 0.80 0.82 2.75 +0.85 0.92 0.96 0.96 0.019 0.20 0.24 3.56 0.20 0.70 0.75 1.79 +0.95 0.98 0.98 0.98 0.045 0.23 0.22 2.16 0.20 0.97 0.89 4.03 +Long +InsV2V AnyV2V† StableV2VE† VACE‡ 0.66 0.80 0.37 0.79 0.55 0.72 0.36 0.57 0.51 0.69 0.42 0.41 0.62 0.80 0.27 0.78 0.90 0.94 0.98 0.98 0.048 0.24 0.23 3.10 0.20 0.95 0.68 4.13 +0.84 0.92 0.97 0.97 0.029 0.22 0.23 3.25 0.00 0.80 0.82 2.65 +0.83 0.91 0.96 0.96 0.021 0.23 0.23 3.45 0.25 0.70 0.77 1.79 +0.92 0.95 0.96 0.96 0.048 0.24 0.22 2.27 0.20 0.96 0.96 3.74 +Motion +Smoothness +Motion +Smoothness +VTSS +Background +Consistency +VTSS +Background +Consistency +Quantity +Accuracy +Motion +Fidelity +AnyV2V +StableV2V +Quantity +Accuracy +Motion +Fidelity +Semantic +Fidelity +(a) Metric Score in Short Subset InsV2V +VACE +Semantic +Fidelity +(b) Metric Score in Long Subset +(c) Dimension Score in Short Subset (d) Dimension Score in Long Subset +Figure 4. IVEBench Evaluation Results of Video Editing Models. We visualize the evaluation results of four IVE models in 12 +IVEBench metrics. We normalize the results per dimension for clearer comparisons. For comprehensive numerical results, please +refer to Tab. 2. +6.2 Benchmarking State-of-The-Art Methods on IVEBench +This section reports the quantitative and qualitative benchmarking results of state-of-the-art instruction-guided video +editing methods on IVEBench, and further presents human alignment results to validate the effectiveness of metrics. +8 + +===== PAGE 9 ===== +IVEBench +Camera Angle +High angle +Change the view to a +high angle. +Subject +Replace subject +Replace the water +bottle in the scene +with a newspaper. +Style +Low-poly +Convert the video to a +low-poly style +Subject Motion +Multi subject motion +Make the parents and +five children clap their +hands. +Category +Subcategory Edit Prompt +Source Video +InsV2V AnyV2V +StableV2V VACE +Figure 5. Qualitative comparison of state-of-the-art IVE methods. +Table 3. Inference efficiency and resolution. +Database Method Time per +Frame↓ +Max +Memory↓ +Video +Resolution +Short +InsV2V AnyV2V StableV2V VACE‡ 3.96s 12.81GB 11.66s 27.37GB 3.90s 28.31GB 27.03s 122.18GB 512×512 +512×512 +512×512 +1280×720 +Quantitative analysis. From the numerical results +in Tab. 2 and Tab. 3 as well as the visualizations in Fig. 4, +it can be observed that four evaluated methods demon- +strate relatively good frame-to-frame consistency. How- +ever, the per-frame image quality remains unsatisfactory, +which consequently leads to low Video Fidelity scores. +Moreover, these methods achieve very limited perfor- +mance in instruction adherence, primarily due to the +narrow range of task types they support. Among them, +StableV2V exhibits the best performance in both instruc- +tion adherence and editing speed. InsV2V demonstrates +the best overall performance in terms of editing capabil- +ity and inference efficiency. Nevertheless, these models +achieve a Total Score of no more than 0.7 and an Instruction Compliance score of no more than 0.45, indicating that +existing IVE methods still have substantial room for improvement in overall editing capability, particularly in Instruction +Compliance. +Long +InsV2V AnyV2V† StableV2V† VACE‡ 4.05s 13.48GB 11.47s 63.15GB 3.72s 49.82GB 51.00s 132.90GB 512×512 +512×512 +512×512 +1280×720 +Qualitative analysis. As illustrated in Fig. 5, the outputs of different models reveal consistent weaknesses across +multiple editing scenarios. First, all models tend to introduce inaccurate localization of the desired edit, leading to visible +artifacts such as geometric distortion, semantic bleeding, semantic collapsing, boundary blurring, and texture flickering. +These artifacts significantly compromise the per-frame visual quality of edited videos, which in turn diminishes their +overall fidelity. Second, when observing more challenging editing types, such as subject motion editing and camera +angle editing, we find that the editing capability of current models is particularly limited, underscoring an urgent need +for broader task coverage in future development. Moreover, the models show distinct behavioral patterns: StableV2V +often applies overly aggressive modifications that satisfy the editing prompt but neglect the preservation of unedited +content; InsV2V, in contrast, tends to adopt a conservative strategy, retaining much of the source content when dealing +with unfamiliar instructions; while VACE, not being a native IVE model, frequently fails to properly execute the given +edits, resulting in weak compliance with the prompts. These qualitative findings highlight that improving per-frame +image fidelity and expanding editing versatility are essential directions for advancing IVE models. More detailed +qualitative comparisons and analyses can be found in Sec. E. +Human alignment results. To validate that our evaluation metrics align with human perception, as described in Sec. 4.4, +9 + +===== PAGE 10 ===== +IVEBench +Table 4. Spearman’s Rho (ρ) across different metrics. These scores show that IVEBench metrics are highly aligned with human +judgments. +Video Quality Instruction Compliance Video Fidelity +SC BC TF MS VTSS OSC PSC IS QA SF MF CF +ρ 0.9583 0.9442 0.8907 0.9763 0.9982 0.7105 0.8465 0.9859 0.8216 0.9400 0.9373 0.9896 +we conduct human annotations for each metric. In pairwise model comparisons, the preferred model is assigned a score +of 1, while the other receives 0. If annotators express no preference, both models are assigned 0.5. For each metric, a +model’s final human score is computed as the total score divided by the number of comparisons. We then calculate +Spearman’s rank correlation coefficient between these human scores and the automatic evaluation metric scores. The +results in Tab. 4 demonstrate that our proposed evaluation metrics exhibit a high degree of consistency with human +preferences. +6.3 Insights and discussions +High frame-to-frame consistency, weak single-frame quality. Across models, frame-to-frame consistency is generally +well preserved, with limited temporal flickering. However, the quality of individual frames often shows frequent visible +artifacts such as semantic bleeding, boundary blurring and texture flickering. These issues also lead to a noticeable +degradation in Video Fidelity, highlighting the necessity for future work to develop effective strategies to mitigate such +artifacts. +Limited support for diverse editing prompt types. Models perform poorly in the Compliance dimension mainly +because they only handle a few basic editing types reasonably well, namely subject editing, style editing and attribution +editing. In contrast, they lack the capacity to execute more advanced editing types such as quantity editing, subject +motion editing, visual effect editing, camera motion editing and camera angle editing. This leads to consistently low +scores across all compliance-related metrics. Future video editing models should therefore place greater emphasis on +broadening the range of supported editing prompts. +Intrinsic limitations of first-frame-based editing models. Video editing, unlike image editing, requires maintaining +temporal coherence, which introduces the need to modify middle or later frames of a video. For example, to handle +transitions or to insert intermediate events. These tasks do not originate from modifications in the initial frames but +instead focus on transformations that occur later in the sequence. First-frame-based models, however, propagate changes +from the beginning throughout the entire video, making them inadequate for such editing requirements. +Scalability to long video sequences. A critical challenge in IVE lies in handling long sequences with hundreds or even +thousands of frames. Most existing methods, especially those relying on frame-wise diffusion or first-frame propagation, +exhibit a near-linear growth in GPU memory consumption and latency as sequence length increases, making them +impractical for videos beyond 128 frames. In contrast, InsV2V demonstrates superior scalability by adopting a chunked +inference strategy with latent overlap, where only a limited set of reference frames is preserved across segments. This +design effectively constrains memory growth while maintaining temporal continuity. +Resolution limitations. Existing IVE methods, including InsV2V, AnyV2V and StableV2V, typically operate at +512×512 resolution, which is far below the standard of real-world user content. The multi-conditional video editing +model VACE can support 720P outputs; however, this still falls short of the practical demand, as user videos are +commonly recorded in 1080P or higher resolutions, and the expectation is that edited outputs should preserve this level +of detail. The low-resolution setting limits visual fidelity, which results in artifacts such as blurred textures and edge +degradation, and also reduces usability in professional media workflows. +10 + +===== PAGE 11 ===== +IVEBench +7 Conclusion +With the rapid progress of IVE, how to systematically and comprehensively evaluate these methods has become a central +challenge in the field. Existing benchmarks exhibit clear limitations in terms of video source diversity, task coverage, +and evaluation dimensions, making them insufficient to reliably reflect the true capabilities of current approaches or +to provide meaningful guidance for subsequent research. To address these issues, we propose IVEBench, a modern +benchmarking suite designed for IVE models. IVEBench integrates a large-scale and diverse dataset, a broad range +of editing tasks, and a multi-dimensional evaluation protocol that leverages MLLMs and aligns closely with human +perception. We expect IVEBench to play a key role in the evaluation of video editing models and in advancing the +development of the field. +References +[1] Zhuoyi Yang, Jiayan Teng, Wendi Zheng, Ming Ding, Shiyu Huang, Jiazheng Xu, Yuanming Yang, Wenyi Hong, +Xiaohan Zhang, Guanyu Feng, et al. Cogvideox: Text-to-video diffusion models with an expert transformer. arXiv +preprint arXiv:2408.06072, 2024. +[2] Shuai Bai, Keqin Chen, Xuejing Liu, Jialin Wang, Wenbin Ge, Sibo Song, Kai Dang, Peng Wang, Shijie Wang, +Jun Tang, et al. Qwen2. 5-vl technical report. arXiv preprint arXiv:2502.13923, 2025. +[3] Jiaxin Cheng, Tianjun Xiao, and Tong He. Consistent video-to-video transfer using synthetic dataset. arXiv +preprint arXiv:2311.00213, 2023. +[4] Shangkun Sun, Xiaoyu Liang, Songlin Fan, Wenxu Gao, and Wei Gao. Ve-bench: Subjective-aligned benchmark +suite for text-driven video editing quality assessment. In AAAI, 2025. +[5] Yupeng Chen, Penglin Chen, Xiaoyu Zhang, Yixian Huang, and Qian Xie. Editboard: Towards a comprehensive +evaluation benchmark for text-based video editing models. In AAAI, 2025. +[6] Minghan Li, Chenxi Xie, Yichen Wu, Lei Zhang, and Mengyu Wang. Five: A fine-grained video editing +benchmark for evaluating emerging diffusion and rectified flow models. arXiv preprint arXiv:2503.13684, 2025. +[7] Juntong Wang, Jiarui Wang, Huiyu Duan, Guangtao Zhai, and Xiongkuo Min. Tdve-assessor: Benchmarking and +evaluating the quality of text-driven video editing with lmms. arXiv preprint arXiv:2505.19535, 2025. +[8] Tim Brooks, Aleksander Holynski, and Alexei A Efros. Instructpix2pix: Learning to follow image editing +instructions. In CVPR, 2023. +[9] Jay Zhangjie Wu, Yixiao Ge, Xintao Wang, Stan Weixian Lei, Yuchao Gu, Yufei Shi, Wynne Hsu, Ying Shan, +Xiaohu Qie, and Mike Zheng Shou. Tune-a-video: One-shot tuning of image diffusion models for text-to-video +generation. In ICCV, 2023. +[10] Jiaming Song, Chenlin Meng, and Stefano Ermon. Denoising diffusion implicit models. In ICLR, 2021. +[11] Chenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, Xintao Wang, Ying Shan, and Qifeng Chen. Fatezero: +Fusing attentions for zero-shot text-based video editing. In ICCV, 2023. +[12] Duygu Ceylan, Chun-Hao P Huang, and Niloy J Mitra. Pix2video: Video editing using image diffusion. In ICCV, +2023. +[13] Xirui Li, Chao Ma, Xiaokang Yang, and Ming-Hsuan Yang. Vidtome: Video token merging for zero-shot video +editing. In CVPR, 2024. +[14] Michal Geyer, Omer Bar-Tal, Shai Bagon, and Tali Dekel. Tokenflow: Consistent diffusion features for consistent +video editing. arXiv preprint arXiv:2307.10373, 2023. +11 + +===== PAGE 12 ===== +IVEBench +[15] Hyeonho Jeong and Jong Chul Ye. Ground-a-video: Zero-shot grounded video editing using text-to-image +diffusion models. arXiv preprint arXiv:2310.01107, 2023. +[16] Yuren Cong, Mengmeng Xu, Christian Simon, Shoufa Chen, Jiawei Ren, Yanping Xie, Juan-Manuel Perez-Rua, +Bodo Rosenhahn, Tao Xiang, and Sen He. Flatten: optical flow-guided attention for consistent text-to-video +editing. arXiv preprint arXiv:2310.05922, 2023. +[17] Danah Yatim, Rafail Fridman, Omer Bar-Tal, Yoni Kasten, and Tali Dekel. Space-time diffusion features for +zero-shot text-driven motion transfer. In CVPR, 2024. +[18] Ozgur Kara, Bariscan Kurtkaya, Hidir Yesiltepe, James M Rehg, and Pinar Yanardag. Rave: Randomized noise +shuffling for fast and consistent video editing with diffusion models. In CVPR, 2024. +[19] Levon Khachatryan, Andranik Movsisyan, Vahram Tadevosyan, Roberto Henschel, Zhangyang Wang, Shant +Navasardyan, and Humphrey Shi. Text2video-zero: Text-to-image diffusion models are zero-shot video generators. +In ICCV, 2023. +[20] Max Ku, Cong Wei, Weiming Ren, Harry Yang, and Wenhu Chen. Anyv2v: A tuning-free framework for any +video-to-video editing tasks. arXiv preprint arXiv:2403.14468, 2024. +[21] Chang Liu, Rui Li, Kaidong Zhang, Yunwei Lan, and Dong Liu. Stablev2v: Stablizing shape consistency in +video-to-video editing. arXiv preprint arXiv:2411.11045, 2024. +[22] Yuhui Wu, Liyi Chen, Ruibin Li, Shihao Wang, Chenxi Xie, and Lei Zhang. Insvie-1m: Effective instruction-based +video editing with elaborate dataset construction. arXiv preprint arXiv:2503.20287, 2025. +[23] Ziqi Huang, Yinan He, Jiashuo Yu, Fan Zhang, Chenyang Si, Yuming Jiang, Yuanhan Zhang, Tianxing Wu, +Qingyang Jin, Nattapol Chanpaisit, et al. Vbench: Comprehensive benchmark suite for video generative models. +In CVPR, 2024. +[24] Kaiyue Sun, Kaiyi Huang, Xian Liu, Yue Wu, Zihan Xu, Zhenguo Li, and Xihui Liu. T2v-compbench: A +comprehensive benchmark for compositional text-to-video generation. In CVPR, 2025. +[25] Ingo, Bruno Joseph, and Daniel Frese. Pexels videos. https://www.pexels.com/videos/, 2014. +Accessed: 2025-04-06. +[26] Collis Ta’eed and Hichame Assi. Mixkit. https://mixkit.co/free-stock-video/, 2019. Accessed: +2025-04-06. +[27] Zhucun Xue, Jiangning Zhang, Teng Hu, Haoyang He, Yinan Chen, Yuxuan Cai, Yabiao Wang, Chengjie Wang, +Yong Liu, Xiangtai Li, et al. Ultravideo: High-quality uhd video dataset with comprehensive captions. arXiv +preprint arXiv:2506.13691, 2025. +[28] Hui Li, Mingwang Xu, Yun Zhan, Shan Mu, Jiaye Li, Kaihui Cheng, Yuxuan Chen, Tan Chen, Mao Ye, Jingdong +Wang, and Siyu Zhu. Openhumanvid: A large-scale high-quality dataset for enhancing human-centric video +generation. In CVPR, 2025. +[29] ByteDance Seed, Jiaze Chen, Tiantian Fan, Xin Liu, Lingjun Liu, Zhiqi Lin, Mingxuan Wang, Chengyi Wang, +Xiangpeng Wei, Wenyuan Xu, et al. Seed1. 5-thinking: Advancing superb reasoning models with reinforcement +learning. arXiv preprint arXiv:2504.13914, 2025. +[30] Mathilde Caron, Hugo Touvron, Ishan Misra, Hervé Jégou, Julien Mairal, Piotr Bojanowski, and Armand Joulin. +Emerging properties in self-supervised vision transformers. In ICCV, 2021. +[31] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, +Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual models from natural language +supervision. In ICML, 2021. +[32] Zhen Li, Zuo-Liang Zhu, Ling-Hao Han, Qibin Hou, Chun-Le Guo, and Ming-Ming Cheng. Amt: All-pairs +multi-field transforms for efficient frame interpolation. In CVPR, 2023. +12 + +===== PAGE 13 ===== +IVEBench +[33] Qiuheng Wang, Yukai Shi, Jiarong Ou, Rui Chen, Ke Lin, Jiahao Wang, Boyuan Jiang, Haotian Yang, Mingwu +Zheng, Xin Tao, Fei Yang, Pengfei Wan, and Di Zhang. Koala-36m: A large-scale video dataset improving +consistency between fine-grained conditions and video content. In CVPR, 2025. +[34] Jiapeng Wang, Chengyu Wang, Kunzhe Huang, Jun Huang, and Lianwen Jin. Videoclip-xl: Advancing long +description understanding for video CLIP models. In EMNLP, 2024. +[35] Shilong Liu, Zhaoyang Zeng, Tianhe Ren, Feng Li, Hao Zhang, Jie Yang, Qing Jiang, Chunyuan Li, Jianwei Yang, +Hang Su, Jun Zhu, and Lei Zhang. Grounding DINO: marrying DINO with grounded pre-training for open-set +object detection. In ECCV, 2024. +[36] Nikita Karaev, Iurii Makarov, Jianyuan Wang, Natalia Neverova, Andrea Vedaldi, and Christian Rupprecht. +Cotracker3: Simpler and better point tracking by pseudo-labelling real videos. arXiv preprint arXiv:2410.11831, +2024. +[37] Zeyinzi Jiang, Zhen Han, Chaojie Mao, Jingfeng Zhang, Yulin Pan, and Yu Liu. Vace: All-in-one video creation +and editing. arXiv preprint arXiv:2503.07598, 2025. +13 + +===== PAGE 14 ===== +IVEBench +Appendix +Overview +The supplementary material presents more comprehensive results of our IVEBench to facilitate the comparison of +subsequent benchmarks: +• Sec. A provides more detailed descriptions of edit prompt subcategories, accompanied by concrete examples. +• Sec. B provides the detailed procedure for computing motion fidelity score +• Sec. C provides the unified scoring formulation and detailed explanations of the weighting strategy across metrics +and dimensions +• Sec. D provides experimental details, including hardware configurations, dataset partitioning for evaluation, +model implementations and failed video IDs. +• Sec. E provides a detailed comparison of model performance. +• Sec. F provides human alignment details, including annotator guideline design and annotation interface, +• Sec. G provides information on the use of LLMs. +A Descriptions of Various Categories of Edit Prompts +In this section, we provide detailed descriptions of all 35 subcategories of editing prompts included in IVEBench. Each +subcategory is defined with its specific editing operation and supported by a representative example to illustrate how the +editing request is expressed. The purpose of this collection is to ensure clarity, reproducibility, and comprehensive cov- +erage of diverse instruction-guided video editing tasks. Tab. A1 summarizes the categories, subcategories, descriptions, +and corresponding examples for ease of reference. +Table A1. Description and example for each subcategory. We provide detailed descriptions of 35 subcategories along with +corresponding examples to facilitate understanding. +Category Subcategory Description Example +Style Editing watercolor Apply watercolor +painting style to video +Convert the video to a watercolor +style +Style Editing pixel Convert video to retro +pixel art style Convert the video to a pixel-style +Style Editing anime Render video in anime +style +Change the style of the video to +anime +Style Editing American +comic style +Apply American +comic book style +Transform the video into a Ameri- +can comic style +Style Editing ukiyo-e Render video in +Japanese ukiyo-e style Convert the video style to ukiyo-e +Style Editing black and +white +Convert video to +black-and-white tones Convert the video to black and white +14 + +===== PAGE 15 ===== +Category Style Editing Style Editing Style Editing Style Editing Style Editing Subject Edit- +ing +Subject Edit- +ing +Subject Edit- +ing +Attribute Edit- +ing +Attribute Edit- +ing +Attribute Edit- +ing +Subject Mo- +tion Editing +Subject Mo- +tion Editing +tion Editing Camera Mo- +tion Editing Camera Mo- +tion Editing Camera Mo- +tion Editing Camera Mo- +tion Editing Camera Mo- +tion Editing Camera Mo- +Camera Mo- +tion Editing Editing Camera Angle +Editing Camera Angle +Subcategory oil painting cyberpunk +Ghibli +low-poly +weather shift add new sub- +ject +remove exist- +ing subject +replace exist- +ing subject +color adjust- +ment +subject scal- +ing +position +change +single subject +motion +multiple sub- +ject motion +dolly in dolly out tracking boom up arc shot zoom in zoom out +high angle low angle Description Apply oil painting ef- +fect to video +Render video in neon +futuristic cyberpunk +style +Apply Studio Ghibli- +inspired animation +style +Convert video to sim- +plified low-poly visu- +als +Change weather condi- +tions in the video +Add a new subject into +the video +Remove a subject +from the video +Replace one subject +with another +Adjust colors of video +or subjects Resize a subject in the +video +Change subject posi- +tion in the scene +Animate or adjust one +subject’s motion +Animate or adjust mul- +tiple subjects’ motions +Simulate camera mov- +ing forward +Simulate camera mov- +ing backward +Simulate camera fol- +lowing a subject +Simulate camera mov- +ing upward +Simulate camera cir- +cling around a subject +Zoom in on the video +subject +Zoom out to show +more scene +View subject from a +high angle View subject from a +low angle 15 +IVEBench +Example +Transform the video into an oil paint- +ing style +Convert the video to a cyberpunk +style +Change the video style to Ghibli +style +Transform the video into a low-poly +style +Change the weather to a torrential +downpour +Add a heron standing among the +reeds +Remove the young child from the +video +Replace the grotesque creatures with +friendly fairy-like beings +Change the sky to a deep red color +Scale up the man dressed in ancient +Egyptian attire +Move the girl to the left side of the +stone steps +Make the man in the black leather +jacket stand up and stretch +Make the woman and the man cry +and wipe their tears with their hands +Move the camera closer to the man +in the black shirt +Gradually move the camera away +from the group of men +Track the movement of the red pow- +der as it falls into the bottle +Perform a boom up shot on the white +Toyota SUV driving up the dirt hill +Perform an arc shot around the tram +as it arrives at the station +Zoom in on the slice of yellow cake +being lifted +Gradually move the camera away to +the ancient temple +Change the view to a high angle +Change the view to a low angle + +===== PAGE 16 ===== +IVEBench +Category Subcategory Description Example +Editing Camera Angle +front view Show subject from the +front Change the view to a front view +Editing Camera Angle +side view Show subject from the +side Change the view to a side view +ing Quantity Edit- +increase Increase number of +subjects +Increase the number of A woman +with a tattoo to 2 +ing Quantity Edit- +decrease Decrease number of +subjects Decrease the number of flowers to 1 +Editing Visual Effect +transition Add transition be- +tween video contents +A particle effect transition, the man +wearing sunglasses and smiling +Visual Effect +Editing +decoration ef- +fect +Add decorative visual +overlays Add a flame effect to the metal file +Editing Visual Effect +event effect Add event-based ef- +fects +The man turns into sand and is +blown away +B Motion Fidelity Computation Details +We describe the computation of motion fidelity between a source video and a target video. Given a video sequence, +we sample query points on a uniform grid of size g. For each query point p, CoTracker3 [36] outputs a trajectory +xp = (xp +1 , xp +2 , . . . , xp +T ) with xp +t ∈R2, together with a visibility vector vp = (vp +1 , vp +2 , . . . , vp +T ) where vp +t ∈[0, 1] +indicates whether p is visible at frame t. To compare two videos of different lengths, all trajectories are interpolated to +a synchronized length T= min(T1, T2) using linear interpolation based on visible frames. +Given two synchronized tracks (˜ +xp, ˜ vp) and (˜ +yq +˜ +, +wq), we compute the frame-wise position distance +dpos +t = ∥˜ +xp +t− +˜ +yq +t ∥2, +and velocity distance +dvel +t = ∥(˜ +xp +t− +˜ +xp +t−1)−(˜ +yq +t− +˜ +yq +t−1)∥2 for t > 1, +with dvel +1 = dvel +2 . Both distances are normalized by the average spatial span of the tracks +α = +1 +2 ∥max +t +˜ +xp +t−min +˜ +xp +t ∥2 + ∥max +˜ +yq +t−min +˜ +yq +t +t +t +t ∥2 , +with α ≥10−6. We then define normalized distancesˆ +dpos +t = dpos +ˆ +t /α, +dvel +t = dvel +t /α and convert them into similarities +spos +t = 1/(1 +ˆ +dpos +t ), svel +t = 1/(1 +ˆ +dvel +t ). The frame-wise similarity is obtained by weighted combination +st = 0.7spos +t + 0.3svel +t , +and further weighted by visibility wt = min(˜ +vp +t , +˜ +wq +t ). The overall track similarity is +S(p, q) = +   +∑T +t=1 st wt +∑T +, if ∑t wt > 0, +t=1 wt +0, otherwise. +Let N1 and N2 be the numbers of valid tracks in the source and target videos. We construct a similarity matrix +M ∈RN1 ×N2 with Mij= S(pi, qj). To establish correspondence, we apply the Hungarian algorithm to maximize +16 + +===== PAGE 17 ===== +IVEBench +∑i Mi,π(i) with one-to-one mapping π. We discard pairs with Mi,π(i) ≤0.3 and compute the final motion fidelity +between videos V 1 and V 2 as +MF(V 1, V 2) = 1 +|P|∑ +Mi,π(i), +i∈P +where P= {i |Mi,π(i) > 0.3}is the set of valid correspondences. Finally, given K video pairs, the dataset-level +motion fidelity score is +1 +MF= +K +∑ +MF(V(k) +src , V(k) +tgt ). +k=1 +K +Here, T is the number of synchronized frames, xp +t ∈R2 is the 2D position of track p at time t, vp +t is its visibility, dpos +t +and dvel +t are frame-wise distances, st ∈[0, 1] is the frame-wise similarity, S(p, q) is the similarity of two tracks, Mij +the similarity matrix, and π the matching permutation given by the Hungarian algorithm. +C Unified Scoring Formulation and Details +For a given evaluation dimension D, let the set of metrics be {m1, m2, . . . , mnD }with corresponding weights +{w1, w2, . . . , wnD }. The score for dimension D is defined as: +SD = +∑nD +i=1 wi·mi +∑nD +i=1 wi +. +In our study, the three dimensions are computed as: +∑i∈Vwi·mi +Video Quality= +∑i∈Vwi +, +∑i∈Iwi·mi +Instruction Compliance= +∑i∈Iwi +∑i∈Fwi·mi +, +Video Fidelity= +∑i∈Fwi. +where V, I, and Fdenote the sets of metrics belonging to Video Quality, Instruction Compliance, and Video Fidelity, +respectively. The overall score is obtained by treating the three dimension scores as higher-level metrics. Let the set of +dimensions be D, with scores {Sj}and corresponding weights {αj}. The total score is given by: +∑j∈Dαj·Sj +Total Score= +∑j∈Dαj +. +Both metric-level weights wi and dimension-level weights αj are determined from the user study: each participant +provided importance ratings (0-5) for metrics and dimensions. The ratings were averaged across participants, rounded +to the nearest integer, and applied directly in the above formulas. According to the participants’ ratings, the weight of +VTSS is 5, the weights of IS and CF are 3, while the weights of other metrics are 1. Since the weights of the three +dimensions are all 4, they are normalized to 1. The resulting scores for different models are reported in Tab. 2. +17 + +===== PAGE 18 ===== +IVEBench +D Experiment Details +All experiments were performed on NVIDIA H20 GPUs: InsV2V, AnyV2V, and StableV2V were run on a single +GPU, while VACE required two GPUs for 720P inputs. Each model’s output video resolution followed its officially +recommended setting, and the number of generated frames was matched to the input sequence. When certain videos +could not be processed due to out-of-memory errors, the corresponding results were excluded, and the indices of these +failed videos are provided in Tab. A2. Moreover, due to VACE’s fixed maximum frame limit of 81 frames, source +videos exceeding this length were uniformly sampled to 81 frames specifically for VACE editing. Both short and long +subsets of the IVEBench Database were used to assess editing capability across video lengths. For each model and +subset, we also recorded the average runtime per frame and the peak GPU memory consumption. Evaluation was +carried out using the twelve indicators of IVEBench Metrics, organized into three dimensions, where indicator scores +were first computed per task, then averaged across videos, with irrelevant indicators omitted depending on the editing +type; finally, all scores were normalized before visualization. +Table A2. Failed video count and IDs of IVE methods. We present the methods that cause GPU memory usage to exceed the +capacity of a single H20 card due to excessively long frame sequences in certain videos. +Method Failed videos count Failed video IDs +AnyV2V 65 +long_0001, long_0004, long_0005, long_0007, long_0008, +long_0009, long_0010, long_0011, long_0013, long_0014, +long_0015, long_0016, long_0018, long_0020, long_0021, +long_0022, long_0023, long_0025, long_0028, long_0029, +long_0030, long_0031, long_0032, long_0033, long_0034, +long_0035, long_0037, long_0039, long_0042, long_0043, +long_0053, long_0055, long_0058, long_0059, long_0060, +long_0061, long_0064, long_0068, long_0070, long_0074, +long_0075, long_0082, long_0088, long_0091, long_0094, +long_0095, long_0096, long_0098, long_0100, long_0104, +long_0113, long_0114, long_0115, long_0117, long_0125, +long_0150, long_0152, long_0153, long_0155, long_0159, +long_0169, long_0179, long_0180, long_0186, long_0200 +StableV2V 102 +long_0001, long_0004, long_0005, long_0007, long_0008, +long_0009, long_0010, long_0011, long_0012, long_0013, +long_0014, long_0015, long_0016, long_0018, long_0020, +long_0021, long_0022, long_0023, long_0025, long_0028, +long_0029, long_0030, long_0031, long_0032, long_0033, +long_0034, long_0035, long_0036, long_0037, long_0038, +long_0039, long_0040, long_0041, long_0042, long_0043, +long_0044, long_0045, long_0047, long_0049, long_0053, +long_0055, long_0057, long_0058, long_0059, long_0060, +long_0061, long_0064, long_0067, long_0068, long_0070, +long_0071, long_0073, long_0074, long_0075, long_0077, +long_0079, long_0082, long_0083, long_0088, long_0089, +long_0091, long_0094, long_0095, long_0096, long_0097, +long_0098, long_0100, long_0102, long_0104, long_0106, +long_0108, long_0110, long_0111, long_0112, long_0113, +long_0114, long_0115, long_0117, long_0123, long_0124, +long_0125, long_0128, long_0130, long_0150, long_0152, +long_0155, long_0159, long_0160, long_0164, long_0168, +long_0169, long_0171, long_0173, long_0177, long_0179, +long_0180, long_0186, long_0188, long_0195, long_0197, +long_0198, long_0200 +18 + +===== PAGE 19 ===== +IVEBench +Subject +Replace subject +Replace the rocky beach with +a sandy beach +Camera Angle +Front View +Change the view to +a front view +Style +Anime +Change the style of the video +to anime +Subject Motion +Single subject motion +Make the static spider-man in the mural +dynamic and make him swing faster +Camera Motion +Dolly in +Move the camera closer to +the man in the black shirt +Quantity +Decrease +Decrease the number of +medieval knights to 1 +Convert the video to +a low-poly style +Visual Effect +Transition +After a wave-foam transition, the small +fishing boat is eaten by a giant whale. +Style +Anime +Transform the video into a +watercolor style +Convert the video to +a low-poly style +Source Video InsV2V StableV2V VACE +InsV2V StableV2V VACE +AnyV2V +Source Video +AnyV2V +Figure A1. Visualization of Model Output Comparison. We concatenate the first, middle, and last frames of the video to facilitate +comparison of the temporal performance across different models. +19 + +===== PAGE 20 ===== +IVEBench +E Detailed quantitative comparison and analysis +In this section, we provide a more detailed quantitative comparison of the evaluated models across different categories +of instruction-guided video editing. While the main results are summarized in Table 2 and Figure 4 of the main paper, +here we extend the analysis to highlight model behaviors under specific editing tasks and frame lengths. We further +complement the numerical results with Fig. A1, which illustrates representative editing scenarios by concatenating the +first, middle, and last frames of each generated video. This visualization helps reveal temporal dynamics and qualitative +differences that may not always be fully captured by scalar metrics. +Specifically, InsV2V demonstrates relatively balanced performance across most categories, maintaining higher semantic +fidelity and motion fidelity even in longer sequences. However, its conservative strategy sometimes leads to under- +editing, resulting in lower scores in instruction satisfaction. AnyV2V exhibits strong Instruction Compliance in simpler +style and attribute editing tasks, yet struggles under difficult editing tasks. The aggressive editing strategy of stableV2V +leads to a higher instruction satisfaction score, but visual inspections clearly show severe semantic bleeding and +boundary artifacts when dealing with complex prompts. Finally, VACE, though not originally designed for IVE, +achieves reasonable temporal smoothness and high resolution outputs; nevertheless, its restricted maximum frame +length limits its applicability, and its overall performance in instruction compliance remains unsatisfactory compared to +native IVE models. +Taken together, these detailed results and the examples in Fig. A1 confirm that current models, while capable of +maintaining frame-to-frame coherence, still fall short in faithfully executing diverse instructions and preserving high +per-frame fidelity. This underscores the necessity of IVEBench in identifying fine-grained weaknesses and providing +clear guidance for future methodological improvements. +F Human Alignment Details +To validate the alignment of IVEBench metrics, we first provided each annotator with a detailed explanation of the +meaning of each metric along with illustrative examples of good and poor cases, followed by additional case-based +tests to ensure that the annotators fully understood the intended interpretation of the metric. Moreover, we conducted +further tests to confirm that the annotators focused exclusively on the designated metric during comparisons, rather +than being influenced by the overall quality of the videos. For ease of experimentation, we designed a dedicated +annotation interface for human evaluators. The interface displays the source video, editing instruction, and the outputs +of different models for direct comparison under a specified evaluation dimension. Annotators are instructed to make +pairwise comparisons between outputs, choosing the video that better satisfies the designated metric or marking them +as indistinguishable when necessary. The design of the interface is illustrated in Fig. A2. +G The Use of Large Language Models +We use large language models solely for polishing our writing, and we have conducted a careful check, taking full +responsibility for all content in this work. +20 + +===== PAGE 21 ===== +IVEBench +Figure A2. Human Annotation Interface for Benchmark Validation. The interface presents the source video, the editing +instruction, and the outputs of different models under a specified evaluation dimension, enabling annotators to conduct pairwise +comparisons and judge which video better satisfies the given criterion. +21 diff --git a/benchmarks/edit/pdf/_extracted/sst-em.meta.txt b/benchmarks/edit/pdf/_extracted/sst-em.meta.txt new file mode 100644 index 0000000000000000000000000000000000000000..22c7d50f5819740fc78dd1edcf3d6bbd6d355863 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/sst-em.meta.txt @@ -0,0 +1,3 @@ +title= +author= +pages=10 diff --git a/benchmarks/edit/pdf/_extracted/sst-em.txt b/benchmarks/edit/pdf/_extracted/sst-em.txt new file mode 100644 index 0000000000000000000000000000000000000000..a759de570a2b160e57d660d4ad3b5c213a214e17 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/sst-em.txt @@ -0,0 +1,865 @@ +FILE: SST-EM- Advanced Metrics for Evaluating Semantic, Spatial and Temporal Aspects in Video Editing .pdf +PAGES: 10 + + +===== PAGE 1 ===== +arXiv:2501.07554v1 [cs.CV] 13 Jan 2025 +SST-EM: Advanced Metrics for Evaluating Semantic, Spatial and Temporal +Aspects in Video Editing +Varun Biyyala, Bharat Chanderprakash Kathuria, Jialu Li, and Youshan Zhang +Graduate Computer Science and Engineering Department +Katz School of Science and Health, Yeshiva University +205 Lexington Avenue, New York, NY 10016 +{biyyala, bkathuri, jli10}@mail.yu.edu, youshan.zhang@yu.edu +Abstract +Video editing models have advanced significantly, but +evaluating their performance remains challenging. Tradi- +tional metrics, such as CLIP text and image scores, often +fall short: text scores are limited by inadequate training +data and hierarchical dependencies, while image scores +fail to assess temporal consistency. We present SST-EM +(Semantic, Spatial, and Temporal Evaluation Metric), a +novel evaluation framework that leverages modern Vision- +Language Models (VLMs), Object Detection, and Tempo- +ral Consistency checks. SST-EM comprises four compo- +nents: (1) semantic extraction from frames using a VLM, +(2) primary object tracking with Object Detection, (3) fo- +cused object refinement via an LLM agent, and (4) tem- +poral consistency assessment using a Vision Transformer +(ViT). These components are integrated into a unified met- +ric with weights derived from human evaluations and re- +gression analysis. The name SST-EM reflects its focus on +Semantic, Spatial, and Temporal aspects of video evalua- +tion. SST-EM provides a comprehensive evaluation of se- +mantic fidelity and temporal smoothness in video editing. +The source code is available in the GitHub Repository. +1. Introduction +The rapid development of deep learning-powered video +editing models has increased the need for effective eval- +uation methods. Traditional metrics like CLIP-based text +and image similarity scores provide limited insights into +model performance, particularly in dynamic video contexts. +The CLIP text score, based on pre-trained Vision-Language +Models (VLMs), struggles with generalization due to out- +dated or biased training data. The CLIP image score fails to +account for temporal consistency, leading to inaccurate as- +sessments when videos replicate original frames with mini- +mal edits. +To address these limitations, we propose a novel multi- +stage evaluation pipeline integrating multiple advanced +models focusing on semantic fidelity, object presence, and +temporal smoothness. Our pipeline operates in four stages: +(1) semantic extraction using a VLM to compare frames +with the editing prompt, (2) object tracking with Object De- +tection to ensure object consistency, (3) refinement through +an LLM agent to focus on primary objects, and (4) tempo- +ral consistency evaluation using a Vision Transformer (ViT) +model. We also introduce a unified metric that combines +results from each stage, with weights determined through +human evaluations and regression techniques. +Our proposed evaluation pipeline improves traditional +methods by incorporating semantic understanding and tem- +poral coherence. It demonstrates the effectiveness of com- +bining VLMs, Object Detection, and Temporal Consistency +checks, providing a more robust framework for video edit- +ing evaluation. Our empirically validated metric enables +more reliable performance benchmarks in video editing re- +search. +2. Related Work +The evaluation of video editing models has been under- +explored compared to other video-related tasks like video +generation and action recognition. With the rise of deep +learning-based video editing techniques, there has been a +growing interest in developing robust and reliable metrics +for evaluating video editing quality. However, most exist- +ing works primarily focus on image-based metrics or adapt +video generation metrics, often overlooking the nuances of +video editing. +Evaluation Metrics for Video Editing Models. Histor- +ically, the evaluation of video editing models relied heav- +ily on traditional image-based metrics, such as PSNR (Peak +Signal-to-Noise Ratio), SSIM (Structural Similarity Index), +and more recently, CLIP-based image and text similarity +scores. These metrics provide valuable information about + +===== PAGE 2 ===== +Table 1. Comparison of Vision-Language Models (VLMs) and Object Detection Models. +Model Vision-Language Tasks Object Detection Semantic Segmentation Image Captioning Zero-shot Learning Backbone Architecture Pretrained on Large-scale Dataset? +CLIP [8] ✓ ✓ ✓ ✓ ✓ Vision Transformer (ViT) ✓ +Florence [30] ✓ ✓ ✓ ✓ ✓ Swin Transformer ✓ +DETR [35] × ✓ ✓ × × Transformer ✓ +YOLOv7 [26] × ✓ × × ✓ CNN-based (CSPDarknet) ✓ +ViLT [13] ✓ × × ✓ ✓ Vision Transformer (ViT) ✓ +SAM [14] ✓ ✓ ✓ ✓ ✓ Vision Transformer (ViT) ✓ +MedCLIP [28] ✓ × ✓ ✓ ✓ ViT ✓ +YOLOv5 [12] × ✓ × × ✓ CNN-based (CSPDarknet) ✓ +Detectron2 [1] × ✓ ✓ × × CNN-based (ResNet) ✓ +ActionCLIP [27] ✓ × × ✓ ✓ ViT ✓ +BLIP [17] ✓ × ✓ ✓ ✓ CNN-based (ResNet, ViT) ✓ +the visual similarity of individual frames or the relationship +between video content and editing prompts. However, they +are limited in capturing higher-order semantic relationships +between objects and their temporal transitions, which are +central to video editing tasks. +To address these limitations, some researchers have de- +veloped evaluation frameworks tailored to video editing. +Kumar et al. [22] proposed an evaluation system that com- +bines semantic segmentation with temporal consistency to +assess video content edits. Similarly, Zhou et al. [11] ex- +plored the application of recurrent neural networks (RNNs) +for capturing temporal dependencies between frames in +edited videos, although their focus was limited to video gen- +eration and lacked the consideration of object-specific edits +in video editing tasks. +Object Detection in Video Editing and Generation. +Object detection plays a critical role in video editing, espe- +cially in ensuring that specific objects mentioned in an edit- +ing prompt are consistently modified across frames. Several +works have explored object detection in the context of video +generation. Carion et al. [35] introduced DETR (Detection +Transformer), a powerful object detection model that inte- +grates Transformer architectures for end-to-end object de- +tection. +Recent advancements in object detection have also been +incorporated into video analysis. Yolov7 [26] and DETR +v2 have achieved state-of-the-art results in real-time object +detection in videos, and their application to video editing +tasks is promising. For instance, Chen et al. [5] proposed a +framework where object detection models track object iden- +tities and their transformations over time, making it easier +to evaluate how well an editing model maintains object con- +sistency across frames. However, these models are typically +evaluated with traditional metrics, such as Intersection over +Union (IoU), which do not fully capture the importance of +maintaining visual coherence and alignment with the edit- +ing prompt. +Vision-Language Models (VLMs) for Video Editing +Evaluation. Integrating Vision-Language Models (VLMs) +into video analysis has revolutionized how we evalu- +ate video content. Models, such as CLIP (Contrastive +Language-Image Pretraining), Florence2, and SAM (Seg- +ment Anything Model), excel at understanding visual con- +tent in the context of natural language, making them highly +suitable for tasks that involve text-to-video or text-to-image +relations. Godfrey et al. [10] demonstrated that CLIP can +bridge the gap between visual and textual domains, pro- +viding a powerful metric for aligning visual content with +text prompts. Florence2 and SAM extend this by providing +more granular segmentation capabilities, enabling precise +identification of objects and regions in images and videos. +Recent works, such as Lee et al. [16] and Dong et al. +[32], have applied these models to tasks like image caption- +ing and scene understanding, which can be directly adapted +to video editing evaluation by comparing the edited con- +tent to a given editing prompt. However, a challenge re- +mains in integrating these models effectively with temporal +consistency checks, as VLMs typically operate on a frame- +by-frame basis without considering the dynamic nature of +video content. +Human Evaluation Scores in Video Editing. Human +evaluation has long been regarded as the gold standard for +assessing video editing quality due to its ability to cap- +ture subjective and nuanced aspects of edits that automated +metrics often overlook. Human evaluators can assess var- +ious dimensions, such as semantic relevance to the editing +prompt, visual quality, and temporal consistency, providing +insights into the perceptual quality of the video edits. +Previous works have incorporated human evaluation +scores to validate automated metrics in video editing. For +instance, Xu et al. [31] conducted large-scale studies where +participants scored videos on aspects like semantic fidelity +and visual consistency. These scores were then used to +benchmark automated metrics, revealing that traditional +metrics like PSNR and SSIM often correlate poorly with hu- +man judgments in video editing tasks. Similarly, Wang et al. +[33] introduced a crowdsourced framework for evaluating +text-to-video generation, where human evaluators scored +the alignment of video content with given prompts. Their +findings highlighted the importance of capturing higher- +order semantic relationships and temporal coherence, which +automated metrics struggle to emulate. +In the context of video editing, human evaluation also +aids in understanding the relative performance of different + +===== PAGE 3 ===== +models. For example, in recent studies by Zhao et al. [2], +human evaluations were used to compare various editing +techniques on dimensions like artifact removal and natural +transition consistency. However, the subjective nature of +human evaluation introduces variability, making it crucial +to design experiments with adequate inter-rater agreement +metrics, such as Krippendorff’s alpha or Cohen’s kappa, to +ensure reliability. +Despite its advantages, human evaluation has notable +limitations, including its time-intensive nature, high costs, +and dependence on subjective interpretations. These chal- +lenges have motivated researchers to use human scores as a +benchmark to develop automated metrics that can approxi- +mate human judgments. To this end, regression techniques +have been employed to optimize the weights of combined +metrics against human evaluation scores, as seen in Kumar +et al. [22] and Zhou et al. [11]. +Combining Object Detection, VLMs, and Tempo- +ral Consistency. While some work integrated object de- +tection and VLMs for video tasks, combining these with +temporal consistency remains a relatively unexplored area. +Pelechano et al. [25] introduce a framework that combines +visual semantic understanding with temporal consistency +models for video generation. Their approach focuses on +maintaining a balance between frame-level object consis- +tency and overall video coherence, while not fully exploring +the integration of advanced models like ViT (Vision Trans- +formers) for assessing temporal continuity between frames. +In this paper, we propose a novel pipeline that combines +the strengths of VLMs for semantic analysis, Object De- +tection for object consistency, and Vision Transformers for +temporal consistency, bridging the gap between these do- +mains. Unlike previous work, our approach integrates all +these elements to provide a more comprehensive evaluation +of video editing models, accounting for both the accuracy +of object edits and the smooth transitions between consecu- +tive frames. We further leveraging human evaluation scores +to fine-tune our proposed metric, SST-EM. Specifically, we +regress our metric’s components against human evaluation +results on one video editing model and validate its perfor- +mance on another model. This approach ensures the metric +aligns closely with human judgments while being robust to +variations across different video editing techniques. More- +over, to demonstrate the generalizability of our metric, we +evaluate its performance, alongside existing metrics, across +four state-of-the-art video editing models using human eval- +uation as the baseline. +3. Dataset Collection +We curated a diverse dataset consisting of 40 distinct +video pairs from the Enhanced End-to-End Video Editing +dataset [24], which includes both original and edited video +pairs (see Table 2). These videos were generated using a +variety of state-of-the-art video editing models, such as Mo- +tionDirector [34], Trailblazer [21], Tune-A-Video [29], and +Text2LIVE [3]. This extensive dataset allows us to compre- +hensively evaluate the video editing capabilities of different +models across various tasks, ensuring a robust and diverse +set of test cases (see Figure 1). +Figure 1. Examples of generated video frames with generation +prompt. +To further enhance the evaluation process, additional +data from various other sources was collected to validate +our mathematical evaluation formula. The collected dataset +spans a wide range of motions, colors, and programmed +zoom actions, designed to challenge the models in handling +complex video synthesis scenarios. Each video sequence in +this collection features a variety of motion dynamics, di- +verse background environments, and distinct trajectories. +These videos provide a comprehensive set of sequences to +assess the performance and robustness of the models in di- +verse editing contexts, including changes in movement pat- +terns, lighting, and object manipulation. +3.1. Data Preparation for Evaluation +The dataset has been carefully organized into two dis- +tinct sets for optimizing and validating our evaluation +model: +Optimization Set: This set is used to optimize the +weights in our evaluation formula. The model is trained to +fit the mathematical evaluation model using a linear regres- +sion methodology, with Human Evaluation (Human Eval) +scores as the ground truth. Human Eval scores are subjec- +tive ratings collected from multiple individuals who were +asked to assess the quality of the edited videos based on +semantic accuracy, spatial coherence, and temporal con- +sistency. To mitigate personal bias and differences in hu- +man perception, the evaluations were averaged across par- +ticipants, ensuring a more reliable and objective evaluation +process. +Validation Set: A separate set is used to validate the +performance of our Mathematical Evaluation model. We + +===== PAGE 4 ===== +compare the model’s predictions with the Human Evalua- +tion scores once again, ensuring the consistency and relia- +bility of the evaluation methodology. This validation helps +confirm our model’s ability to replicate human judgment ac- +curately in video editing evaluations. +For each video in the dataset, we convert the edited +videos into individual frames, paired with their correspond- +ing editing prompts. These frame-prompt pairs serve two +purposes: optimizing the weights in our evaluation model +and evaluating the performance of the video editing mod- +els. By maintaining this structure, we can efficiently assess +how well the models perform across a wide range of editing +tasks, from motion manipulation to visual style transfer. +Table 2. Summary of the Dataset +Task Type No. of Videos Frame-Prompt +Pairs +Weights- +Optimization +40 640 +Evaluation 40 900 +4. Methodology +This section describes the detailed methodology under- +lying our SST benchmarking evaluation formula for the +performance of video editing models. The evaluation pro- +cess involves measuring several key aspects of the edited +video, including semantic alignment, object detection ac- +curacy, temporal consistency, and overall editing quality. +These metrics are then combined into a final score using +a weighted sum approach, where the weights are optimized +through a linear regression model based on human evalua- +tion scores. +4.1. Stage 1: Context Similarity Score +The Context Similarity Score Ssimilarity measures how +closely the edited video matches the editing prompt in terms +of semantic content. To compute this score, we use a +Vision-Language Model (VLM), PaliGemma [4], to gen- +erate textual captions for each video frame. PaliGemma is a +state-of-the-art VLM known for its robust multimodal capa- +bilities, enabling precise textual descriptions of visual con- +tent. It leverages extensive pretraining on diverse datasets, +ensuring high accuracy in generating contextually rich and +semantically aligned captions. This makes PaliGemma par- +ticularly suitable for evaluating video edits where under- +standing nuanced visual-text relationships is critical. +The similarity between the frame’s caption Cframe and +the editing prompt Cprompt is computed using the cosine +similarity measure: +Ssimilarity= sim(CframeCprompt), +where sim(·) denotes the cosine similarity function. The +context similarity score quantifies how well the semantic +content of the video matches the intended modifications de- +scribed in the editing prompt. +Figure 2. Comparison between Final and Human Eval Results +4.2. Stage 2: Object Detection Score +The Object Detection Score Sobject detection evaluates how +accurately the primary object described in the editing +prompt is detected in each frame of the video. To achieve +this, we utilize an object detection model that outputs confi- +dence probabilities for detecting the specified object in each +frame. The object detection score is computed by averaging +the confidence scores across all video frames. +We employ the Grounding DINO model for this stage, +which excels at text-conditioned object detection. Ground- +ing DINO [19] integrates a transformer-based architecture +that enables robust object identification by directly leverag- +ing textual prompts. This capability is particularly benefi- +cial in our evaluation framework, allowing us to seamlessly +match the editing prompt with the detected objects in the +video frames. By using editing prompts as input, Ground- +ing DINO provides confidence scores for the presence of +the described objects, ensuring alignment with the editing +task and enabling precise evaluation of object-specific ed- +its. Its high accuracy and ability to handle text-to-object +associations make it well-suited for our methodology. +Sobject detection = +1 +N +N +i=1 +P(i) +object, +where P(i) +object is the confidence probability for detecting the +primary object in frame i, and N is the total number of +frames in the video. +At this stage, we also use an LLM agent, Mistral-7B- +Instruct-v0.3, to help focus the object detection model on + +===== PAGE 5 ===== +the primary object specified in the editing prompt, filter- +ing out any irrelevant objects or background noise. Us- +ing Prompt Engineering, a carefully crafted prompt dynam- +ically takes the editing prompt and passes it to the LLM +agent, which in turn outputs the primary object of interest +from the editing prompt. This ensures that the object de- +tection model is specifically guided to detect and track the +relevant object throughout the video, improving the accu- +racy and relevance of the object detection score. +4.3. Stage 3: Temporal Consistency Score +The Temporal Consistency Score Stemporal measures the +smoothness and coherence of transitions between consec- +utive frames in the video. A key aspect of video editing is +ensuring that changes are smoothly applied over time, main- +taining visual consistency. To calculate the temporal con- +sistency score, we use a Vision Transformer (ViT) model, +which computes embeddings for each frame in the video. +The similarity between consecutive frame embeddings is +measured using cosine similarity. The temporal consistency +score is defined as: +1 +Stemporal= +N−1 +N−1 +sim(Fi,Fi+1), +i=1 +where Fi and Fi+1 are the feature embeddings for con- +secutive frames i and i+ 1, and N is the total number of +frames in the video. Higher values of Stemporal indicate bet- +ter temporal consistency, where transitions between frames +are smoother. +4.4. Stage 4: Final Score Calculation +The final evaluation score Sfinal is computed as a +weighted sum of the three metrics: context similarity, ob- +ject detection, and temporal consistency. The final score is +given by: +Sfinal = w1·Ssimilarity +w2·Sobject detection +w3·(S1−temporal), +where w1, w2, and w3 are the weights corresponding to each +metric, and Stemporal is subtracted from 1 to ensure that a +higher temporal consistency score yields a higher final score +(see Figure 3). +4.5. Optimization and Regression +The weights w1, w2, and w3 for the final score formula +are optimized using a linear regression model. +To derive these weights, we first organize the data into +two distinct sets: +Optimization Set: Used to optimize the weights by fit- +ting the mathematical evaluation model to human evalua- +tion scores. Human scores are gathered from multiple eval- +uators to mitigate individual biases and perception differ- +ences. The objective is to minimize the difference between +the predicted scores from our model and the human evalua- +tion scores. +Validation Set: Used to validate the performance and +consistency of the mathematical evaluation model. The +model’s predictions are compared against human evaluation +scores to ensure consistent behavior. +Each edited video is converted into frames, and each +frame is paired with its corresponding editing prompt. +These pairs are then used to compute three individual scores +(context similarity, object detection, and temporal consis- +tency) for each video. These calculated scores are sub- +sequently used as input features for the linear regression +model training. +The optimization objective is to minimize the error be- +tween the predicted final scores and the human evaluation +scores. This is done by solving the following loss function: +L= +1 +M +M +j=1 +S(j) +final−S(j) +human +2 +, +where S(j) +final is the final score predicted by the model for the +j-th video, and S(j) +human is the corresponding human evalua- +tion score. M is the number of videos in the dataset used +for training. +The optimization set is used to optimize the weights w1, +w2, and w3, ensuring that the model accurately reflects +human judgment. The validation set is then used to test +the generalization ability of the model and ensure consis- +tent evaluation behavior across different videos and editing +tasks. +4.6. Finalizing Weights Optimization +Once the initial optimization process is complete, we +compare the results generated from the final score formula +with the human evaluation results to assess the consistency +of our model. This is done using statistical methods such +as correlation and the R1 score, which are commonly used +to measure the degree of similarity between predicted and +actual values. +We calculate the Pearson correlation coefficient ρ be- +tween the predicted final scores and the human evaluation +scores: +ρ= +M +i=1(S(i) +final−Sfinal)(S(i) +human−Shuman) +M +i=1(S(i) +final−Sfinal)2 M +i=1(S(i) +human−Shuman)2 +, +where Sfinal and Shuman are the mean predicted and human +evaluation scores, respectively. A higher correlation indi- +cates that the model can predict human evaluation scores +accurately (see Figure 2). +Additionally, we calculate the R1 score, which measures +the precision of the predicted final scores in terms of their + +===== PAGE 6 ===== +Figure 3. Pipeline for evaluating video editing models using custom metrics: semantic analysis, object detection, and temporal consistency +alignment with human evaluations. High correlation and +R1 scores indicate that the model’s predictions are consis- +tent with human judgment, confirming that the weight opti- +mization process has been successful. +By comparing the optimized final scores with human +evaluations through these metrics, we ensure that the final +model is robust and produces reliable results that align with +human perception. +5. Results +We compare the performance of our SST-EM evalua- +tion framework with various established metrics using video +editing models such as VideoP2P, TokenFlow, Control-A- +Video, and FateZero. Video results are displayed in Figure +4. Correlation analysis (Pearson, Spearman, and Kendall) +is conducted to compare all available metrics, including +SST-EM, which is based on the Human Evaluation Score. +The Human Evaluation Score integrates key aspects such +as Imaging Quality, FF-α, FF-β, Background Consistency +Score, Success Rate, Subject Consistency, and Aesthetic +Quality. +The human evaluation assesses critical aspects like se- +mantic alignment, object detection accuracy, temporal con- +sistency, and overall editing quality. These are combined +into a final score using a weighted sum approach. +An ablation study is conducted on video editing models +like AnyV2V, Vid2Me, VideoP2P, TokenFlow, Control-A- +Video, and FateZero, with each model evaluated across Se- +mantic Similarity Score, Object Detection Score, Temporal +Consistency Score, SST-EM final score, and the CLIP-Text +score (see Table 4). +Table 5 compares models based on Imaging Quality, FF- +α, FF-β, Background Consistency, Success Rate, Subject +Consistency, Aesthetic Quality, and SST-EM final score us- +ing Human Evaluation Score. This table offers a detailed +breakdown of each model’s performance and demonstrates +why SST-EM is a superior framework for evaluating video +editing. +These results highlight SST-EM’s advantages in captur- +ing overall video editing quality and its correlation with hu- +man judgment. +5.1. Comparison with Other Metrics +We computed Pearson, Spearman, and Kendall correla- +tions between SST-EM and other evaluation metrics. The +results, summarized in Table 3, show the alignment between +our final score and other metrics assessing video quality. +The individual components of SST-EM, Context Similar- +ity Score, Object Detection Score, Temporal Consistency +Score also show notable correlation with the Human Evalu- +ation Score, demonstrating the contribution of each compo- +nent to the final score. +Table 3. Comparison of Correlations of all the metrics with Hu- +man Evaluation Scores. Our final score and individual component +scores are highlighted +Metric Pearson Spearman Kendall +Imaging Quality [7] 0.951 0.800 0.666 +FF-α[7] -0.515 -0.800 -0.666 +FF-β[7] -0.652 -0.800 -0.666 +Background Consistency Score [7] 0.724 -0.600 -0.333 +Success Rate [7] 0.794 0.800 0.666 +Subject Consistency [7] 0.827 0.800 0.666 +Aesthetic Quality [7] 0.837 0.946 0.912 +Context Similarity Score 0.072 -0.400 -0.333 +Object Detection Score 0.835 0.800 0.666 +Temporal Consistency Score 0.927 1.000 1.000 +SST-EM Score 0.962 1.000 1.000 + +===== PAGE 7 ===== +Figure 4. Comparison of results between different video editing models. The primary object of interest and the original video are high- +lighted in red. +Table 4. Comparison between different elements of our Framework +Model Name CLIP-Text Semantic Similarity Score Object Detection Score Temporal Consistency Score *Our SST-EM Score +AnyV2V [15] 0.2918 0.780449 0.719760 0.966250 0.864687 +Vid2Me [18] 0.2747 0.725520 0.724870 0.978866 0.851886 +VideoP2P [20] 0.2783 0.749997 0.701194 0.932500 0.834226 +TokenFlow [9] 0.2915 0.794004 0.743507 0.979918 0.879671 +Control-A-Video [6] 0.2764 0.732529 0.738756 0.958416 0.846039 +FateZero [23] 0.3137 0.729603 0.736148 0.972566 0.851731 +5.2. Pearson Correlation +The Pearson correlation coefficient ρ measures the lin- +ear relationship between two variables, providing a value +between -1 and +1. A value of +1 indicates a perfect posi- +tive linear relationship, -1 indicates a perfect negative linear +relationship, and 0 indicates no linear relationship. +In our evaluation, Imaging Quality and Aesthetic Qual- +ity show high Pearson correlations with Human Evaluation +scores (0.951 and 0.837, respectively), indicating strong lin- +ear relationships (see Table 3). However, our SST-EM score +surpasses all other metrics with a Pearson correlation of +0.962. Moreover, the individual components of SST-EM, +particularly the Temporal Consistency and Object Detec- +tion Scores, demonstrate Pearson correlations of 0.927 and +0.835, respectively, highlighting their significance in evalu- +ating video editing quality. +5.3. Spearman Rank Correlation +The Spearman rank correlation assesses how well the +rankings of two variables agree. The Spearman’s correla- +tion considers the relative order of values. It is useful when +the relationship between variables is monotonic but not nec- +essarily linear. +A Spearman correlation ranges from -1 to +1, with +1 +indicating perfect agreement between rankings, and -1 in- +dicating a perfect disagreement. Our SST-EM final score +achieves a Spearman correlation of 1.000 with both Imaging +Quality and Aesthetic Quality, demonstrating perfect rank +agreement. +5.4. Kendall Tau Correlation +The Kendall Tau correlation coefficient measures the +strength of association between two variables based on the +concordance and discordance of their pairs. +Kendall Tau values range from -1 to +1, with +1 indicat- +ing perfect agreement, -1 indicating perfect disagreement, +and 0 indicating no agreement. Our SST-EM final score +again shows a perfect agreement with Imaging Quality and +Aesthetic Quality, yielding a Kendall Tau of 1.000. +5.5. Interpretation of Results +Table 3 highlights the performance of each metric com- +pared to our SST-EM final score. Imaging Quality and +Aesthetic Quality exhibit strong positive correlations with +the Human Evaluation score, but our SST-EM surpassed all +scores, particularly in Pearson and Spearman correlations. +This indicates that our final score aligns well with these es- +tablished metrics. On the other hand, metrics like FF-αand + +===== PAGE 8 ===== +Table 5. Comparison of our Framework with different other metrics using Human Evaluation Score +Model Name Imaging Quality FF-α FF-β Background +Consistency Score +Success +Rate +Subject +Consistency +Aesthetic +Quality +Human +Evaluation Score +*Our +SST-EM Score +VideoP2P [20] 0.6665 11.8893 0.2216 0.9696 0.5156 0.9692 0.4847 0.411 0.834226 +TokenFlow [9] 0.7408 7.2708 0.1566 0.9525 0.6471 0.9790 0.5546 0.452 0.879671 +Control-A-Video [6] 0.6973 18.0534 0.2674 0.9700 0.6050 0.9672 0.5377 0.425 0.846039 +FateZero [23] 0.6907 8.0082 0.1723 0.9497 0.5294 0.9696 0.5546 0.433 0.851731 +FF-βshow negative correlations, indicating a less favorable +alignment with the Human Evaluation score. However, they +still provide valuable insights into specific quality aspects +that our formula aims to capture, such as temporal and fea- +ture consistency. +Our SST-EM final score exhibits the highest correlations +(Pearson, Spearman, and Kendall) with the Human Eval- +uation scores, followed by the Imaging Quality and Aes- +thetic Quality metrics. This confirms that our final eval- +uation framework is consistent with human judgments of +overall video quality. The individual components - Con- +text Similarity Score, Object Detection Score, and Tempo- +ral Consistency Score - each contribute significantly to the +overall performance, with Temporal Consistency showing +the strongest correlations across all metrics, followed by +Object Detection Score. +The high correlation values suggest that our SST-EM +evaluation formula performs well not only in alignment +with human evaluations but also in comparison to other +standard metrics. +6. Discussion +We analyze the insights, implications, and limitations of +our SST-EM evaluation framework. The results show that +SST-EM aligns well with human judgment and outperforms +traditional metrics in capturing video editing quality. Our +high Pearson correlation (0.962) and perfect Spearman and +Kendall correlations (1.000) indicate that our framework +ranks video edits similarly to human evaluations, balancing +semantic accuracy, temporal consistency, and overall video +quality. +While SST-EM aligns well with metrics like Imaging +Quality and Aesthetic Quality, traditional metrics like FF- +α and FF-β show lower correlations, suggesting that they +do not fully capture the complexities of video editing, espe- +cially in scenes with rapid changes. The lower correlation +with the Background Consistency Score highlights its lim- +ited ability to assess overall video quality. +6.1. Insights into SST-EM Metric Components +Our framework includes Semantic Similarity, Object De- +tection, Temporal Consistency, and Aesthetic Quality. The +high Pearson correlation (0.951) with Imaging Quality and +perfect rank agreement with Aesthetic Quality show that +our metric captures the semantic and aesthetic aspects ef- +fectively. Context similarity from Vision-Language Models +(VLMs) ensures semantic accuracy. +The Object Detection and Temporal Consistency compo- +nents are important but may need refinement for dynamic +or cluttered backgrounds and rapid scene transitions. The +ViT-based Temporal Consistency Score captures frame co- +herence but may require further tuning for subtle temporal +variations. +6.2. Comparison to Traditional Metrics +Compared to CLIP-based metrics, SST-EM offers a +more holistic evaluation by considering temporal consis- +tency and object continuity. CLIP metrics excel at semantic +alignment but fall short in addressing video-specific chal- +lenges like maintaining object consistency. By incorporat- +ing human-derived weights, SST-EM provides a more bal- +anced evaluation, better reflecting overall video quality. +In conclusion, SST-EM provides a robust approach to +evaluating video editing models. Future work will refine +weighting mechanisms and handle complex editing scenar- +ios to optimize performance across diverse tasks. +7. Conclusion +We introduce the SST-EM evaluation framework, a novel +approach combining context similarity, object detection ac- +curacy, and temporal consistency to address limitations in +existing video editing evaluation methodologies. SST-EM +captures nuances such as temporal coherence and seman- +tic relevance, offering a multidimensional perspective that +aligns moderately with human evaluations. +The key strength of SST-EM lies in its ability to bridge +semantic understanding and visual perception, enabling +comprehensive evaluations. For future work, we plan to +expand the dataset with diverse video samples, incorporate +more human evaluation data, and explore deep learning- +based weighting models to improve metric adaptability and +robustness. We also aim to apply SST-EM to state-of-the- +art models, providing insights into their strengths and weak- +nesses. Ultimately, SST-EM has the potential to standardize +video editing evaluation, fostering meaningful comparisons +and advancing research in this field. +References +[1] Allena Venkata Sai Abhishek and Sonali Kotni. Detectron2 +object detection & manipulating images using cartooniza- + +===== PAGE 9 ===== +tion. Int. J. Eng. Res. Technol.(IJERT), 10:1–5, 2021. 2 +[2] Sharib Ali, Felix Zhou, Adam Bailey, Barbara Braden, +James E East, Xin Lu, and Jens Rittscher. A deep learning +framework for quality assessment and restoration in video +endoscopy. Medical image analysis, 68:101900, 2021. 3 +[3] Omer Bar-Tal, Dolev Ofri-Amar, Rafail Fridman, Yoni Kas- +ten, and Tali Dekel. Text2live: Text-driven layered image +and video editing. In European conference on computer vi- +sion, pages 707–723. Springer, 2022. 3 +[4] Lucas Beyer, Andreas Steiner, Andr´ e Susano Pinto, Alexan- +der Kolesnikov, Xiao Wang, Daniel Salz, Maxim Neumann, +Ibrahim Alabdulmohsin, Michael Tschannen, Emanuele +Bugliarello, et al. Paligemma: A versatile 3b vlm for trans- +fer. arXiv preprint arXiv:2407.07726, 2024. 4 +[5] Feng Chen, Zhen Yang, Bohan Zhuang, and Qi Wu. Stream- +ing video diffusion: Online video editing with diffusion +models. arXiv preprint arXiv:2405.19726, 2024. 2 +[6] Weifeng Chen, Yatai Ji, Jie Wu, Hefeng Wu, Pan Xie, Jiashi +Li, Xin Xia, Xuefeng Xiao, and Liang Lin. Control-a-video: +Controllable text-to-video generation with diffusion models. +arXiv preprint arXiv:2305.13840, 2023. 7, 8 +[7] Yupeng Chen, Penglin Chen, Xiaoyu Zhang, Yixian Huang, +and Qian Xie. Editboard: Towards a comprehensive evalu- +ation benchmark for text-based video editing models. arXiv +preprint arXiv:2409.09668, 2024. 6 +[8] Peng Gao, Shijie Geng, Renrui Zhang, Teli Ma, Rongyao +Fang, Yongfeng Zhang, Hongsheng Li, and Yu Qiao. +Clip-adapter: Better vision-language models with fea- +ture adapters. International Journal of Computer Vision, +132(2):581–595, 2024. 2 +[9] Michal Geyer, Omer Bar-Tal, Shai Bagon, and Tali Dekel. +Tokenflow: Consistent diffusion features for consistent video +editing. arXiv preprint arXiv:2307.10373, 2023. 7, 8 +[10] W Wilfred Godfrey and Abhinav Ratna. Enhancing the video +editing capabilities of text-to-video generators using ddpm +inversion. In 2023 IEEE International Conference on Com- +puter Vision and Machine Intelligence (CVMI), pages 1–5. +IEEE, 2023. 2 +[11] Bo Han, Heqing Zou, Haoyang Li, Guangcong Wang, +and Chng Eng Siong. Text-based talking video edit- +ing with cascaded conditional diffusion. arXiv preprint +arXiv:2407.14841, 2024. 2, 3 +[12] Glenn Jocher, Ayush Chaurasia, Alex Stoken, Jirka Borovec, +Yonghye Kwon, Kalen Michael, Jiacong Fang, Colin Wong, +Zeng Yifu, Diego Montes, et al. ultralytics/yolov5: v6. +2-yolov5 classification models, apple m1, reproducibility, +clearml and deci. ai integrations. Zenodo, 2022. 2 +[13] Wonjae Kim, Bokyung Son, and Ildoo Kim. Vilt: Vision- +and-language transformer without convolution or region su- +pervision. In International conference on machine learning, +pages 5583–5594. PMLR, 2021. 2 +[14] Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, +Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer White- +head, Alexander C Berg, Wan-Yen Lo, et al. Segment any- +thing. In Proceedings of the IEEE/CVF International Con- +ference on Computer Vision, pages 4015–4026, 2023. 2 +[15] Max Ku, Cong Wei, Weiming Ren, Huan Yang, and Wenhu +Chen. Anyv2v: A plug-and-play framework for any video- +to-video editing tasks. arXiv preprint arXiv:2403.14468, +2024. 7 +[16] Yao-Chih Lee, Ji-Ze Genevieve Jang, Yi-Ting Chen, Eliza- +beth Qiu, and Jia-Bin Huang. Shape-aware text-driven lay- +ered video editing. In Proceedings of the IEEE/CVF Con- +ference on Computer Vision and Pattern Recognition, pages +14317–14326, 2023. 2 +[17] Junnan Li, Dongxu Li, Caiming Xiong, and Steven Hoi. +Blip: Bootstrapping language-image pre-training for unified +vision-language understanding and generation. In Interna- +tional conference on machine learning, pages 12888–12900. +PMLR, 2022. 2 +[18] Xirui Li, Chao Ma, Xiaokang Yang, and Ming-Hsuan Yang. +Vidtome: Video token merging for zero-shot video editing. +In Proceedings of the IEEE/CVF Conference on Computer +Vision and Pattern Recognition, pages 7486–7495, 2024. 7 +[19] Shilong Liu, Zhaoyang Zeng, Tianhe Ren, Feng Li, Hao +Zhang, Jie Yang, Qing Jiang, Chunyuan Li, Jianwei Yang, +Hang Su, et al. Grounding dino: Marrying dino with +grounded pre-training for open-set object detection. In +European Conference on Computer Vision, pages 38–55. +Springer, 2025. 4 +[20] Shaoteng Liu, Yuechen Zhang, Wenbo Li, Zhe Lin, and Jiaya +Jia. Video-p2p: Video editing with cross-attention control. +In Proceedings of the IEEE/CVF Conference on Computer +Vision and Pattern Recognition, pages 8599–8608, 2024. 7, +8 +[21] Wan-Duo Kurt Ma, John P Lewis, and W Bastiaan Kleijn. +Trailblazer: Trajectory control for diffusion-based video +generation. arXiv preprint arXiv:2401.00896, 2023. 3 +[22] KL Bhanu Moorthy, Moneish Kumar, Ramanathan Subra- +manian, and Vineet Gandhi. Gazed–gaze-guided cinematic +editing of wide-angle monocular video recordings. In Pro- +ceedings of the 2020 CHI Conference on Human Factors in +Computing Systems, pages 1–11, 2020. 2, 3 +[23] Chenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, +Xintao Wang, Ying Shan, and Qifeng Chen. Fatezero: Fus- +ing attentions for zero-shot text-based video editing. In +Proceedings of the IEEE/CVF International Conference on +Computer Vision, pages 15932–15942, 2023. 7, 8 +[24] Lakshmi Priya Ramisetty, Namrata Patel, Hiep Dang, and +Aditya Singh Parmar. Enhanced end-to-end video editing: +Adaptive customization of path, object, and motion dynam- +ics. 3 +[25] Otger Rogla, Gustavo A Patow, and Nuria Pelechano. Pro- +cedural crowd generation for semantically augmented virtual +cities. Computers & Graphics, 99:83–99, 2021. 3 +[26] Chien-Yao Wang, Alexey Bochkovskiy, and Hong- +Yuan Mark Liao. Yolov7: Trainable bag-of-freebies sets +new state-of-the-art for real-time object detectors. In Pro- +ceedings of the IEEE/CVF conference on computer vision +and pattern recognition, pages 7464–7475, 2023. 2 +[27] Mengmeng Wang, Jiazheng Xing, Jianbiao Mei, Yong Liu, +and Yunliang Jiang. Actionclip: Adapting language-image +pretrained models for video action recognition. IEEE Trans- +actions on Neural Networks and Learning Systems, 2023. 2 + +===== PAGE 10 ===== +[28] Zifeng Wang, Zhenbang Wu, Dinesh Agarwal, and Jimeng +Sun. Medclip: Contrastive learning from unpaired medical +images and text. arXiv preprint arXiv:2210.10163, 2022. 2 +[29] Jay Zhangjie Wu, Yixiao Ge, Xintao Wang, Stan Weixian +Lei, Yuchao Gu, Yufei Shi, Wynne Hsu, Ying Shan, Xiaohu +Qie, and Mike Zheng Shou. Tune-a-video: One-shot tuning +of image diffusion models for text-to-video generation. In +Proceedings of the IEEE/CVF International Conference on +Computer Vision, pages 7623–7633, 2023. 3 +[30] Bin Xiao, Haiping Wu, Weijian Xu, Xiyang Dai, Houdong +Hu, Yumao Lu, Michael Zeng, Ce Liu, and Lu Yuan. +Florence-2: Advancing a unified representation for a variety +of vision tasks. In Proceedings of the IEEE/CVF Conference +on Computer Vision and Pattern Recognition, pages 4818– +4829, 2024. 2 +[31] Yiran Xu, Badour AlBahar, and Jia-Bin Huang. Temporally +consistent semantic video editing. In European Conference +on Computer Vision, pages 357–374. Springer, 2022. 2 +[32] Songlin Yang, Wei Wang, Jun Ling, Bo Peng, Xu Tan, and +Jing Dong. Context-aware talking-head video editing. In +Proceedings of the 31st ACM International Conference on +Multimedia, pages 7718–7727, 2023. 2 +[33] Tianle Zhang, Langtian Ma, Yuchen Yan, Yuchen Zhang, Kai +Wang, Yue Yang, Ziyao Guo, Wenqi Shao, Yang You, Yu +Qiao, et al. Rethinking human evaluation protocol for text- +to-video models: Enhancing reliability, reproducibility, and +practicality. arXiv preprint arXiv:2406.08845, 2024. 2 +[34] Rui Zhao, Yuchao Gu, Jay Zhangjie Wu, David Jun- +hao Zhang, Jia-Wei Liu, Weijia Wu, Jussi Keppo, and +Mike Zheng Shou. Motiondirector: Motion customization +of text-to-video diffusion models. In European Conference +on Computer Vision, pages 273–290. Springer, 2025. 3 +[35] Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang +Wang, and Jifeng Dai. Deformable detr: Deformable trans- +formers for end-to-end object detection. arXiv preprint +arXiv:2010.04159, 2020. 2 diff --git a/benchmarks/edit/pdf/_extracted/ve-bench.meta.txt b/benchmarks/edit/pdf/_extracted/ve-bench.meta.txt new file mode 100644 index 0000000000000000000000000000000000000000..a6ccf8a426dcda4fbcc02f0bea208da86b699d54 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/ve-bench.meta.txt @@ -0,0 +1,3 @@ +title= +author= +pages=11 diff --git a/benchmarks/edit/pdf/_extracted/ve-bench.txt b/benchmarks/edit/pdf/_extracted/ve-bench.txt new file mode 100644 index 0000000000000000000000000000000000000000..ecf539587e896edeab1e50c091e9bf702cbfbb3d --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/ve-bench.txt @@ -0,0 +1,1027 @@ +FILE: VE-Bench- Subjective-Aligned Benchmark Suite for Text-Driven Video Editing Quality Assessment.pdf +PAGES: 11 + + +===== PAGE 1 ===== +arXiv:2408.11481v2 [cs.CV] 18 Dec 2024 +VE-Bench: Subjective-Aligned Benchmark Suite for Text-Driven Video Editing +Quality Assessment +Shangkun Sun1, 2, Xiaoyu Liang1, Songlin Fan1,2, Wenxu Gao1,2, Wei Gao1,2* +1SECE, Peking University, 2Peng Cheng Laboratory +{sunshk, liangxiaoyu yy, gaowx}@stu.pku.edu.cn, {slfan, gaowei262}@pku.edu.cn +Abstract +Text-driven video editing has recently experienced rapid de- +velopment. Despite this, evaluating edited videos remains a +considerable challenge. Current metrics tend to fail to align +with human perceptions, and effective quantitative metrics for +video editing are still notably absent. To address this, we in- +troduce VE-Bench, a benchmark suite tailored to the assess- +ment of text-driven video editing. This suite includes VE- +Bench DB, a video quality assessment (VQA) database for +video editing. VE-Bench DB encompasses a diverse set of +source videos featuring various motions and subjects, along +with multiple distinct editing prompts, editing results from +8 different models, and the corresponding Mean Opinion +Scores (MOS) from 24 human annotators. Based on VE- +Bench DB, we further propose VE-Bench QA, a quantitative +human-aligned measurement for the text-driven video edit- +ing task. In addition to the aesthetic, distortion, and other vi- +sual quality indicators that traditional VQA methods empha- +size, VE-Bench QA focuses on the text-video alignment and +the relevance modeling between source and edited videos. It +proposes a new assessment network for video editing that at- +tains superior performance in alignment with human prefer- +ences. To the best of our knowledge, VE-Bench introduces +the first quality assessment dataset for video editing and an ef- +fective subjective-aligned quantitative metric for this domain. +All data and code will be publicly available to the community. +VE-Bench +Database Quality Assessment +Source Video Collection +Real-world, CG, AIGC; Human, +Animal, Object, Nature; Pose, Action, +Ego/ Exo Motion, … +Prompt Selection +Addition, Removal, Replacement, +A polar bear is playing guitar by the lake +Color, Texture, Style, Size, Shape, Pose, +Motion, Background, … +Video Editing +0-shot, fine-tuned; SD 1-4 / 1-5 / 2-1; +PnP, ControlNet, InstructP2P, … +Text-Target +Alignment Source-Target +Relationship +Technical +Distortion Aesthetic +Subjective Annotation +MOS: 1, 4, 5, 8 … +Score +Figure 1: Overview of the proposed VE-Bench. +Introduction +With the rise of the AI-Generated Content (AIGC) trend, an +increasing number of text-driven video editing methods (Ma +et al. 2024a,b, 2023, 2024c; Feng et al. 2024a) are gain- +ing momentum and finding widespread application in daily +life. However, there remains a lack of a suitable quantita- +tive metric to assess video editing quality. Currently, the +predominant evaluation method involves subjective exper- +iments with human participants, which are costly and yield +non-reusable results. +Currently, quantitative metrics such as CLIP and LPIPS +scores (Radford et al. 2021; Zhang et al. 2018), FVD (Un- +terthiner et al. 2018), and Warp scores (Ceylan, Huang, and +Mitra 2023; Kara et al. 2024) are commonly used in recent +*Corresponding author. +Copyright © 2025, Association for the Advancement of Artificial +Intelligence (www.aaai.org). All rights reserved. +works. They mainly quantify results based on objective mea- +surements in dimensions like editing quality, temporal con- +sistency, and text consistency. Nevertheless, these existing +metrics primarily face two main issues: (1) The tendency of +misalignment with human subjective perceptions. (2) Incom- +plete evaluation. As they mainly measure results from a sin- +gle dimension, making it difficult to comprehensively reflect +the overall quality of the effects. +Traditional video quality assessment (VQA) meth- +ods (Wu et al. 2023a, 2022; Kou et al. 2023) have been +able to align with human perceptions. However, these meth- +ods are primarily designed for natural videos and struggle to +evaluate AIGC video editing tasks adequately. In this case, +these methods overlook the different distortions in AIGC +videos (Kou et al. 2024), such as irrational objects and ir- +regular motion patterns. Besides, they do not simultaneously +consider text-video alignment and the inner connection be- +tween source and edited videos, which are crucial for the +assessment of editing results. +To address these challenges, we propose VE-Bench, a +specialized suite tailored for text-driven AIGC video edit- +ing, as shown in Figure 1. We first establish VE-Bench DB, +a quality assessment database for video editing. VE-Bench +DB collects source videos containing real-world videos, +CG-rendered videos, and AIGC videos, with multiple differ- + +===== PAGE 2 ===== +ent actions, subjects, and scenarios, along with various types +of prompts and edited results from different video editing +methods. We then assembled 24 human subjects to gather +the Mean Opinion Scores (MOS) for each video. To the best +of our knowledge, this is the first AIGC VQA dataset for +evaluating the quality of edited videos. +Building on this foundation, we introduce VE-Bench QA, +a novel multi-modal quality assessment network specifi- +cally designed for AIGC video editing. VE-Bench QA eval- +uates edited videos from various aspects such as source- +target video relationship, text-video alignment, and other +aspects such as aesthetics and distortion. Detailed experi- +ments demonstrate that VE-Bench QA achieves state-of-the- +art alignment with human preferences, surpassing existing +advanced metrics and VQA methods. +Our contributions could be summarized as: (1) We col- +lect VE-Bench DB, a diverse dataset with videos featuring +various motions and subjects, along with multiple distinct +editing prompts, and the corresponding editing results with +rich human feedback. To the best of our knowledge, it is the +first quality assessment dataset for text-driven video editing. +(2) Unlike traditional VQA methods that focus mainly on +visual quality indicators, we propose VE-Bench QA, which +further emphasizes text-video alignment and relevance mod- +eling between source and edited videos. (3) The proposed +VE-Bench QA is tailored to the assessment of the text- +driven video editing task, surpassing existing advanced eval- +uation methods in aligning with human subjective ratings +and showcasing the effectiveness of VE-Bench QA in eval- +uating AIGC video editing quality. +Related Work +Metrics for Video Editing +Currently, metrics commonly used in text-driven video edit- +ing include some objective metrics (Radford et al. 2021; +Zhang et al. 2018; Kara et al. 2024; Unterthiner et al. 2018), +as well as some Video Quality Assessment (VQA) meth- +ods (Hartwig et al. 2024; Wu et al. 2023b, 2024a; Qu et al. +2024; Wu et al. 2023e; Xu et al. 2024) aligned with human +feedback. CLIP (Radford et al. 2021) has been widely used +due to its success in vision-language tasks (Wu et al. 2024b; +Jia et al. 2024a,b). CLIP-T calculates the average cosine +similarity between each edited frame and the correspond- +ing textual prompt. CLIP-F(Tmp-Con), refers to the average +cosine similarity between consecutive edited frames. Fram- +Acc (Qi et al. 2023) represents the percentage of edited +frames that has a higher similarity to the target text than +to the original source text. LPIPS-P (Chai et al. 2023) and +LPIPS-T (Chai et al. 2023) denote the LPIPS deviation from +the original video frames and deviation between adjacent +edited frames, respectively. FVD (Unterthiner et al. 2018) +calculates the Fr´ echet Distance between two videos. Spat- +Con (Yang et al. 2024) refers to the average distance be- +tween VGG features. OSV (Objective Semantic Variance), +proposed by (Liu et al. 2024), uses DINO-ViT (Oquab et al. +2024) to measure semantic consistency and calculates the +frame-wise feature variance in the edited region. Warp-MSE +and Warp-SSIM (Kara et al. 2024) represent the MSE and +SSIM between the edited video and the warped edited video +by optical flow models. However, these individual metrics +often only assess the editing results from a single dimension. +Qedit (Kara et al. 2024) multiplies Warp-SSIM with CLIP- +T to obtain a more comprehensive evaluation. Sedit (Cong +et al. 2024) (CLIP-T / Warp-MSE) combines Warp-MSE +with CLIP-T to provide overall the assessment for videos. +Nevertheless, these metrics are not aligned with human per- +ceptions. PickScore (Kirstain et al. 2023) calculates the es- +timated alignment with human preferences via a CLIP-style +model fine-tuned on human preference data. FastVQA (Wu +et al. 2022) proposes grid mini-patch sampling to evaluate +videos efficiently via the consideration of local quality. Sim- +pleVQA (Sun et al. 2022) leverages quality-aware spatial +features and motion features to assess videos. DOVER (Wu +et al. 2023a) evaluates natural videos from the aesthetic and +technical distortion perspective. However, these methods are +typically suitable for evaluating single videos, neglecting the +inherent relationship between edited results and the source +video, and many VQA methods do not model the alignment +between text and video. Currently, there is still a lack of +a proper metric to evaluate the edited results based on the +source video and editing prompts. +Datasets for Video Editing Assessment +In assessing edited videos, a common practice in prior +works (Qi et al. 2023; Wu et al. 2023c; Yang et al. 2024; +Sun et al. 2024) has been to assemble human annota- +tors to conduct subjective preference experiments. However, +the results of subjective preference experiments are diffi- +cult to reproduce, and there is considerable variance in the +data and prompts selected when comparing different meth- +ods. Recently, some studies (Wu et al. 2023d; Feng et al. +2024b) have curated high-quality video-editing prompt pairs +through diverse data collection and prompt design for uni- +fied community assessment. Nevertheless, these efforts still +face two challenges: (1) These datasets do not include sub- +jective experimental feedback (Mean Opinion Score, MOS) +corresponding to the video data, requiring others to still use +objective metrics or conduct subjective experiments again +when utilizing these datasets. (2) The scenarios covered by +these datasets could potentially be expanded further. For +instance, TGVE (Wu et al. 2023d) has only collected 76 +videos, and BalanceCC (Feng et al. 2024b) has gathered 100 +videos, both of which mainly focus on real-world scenes. In +this work, we introduce VE-Bench DB, a dataset for assess- +ing video editing quality that includes diverse content and +human feedback scores. This dataset encompasses a vari- +ety of categories including real-world scenes, CG-rendered +scenes, and AIGC-generated scenes. It covers various sub- +jects such as people performing different actions, occupa- +tions, genders, and ages, as well as different animals, ob- +jects, and landscapes. The dataset also includes multiple +types of motion, such as ego-motion and exo-motion, along +with various editing prompts. This provides a solid foun- +dation for more robust video editing evaluation. Details on +the dataset are provided in the following sections. In total, +VE-Bench DB comprises 169 different videos edited using +8 different video editing methods, yielding 1,170 edited re- + +===== PAGE 3 ===== +sults after manual screening. After that, 24 human subjects +are invited to obtain the corresponding MOS scores. To the +best of our knowledge, it is the first VQA dataset for text- +driven video editing. +Methods for Video Editing +Recently, with the fast development of diffusion mod- +els (Wei et al. 2024), lots of video editing methods have +emerged (Wu et al. 2023c; Chai et al. 2023; Ma et al. 2022; +Chen et al. 2024; Zhu et al. 2024; Wang et al. 2024c). Differ- +ent from image editing, one key to video editing is to main- +tain temporal consistency. Tune-a-video (Wu et al. 2023c) +inflates the 2D convolutions in T2I models to pseudo-3D +convolutions and fine-tunes the attention matrix with source +videos. Text2Video-Zero (Khachatryan et al. 2023) lever- +ages cross-frame attention and introduces latent motion dy- +namics to keep the global scene and the background consis- +tent. FateZero (Qi et al. 2023) proposes to fuse the attention +maps in the inversion process and generation process and +utilizes the source prompt’s cross-attention map to improve +consistency. ControlVideo (Zhang et al. 2024) introduces the +interleaved-frame smoother and full-frame attention to keep +the temporal consistency and model the temporal relation- +ship in different frames. Flatten (Cong et al. 2024) utilizes +optical-flow-guided attention during the diffusion process +to improve the visual consistency, which models the sim- +ilarity of patch trajectories in different clips. RAVE (Kara +et al. 2024) leverages the full-frame attention and proposes +the grid sampling strategy to maintain the temporal consis- +tency in video sequences. Based on Rerender-a-video (Yang +et al. 2023) and the flow-guided attention in (Cong et al. +2024), Fresco (Yang et al. 2024) further develops a group +of temporal attention including efficient cross-frame atten- +tion, spatial/temporal-guided attention, etc., and fine-tunes +the translated feature for better temporal consistency. In this +work, we selected a variety of methods for video editing, in- +cluding early and recent approaches, Zero-shot and few-shot +techniques, different Stable Diffusion (SD) base models, and +various editing methodologies, to ensure the diversity of the +generated results. +VE-Bench DB: Subjective-Aligned Dataset for +Text-Driven Video Editing +The collection of VE-Bench DB involves four primary +stages: source video collection, prompt composition, selec- +tion and execution of video editing methods, and subjective +experiments. We will discuss each part in subsequent sec- +tions. +Source Video Collection +To support a more robust quality assessment for video edit- +ing, VE-Bench collected a diverse set of source videos +that are not limited to real-world scenes but also include +some content rendered by computer graphics and text-driven +AIGC videos. Notably, considering the current wide range +of use cases, real-world scenes still account for a larger +proportion. Different from previous works, given concerns +about copyright issues, watermarks, and resolution, we did +not randomly sample videos from Webvid (Bain et al. 2021). +Instead, to cover as many different content subjects, action +categories, and scenarios as possible, VE-Bench manually +selected 123 videos from four datasets: DAVIS (Pont-Tuset +et al. 2017), Kinetics-700 (Kay et al. 2017), Sintel (Butler +et al. 2012), and Spring (Mehl et al. 2023). Spring and Sintel +are high-resolution datasets rendered by computer graphics. +To ensure a diversity of actions and rich content, we did not +randomly sample but carefully handpicked the correspond- +ing video content. We tag each sample as Nature/Object/An- +imal/Human, Ego/Exo, etc., skipping similar or short videos +until datasets are exhausted. We start from small datasets to +large ones, and finally supplement from the Internet, which +is vital to finding cases like auroras, lava, and lightning, as +well as diverse action cases absent in traditional datasets. In +addition, we selected 15 different videos from Sora (Brooks +et al. 2024) and Kling (Kuaishou 2024) based on the prin- +ciple of diversity in motion and content. Furthermore, to +cover more content and a variety of actions, we selected 31 +videos from the internet with the appropriate permissions. +Ultimately, we collected 169 source videos with diverse con- +tent, and their specific sources, contents, and category com- +positions are shown in Figure 2. All selected videos were +resized to have a long side of 768 pixels while maintaining +their original aspect ratios. Considering the limited length +supported by existing video editing methods, each video was +trimmed to 32 frames. +Prompt Selection +Referring to past work (Huang et al. 2024), we classify +prompts used for video editing into three major categories: +(1) Style editing, which includes the edit on color, texture, +or the overall atmosphere. (2) Semantic editing, which in- +cludes background editing and local editing such as the addi- +tion, replacement, or removal on a certain object. (3) Struc- +tural editing, which includes the change in object size, pose, +motion, etc. To ensure the specificity and diversity of the +prompts, we manually crafted corresponding prompts for +each video, and the specific distribution is shown in Figure 3. +Video Editing +We then select 8 video editing methods. To ensure the dis- +tribution of edited video quality, in addition to recent top- +performance models, we also include some earlier video +editing methods. Besides, we select methods with different +base models ranging from SD 1-4 to SD2-1 to improve the +diversity of edited results. Furthermore, to ensure the diver- +sity of edited content, we choose both Zero-shot methods +and methods that require fine-tuning. We also select mod- +els based on different editing paradigms, including effec- +tive editing strategies such as Instruct P2P (Brooks, Holyn- +ski, and Efros 2023), PnP (Tumanyan et al. 2023), Control- +Net (Zhang, Rao, and Agrawala 2023), etc. The specific de- +tails are presented in Table 1. +Subjective Study +According to the ITU standard (Series 2002), the number +of participants in subjective experiments should be at least + +===== PAGE 4 ===== +Internet AIGC +CG +DAVIS +Ego motion +Exo +motion +Landscape +Object +Kling +Sora +Sintel +Spring +Human +Real-world +Ego + Exo +motion +Animal +Kinetics +(a) (b) (c) (d) +Figure 2: Collection of source videos. (a) Sources of videos. (b) Types of videos. (c) Motion categories. (d) Content categories. +Model Time Zero-shot Edit. SD. +Tune-a-video (Wu et al. 2023c) ICCV’23 ✗ Others 1-4 +T2V-Zero (Khachatryan et al. 2023) ICCV’23 ✓ Instruct-P2P (Brooks, Holynski, and Efros 2023) 1-5 +Fate-Zero (Qi et al. 2023) ICCV’23 ✓ Others 1-4 +ControlVideo (Zhang et al. 2024) ICLR’24 ✓ ControlNet (Zhang, Rao, and Agrawala 2023) 1-5 +TokenFlow (Geyer et al. 2024) ICLR’24 ✓ PnP (Tumanyan et al. 2023) 2-1 +Flatten (Cong et al. 2024) ICLR’24 ✓ Others 2-1 +RAVE (Kara et al. 2024) CVPR’24 ✓ Others 1-5 +Fresco (Yang et al. 2024) CVPR’24 ✓ ControlNet (Zhang, Rao, and Agrawala 2023) 1-5 +Table 1: Collection of the editing models. +15 to ensure that the results’ variance is within a control- +lable range. For this experiment, a total of 24 human sub- +jects with diverse backgrounds were recruited. During the +experiment, the subjects were asked to consider their sub- +jective impressions and evaluate the text-video consistency, +source-target fidelity, and quality of the edited videos in a +comprehensive manner. The text-video consistency refers to +whether the edited content adheres to the given prompt. The +source-target fidelity indicates the degree to which the orig- +inal video and the edited video maintain a certain level of +connection. The edited video quality can be assessed from +aspects such as temporal and spatial coherence, aesthetics, +and technical distortions. When evaluating, all participants +rated the videos on a scale from 1 to 10. These participants +are all over 18 years old with bachelor’s degrees in business, +engineering, science, or law. Before started, they receive of- +fline training including cases of varying editing quality be- +yond the dataset. After that, they rate all samples, taking 5- +min breaks every 15 mins to prevent fatigue. Following pre- +vious works (Wu et al. 2023a; Kou et al. 2024; Chai et al. +2023), Z-scores are used to normalize the raw MOS values, +which could be formulated as After collecting all raw Mean +Opinion Score (MOS) values, we use the Z-score normal- +ization method to eliminate inter-subject differences, which +could be formulated as: +the i-th annotator. Then we apply the screening method in +BT.500 (Int.Telecommun.Union 2000) to filter the outliers. +The difference between the raw scores and the normalized +scores is illustrated in Figure 4. +Style +Structure +Semantics +(a) (b) +Figure 3: Statistics of VE-Bench DB prompts. (a) Word +cloud of VE-Bench DB prompts. (b) Proportion of differ- +ent types +Xm,i−µ(Xi) +Zm,i= +σ(Xi), (1) +where Xm,i and Zm,i refer to the raw MOS and Z- +score of m-th video from i-th participant, respectively. µ(·) +and σ(·) represent the mean and standard deviation opera- +tors, respectively, and Xi is the collection of all MOS from +Dataset Analysis +We further conducted a detailed analysis of the data in the +VE-Bench DB and investigated the scores for the editing +results of each model on the collected videos, as shown in +Fig. 5. We can see that different models have varying ca- +pabilities across different types of edits. Currently, models +generally score relatively low on “Removal” tasks, while +they excel in stylization instructions. Their proficiency in +stylization is likely due to SD (Stable Diffusion) being pre- +trained on a large variety of images across different styles, +leveraging this prior knowledge. This phenomenon is indi- +rectly validated by some training-free style transfer meth- +ods based on SD, such as InstantStyle (Wang et al. 2024a,b) +and RB-modulation (Rout et al. 2024). Compared to “Ad- + +===== PAGE 5 ===== +(a) (b) +Figure 4: Statistics on MOS. (a) The distribution of the raw/Z-score MOS. (b) Z-score MOS distributions of 8 editing methods. +dition”, “Removal” is more challenging, likely because re- +moval tasks involve background reconstruction, which de- +mands stronger semantic understanding and fine-grained +feature extraction capabilities. This area might see signif- +icant advancements in future editing models. Additionally, +models struggle with shape and size edits, with the excep- +tion of FateZero (Qi et al. 2023). This model excels due to its +proposed shape-aware Attention Blending technique, which +merges the generated shape with the inverted attention of the +original image in the latent space, enhancing shape editing +capabilities. This technique is one of the core contributions +of FateZero, as demonstrated in the original paper, where +it achieves superior shape editing performance, supporting +the conclusions of this experiment. It is evident that relying +solely on native SD models for shape-related edits produces +suboptimal results. Future base models could consider in- +corporating similar shape-aware supervision during training. +Furthermore, most open-source video editing models cur- +rently use CLIP-based text encoders, which lack the com- +prehension capabilities of large language models (LLMs). +As a result, prompts involving changes in the number of ob- +jects often yield subpar outcomes. The motion degree of the +source video also impacts editing results—especially for op- +tical flow-based editing methods—since large movements +can result in inaccurate optical flow, thereby affecting the +final outcome. Complex motion dynamics also pose signifi- +cant challenges for maintaining frame-to-frame consistency. +Figure 5: Model performance on different types of prompts. +Video-Text Alignment +Traditional natural video evaluation methods do not need to +consider the alignment between the video and text prompt, +which is one reason why they tend to fail when directly ap- +plied to AIGC video quality assessment (VQA). Therefore, +based on the successful VQA method (Wu et al. 2023a), we +incorporate the text branch to model the alignment between +the generated content and the corresponding text. Inspired +by BLIP (Li et al. 2022b), we design an effective tempo- +ral adapter to extend it to the temporal dimension, as shown +in 6, which could be formulated as, +VE-Bench QA: Subjective-Aligned Metric for +Text-Driven Video Editing +Based on the VE-Bench DB, we further developed the VE- +Bench Quality Assessment (VE-Bench QA) network, which +aligns with human subjective perceptions for evaluating the +quality of edited videos, as illustrated in Fig. 6. The VE- +Bench QA evaluates the quality of edited videos from three +aspects: (1) Alignment between the edited video and the +prompt. (2) Relevance between the edited video and the +original video. (3) Quality of the edited video. We will elab- +orate on each component in the following sections. +ebv = Fbv(V⋆), (2) +tbv = Fta(ebv ), (3) +ebt = Fbt(p,Fca(tbv )), (4) +where Fbv, Fbt refer to the BLIP visual and text encoder, +and Fta represents the temporal adapter. p is the prompt. +The derived spatio-temporal feature tbv is then interacted +with the text encoder via cross-attention (denoted as Fca). +Source-Target Relationship +Measuring the consistency between the src and dst videos +is challenging. There is inherently a connection between the + +===== PAGE 6 ===== +Aesthetic Evaluator +Distortion Evaluator +Edited video +Encoder +BLIP-V +Score +Head +Source video +Temporal Adapter +Prompt: A white swan +Spatio-Temporal +Encoder +Spatio-Temporal +Encoder +Encoder +BLIP-T +Score +Head +Fusion +Figure 6: Network architecture of VE-Bench QA. +src and dst videos, but there are also significant differences +in the pixel space. Therefore, directly using methods like +MSE for RGB space measurements has certain limitations. +We design an effective spatiotemporal extractor to project +the src-dst videos into a latent space. After concatenating +them along the dimension, we obtain a reasonable score es- +timate through a FFN which could be formulated as, +f= F(V), (5) +f⋆ += F⋆(V⋆), (6) +os = Hs(Concat(f,f⋆)), (7) +where V, V⋆ denote the original and edited videos, respec- +tively. os is the output vector measuring the relevance be- +tween source and edited videos. Hs is the lightweight feed- +forward network. F and F⋆ denote the spatio-temporal en- +coder for source and target, respectively. In practice, we test +different spatio-temporal backbones and finally choose the +Uniformer (Li et al. 2023). +Visual Quality +To assess the quality of the edited video, we start from the +perspectives used in the previous top-performance method +DOVER (Wu et al. 2023a), which evaluates videos based +on aesthetics and technical distortion. DOVER achieves suc- +cess in some natural video quality assessment datasets such +as (Ying et al. 2021; Sinno and Bovik 2018). In practice, the +measurement of aesthetics is implemented via the inflated +ConvNext (Liu et al. 2022a) pre-trained on AVA (Murray, +Marchesotti, and Perronnin 2012), and the distortion is as- +sessed with the Video-Swin (Liu et al. 2022b) backbone pre- +trained with GRPB (Wu et al. 2022). At the first stage of +training, the backbones from DOVER are frozen and only +the parameters of the regression head are updated. In the +second stage, all parameters of the visual quality branches +(namely, the aesthetic and technical branch) are updated. +Supervision +Following previous works (Wu et al. 2023a, 2022; Qu et al. +2024), we adopt the combination of PLCC (Pearson Linear +Correlation Coefficient) loss and rank loss (Gao et al. 2019) +with the weight of αas the total loss for all branches of the +overall network, which could be formulated as follows. +L= Lplcc + α·Lrank , where αis set to 0.3 in practice. +(8) +Experiments +Implementation Details +We build all models via PyTorch and train them via NVIDIA +V100 GPUs. Following the 10-fold method (Kou et al. 2023; +Wu et al. 2023a; Sun et al. 2022), all models are trained with +the initial learning rate of 1e−3 and the batch size of 8 +on VE-Bench DB for 60 epochs. Following DOVER (Wu +et al. 2023a), we first fine-tuning the head for 40 epochs with +linear probing, and then train all parameters for another 20 +epochs. Adam (Kingma and Ba 2014) optimizer and a co- +sine scheduler are applied during training. Following pre- +vious works (Wu et al. 2023a), the aesthetic and techni- +cal branches of the evaluator are initialized with pre-trained +ConvNext (Liu et al. 2022a) and VideoSwin-Tiny (Liu et al. +2022b) with GRPB (Wu et al. 2022). +Evaluation Metrics +Following previous works (Wu et al. 2023a; Kou et al. 2024, +2023; Sun et al. 2022), we use four metrics as our eval- +uation metrics: Spearman’s Rank Order Correlation Coef- +ficient (SROCC), Pearson’s Linear Correlation Coefficient +(PLCC), Kendall rank-order correlation coefficient (KRCC), +and Root Mean Square Error (RMSE). +Quantitative Results +We compare our results with advanced evaluation metrics +in video editing, including objective metrics (Radford et al. +2021; Cong et al. 2024; Kirstain et al. 2023) and state- +of-the-art human-aligned Video Quality Assessment (VQA) +methods (Kou et al. 2023; Wu et al. 2022, 2023a). The re- +sults are shown in Table 2. We further collected a valida- +tion set generated by other models (Cohen et al. 2024; Cey- +lan, Huang, and Mitra 2023), which are also voted by 24 +annotators, and tested on more datasets (Kou et al. 2024). +Compared with the baseline DOVER (Wu et al. 2023a) re- +sult, which obtains SRCC and PLCC of 0.4929 and 0.5924. +VE-Bench QA attains 0.6008 and 0.6544, respectively. We +further test models on T2VQA-DB (Kou et al. 2024), re- +moving the src-dst branch for lack of src videos, as shown +in Table 4. From these, it can be seen that compared to +previous traditional VQA methods (Wu et al. 2023a, 2022; +Kou et al. 2023) and commonly used objective metrics, VE- +Bench QA achieves significantly superior performance in +aligning with human subjective perception, surpassing the +second by 7.64%, 8.06%, 8.85%, 13.2% in SROCC, PLCC, +KLCC, and RMSE, respectively. Compared with our base- +line method DOVER, VE-Bench attains higher performance +gain, with the improvements of 0.1296,0.1035,0.1060, and +0.216 on SROCC, PLCC, KLCC, and RMSE, respectively. +Compared with learning-based methods, the performances +of Zero-shot objective measurements are relatively low. + +===== PAGE 7 ===== +(a) FastVQA +(b) StableVQA (c) DOVER (d) VE-Bench QA +Figure 7: Plots of predicted vs. GT scores. The brightness of scatter points from dark to bright means density from low to high. +Type Models VE-Bench DB 10-fold +SROCC ↑ PLCC ↑ KRCC ↑ RMSE ↓ +Zero-shot +CLIP-F (Radford et al. 2021) 0.2284 0.1860 0.1545 4.448 +Sedit (Cong et al. 2024) 0.1686 0.1865 0.1135 3.981 +PickScore (Kirstain et al. 2023) 0.2266 0.2446 0.1540 1.786 +Fine-tuned +FastVQA (Wu et al. 2022) 0.6333 0.6326 0.4545 1.312 +StableVQA (Kou et al. 2023) 0.6889 0.6783 0.4974 1.262 +DOVER (Wu et al. 2023a) 0.6119 0.6295 0.4354 1.311 +Ours VE-Bench QA 0.7415 0.7330 0.5414 1.095 +Table 2: Comparison of different methods with VE-Bench QA. +Experiment Method SROCC ↑ PLCC ↑ KRCC ↑ RMSE ↓ +Baseline DOVER 0.6119 0.6295 0.4354 1.311 +Text CLIP 0.6379 0.6529 0.4560 1.269 +BLIP 0.7171 0.7094 0.5193 1.146 +Temporal +None 0.7171 0.7094 0.5193 1.146 +VSwin 0.7187 0.7101 0.5197 1.143 +MVD 0.7228 0.7143 0.5240 1.134 +Uformer 0.7317 0.7252 0.5328 1.116 +Fusion +None 0.7317 0.7252 0.5328 1.116 +MCA 0.7330 0.7255 0.5341 1.113 +Concat 0.7415 0.7330 0.5414 1.095 +Param. w/o 0.7251 0.7174 0.5262 1.130 +w 0.7415 0.7330 0.5414 1.095 +Table 3: Ablation study of the proposed VE-Bench QA. +Similar situations are quite common in previous works such +as (Kou et al. 2024; Qu et al. 2024), as the objective quan- +titative metric struggles to align with human perceptions. +Among all Zero-shot methods, PickScore (Kirstain et al. +2023) achieves the top overall performance, which is pre- +trained via a reward model with human feedback. CLIP- +F (Radford et al. 2021) achieved comparable SROCC and +KRCC metrics to PickScore, but was significantly weaker in +terms of PLCC and RMSE metrics. Sedit(Cong et al. 2024), +is obtained by dividing the CLIP-T metric by the Warp- +MSE (Ceylan, Huang, and Mitra 2023) metric. It reflects the +scores on the spatio-temporal quality of the edited video and +its alignment with the text prompt to some extent. However, +it is not aligned with human subjective perception and ob- +tains limited scores. +Qualitative Results +We also plot the difference between the predicted scores af- +ter training and the MOS scores, as illustrated in Figure 7. +The curves are obtained by a four-order polynomial nonlin- +ear fitting. As the brightness of scatter points grows from low +to high, the density goes from low to high. From there, it can +be intuitively seen that VE-Bench QA has prediction results +more aligned with human perception. We further conducted +a qualitative comparison for different score levels in VE- +Bench, as illustrated in the supplements, where we present +several video examples in VE-Bench DB with varying MOS. +Ablation Study +To further validate the results of each module in VE-Bench +QA, we performed detailed ablation experiments on each +module, as shown in Table 3. All results were obtained +through 10-fold validation training on the VE-Bench DB +with the same experimental hyper-parameter design. The +settings we adopted in our final model are underlined. We +first explore different ways of video-text alignment. Here, +we experimented with CLIP and fine-tuned the regression +head composed of Feed-Forward Networks, which learn +the alignment from the cosine similarity of its visual and +text Backbone outputs. Experiments demonstrate that, al- +though both CLIP and BLIP possess rich vision-language +prior knowledge and enhance network performance, BLIP +achieved more effective improvements. Furthermore, we ex- +plored how to effectively model the relevance between the + +===== PAGE 8 ===== +Type Models T2VQA-DB +SROCC ↑ PLCC ↑ KRCC ↑ +Zero-shot +CLIPSim (Radford et al. 2021) 0.1047 0.1277 0.0702 +BLIP (Li et al. 2022b) 0.1659 0.1860 0.1112 +ImageReward (Xu et al. 2024) 0.1875 0.2121 0.1266 +ViCLIP (Wang et al. 2023b) 0.1162 0.1449 0.0781 +UMTScore (Liu et al. 2023) 0.0676 0.0721 0.0453 +Finetuned +SimpleVQA (Sun et al. 2022) 0.6275 0.6338 0.4466 +BVQA (Li et al. 2022a) 0.7390 0.7486 0.5487 +FAST-VQA (Wu et al. 2022) 0.7173 0.7295 0.5303 +DOVER (Wu et al. 2023a) 0.7609 0.7693 0.5704 +T2VQA (Kou et al. 2024) 0.7965 0.8066 0.6058 +Ours VE-Bench QA 0.8179 0.8227 0.6370 +Table 4: Quantitative comparison on T2VQA-DB. +source video and the edited video. We attempted to effi- +ciently extract video features and, through experiments con- +ducted on methods such as Video SwinTransformer (Liu +et al. 2022b) (VSwin), Masked Video Distillation (Wang +et al. 2023a) (MVD), and Uniformer (Li et al. 2023) +(Uformer), we identified suitable feature extractors. Addi- +tionally, we explored effective ways to fuse features from +the source video and the edited video, as presented in Ta- +ble 3. MCA denotes the mutli-head cross-attention, which +proves effective in lots of prior works (Meng et al. 2022; +Xie et al. 2024b,a). We found that concatenation along the +dimension is a simple and effective design for the assess- +ment. We further ablate the effect of additional parameter, +which demonstrates the improvements are not from more pa- +rameters. During these experiments, we could learn that the +design of video-text similarity and the focus on the source- +target video relationship modeling is of importance to the +overall performance. +Conclusion +In this work, we introduce VE-Bench DB, a subjective- +aligned dataset specifically designed for evaluating text- +driven video editing, and VE-Bench QA, a novel human- +aligned metric for assessing the effects of text-driven video +editing. VE-Bench DB features rich video content and de- +tailed editing prompt categories. To the best of our knowl- +edge, VE-Bench DB is the first VQA dataset tailored for +text-driven video editing. Furthermore, extensive exper- +iments demonstrate the effectiveness of VE-Bench QA. +Compared to traditional metrics commonly used in editing +tasks, VE-Bench QA achieves significantly better alignment +with human perceptions. +Acknowledgments +This work was supported by National Science and Technol- +ogy Major Project (2024ZD01NL00101), Natural Science +Foundation of China (62271013, 62031013), Guang- +dong Provincial Key Laboratory of Ultra High Definition +Immersive Media Technology (2024B1212010006), +Guangdong Province Pearl River Talent Program +(2021QN020708), Guangdong Basic and Applied Basic +Research Foundation (2024A1515010155), Shenzhen Sci- +ence and Technology Program (JCYJ20240813160202004, +JCYJ20230807120808017). +References +Bain, M.; Nagrani, A.; Varol, G.; and Zisserman, A. 2021. Frozen +in time: A joint video and image encoder for end-to-end retrieval. +In Proceedings of the IEEE/CVF international conference on com- +puter vision, 1728–1738. +Brooks, T.; Holynski, A.; and Efros, A. A. 2023. Instructpix2pix: +Learning to follow image editing instructions. In Proceedings of +the IEEE/CVF Conference on Computer Vision and Pattern Recog- +nition, 18392–18402. +Brooks, T.; Peebles, B.; Holmes, C.; DePue, W.; Guo, Y.; Jing, L.; +Schnurr, D.; Taylor, J.; Luhman, T.; Luhman, E.; Ng, C.; Wang, R.; +and Ramesh, A. 2024. Video generation models as world simula- +tors. +Butler, D. J.; Wulff, J.; Stanley, G. B.; and Black, M. J. 2012. A +naturalistic open source movie for optical flow evaluation. In A. +Fitzgibbon et al. (Eds.), ed., European Conf. on Computer Vision +(ECCV), Part IV, LNCS 7577, 611–625. Springer-Verlag. +Ceylan, D.; Huang, C.-H. P.; and Mitra, N. J. 2023. Pix2video: +Video editing using image diffusion. In Proceedings of the +IEEE/CVF International Conference on Computer Vision, 23206– +23217. +Chai, W.; Guo, X.; Wang, G.; and Lu, Y. 2023. Stablevideo: Text- +driven consistency-aware diffusion video editing. In Proceedings +of the IEEE/CVF International Conference on Computer Vision, +23040–23050. +Chen, Q.; Ma, Y.; Wang, H.; Yuan, J.; Zhao, W.; Tian, Q.; Wang, +H.; Min, S.; Chen, Q.; and Liu, W. 2024. Follow-Your-Canvas: +Higher-Resolution Video Outpainting with Extensive Content Gen- +eration. arXiv preprint arXiv:2409.01055. +Cohen, N.; Kulikov, V.; Kleiner, M.; Huberman-Spiegelglas, I.; +and Michaeli, T. 2024. Slicedit: Zero-Shot Video Editing With +Text-to-Image Diffusion Models Using Spatio-Temporal Slices. In +Salakhutdinov, R.; Kolter, Z.; Heller, K.; Weller, A.; Oliver, N.; +Scarlett, J.; and Berkenkamp, F., eds., Proceedings of the 41st In- +ternational Conference on Machine Learning, volume 235 of Pro- +ceedings of Machine Learning Research, 9109–9137. PMLR. + +===== PAGE 9 ===== +Cong, Y.; Xu, M.; Chen, S.; Ren, J.; Xie, Y.; Perez-Rua, J.-M.; +Rosenhahn, B.; Xiang, T.; He, S.; et al. 2024. FLATTEN: opti- +cal FLow-guided ATTENtion for consistent text-to-video editing. +In The Twelfth International Conference on Learning Representa- +tions. +Feng, K.; Ma, Y.; Wang, B.; Qi, C.; Chen, H.; Chen, Q.; and Wang, +Z. 2024a. Dit4edit: Diffusion transformer for image editing. arXiv +preprint arXiv:2411.03286. +Feng, R.; Weng, W.; Wang, Y.; Yuan, Y.; Bao, J.; Luo, C.; Chen, Z.; +and Guo, B. 2024b. Ccedit: Creative and controllable video editing +via diffusion models. In Proceedings of the IEEE/CVF Conference +on Computer Vision and Pattern Recognition, 6712–6722. +Gao, F.; Tao, D.; Gao, X.; and Li, X. 2019. Learning to Rank for +Blind Image Quality Assessment. arXiv:1309.0213. +Geyer, M.; Bar-Tal, O.; Bagon, S.; and Dekel, T. 2024. TokenFlow: +Consistent Diffusion Features for Consistent Video Editing. In The +Twelfth International Conference on Learning Representations. +Hartwig, S.; Engel, D.; Sick, L.; Kniesel, H.; Payer, T.; Ropin- +ski, T.; et al. 2024. Evaluating Text to Image Synthesis: Sur- +vey and Taxonomy of Image Quality Metrics. arXiv preprint +arXiv:2403.11821. +Huang, Y.; Huang, J.; Liu, Y.; Yan, M.; Lv, J.; Liu, J.; Xiong, W.; +Zhang, H.; Chen, S.; and Cao, L. 2024. Diffusion model-based +image editing: A survey. arXiv preprint arXiv:2402.17525. +Int.Telecommun.Union. 2000. Methodology for the Subjective As- +sessment of the Quality of Television Pictures ITU-R Recommen- +dation. Tech. Rep. +Jia, M.; Zhao, L.; Li, G.; and Zheng, Y. 2024a. ContextHOI: +Spatial Context Learning for Human-Object Interaction Detection. +arXiv:2412.09050. +Jia, M.; Zhao, L.; Li, G.; and Zheng, Y. 2024b. Orchestrating the +Symphony of Prompt Distribution Learning for Human-Object In- +teraction Detection. arXiv:2412.08506. +Kara, O.; Kurtkaya, B.; Yesiltepe, H.; Rehg, J. M.; and Yanardag, +P. 2024. Rave: Randomized noise shuffling for fast and consis- +tent video editing with diffusion models. In Proceedings of the +IEEE/CVF Conference on Computer Vision and Pattern Recogni- +tion, 6507–6516. +Kay, W.; Carreira, J.; Simonyan, K.; Zhang, B.; Hillier, C.; Vijaya- +narasimhan, S.; Viola, F.; Green, T.; Back, T.; Natsev, P.; et al. +2017. The kinetics human action video dataset. arXiv preprint +arXiv:1705.06950. +Khachatryan, L.; Movsisyan, A.; Tadevosyan, V.; Henschel, R.; +Wang, Z.; Navasardyan, S.; and Shi, H. 2023. Text2video-zero: +Text-to-image diffusion models are zero-shot video generators. In +Proceedings of the IEEE/CVF International Conference on Com- +puter Vision, 15954–15964. +Kingma, D. P.; and Ba, J. 2014. Adam: A method for stochastic +optimization. arXiv preprint arXiv:1412.6980. +Kirstain, Y.; Polyak, A.; Singer, U.; Matiana, S.; Penna, J.; and +Levy, O. 2023. Pick-a-pic: An open dataset of user preferences +for text-to-image generation. Advances in Neural Information Pro- +cessing Systems, 36: 36652–36663. +Kou, T.; Liu, X.; Sun, W.; Jia, J.; Min, X.; Zhai, G.; and Liu, N. +2023. Stablevqa: A deep no-reference quality assessment model +for video stability. In Proceedings of the 31st ACM International +Conference on Multimedia, 1066–1076. +Kou, T.; Liu, X.; Zhang, Z.; Li, C.; Wu, H.; Min, X.; Zhai, G.; and +Liu, N. 2024. Subjective-Aligned Dateset and Metric for Text-to- +Video Quality Assessment. arXiv preprint arXiv:2403.11956. +Kuaishou. 2024. Kling. URL:https://kling.kuaishou.com/. +Li, B.; Zhang, W.; Tian, M.; Zhai, G.; and Wang, X. 2022a. +Blindly Assess Quality of In-the-Wild Videos via Quality-aware +Pre-training and Motion Perception. IEEE Transactions on Cir- +cuits and Systems for Video Technology, 32(9): 5944–5958. +Li, J.; Li, D.; Xiong, C.; and Hoi, S. 2022b. Blip: Bootstrap- +ping language-image pre-training for unified vision-language un- +derstanding and generation. In International conference on ma- +chine learning, 12888–12900. PMLR. +Li, K.; Wang, Y.; Zhang, J.; Gao, P.; Song, G.; Liu, Y.; Li, H.; and +Qiao, Y. 2023. Uniformer: Unifying convolution and self-attention +for visual recognition. IEEE Transactions on Pattern Analysis and +Machine Intelligence, 45(10): 12581–12600. +Liu, S.; Zhang, Y.; Li, W.; Lin, Z.; and Jia, J. 2024. Video-p2p: +Video editing with cross-attention control. In Proceedings of the +IEEE/CVF Conference on Computer Vision and Pattern Recogni- +tion, 8599–8608. +Liu, Y.; Li, L.; Ren, S.; Gao, R.; Li, S.; Chen, S.; Sun, X.; and +Hou, L. 2023. FETV: A Benchmark for Fine-Grained Evaluation +of Open-Domain Text-to-Video Generation. arXiv preprint arXiv: +2311.01813. +Liu, Z.; Mao, H.; Wu, C.-Y.; Feichtenhofer, C.; Darrell, T.; and +Xie, S. 2022a. A convnet for the 2020s. In Proceedings of the +IEEE/CVF conference on computer vision and pattern recognition, +11976–11986. +Liu, Z.; Ning, J.; Cao, Y.; Wei, Y.; Zhang, Z.; Lin, S.; and Hu, H. +2022b. Video swin transformer. In Proceedings of the IEEE/CVF +conference on computer vision and pattern recognition, 3202– +3211. +Ma, Y.; Cun, X.; He, Y.; Qi, C.; Wang, X.; Shan, Y.; Li, X.; and +Chen, Q. 2023. MagicStick: Controllable Video Editing via Con- +trol Handle Transformations. arXiv preprint arXiv:2312.03047. +Ma, Y.; He, Y.; Cun, X.; Wang, X.; Chen, S.; Li, X.; and Chen, +Q. 2024a. Follow your pose: Pose-guided text-to-video generation +using pose-free videos. In Proceedings of the AAAI Conference on +Artificial Intelligence, volume 38, 4117–4125. +Ma, Y.; He, Y.; Wang, H.; Wang, A.; Qi, C.; Cai, C.; Li, X.; +Li, Z.; Shum, H.-Y.; Liu, W.; et al. 2024b. Follow-Your-Click: +Open-domain Regional Image Animation via Short Prompts. arXiv +preprint arXiv:2403.08268. +Ma, Y.; Liu, H.; Wang, H.; Pan, H.; He, Y.; Yuan, J.; Zeng, A.; Cai, +C.; Shum, H.-Y.; Liu, W.; et al. 2024c. Follow-Your-Emoji: Fine- +Controllable and Expressive Freestyle Portrait Animation. arXiv +preprint arXiv:2406.01900. +Ma, Y.; Wang, Y.; Wu, Y.; Lyu, Z.; Chen, S.; Li, X.; and Qiao, +Y. 2022. Visual knowledge graph for human action reasoning in +videos. In Proceedings of the 30th ACM International Conference +on Multimedia, 4132–4141. +Mehl, L.; Schmalfuss, J.; Jahedi, A.; Nalivayko, Y.; and Bruhn, +A. 2023. Spring: A high-resolution high-detail dataset and bench- +mark for scene flow, optical flow and stereo. In Proceedings of the +IEEE/CVF Conference on Computer Vision and Pattern Recogni- +tion, 4981–4991. +Meng, L.; Li, H.; Chen, B.-C.; Lan, S.; Wu, Z.; Jiang, Y.-G.; and +Lim, S.-N. 2022. Adavit: Adaptive vision transformers for efficient +image recognition. In Proceedings of the IEEE/CVF Conference on +Computer Vision and Pattern Recognition, 12309–12318. +Murray, N.; Marchesotti, L.; and Perronnin, F. 2012. AVA: A large- +scale database for aesthetic visual analysis. In 2012 IEEE con- +ference on computer vision and pattern recognition, 2408–2415. +IEEE. + +===== PAGE 10 ===== +Oquab, M.; Darcet, T.; Moutakanni, T.; Vo, H. V.; Szafraniec, M.; +Khalidov, V.; Fernandez, P.; HAZIZA, D.; Massa, F.; El-Nouby, +A.; et al. 2024. DINOv2: Learning Robust Visual Features without +Supervision. Transactions on Machine Learning Research. +Pont-Tuset, J.; Perazzi, F.; Caelles, S.; Arbel´ aez, P.; Sorkine- +Hornung, A.; and Van Gool, L. 2017. The 2017 davis challenge +on video object segmentation. arXiv preprint arXiv:1704.00675. +Qi, C.; Cun, X.; Zhang, Y.; Lei, C.; Wang, X.; Shan, Y.; and Chen, +Q. 2023. Fatezero: Fusing attentions for zero-shot text-based video +editing. In Proceedings of the IEEE/CVF International Conference +on Computer Vision, 15932–15942. +Qu, B.; Liang, X.; Sun, S.; and Gao, W. 2024. Exploring aigc +video quality: A focus on visual harmony, video-text consistency +and domain distribution gap. arXiv preprint arXiv:2404.13573. +Radford, A.; Kim, J. W.; Hallacy, C.; Ramesh, A.; Goh, G.; Agar- +wal, S.; Sastry, G.; Askell, A.; Mishkin, P.; Clark, J.; et al. 2021. +Learning transferable visual models from natural language supervi- +sion. In International conference on machine learning, 8748–8763. +PMLR. +Rout, L.; Chen, Y.; Ruiz, N.; Kumar, A.; Caramanis, C.; Shakkottai, +S.; and Chu, W. 2024. RB-Modulation: Training-Free Personaliza- +tion of Diffusion Models using Stochastic Optimal Control. +Series, B. 2002. Methodology for the subjective assessment of the +quality of television pictures. Recommendation ITU-R BT, 500(13). +Sinno, Z.; and Bovik, A. C. 2018. Large-scale study of percep- +tual video quality. IEEE Transactions on Image Processing, 28(2): +612–627. +Sun, K.; Huang, K.; Liu, X.; Wu, Y.; Xu, Z.; Li, Z.; and Liu, X. +2024. T2v-compbench: A comprehensive benchmark for composi- +tional text-to-video generation. arXiv preprint arXiv:2407.14505. +Sun, W.; Min, X.; Lu, W.; and Zhai, G. 2022. A deep learning +based no-reference quality assessment model for ugc videos. In +Proceedings of the 30th ACM International Conference on Multi- +media, 856–865. +Tumanyan, N.; Geyer, M.; Bagon, S.; and Dekel, T. 2023. Plug- +and-play diffusion features for text-driven image-to-image transla- +tion. In Proceedings of the IEEE/CVF Conference on Computer +Vision and Pattern Recognition, 1921–1930. +Unterthiner, T.; Van Steenkiste, S.; Kurach, K.; Marinier, R.; +Michalski, M.; and Gelly, S. 2018. Towards accurate generative +models of video: A new metric & challenges. arXiv preprint +arXiv:1812.01717. +Wang, H.; Spinelli, M.; Wang, Q.; Bai, X.; Qin, Z.; and Chen, A. +2024a. Instantstyle: Free lunch towards style-preserving in text-to- +image generation. arXiv preprint arXiv:2404.02733. +Wang, H.; Xing, P.; Huang, R.; Ai, H.; Wang, Q.; and Bai, X. +2024b. Instantstyle-plus: Style transfer with content-preserving in +text-to-image generation. arXiv preprint arXiv:2407.00788. +Wang, J.; Ma, Y.; Guo, J.; Xiao, Y.; Huang, G.; and Li, X. 2024c. +COVE: Unleashing the Diffusion Feature Correspondence for Con- +sistent Video Editing. arXiv preprint arXiv:2406.08850. +Wang, R.; Chen, D.; Wu, Z.; Chen, Y.; Dai, X.; Liu, M.; Yuan, +L.; and Jiang, Y.-G. 2023a. Masked video distillation: Rethinking +masked feature modeling for self-supervised video representation +learning. In Proceedings of the IEEE/CVF conference on computer +vision and pattern recognition, 6312–6322. +Wang, Y.; He, Y.; Li, Y.; Li, K.; Yu, J.; Ma, X. J.; Chen, X.; Wang, +Y.; Luo, P.; Liu, Z.; Wang, Y.; Wang, L.; and Qiao, Y. 2023b. In- +ternVid: A Large-scale Video-Text Dataset for Multimodal Under- +standing and Generation. ArXiv, abs/2307.06942. +Wei, Y.; Huang, L.; Wu, Z.-F.; Wang, W.; Liu, Y.; Jia, M.; and Ma, +S. 2024. Chains of Diffusion Models. +Wu, H.; Chen, C.; Hou, J.; Liao, L.; Wang, A.; Sun, W.; Yan, Q.; +and Lin, W. 2022. Fast-vqa: Efficient end-to-end video quality +assessment with fragment sampling. In European conference on +computer vision, 538–554. Springer. +Wu, H.; Zhang, E.; Liao, L.; Chen, C.; Hou, J.; Wang, A.; Sun, W.; +Yan, Q.; and Lin, W. 2023a. Exploring video quality assessment +on user generated contents from aesthetic and technical perspec- +tives. In Proceedings of the IEEE/CVF International Conference +on Computer Vision, 20144–20154. +Wu, H.; Zhang, Z.; Zhang, E.; Chen, C.; Liao, L.; Wang, A.; Li, +C.; Sun, W.; Yan, Q.; Zhai, G.; and Lin, W. 2024a. Q-Bench: A +Benchmark for General-Purpose Foundation Models on Low-level +Vision. In ICLR. +Wu, H.; Zhang, Z.; Zhang, W.; Chen, C.; Liao, L.; Li, C.; Gao, +Y.; Wang, A.; Zhang, E.; Sun, W.; et al. 2023b. Q-align: Teach- +ing lmms for visual scoring via discrete text-defined levels. arXiv +preprint arXiv:2312.17090. +Wu, J. Z.; Ge, Y.; Wang, X.; Lei, S. W.; Gu, Y.; Shi, Y.; Hsu, W.; +Shan, Y.; Qie, X.; and Shou, M. Z. 2023c. Tune-a-video: One-shot +tuning of image diffusion models for text-to-video generation. In +Proceedings of the IEEE/CVF International Conference on Com- +puter Vision, 7623–7633. +Wu, J. Z.; Li, X.; Gao, D.; Dong, Z.; Bai, J.; Singh, A.; Xiang, X.; +Li, Y.; Huang, Z.; Sun, Y.; et al. 2023d. Cvpr 2023 text guided +video editing competition. arXiv preprint arXiv:2310.16003. +Wu, X.; Hao, Y.; Sun, K.; Chen, Y.; Zhu, F.; Zhao, R.; and Li, H. +2023e. Human preference score v2: A solid benchmark for evalu- +ating human preferences of text-to-image synthesis. arXiv preprint +arXiv:2306.09341. +Wu, Z.; Weng, Z.; Peng, W.; Yang, X.; Li, A.; Davis, L. S.; and +Jiang, Y.-G. 2024b. Building an open-vocabulary video CLIP +model with better architectures, optimization and data. IEEE +Transactions on Pattern Analysis and Machine Intelligence. +Xie, L.; Gao, W.; Zheng, H.; and Li, G. 2024a. ROI-Guided Point +Cloud Geometry Compression Towards Human and Machine Vi- +sion. In Proceedings of the 32nd ACM International Conference +on Multimedia. +Xie, L.; Gao, W.; Zheng, H.; and Li, G. 2024b. SPCGC: Scalable +Point Cloud Geometry Compression for Machine Vision. In IEEE +International Conference on Robotics and Automation, 594–595. +Xu, J.; Liu, X.; Wu, Y.; Tong, Y.; Li, Q.; Ding, M.; Tang, J.; and +Dong, Y. 2024. Imagereward: Learning and evaluating human pref- +erences for text-to-image generation. Advances in Neural Informa- +tion Processing Systems, 36. +Yang, S.; Zhou, Y.; Liu, Z.; and Loy, C. C. 2023. Rerender a video: +Zero-shot text-guided video-to-video translation. In SIGGRAPH +Asia 2023 Conference Papers, 1–11. +Yang, S.; Zhou, Y.; Liu, Z.; and Loy, C. C. 2024. FRESCO: Spatial- +Temporal Correspondence for Zero-Shot Video Translation. In +Proceedings of the IEEE/CVF Conference on Computer Vision and +Pattern Recognition, 8703–8712. +Ying, Z.; Mandal, M.; Ghadiyaram, D.; and Bovik, A. 2021. Patch- +vq:’patching up’the video quality problem. In Proceedings of the +IEEE/CVF conference on computer vision and pattern recognition, +14019–14029. +Zhang, L.; Rao, A.; and Agrawala, M. 2023. Adding conditional +control to text-to-image diffusion models. In Proceedings of the +IEEE/CVF International Conference on Computer Vision, 3836– +3847. + +===== PAGE 11 ===== +Zhang, R.; Isola, P.; Efros, A. A.; Shechtman, E.; and Wang, O. +2018. The unreasonable effectiveness of deep features as a percep- +tual metric. In Proceedings of the IEEE conference on computer +vision and pattern recognition, 586–595. +Zhang, Y.; Wei, Y.; Jiang, D.; ZHANG, X.; Zuo, W.; and Tian, +Q. 2024. ControlVideo: Training-free Controllable Text-to-video +Generation. In The Twelfth International Conference on Learning +Representations. +Zhu, C.; Li, K.; Ma, Y.; Tang, L.; Fang, C.; Chen, C.; Chen, Q.; +and Li, X. 2024. InstantSwap: Fast Customized Concept Swapping +across Sharp Shape Differences. arXiv preprint arXiv:2412.01197. diff --git a/benchmarks/edit/pdf/_extracted/vedit-bench.meta.txt b/benchmarks/edit/pdf/_extracted/vedit-bench.meta.txt new file mode 100644 index 0000000000000000000000000000000000000000..73974616a2a97b30e10931726a55bd5763436d95 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/vedit-bench.meta.txt @@ -0,0 +1,3 @@ +title= +author= +pages=14 diff --git a/benchmarks/edit/pdf/_extracted/vedit-bench.txt b/benchmarks/edit/pdf/_extracted/vedit-bench.txt new file mode 100644 index 0000000000000000000000000000000000000000..a828c6ce3b485b3a24b4776c2e386297c23ce10e --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/vedit-bench.txt @@ -0,0 +1,1767 @@ +FILE: VEDITBENCH- HOLISTIC BENCHMARK FOR TEXT-GUIDED VIDEO EDITING.pdf +PAGES: 14 + + +===== PAGE 1 ===== +000 +001 +002 +003 +004 +005 +006 +007 +008 +009 +010 +011 +012 +013 +014 +015 +016 +017 +018 +019 +020 +021 +022 +023 +024 +025 +026 +027 +028 +029 +030 +031 +032 +033 +034 +035 +036 +037 +038 +039 +040 +041 +042 +043 +044 +045 +046 +047 +048 +049 +050 +051 +052 +053 +Under review as a conference paper at ICLR 2025 +VEDITBENCH: HOLISTIC BENCHMARK FOR +TEXT-GUIDED VIDEO EDITING +Anonymous authors +Paper under double-blind review +420 Real-world Videos +animal food vehicles +sports activity technology +scenery +Semantic Fidelity +Video Editing +Models +• Spatial Alignment +• Spatio-Temporal +Alignment +• Motion Similarity +• Structure Similarity +6 Editing Tasks +Object +Addition +Object +Removal +Object +Swap +Scene +Replacement +Motion +Change +Style +Translation +9 Evaluation Dimensions +• Frame Quality +• Frame Aesthetic +• Video Quality +• Motion Smoothness +• Overall Quality +Motion +Similarity +Structural +Similarity +Spatio-Temporal +Alignment +Image +Quality +Spatial +Alignment +Image +Aesthetic +Overall +Quality +Visual Quality +Temporal +Quality Motion +Smoothness +Tune-A-Video +MotionDirector +VidToMe +DMT +Text2Video-Zero +Pix2Video +TokenFlow +Flatten +RAVE +InsV2V +Figure 1: Introducing VEditBench, a holistic framework for the evaluation of Text-Guided Video +Editing (TGVE) models. VEditBench features a diverse dataset of 420 real-world videos across +six categories, along with six editing tasks driven by text prompts. We define nine distinct evaluation +metrics to access the model’s semantic fidelity and visual quality. Our evaluation of ten TGVE +models using VEditBench provides a comprehensive analysis of their performance. +ABSTRACT +Video editing usually requires substantial human expertise and effort. However, +recent advances in generative models have democratized this process, enabling +video edits to be made using simple textual instructions. Despite this progress, +the absence of a standardized and comprehensive benchmark has made it difficult +to compare different methods within a common framework. To address this gap, +we introduce VEditBench, a comprehensive benchmark for text-guided video +editing (TGVE). VEditBench offers several key features: (1) 420 real-world +videos spanning diverse categories and durations, including 300 short videos (2-4 +seconds) and 120 longer videos (10-20 seconds); (2) 6 editing tasks that capture +a broad range of practical editing challenges: object insertion, object removal, +object swap, scene replacement, motion change, and style translation; (3) 9 eval- +uation dimensions to assess the semantic fidelity and visual quality of edits. We +evaluate ten state-of-the-art video editing models using VEditBench, offering +an in-depth analysis of their performance across metrics, tasks, and models. We +hope VEditBench will provide valuable insights to the community and serve as +the standard benchmark for TGVE models following its open-sourcing. +1 INTRODUCTION +The recent explosion of generative AI models has revolutionized content creation, with video editing +emerging as a critical application in this rapidly evolving landscape. Millions of videos are produced +1 + +===== PAGE 2 ===== +054 +055 +056 +057 +058 +059 +060 +061 +062 +063 +064 +065 +066 +067 +068 +069 +070 +071 +072 +073 +074 +075 +076 +077 +078 +079 +080 +081 +082 +083 +084 +085 +086 +087 +088 +089 +090 +091 +092 +093 +094 +095 +096 +097 +098 +099 +100 +101 +102 +103 +104 +105 +106 +107 +Under review as a conference paper at ICLR 2025 +Table 1: Existing benchmarks for text-guided video editing. Many studies rely on private and +non-standardized benchmarks, while existing open-source TGVE benchmarks are inadequate in +terms of data scale and diversity. +Paper #Videos Video Duration Video Source #Edit Prompts Open-source +Tune-A-Video (Wu et al., 2023c) 42 1-4s DAVIS 140 8 +Dreamix (Molad et al., 2023) 29 - YouTube-8M 127 8 +Gen-1 (Esser et al., 2023) - - DAVIS 35 8 +Rerender A Video (Yang et al., 2023) 8 - Pexels, Pixabay - 8 +TokenFlow (Geyer et al., 2023) 61 40-200 frames DAVIS, Internet 61 8 +FlowVid (Liang et al., 2023) 25 1-4s DAVIS 115 8 +STDF (Yatim et al., 2023) 21 - - 54 8 +Fairy (Wu et al., 2023a) 50 - ShutterStock 1000 8 +RAVE (Wu et al., 2023a) 186 8 / 36 / 90 frames Pexel, Pixaba, DAVIS, Internet 186 8 +TGVE-2023 (Wu et al., 2023d) 76 32 / 128 frames DAVIS, YouTube, Videvo 304 3 +BalanceCC (Feng et al., 2024) 100 2-20s - 400 3 +V2VBench (Sun et al., 2024b) 50 2-200s Internet 150 3 +VEditBench (Ours) 420 2-4s / 10-40s YouTube, Videvo 2520 3 +daily, and AI-driven tools are increasingly sought after to streamline and enhance the editing pro- +cess. However, evaluating and comparing these text-guided video editing (TGVE) models presents +a significant challenge due to the lack of a standardized and comprehensive benchmark. +Existing efforts to evaluate TGVE models suffer from several limitations. Many studies rely on +small, private datasets that lack diversity and fail to reflect real-world editing scenarios (Wu et al., +2023c; Molad et al., 2023; Esser et al., 2023). This reliance on non-standardized and inaccessible +data hinders fair and open comparisons between different approaches. While recent works like +LOVEU-TGVE-2023 (Wu et al., 2023d), BalanceCC (Feng et al., 2024), and V2VBench (Sun et al., +2024b) have introduced open-source benchmarks, they remain limited in terms of data scale, prompt +diversity, and the range of editing tasks they cover. These limitations underscore the urgent need for +a more robust and comprehensive benchmark that can effectively assess the capabilities of TGVE +models. +To address this gap, we introduce VEditBench, a comprehensive benchmark specifically designed +for evaluating text-guided video editing. VEditBench provides a unified framework for assessing +the performance of diverse video editing models across a wide range of real-world scenarios. +VEditBench distinguishes itself through three key advancements: +• Diverse and Extensive Video Collection: We curated a diverse collection of videos from +YouTube and Videvo, spanning six categories: Animals, Food, Scenery, Sports Activity, Tech- +nology, and Vehicles. Recognizing the need for both short-form and long-form video editing, +we include videos ranging from 2-4 seconds to more challenging 10-40 second clips, addressing +a gap in existing benchmarks that primarily focus on short videos. +• Expanded Scope of Editing Tasks: VEditBench expands the scope of editing tasks beyond +the limitations of previous benchmarks. Instead of focusing solely on foreground, background, +and style modifications, we incorporate six diverse editing tasks reflective of real-world appli- +cations: object insertion, object removal, object swap, scene replacement, motion change, and +style translation. This expanded task set allows for a more comprehensive evaluation of model +capabilities across various editing scenarios. +• Multi-Dimensional Evaluation Framework: VEditBench addresses the challenge of eval- +uating video edits by employing a multi-dimensional evaluation framework. This framework +encompasses both Semantic Fidelity (i.e., how accurately the edited video adheres to the user’s +command) and Visual Quality (i.e., the overall visual appeal of the edited video, independent +of the edit itself ). Within each perspective, we define specific sub-dimensions to enable a more +fine-grained and insightful analysis of model performance. +To demonstrate the utility of VEditBench, we evaluate ten state-of-the-art video editing models, +offering an in-depth analysis of their performance across different dimensions, tasks, and model +architectures. This analysis provides valuable insights into the current state of TGVE and highlights +areas for future research and development. VEditBench will be made fully open-source to foster +further advancements in the field. +2 + +===== PAGE 3 ===== +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +Under review as a conference paper at ICLR 2025 +2 RELATED WORK +2.1 TEXT-GUIDED VIDEO EDITING (TGVE) MODELS. +TGVE aims to modify the visual content of a video based on textual prompts while preserving +its inherent characteristics. Pioneer Tune-A-Video (Wu et al., 2023c) inflates the image diffusion +models by incorporating cross-frame attention and fine-tuning on source videos to implicitly learn +and transfer motion. While demonstrating versatility across various editing tasks, Tune-A-Video +suffers from limitations in temporal consistency. +Subsequent works focus on extracting various correspondences from the source video to enhance +temporal consistency. Methods like FateZero (Qi et al., 2023), Video-P2P (Liu et al., 2023a), and +VidToMe (Li et al., 2024) extract cross- and self-attention features from the source video to guide +spatial layout and maintain coherence across frames. Others, such as Rerender A Video (Yang +et al., 2023), TokenFlow (Geyer et al., 2023), and Flatten (Cong et al., 2023b), focus on extracting +and aligning optical flows to improve the consistency of editing results. Meanwhile, Text2Video- +Zero (Khachatryan et al., 2023) and RAVE (Kara et al., 2024) utilize spatial conditioning tech- +niques from ControlNet (Zhang & Agrawala, 2023) to guide the editing process. Instruct Video- +to-Video (Cheng et al., 2023) explores instruction-guided video editing and investigates sampling +techniques for consistent long video generation. +More recently, with the emergence of advanced text-to-video (T2V) foundation models, researchers +have begun leveraging these models for improved temporal consistency in TGVE. MotionDirector +fine-tune T2V diffusion models with disentangled spatial and temporal LoRA modules for motion +customization. Diffusion Motion Transfer (DMT) (Yatim et al., 2024) employs a space-time feature +loss derived directly from the model to preserve overall motion during editing. +Despite these advancements, the field of TGVE still lacks a standardized benchmark for evaluating +and comparing different models. To address this critical gap, we introduce VEditBench, an open +and comprehensive benchmark designed to facilitate the standardized evaluation of TGVE models +2.2 BENCHMARKS FOR VIDEO GENERATIVE MODELS. +Early efforts rely on datasets like UCF-101 (Soomro et al., 2012), MSR-VTT (Xu et al., 2016), +and Kinetics (Carreira & Zisserman, 2017b; Carreira et al., 2018), which offer limited diversity. +Make-A-Video (Singer et al., 2023) evaluates on 300 text prompts across five common categories, +while FETV (Liu et al., 2023c) introduces fine-grained category labels and temporal dimensions +for a more in-depth assessment. EvalCrafter (Liu et al., 2023b) expands the scope with 700 real- +world prompts, and VBench (Huang et al., 2024) designs a compact yet representative prompt suite +across various evaluation dimensions and content categories. T2V-CompBench (Sun et al., 2024a) +focuses specifically on compositional text-to-video generation with 700 prompts spanning seven +compositional categories. +While these works advance the evaluation of text-to-video generation, video editing benchmarks +remain limited. LOVEU-TGVE-2023 (Wu et al., 2023d) introduces the first benchmark for text- +guided video editing, featuring 76 videos and 304 edit prompts across four edit types. Similarly, +BalanceCC (Feng et al., 2024) includes 100 videos, each paired with four edit prompts. However, +both benchmarks lack sufficient video variety and task diversity. +To address these limitations, we propose VEditBench, a comprehensive benchmark compris- +ing 420 diverse real-world videos, each annotated with six fine-grained edit tasks. Importantly, +VEditBench includes 120 long videos (10-40 seconds), addressing the under-explored challenge +of long video editing. +2.3 EVALUATION METRICS FOR VIDEO GENERATIVE MODELS. +Image-level metrics assess the quality of individual frames in generated videos. Common metrics +include Inception Score (IS) (Barratt & Sharma, 2018) for image quality and diversity, Fr´ echet In- +ception Distance (FID) (Parmar et al., 2022) for similarity to real images, and CLIP Score (Radford +et al., 2021) for alignment between images and text descriptions. +3 + +===== PAGE 4 ===== +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +Under review as a conference paper at ICLR 2025 +a) source prompt b) edit instruction +Video +Database +VEditBench +Data +Prompt Generation +Video Database +Human VEditBench Data +Human +source prompt: “An orange cat getting up +from floor and walking on its hind legs.” +edit instruction: “Change the cat to a rabbit.” +Quality +target prompt: “A rabbit getting up from the +Diversity +Prompt +floor and walking on its hind legs.” +Generation +Accuracy +Diversity +Figure 2: VEditBench data curation pipeline +that involves both machine and human. +Figure 3: Visualization of word distribu- +tion in source and edit prompt. +Video metrics prioritize temporal aspects. Fr´ echet Video Distance (FVD) (Unterthiner et al., 2019) +uses features from I3D (Carreira & Zisserman, 2017a) to compute the distance between generated +and real video distributions, but can be biased towards frame quality over motion realism. To address +this, Content-Debiased FVD (Ge et al., 2024) utilizes features from large-scale unsupervised models. +Frame Consistency CLIP Score (Radford et al., 2021) measures the consistency of edited videos by +comparing CLIP embeddings across frames. +Recent work has introduced dedicated metrics for T2V evaluation, such as T2VScore (Wu et al., +2024), VBench (Huang et al., 2024) and EvalCrafter (Liu et al., 2023b). Building upon prior re- +search, we incorporate established metrics and introduce new ones tailored for video editing tasks, +including scores for motion and sturctural similarity between source and edited video. +3 BENCHMARK CURATION +3.1 COLLECTION OF VIDEOS. +We aim to curate a diverse benchmark for real-world video editing applications. We consider six +categories from everyday life: Animal, Food, Scenery, Sports Activity, Technology, and Vehicle. We +search two large-scale video databases: YouTube1 and Videvo2. YouTube serves as one of the largest +video repositories, featuring diverse user-generated content, while Videvo offers high-quality stock +videos shot by professionals. +To diversify the video content, we first ask GPT-4o to provide distinct keywords for each category +and use these keywords to search within the Panda-70M dataset (Chen et al., 2024) and YouTube. +To ensure data quality, we manually check each video and filter out those of low quality (e.g., blurry, +shaking, ghosting). We obtain the video captions using GPT-4o. Since the captions generated by +large multimodal models may exhibit issues such as missing objects or hallucinations of non-existent +objects (Bai et al., 2024), we also dedicate manual effort to reviewing and revising the captions, +ensuring that the key pixels are accurately described. +Mainstream TGVE models typically focus on short video editing, handling clips of 2 to 4 seconds +(24-30fps) in length (usually under 100 frames). To support this, we collect 300 short videos within +this range. Additionally, we explore a more challenging task: editing longer videos of 10 to 40 +seconds (24-30fps). This task presents greater difficulty, as it requires the model to maintain long- +range consistency in video content (e.g., subject and style) across transitions. Solving this challenge +will make TGVE models more practical and applicable to real-world scenarios, such as the film +production. +Finally, we curate a collection of 420 videos, comprising 300 short videos and 120 long videos, all +at a resolution of 720⇥1280. These videos are balanced across and diversified within six categories. +1https://www.youtube.com/ +2https://www.videvo.net/ +4 + +===== PAGE 5 ===== +Under review as a conference paper at ICLR 2025 +Object Addition +Object Removal Object Swap +Scene Replacement +Motion Change Style Translation +Remove the cat. Change the cat to a rabbit. +Place it in a +grassy field. +Tilt the camera +downwards. +Make it in Van +Gogh style. +Figure 4: Illustration of six video editing tasks in VEditBench. +3.2 216 +217 +218 +219 +220 +221 +Add a string toy near the cat. 222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +DESIGN OF VIDEO EDITING TASKS. +The existing literature on video editing primarily addresses changes to the subject, background, and +style. In this work, we explore broader applications of video editing and define six distinct video +editing tasks as follows: +• Object Addition: add new objects to the video (e.g., “add a string toy near the cat”) +• Object Removal: remove existing objects from the video (e.g., “remove the cat”) +• Object Swap: replace the object while maintaining its motion (e.g., “change the cat to a rabbit”) +• Scene Replacement: change the location (e.g., “place the cat in a grassy field”) +• Motion Change: modify the object’s or camera’s motion (e.g., “tilt the camera downwards”) +• Style Translation: apply a specific style (e.g., “make it in Van Gogh style”) +Each of these tasks serves a distinct purpose in examining the capability of TGVE models. We +illustrate each editing task in Figure 13. +We task GPT-4o with the above descriptions to generate diverse edit prompts. Specifically, we feed +sampled video frames in a grid along with the video caption to GPT-4o, which then returns the corre- +sponding edit instructions and target prompts for each task (see Figure 2). Still, we manually review +all the machine-generated prompts with necessary modifications to ensure accuracy. In Figure 3, we +visualize the word distribution in our source and edit prompt set. More details about edit prompt +generation can be found in the supplementary material. +4 EVALUATION METRICS +We assess the performance of TGVE models from two primary perspectives: 1) Semantic Fidelity +– Does the edited video adhere to the user’s command?, which evaluates whether the output video +accurately follows the guidance from input video and edit prompt. 2) Video Quality– Regarding +of the editing instructions, is the generated video visually appealing?, which focuses on the overall +visual quality of the resulting video, independent of the applied edits. For each of these perspectives, +we further define several sub-dimensions to enable a more fine-grained evaluation. +4.1 SEMANTIC FIDELITY +A successfully edited video should accurately follow: 1) the explicit instructions provided by users +(i.e., user prompt); 2) the implicit consistency with the source video (e.g., motion, structure, that are +not intended for editing). To this end, we break down Semantic Fidelity into two distinct aspects, +Text Alignment and Video Alignment, where the former focuses on the faithfulness with the target +prompt, and the latter considers the coherence with the source video. +[Text] Spatial Alignment. The CLIP model (Radford et al., 2021) trained on massive text-image +pairs is capable of encoding meaningful embeddings for both modalities in a shared latent space. +5 + +===== PAGE 6 ===== +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 +309 +310 +311 +312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +Under review as a conference paper at ICLR 2025 +It is widely used to measure the similarity between visual and textual data. We compute the CLIP +feature similarity between the generated frames and their corresponding target prompts. +[Text] Spatio-Temporal Alignment. In addition to spatial content, videos display temporal dy- +namics such as object movement and camera motions. Huang et al. (2024) demonstrate the effec- +tiveness of using a video CLIP model, i.e., ViCLIP (Wang et al., 2023b), to evaluate text-video +alignment for text-to-video generation. We measure the Spatio-Temporal Text Alignment by calcu- +lating the feature similarity between the ViCLIP embeddings of edited video and target prompt. +[Video] Structural Similarity. In video editing, it is essential to preserve the integrity of the +original content. We compute the Structural Similarity Index Measure (SSIM) (Wang et al., 2004) +between source and corresponding target frames. SSIM compares the structural features of the +source and target videos, and helps identify any significant alterations that may compromise the +original message. +[Video] Motion Similarity. The goal is to quantify how much the motion dynamics change +between a source video and a target video. We first estimate a set of point trajectories T= +{(pi, vi)}N +i=1, using the off-the-shelf CoTracker (Karaev et al., 2023). Here pi and vi represents +the position and motion vector at i-th trajectory, with N being the total number of trajectories ex- +tracted in video. We denote the trajectory sets for source video and target video as TA and TB +. +To compare these trajectory sets, we define a combined cost matrix for the i-th trajectory from +video A and the j-th trajectory from video B. The matrix considers both positional and directional +differences between the trajectories: +kpA +i pB +j k2 +Dmax +| {z } +Positional Cost ++(1 ↵)· 1 +C(i, j) = ↵· +vA +i· vB +j +kvA +i k2kvB +j k2 + ✏ ! +| {z } +Directional Cost +, +where Dmax is the maximum observed distance used for normalization, ↵ 2 [0, 1] is a weighting +parameter balancing positional and directional terms, and ✏ is a small constant to avoid zero division. +We employ the Hungarian algorithm (Kuhn, 1955) to find the optimal assignment of trajectories +between the two videos, minimizing the total cost: min Pi Ci(i), where (i) maps trajectory i in +video A to a corresponding trajectory in video B. Finally, we compute the motion similarity score +between the two videos as: SMotionSim = 1 +1 +N Pi Ci(i). +This score indicates how closely the motion patterns align between the videos. A higher score +reflects greater similarity. Empirically, we set equal weights for the positional and directional terms, +i.e., ↵ = 0.5, to balance their contributions. +4.2 VISUAL QUALITY +Video can be seen as a sequence of images with consistent temporal dynamics. We evaluate the +visual quality of a video from three perspectives: 1) Spatial Quality, which analyzes the video as +individual frames, independent of temporal dynamics, by calculating the average image score across +the frames; 2) Temporal Quality, which focuses solely on the temporal dimension, assessing the +consistency of the video over time; 3) Spatio-Temporal Quality, which considers the video as a +whole, integrating both spatial and temporal elements. +[Spatial] Image Quality. Image quality focuses on the impact of distortions and other visual im- +perfections in images on human perception. Recently, Wu et al. (2023b) introduce Q-Align, an +advanced approach that trains large multimodal models to perform visual scoring. Q-Align demon- +strates a significant leap in image quality assessment, image aesthetic assessment and video quality +assessment – not only achieving state-of-the-art performance but also enhancing out-of-distribution +generalization capabilities. We adopt Q-Align as the method for image quality scoring. +[Spatial] Image Aesthetic. Image aesthetic measures the visual appeal and beauty of an image. +We evaluate it using the Q-Align’s image aesthetic scorer trained on AVA dataset (Gu et al., 2018). +6 + +===== PAGE 7 ===== +324 +325 +326 +327 +328 +329 +330 +331 +332 +333 +334 +335 +336 +337 +338 +339 +340 +341 +342 +343 +344 +345 +346 +347 +348 +349 +350 +351 +352 +353 +354 +355 +356 +357 +358 +359 +360 +361 +362 +363 +364 +365 +366 +367 +368 +369 +370 +371 +372 +373 +374 +375 +376 +377 +Under review as a conference paper at ICLR 2025 +[Temporal] Motion Smoothness. Motion smoothness refers to the continuity of movement in +visual content, often measured by the absence of noticeable jitter, stuttering, or abrupt transitions +between frames. We follow VBench (Huang et al., 2024) to use the motion priors from the video +frame interpolation model (Li et al., 2023) to assess the smoothness of motion in edited videos. +[Temporal] Temporal Quality. Fr´ echet Video Distance (FVD) is a widely used metric for assess- +ing the temporal quality of generated videos. It measures the similarity between the distributions +of real and generated videos by comparing the feature representations extracted from a pre-trained +neural network. However, Ge et al. (2024) found that FVD tends to prioritize per-frame quality +over temporal consistency. They attribute this bias to the features derived from a supervised video +classifier trained on a content-biased dataset. To address this issue, they suggest using features from +large-scale unsupervised models, which can help mitigate the bias. We employ their implementa- +tion of Content-Debbiased FVD3, calculated using VideoMAE-v2 (Wang et al., 2023a) features, to +evaluate temporal quality. +[Spatio-Temporal] Video Quality. This dimension takes into account both spatial and temporal +factors, offering a comprehensive understanding of a video’s performance. Q-Align (Wu et al., +2023b) utilizes a language decoder to assemble videos as sequences of frames, so as to unify video +quality assessment with image quality/aesthetic assessment under one structure. It also marks state- +of-the-art in video quality assessment; therefore, we utilize it as video quality scorer. +5 EXPERIMENTS +Evaluated Models. We evaluate ten TGVE models on VEditBench, including Tune-A- +Video (Wu et al., 2023c), MotionDirector (Zhao et al., 2023), VidToMe (Li et al., 2024), +Pix2Video (Ceylan et al., 2023), TokenFlow (Geyer et al., 2023), Flatten (Cong et al., 2023a), +Diffusion Motion Transfer (DMT) (Yatim et al., 2024), RAVE (Kara et al., 2024), Text2Video- +Zero (Khachatryan et al., 2023), and Instruct Video-to-Video (InsV2V) (Cheng et al., 2023). Among +them, Text2Video-Zero and InsV2V accept editing instructions as input, whereas the others rely on +a target prompt. +Settings. To account for the varying capabilities of TGVE models in handling different +video lengths, we partition VEditBench into two subsets: VEditBench-Short and +VEditBench-Long, designed for evaluating short and long video editing, respectively. +VEditBench-Short includes all ten models outlined above, enabling a comprehensive com- +parison of their performance on short videos. However, since some models are not optimized for +long video editing, VEditBench-Long focuses on evaluating four models specifically designed +or adapted: Pix2Video, Text2Video-Zero, VidToMe, and InsV2V. +Results. To comprehensively assess the performance of different TGVE models on +VEditBench, we conduct both quantitative and qualitative analyses. Our quantitative evalua- +tion leverages a diverse set of metrics designed to measure various aspects of video quality and +fidelity to the editing instructions (Table 3, Figure 5). Complementing these quantitative measures, +we also perform a qualitative analysis to provide a more nuanced understanding of the strengths and +weaknesses of each model (Figure 6). This involves visual inspection of the edited videos and a +comparative analysis of their performance across different editing tasks and video categories. +6 INSIGHTS AND DISCUSSIONS +No Single Model Dominates Across All Dimensions. As shown in Table 3, no single TGVE +method consistently excels across all evaluation dimensions. Each model demonstrates strengths in +specific areas while exhibiting weaknesses in others, highlighting the diverse approaches and trade- +offs within the field. For instance, while RAVE achieves strong performance in Spatial and Spatio- +Temporal Alignment, it lags in terms of visual quality, as evidenced by its lower scores in Image +Quality, Image Aesthetics, and Video Quality. The irregular shapes of the radar charts (Figure 5) +also indicate that there are often trade-offs between different evaluation metrics. A model might +3https://github.com/songweige/content-debiased-fvd +7 + +===== PAGE 8 ===== +378 +379 +380 +381 +382 +383 +384 +385 +386 +387 +388 +389 +390 +391 +392 +393 +394 +395 +396 +397 +398 +399 +400 +401 +402 +403 +404 +405 +406 +407 +408 +409 +410 +411 +412 +413 +414 +415 +416 +417 +418 +419 +420 +421 +422 +423 +424 +425 +426 +427 +428 +429 +430 +431 +Under review as a conference paper at ICLR 2025 +Table 2: Results per dimension on VEditBench-Short. This table compares the perfor- +mance of ten TGVE models across nine dimensions. The best and second-best are bold-faced +and underlined. Efficiency measures TGVE models’ runtime (seconds per frame, SPF) and GPU +memory usage (Mem) on an NVIDIA A100 GPU. †T2I-based method, ‡T2V-based method. +Spatial SpatioTemp Motion Structural Image Image Video Motion Temporal Efficiency +Alignment Alignment Sim. Sim. Quality Aesthetic Quality Smooth. Quality (SPF / Mem) +Tune-A-Video† 26.550 0.239 0.887 0.447 0.399 0.233 0.467 0.942 401.023 30.1s / 16GB +Pix2Video† 26.543 0.248 0.889 0.604 0.592 0.375 0.665 0.971 367.610 11.8s / 27GB +MotionDirector‡ 26.393 0.252 0.889 0.489 0.636 0.372 0.682 0.961 262.489 12.5s / 20GB +TokenFlow† 25.806 0.240 0.925 0.681 0.743 0.435 0.778 0.967 181.586 6.4s / 7GB +VidToMe† 26.033 0.244 0.920 0.688 0.736 0.452 0.779 0.968 153.368 5.3s / 6GB +Flatten† 24.448 0.217 0.909 0.683 0.530 0.356 0.614 0.968 235.446 7.5s / 13GB +DMT‡ 25.849 0.243 0.791 0.418 0.716 0.411 0.761 0.973 302.740 20.3s / 40GB +RAVE† 26.801 0.246 0.829 0.652 0.631 0.395 0.676 0.964 230.579 3.2s / 26GB +Text2Video-Zero† 21.631 0.162 0.798 0.490 0.660 0.520 0.714 0.927 725.644 3.1s / 23GB +InsV2V‡ 24.586 0.226 0.925 0.743 0.615 0.363 0.680 0.984 94.294 2.6s / 14GB +Table 3: Results per dimension on VEditBench-Long. This table compares the performance of +ten TGVE models across nine dimensions. +Spatial SpatioTemp Motion Structural Image Image Video Motion Temporal +Alignment Alignment Sim. Sim. Quality Aesthetic Quality Smooth. Quality +Pix2Video 26.741 0.243 0.841 0.597 0.609 0.365 0.684 0.972 505.415 +VidToMe 26.371 0.239 0.876 0.675 0.723 0.430 0.791 0.971 269.596 +Text2Video-Zero 22.767 0.174 0.771 0.477 0.502 0.753 0.714 0.932 869.299 +InsV2V 25.551 0.226 0.906 0.740 0.689 0.383 0.742 0.987 140.232 +score high on image quality but lower on motion smoothness, suggesting that optimizing for one +metric can sometimes come at the expense of another. +Notably, TokenFlow and VidToMe emerge as more well-rounded models, achieving high perfor- +mance in visual quality while maintaining strong semantic fidelity scores. These findings underscore +the importance of a comprehensive benchmark like VEditBench to provide a nuanced under- +standing of model performance and guide future research towards more robust and versatile TGVE +methods. +Model Performance Varies Across Tasks. The charts in Figure 5 clearly show that a model’s +performance can vary significantly depending on the specific editing task. For instance, some models +excel at object swap but struggle with motion change. This highlights the importance of evaluating +models across a diverse range of tasks to understand their strengths and weaknesses. +Semantic Fidelity vs. Visual Quality Our analysis reveals an interesting tension between seman- +tic fidelity and visual quality in TGVE models. While some models excel at accurately adhering to +the editing instructions (high semantic fidelity), they may sometimes produce outputs with notice- +able visual artifacts or inconsistencies (lower visual quality). Conversely, other models prioritize +generating visually appealing results but may struggle to precisely fulfill the user’s intent. This +trade-off highlights a key challenge in TGVE: achieving a balance between accurately interpreting +and executing editing instructions while maintaining high visual quality in the output. Future re- +search could explore novel approaches to optimize both aspects simultaneously, potentially through +improved training strategies or more sophisticated evaluation metrics that explicitly consider the +interplay between semantic fidelity and visual quality. +Challenges in Long Video Editing. Evaluating models on VEditBench-Long reveals unique +challenges associated with editing longer videos. Maintaining temporal consistency and coherence +over extended durations proves to be a significant hurdle for most models. Edited outputs exhibit +increased occurrences of flickering, temporal artifacts, and deviations from the original video’s nar- +rative flow. These challenges stem from the increased complexity of modeling long-range depen- +dencies and the potential for errors to accumulate over time. Furthermore, computational constraints +become more prominent when processing longer videos, which can limit the effectiveness of certain +techniques. These findings highlight the need for further research focused on developing specialized +architectures and training strategies tailored to the specific challenges of long video editing. +8 + +===== PAGE 9 ===== +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 +453 +454 +455 +456 +457 +458 +459 +460 +461 +462 +463 +464 +465 +466 +467 +468 +469 +470 +471 +472 +473 +474 +475 +476 +477 +478 +479 +480 +481 +482 +483 +484 +485 +Under review as a conference paper at ICLR 2025 +Structural +Similarity +Image +Quality +Image +Aesthetic +Temporal +Quality Tune-A-Video Pix2Video Motion +Similarity +Spatio-Temporal +Alignment +Spatial +Alignment +Overall +Quality +Structural +Similarity +Image +Quality +Image +Aesthetic +Temporal +Quality Motion +Similarity +MotionDirector +Structural +Motion +Similarity +TokenFlow +Motion +Similarity +Similarity +Structural +Similarity +Spatio-Temporal +Alignment +Spatial +Alignment +Overall +Quality +Spatio-Temporal +Alignment +Spatio-Temporal +Alignment +Image +Image +Quality +Image +Aesthetic +Motion +Smoothness +Temporal +Quality Motion +Smoothness +Structural +Similarity +Spatial +Alignment +Overall +Quality +Motion +Smoothness +Quality +Motion +Similarity +Image +Aesthetic +Spatial +Alignment +Structural +Motion +Similarity +Motion +Similarity +Overall +Spatio-Temporal +Motion +Quality +Similarity +Alignment +Motion +Similarity +Smoothness +VidToMe +Image +Quality +DMT +Flatten object_change object_insertion +Motion +scene_change stylization +Similarity +Spatio-Temporal +Spatio-Temporal +Alignment +Motion +Alignment +Similarity +motion_change Motion +motion_change object_change object_insertion +Structural +Similarity +object_removal object_removal scene_change stylization +Structural +Similarity +motion_change object_removal Structural +Similarity +object_change Structural +Motion +scene_change Similarity +Similarity +Image +Quality +Image +Aesthetic +Temporal +Quality Similarity +Spatio-Temporal +Alignment +Image +Quality +Spatial +Alignment +Image +Aesthetic +Overall +Quality +Temporal +Quality Motion +Smoothness +Motion +Smoothness +Text2Video-Zero +motion_change object_change object_insertion +motion_change Structural +object_removal scene_change stylization +object_removal Similarity +Spatio-Temporal +Alignment +Spatial +Alignment +Overall +Quality +Spatial +Spatial +Alignment +Alignment +Structural +Temporal +Structural +Quality Similarity +Similarity +Image +Motion +RAVE +Quality +Structural +object_insertion +Image +motion_change object_change object_insertion +Similarity +Motion +stylization +Image +Spatial +object_removal scene_change stylization +Structural +Similarity +Similarity +Quality +Quality +Similarity +Alignment +Spatio-Temporal +Alignment +Spatio-Temporal +Spatio-Temporal +Alignment +Image +Image +Image +Alignment +Quality +Aesthetic +Quality +Image +Image +Image +Aesthetic +Spatial +Quality +Spatial +Quality +Alignment +Image +Overall +Alignment +Image +Image +Aesthetic +Image +Quality +Aesthetic +Temporal +Aesthetic +Aesthetic +Spatial +Quality Overall +Motion +Alignment +Temporal +Overall +Overall +Quality +Quality +Quality Motion +Overall +Temporal +Temporal +Smoothness +Image +Quality +Quality Image +Motion +Quality Motion +Quality +Smoothness +Smoothness +Temporal +Aesthetic +Smoothness +Aesthetic +Temporal +Quality Motion +InsV2V +Quality Motion +Overall +Smoothness +Smoothness +Motion +Motion +object_change object_insertion +motion_change object_change object_insertion +motion_change object_change object_insertion +Quality +Similarity +Structural +Similarity +Temporal +scene_change stylization +object_removal scene_change stylization +motion_change Similarity +Temporal +object_change object_removal scene_change stylization +object_insertion +Object Insertion +Spatio-Temporal +Quality Spatio-Temporal +motion_change Quality Motion +object_change Alignment +object_removal scene_change Motion +Alignment +stylization +Smoothness +Smoothness +object_removal Object Removal +scene_change Overall +Quality +Spatio-Temporal +Alignment +Spatial +Spatio-Temporal +Alignment +Alignment +Overall +Quality +Spatial +Alignment +object_insertion +stylization +Spatial +Alignment +Overall +Quality +Image +Quality +Image +Aesthetic +motion_change object_removal Temporal +Quality Motion +Overall +object_change Quality +scene_change Motion +Smoothness +Smoothness +Image +Quality +Image +Aesthetic +Temporal +Quality Figure 5: Results per model on VEditBench-Short. We visualize each model’s performance +motion_change object_change object_insertion +motion_change object_change object_insertion +object_removal scene_change stylization +object_removal scene_change stylization +across six editing tasks and nine evaluation dimensions. The radar charts reveal that model perfor- +mance varies significantly across tasks, highlighting the importance of comprehensive evaluation +across diverse editing scenarios. +7 CONCLUSION +In this paper, we introduced VEditBench, a comprehensive benchmark designed to standard- +ize and advance the evaluation of text-guided video editing models. VEditBench addresses key +limitations of existing benchmarks by providing a diverse collection of real-world videos, a wider +range of editing tasks, and a multi-dimensional evaluation framework encompassing both semantic +fidelity and visual quality. By evaluating ten state-of-the-art TGVE models on VEditBench, we +offer insights into their capabilities and highlight areas for future improvement. We believe that the +open-source release of VEditBench will serve as a valuable resource for the research community, +fostering further progress in this rapidly evolving field. +Limitation and Future Work. The benchmark currently focuses on single-shot edits based on +a single textual instruction. Future work could explore more complex editing scenarios involving +multi-step edits or the composition of multiple instructions. We also plan to benchmark more TGVE +models using our VEditBench in the future. +motion_change object_change Object Swap +object_insertion +motion_change object_change object_insertion +Spatial +object_removal scene_change stylization +Alignment +object_removal scene_change Scene Replacement +stylization +motion_change Motion Change +object_insertion +object_removal stylization +Style Translation +object_change scene_change object_insertion +stylization +9 + +===== PAGE 10 ===== +Under review as a conference paper at ICLR 2025 +486 +487 +488 +489 +490 +491 +492 +493 +494 +495 +496 +497 +498 +499 +500 +501 +502 +503 +504 +505 +506 +507 +508 +509 +510 +511 +512 +513 +514 +515 +516 +517 +518 +519 +520 +521 +522 +523 +524 +525 +526 +527 +528 +529 +530 +531 +532 +533 +534 +535 +536 +537 +538 +539 +Input Video +Tune-A-VIdeo +Pix2Video +MotionDirector +TokenFlow +VidToMe +Flatten +DMT +RAVE +Text2Video-Zero +Figure 6: Example of “changing the cat to a rabbit” in VEditBench. +10 + +===== PAGE 11 ===== +540 +541 +542 +543 +544 +545 +546 +547 +548 +549 +550 +551 +552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 +571 +572 +573 +574 +575 +576 +577 +578 +579 +580 +581 +582 +583 +584 +585 +586 +587 +588 +589 +590 +591 +592 +593 +Under review as a conference paper at ICLR 2025 +REFERENCES +Zechen Bai, Pichao Wang, Tianjun Xiao, Tong He, Zongbo Han, Zheng Zhang, and Mike Zheng +Shou. Hallucination of multimodal large language models: A survey. arXiv preprint +arXiv:2404.18930, 2024. 4 +Shane Barratt and Rishi Sharma. A note on the inception score. arXiv preprint arXiv:1801.01973, +2018. 3 +Joao Carreira and Andrew Zisserman. Quo vadis, action recognition? a new model and the kinetics +dataset. In CVPR, 2017a. 4 +Joao Carreira and Andrew Zisserman. Quo vadis, action recognition? a new model and the kinetics +dataset. In CVPR, 2017b. 3 +Joao Carreira, Eric Noland, Andras Banki-Horvath, Chloe Hillier, and Andrew Zisserman. A short +note about kinetics-600. arXiv:1808.01340, 2018. 3 +Duygu Ceylan, Chun-Hao Paul Huang, and Niloy J Mitra. Pix2video: Video editing using image +diffusion. In ICCV, 2023. 7 +Tsai-Shien Chen, Aliaksandr Siarohin, Willi Menapace, Ekaterina Deyneka, Hsiang-wei Chao, +Byung Eun Jeon, Yuwei Fang, Hsin-Ying Lee, Jian Ren, Ming-Hsuan Yang, et al. Panda-70m: +Captioning 70m videos with multiple cross-modality teachers. arXiv preprint arXiv:2402.19479, +2024. 4 +Jiaxin Cheng, Tianjun Xiao, and Tong He. Consistent video-to-video transfer using synthetic dataset. +arXiv preprint arXiv:2311.00213, 2023. 3, 7 +Yuren Cong, Mengmeng Xu, Christian Simon, Shoufa Chen, Jiawei Ren, Yanping Xie, Juan-Manuel +Perez-Rua, Bodo Rosenhahn, Tao Xiang, and Sen He. Flatten: optical flow-guided attention for +consistent text-to-video editing. arXiv preprint arXiv:2310.05922, 2023a. 7 +Yuren Cong, Mengmeng Xu, Christian Simon, Shoufa Chen, Jiawei Ren, Yanping Xie, Juan-Manuel +Perez-Rua, Bodo Rosenhahn, Tao Xiang, and Sen He. Flatten: optical flow-guided attention for +consistent text-to-video editing. arXiv:2310.05922, 2023b. 3 +Patrick Esser, Johnathan Chiu, Parmida Atighehchian, Jonathan Granskog, and Anastasis Germani- +dis. Structure and content-guided video synthesis with diffusion models. In ICCV, 2023. 2 +Ruoyu Feng, Wenming Weng, Yanhui Wang, Yuhui Yuan, Jianmin Bao, Chong Luo, Zhibo Chen, +and Baining Guo. Ccedit: Creative and controllable video editing via diffusion models. In Pro- +ceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 6712– +6722, 2024. 2, 3 +Songwei Ge, Aniruddha Mahapatra, Gaurav Parmar, Jun-Yan Zhu, and Jia-Bin Huang. On the +content bias in fr´ echet video distance. In Proceedings of the IEEE/CVF Conference on Computer +Vision and Pattern Recognition, pp. 7277–7288, 2024. 4, 7 +Michal Geyer, Omer Bar-Tal, Shai Bagon, and Tali Dekel. Tokenflow: Consistent diffusion features +for consistent video editing. arXiv:2307.10373, 2023. 2, 3, 7 +Chunhui Gu, Chen Sun, David A Ross, Carl Vondrick, Caroline Pantofaru, Yeqing Li, Sudheendra +Vijayanarasimhan, George Toderici, Susanna Ricco, Rahul Sukthankar, et al. Ava: A video dataset +of spatio-temporally localized atomic visual actions. In Proceedings of the IEEE conference on +computer vision and pattern recognition, pp. 6047–6056, 2018. 6 +Ziqi Huang, Yinan He, Jiashuo Yu, Fan Zhang, Chenyang Si, Yuming Jiang, Yuanhan Zhang, Tianx- +ing Wu, Qingyang Jin, Nattapol Chanpaisit, et al. Vbench: Comprehensive benchmark suite for +video generative models. In Proceedings of the IEEE/CVF Conference on Computer Vision and +Pattern Recognition, pp. 21807–21818, 2024. 3, 4, 6, 7 +11 + +===== PAGE 12 ===== +594 +595 +596 +597 +598 +599 +600 +601 +602 +603 +604 +605 +606 +607 +608 +609 +610 +611 +612 +613 +614 +615 +616 +617 +618 +619 +620 +621 +622 +623 +624 +625 +626 +627 +628 +629 +630 +631 +632 +633 +634 +635 +636 +637 +638 +639 +640 +641 +642 +643 +644 +645 +646 +647 +Under review as a conference paper at ICLR 2025 +Ozgur Kara, Bariscan Kurtkaya, Hidir Yesiltepe, James M Rehg, and Pinar Yanardag. Rave: Ran- +domized noise shuffling for fast and consistent video editing with diffusion models. In Proceed- +ings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 6507–6516, +2024. 3, 7 +Nikita Karaev, Ignacio Rocco, Benjamin Graham, Natalia Neverova, Andrea Vedaldi, and Christian +Rupprecht. Cotracker: It is better to track together. arXiv preprint arXiv:2307.07635, 2023. 6 +Levon Khachatryan, Andranik Movsisyan, Vahram Tadevosyan, Roberto Henschel, Zhangyang +Wang, Shant Navasardyan, and Humphrey Shi. Text2video-zero: Text-to-image diffusion models +are zero-shot video generators. In ICCV, 2023. 3, 7 +Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete +Xiao, Spencer Whitehead, Alexander C Berg, Wan-Yen Lo, et al. Segment anything. In Pro- +ceedings of the IEEE/CVF International Conference on Computer Vision, pp. 4015–4026, 2023. +18 +Harold W. Kuhn. The Hungarian Method for the Assignment Problem. Naval Research Logistics +Quarterly, 2(1–2):83–97, March 1955. doi: 10.1002/nav.3800020109. 6 +Xirui Li, Chao Ma, Xiaokang Yang, and Ming-Hsuan Yang. Vidtome: Video token merging for +zero-shot video editing. In Proceedings of the IEEE/CVF Conference on Computer Vision and +Pattern Recognition, pp. 7486–7495, 2024. 3, 7 +Zhen Li, Zuo-Liang Zhu, Ling-Hao Han, Qibin Hou, Chun-Le Guo, and Ming-Ming Cheng. Amt: +All-pairs multi-field transforms for efficient frame interpolation. In Proceedings of the IEEE/CVF +Conference on Computer Vision and Pattern Recognition, pp. 9801–9810, 2023. 7 +Feng Liang, Bichen Wu, Jialiang Wang, Licheng Yu, Kunpeng Li, Yinan Zhao, Ishan Misra, Jia-Bin +Huang, Peizhao Zhang, Peter Vajda, et al. Flowvid: Taming imperfect optical flows for consistent +video-to-video synthesis. arXiv preprint arXiv:2312.17681, 2023. 2 +Shaoteng Liu, Yuechen Zhang, Wenbo Li, Zhe Lin, and Jiaya Jia. Video-p2p: Video editing with +cross-attention control. arXiv:2303.04761, 2023a. 3 +Yaofang Liu, Xiaodong Cun, Xuebo Liu, Xintao Wang, Yong Zhang, Haoxin Chen, Yang Liu, +Tieyong Zeng, Raymond Chan, and Ying Shan. Evalcrafter: Benchmarking and evaluating large +video generation models, 2023b. 3, 4 +Yuanxin Liu, Lei Li, Shuhuai Ren, Rundong Gao, Shicheng Li, Sishuo Chen, Xu Sun, and Lu Hou. +Fetv: A benchmark for fine-grained evaluation of open-domain text-to-video generation. arXiv +preprint arXiv:2311.01813, 2023c. 3 +Eyal Molad, Eliahu Horwitz, Dani Valevski, Alex Rav Acha, Yossi Matias, Yael Pritch, Yaniv +Leviathan, and Yedid Hoshen. Dreamix: Video diffusion models are general video editors. +arXiv:2302.01329, 2023. 2 +Gaurav Parmar, Richard Zhang, and Jun-Yan Zhu. On aliased resizing and surprising subtleties in +gan evaluation. In CVPR, pp. 11410–11420, 2022. 3 +Chenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, Xintao Wang, Ying Shan, and Qifeng +Chen. Fatezero: Fusing attentions for zero-shot text-based video editing. In ICCV, 2023. 3 +Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, +Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual +models from natural language supervision. In ICML, 2021. 3, 4, 5 +Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu, Ronghang Hu, Chaitanya Ryali, Tengyu Ma, Haitham +Khedr, Roman R¨ adle, Chloe Rolland, Laura Gustafson, et al. Sam 2: Segment anything in images +and videos. arXiv preprint arXiv:2408.00714, 2024. 18, 20 +Uriel Singer, Adam Polyak, Thomas Hayes, Xi Yin, Jie An, Songyang Zhang, Qiyuan Hu, Harry +Yang, Oron Ashual, Oran Gafni, et al. Make-a-video: Text-to-video generation without text-video +data. In ICLR, 2023. 3 +12 + +===== PAGE 13 ===== +648 +649 +650 +651 +652 +653 +654 +655 +656 +657 +658 +659 +660 +661 +662 +663 +664 +665 +666 +667 +668 +669 +670 +671 +672 +673 +674 +675 +676 +677 +678 +679 +680 +681 +682 +683 +684 +685 +686 +687 +688 +689 +690 +691 +692 +693 +694 +695 +696 +697 +698 +699 +700 +701 +Under review as a conference paper at ICLR 2025 +Khurram Soomro, Amir Roshan Zamir, and Mubarak Shah. Ucf101: A dataset of 101 human actions +classes from videos in the wild. arXiv preprint arXiv:1212.0402, 2012. 3 +Kaiyue Sun, Kaiyi Huang, Xian Liu, Yue Wu, Zihan Xu, Zhenguo Li, and Xihui Liu. T2v- +compbench: A comprehensive benchmark for compositional text-to-video generation. arXiv +preprint arXiv:2407.14505, 2024a. 3 +Wenhao Sun, Rong-Cheng Tu, Jingyi Liao, and Dacheng Tao. Diffusion model-based video editing: +A survey. arXiv preprint arXiv:2407.07111, 2024b. 2 +Zachary Teed and Jia Deng. Raft: Recurrent all-pairs field transforms for optical flow. In Computer +Vision–ECCV 2020: 16th European Conference, Glasgow, UK, August 23–28, 2020, Proceedings, +Part II 16, pp. 402–419. Springer, 2020. 17 +Thomas Unterthiner, Sjoerd van Steenkiste, Karol Kurach, Rapha¨ el Marinier, Marcin Michalski, +and Sylvain Gelly. Fvd: A new metric for video generation. In ICLR, 2019. 4 +Limin Wang, Bingkun Huang, Zhiyu Zhao, Zhan Tong, Yinan He, Yi Wang, Yali Wang, and +Yu Qiao. Videomae v2: Scaling video masked autoencoders with dual masking. In Proceedings +of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 14549–14560, +2023a. 7 +Yi Wang, Yinan He, Yizhuo Li, Kunchang Li, Jiashuo Yu, Xin Ma, Xinyuan Chen, Yaohui Wang, +Ping Luo, Ziwei Liu, et al. Internvid: A large-scale video-text dataset for multimodal understand- +ing and generation. arXiv:2307.06942, 2023b. 6 +Zhou Wang, Alan C Bovik, Hamid R Sheikh, and Eero P Simoncelli. Image quality assessment: +from error visibility to structural similarity. TIP, 2004. 6 +Bichen Wu, Ching-Yao Chuang, Xiaoyan Wang, Yichen Jia, Kapil Krishnakumar, Tong Xiao, Feng +Liang, Licheng Yu, and Peter Vajda. Fairy: Fast parallelized instruction-guided video-to-video +synthesis. arXiv preprint arXiv:2312.13834, 2023a. 2 +Haoning Wu, Zicheng Zhang, Weixia Zhang, Chaofeng Chen, Liang Liao, Chunyi Li, Yixuan Gao, +Annan Wang, Erli Zhang, Wenxiu Sun, et al. Q-align: Teaching lmms for visual scoring via +discrete text-defined levels. arXiv preprint arXiv:2312.17090, 2023b. 6, 7 +Jay Zhangjie Wu, Yixiao Ge, Xintao Wang, Weixian Lei, Yuchao Gu, Wynne Hsu, Ying Shan, +Xiaohu Qie, and Mike Zheng Shou. Tune-a-video: One-shot tuning of image diffusion models +for text-to-video generation. In ICCV, 2023c. 2, 3, 7 +Jay Zhangjie Wu, Xiuyu Li, Difei Gao, Zhen Dong, Jinbin Bai, Aishani Singh, Xiaoyu Xiang, +Youzeng Li, Zuwei Huang, Yuanxi Sun, et al. Cvpr 2023 text guided video editing competition. +arXiv preprint arXiv:2310.16003, 2023d. 2, 3 +Jay Zhangjie Wu, Guian Fang, Haoning Wu, Xintao Wang, Yixiao Ge, Xiaodong Cun, David Jun- +hao Zhang, Jia-Wei Liu, Yuchao Gu, Rui Zhao, et al. Towards a better metric for text-to-video +generation. arXiv preprint arXiv:2401.07781, 2024. 4 +Jun Xu, Tao Mei, Ting Yao, and Yong Rui. Msr-vtt: A large video description dataset for bridging +video and language. In CVPR, 2016. 3 +Shuai Yang, Yifan Zhou, Ziwei Liu, and Chen Change Loy. Rerender a video: Zero-shot text-guided +video-to-video translation. In SIGGRAPH Asia, 2023. 2, 3 +Danah Yatim, Rafail Fridman, Omer Bar Tal, Yoni Kasten, and Tali Dekel. Space-time diffusion +features for zero-shot text-driven motion transfer. arXiv preprint arXiv:2311.17009, 2023. 2 +Danah Yatim, Rafail Fridman, Omer Bar-Tal, Yoni Kasten, and Tali Dekel. Space-time diffusion +features for zero-shot text-driven motion transfer. In Proceedings of the IEEE/CVF Conference +on Computer Vision and Pattern Recognition, pp. 8466–8476, 2024. 3, 7 +Lvmin Zhang and Maneesh Agrawala. Adding conditional control to text-to-image diffusion models. +In ICCV, 2023. 3 +13 + +===== PAGE 14 ===== +Under review as a conference paper at ICLR 2025 +702 +703 +704 +705 +706 +707 +708 +709 +710 +711 +712 +713 +714 +715 +716 +717 +718 +719 +720 +721 +722 +723 +724 +725 +726 +727 +728 +729 +730 +731 +732 +733 +734 +735 +736 +737 +738 +739 +740 +741 +742 +743 +744 +745 +746 +747 +748 +749 +750 +751 +752 +753 +754 +755 +Rui Zhao, Yuchao Gu, Jay Zhangjie Wu, David Junhao Zhang, Jiawei Liu, Weijia Wu, Jussi Keppo, +and Mike Zheng Shou. Motiondirector: Motion customization of text-to-video diffusion models. +arXiv preprint arXiv:2310.08465, 2023. 7 +14 diff --git a/benchmarks/edit/pdf/_extracted/vefx-bench.meta.txt b/benchmarks/edit/pdf/_extracted/vefx-bench.meta.txt new file mode 100644 index 0000000000000000000000000000000000000000..dac14fbb127ab4c207cc791cc307e3ec92d2b537 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/vefx-bench.meta.txt @@ -0,0 +1,3 @@ +title=VEFX-Bench: A Holistic Benchmark for Generic Video Editing and Visual Effects +author=Xiangbo Gao; Sicong Jiang; Bangya Liu; Xinghao Chen; Minglai Yang; Siyuan Yang; Mingyang Wu; Jiongze Yu; Qi Zheng; Haozhi Wang; Jiayi Zhang; Jie Yang; Zihan Wang; Qing Yin; Zhengzhong Tu +pages=29 diff --git a/benchmarks/edit/pdf/_extracted/vefx-bench.txt b/benchmarks/edit/pdf/_extracted/vefx-bench.txt new file mode 100644 index 0000000000000000000000000000000000000000..204814af10987c1bb93124c246d19e5396ed16f3 --- /dev/null +++ b/benchmarks/edit/pdf/_extracted/vefx-bench.txt @@ -0,0 +1,1794 @@ +FILE: VEFX-Bench- A Holistic Benchmark for Generic Video Editing and Visual Effects.pdf +PAGES: 29 + + +===== PAGE 1 ===== +VEFX-Bench: A Holistic Benchmark for Generic +Video Editing and Visual Effects +Xiangbo Gao1,2 +, Sicong Jiang3 +, Bangya Liu3 +, Xinghao Chen1 +, Minglai Yang3 +, Siyuan Yang1 +, Mingyang Wu1 +, Jiongze +Yu1 +, Qi Zheng2 +, Haozhi Wang2 +, Jiayi Zhang, Jie Yang2 +, Zihan Wang3 +, Qing Yin2 +, Zhengzhong Tu1,2 +1Texas A&M University 2Visko Platform 3Abaka AI +arXiv:2604.16272v2 [cs.CV] 20 Apr 2026 +Abstract. As AI-assisted video creation becomes increasingly practical, instruction-guided video editing +has become essential for refining generated or captured footage to meet professional requirements. +Yet the field still lacks both a large-scale human-annotated dataset with complete editing examples +and a standardized evaluator for comparing editing systems. Existing resources are limited by small +scale, missing edited outputs, or the absence of human quality labels, while current evaluation often +relies on expensive manual inspection or generic vision-language model judges that are not specialized +for editing quality. We introduce VEFX-Dataset, a human-annotated dataset containing 5,049 video +editing examples across 9 major editing categories and 32 subcategories, each labeled along three +decoupled dimensions: Instruction Following, Rendering Quality, and Edit Exclusivity. Building +on VEFX-Dataset, we propose VEFX-Reward, a reward model designed specifically for video editing +quality assessment. VEFX-Reward jointly processes the source video, the editing instruction, and the +edited video, and predicts per-dimension quality scores via ordinal regression. We further release +VEFX-Bench, a benchmark of 300 curated video-prompt pairs for standardized comparison of editing +systems. Experiments show that VEFX-Reward aligns more strongly with human judgments than +generic VLM judges and prior reward models on both standard IQA/VQA metrics and group-wise +preference evaluation. Using VEFX-Reward as an evaluator, we benchmark representative commercial +and open-source video editing systems, revealing a gap between visual plausibility, instruction following, +and edit locality in current models. +Project Homepage: https://xiangbogaobarry.github.io/VEFX-Bench/ +Date: April 21, 2026 +Contact: Xiangbo Gao (xiangbogaobarry@gmail.com), Zhengzhong Tu +1 Introduction +The landscape of AI-assisted video creation is advancing rapidly. Recent video generation systems have +shown impressive progress in producing photorealistic clips from natural-language prompts [1–7, 7–10]. In +professional production workflows, however, a prompt-generated video rarely satisfies the desired result in a +single pass; it typically undergoes multiple rounds of targeted refinement, such as moving objects, adjusting +camera motion, or adding visual effects, before it can be used. As a result, instruction-guided video editing +[1, 11, 12], where a user specifies a natural-language instruction to modify an existing video, has therefore +become an essential component of AI-assisted filmmaking. +Despite rapid progress, the evaluation of video editing and visual effects (VFX) remains fundamentally +unresolved. Unlike generic video generation, video editing must answer at least three distinct questions: Did +the model execute the requested edit? Is the edited video visually coherent and temporally plausible? Did it +preserve content that should have remained unchanged? These requirements expose two major bottlenecks. +First, the field lacks large-scale human-annotated resources that contain complete editing triplets—the source +video, the editing instruction, and the edited result—along with fine-grained quality labels. Second, evaluation +still relies heavily on costly manual inspection or generic vision-language model (VLM) judges that are not +designed for video-editing-specific assessment. The absence of a dedicated automatic evaluator makes both +systematic benchmarking and preference-based optimization difficult. + +===== PAGE 2 ===== +VEFX-Dataset +VEFX-Reward +Step1: Data Collection & Preprocessing +Multi-source Data Collection +Data Filtering Final High-Quality Dataset (1419 Videos) +Editing Prompt +IF +Score Output +1 2 3 4 +Original +Video +Edited +Video +No Cropping / Resizing +No Editing +“ T r a n s f o r m t h i s r u r a l +l a n d s c a p e i n t o a +w a t e r c o l o r p a i n t i n g s t y l e . +” +RQ +1 2 3 4 +EE +1 2 3 4 +No Retiming / Speed manipulation +No Scene Cut No NSFW +Nature +People +… +Vision Tokenizer +Text Tokenizer +Special Reward Token +Quality Filtering +> 720p, +> 40 frames + +... + +... +... +IF +_ +rw RQ_ +rw EE +rw +_ +Filming +Robotics Portrait +Native Spatiotemporal Dynamics +Multiple Categories +Step2: Editing Pair Data Generation +VLM +Qwen3-VL-4B-Instruct +Hidden States +N-Pairs Video Editing +Task Assignment Tool Box +Instance Editing Camera Editing +ROSE, PISCO, +ReCamMaster, +Wan-Animate, … +LightX, … +Share Linear +Reward Head +… +High-quality Score Labeling +org-video +output-1 output-2 output-3 +Instruction Following +Tools-A +Tools-B +Tools-C +conditional +probabilities +9 major tasks +34 subtasks +1419 Raw +Videos Text Prompt Generation +Generic Editing +Agentic Pipeline +UniVideo, VACE, +VLM, SAM3, +Luma, KlingO1, +DepthAnythingV3, +Grok-Imagine, Wan2.6, … +ViTPose, Wan-Control, … +Manual +Annotation +Rendering Quality +… +org-video +output-1 output-2 output-3 +N-Pairs Video +Editing +Exclusivity of Edit +CORN Loss +Figure 1 Overview of our framework. We construct VEFX-Dataset, a human-annotated dataset with 5,049 video editing +examples across 9 categories and 32 subcategories, scored along three decoupled dimensions: Instruction Following +(IF), Rendering Quality (RQ), and Edit Exclusivity (EE). We train VEFX-Reward, a dedicated reward model for video +editing quality assessment that takes the original video, editing instruction, and edited video as input and predicts +per-dimension quality scores. We further release VEFX-Bench, a benchmark of 300 curated video-prompt pairs for +standardized comparison of editing systems. +Existing resources address only parts of this problem. Benchmarks like EditBoard [13], FiVE-Bench [14], and +IVE-Bench [15] provide instructions without edited outputs; OpenVE [16] offers scale but relies heavily on +automated generation and filtering rather than human annotation; VE-Bench [17] included edited videos +and human scores but reduced quality to a single scalar and are built on older editing systems. On the +reward-model side, prior work focuses on image editing or video generation quality rather than video editing +itself [18, 19]. As a result, there is a pressing need for a benchmark and evaluator that jointly capture +instruction faithfulness, rendering quality, and preservation of unedited content. +To address these gaps, we introduce VEFX-Dataset, VEFX-Reward, and VEFX-Bench. VEFX-Dataset contains +5,049 human-annotated video editing examples spanning 9 major categories and 32 fine-grained subcategories. +Each example contains a source video, an editing instruction, and an edited result produced by a diverse +mixture of commercial systems, open-source models, and agentic editing pipelines. Trained annotators score +each example along three decoupled dimensions: Instruction Following (IF), Rendering Quality (RQ), and Edit +Exclusivity (EE). This design is central to the benchmark: an edit may be semantically wrong but visually +clean, or visually strong while unnecessarily modifying non-target content. Building on VEFX-Dataset, we +train VEFX-Reward, a reward model that takes the source video, the editing instruction, and the edited video +as input and predicts per-dimension quality scores via ordinal regression. We further release VEFX-Bench, +a standardized benchmark of 300 curated video-prompt pairs for systematic model comparison, and use +VEFX-Reward to evaluate representative commercial and open-source editing systems under the same multi- +dimensional protocol. Our contributions are summarized as follows: +• We construct VEFX-Dataset, a human-annotated dataset of 5,049 video editing examples across 9 main +categories and 32 subcategories, generated by a diverse mixture of commercial, open-source, and agentic +editing systems. Each example is scored on a 4-point rubric along three decoupled dimensions: IF, RQ, +and EE. We further release VEFX-Bench, a standardized benchmark of 300 curated video-prompt pairs for +comparing editing systems. +• WeproposeVEFX-Reward,thefirstdedicatedrewardmodelforvideoeditingqualityassessment. VEFX-Reward +jointly reasons over the source video, the editing instruction, and the edited result, and predicts multi- +dimensional quality scores with an ordinal regression objective. +• We conduct comprehensive experiments showing that VEFX-Reward aligns more strongly with human +judgments than generic VLM judges and prior reward-model baselines on both standard IQA/VQA +metrics and group-wise preference evaluation. We further apply VEFX-Reward to benchmark representative +2 + +===== PAGE 3 ===== +commercial and open-source video editing systems, exposing task-dependent strengths and persistent +weaknesses in instruction following and edit locality. +2 Related Work +2.1 Instruction-Guided Video Editing +Instruction-guided video editing aims to modify a video according to natural-language instructions while +preserving unrelated content [11, 12, 20–23]. Early methods extended image editing pipelines to the temporal +domain, typically by introducing temporal attention or consistency modules on top of text-to-image diffusion +models [24, 25]. More recent approaches adopt video-native diffusion or flow-matching architectures. Represen- +tative research models include VACE [11], UniVideo [12], and the broader Wan family [1, 26]. Alongside them, +commercial systems such as Kling Omni, Grok Imagine, Luma Ray2, and the commercial Wan 2.6 service +variant have reached practical quality levels [9, 10, 26, 27]. The resulting ecosystem is highly heterogeneous, +with different systems excelling on different editing types, which makes standardized evaluation increasingly +important. +2.2 Video Editing Quality Evaluation +Evaluating video editing quality is intrinsically multi-faceted. Conventional metrics such as CLIP score, SSIM, +and LPIPS capture only narrow aspects of the problem and do not directly measure instruction fidelity, +temporal consistency, or unintended edits [28, 29]. VBench and VBench++ provide broad evaluation suites +for video generation, but they are not designed for editing, where the source and edited videos must be +considered jointly [30, 31]. Several editing-oriented resources have been introduced more recently. EditBoard +[13] and FiVE [14] provide useful task-oriented protocols, but at limited scope or scale. OpenVE-3M [16] +provides scale without human quality annotation. IVE-Bench [15] includes source videos and instructions with +a multi-dimensional protocol, but no edited results. VE-Bench [17] includes edited videos and human scores, +but reduces quality to a single scalar MOS. In contrast, VEFX-Dataset provides large-scale human-annotated +video editing examples with decoupled quality labels tailored specifically to the editing setting. +2.3 Reward Models for Visual Generation +The success of RLHF in language modeling has motivated analogous efforts in visual generation. For image +generation, reward models such as ImageReward, HPS, and PickScore learn to approximate human preference +signals from large-scale annotations [32–34]. This line of work has extended to image editing: EditReward +trains a multi-dimensional reward model for instruction-guided image editing and demonstrates value for both +evaluation and data curation [18]. In the video domain, VideoScore, VideoReward, DenseDPO, WorldScore, +and Pulse model human preferences or preference-driven alignment primarily for video generation [19, 35–38]. +VE-Bench also includes a video editing assessor, but it predicts only a single scalar score and is tied to an +earlier benchmark setting [17]. These methods do not explicitly reason over the relationship between the +source video and the edited result. VEFX-Reward addresses this gap by jointly processing the original video, +the editing instruction, and the edited result, and by predicting multi-dimensional quality scores tailored to +video editing. +3 VEFX-Dataset and VEFX-Bench +We present VEFX-Dataset, a human-annotated dataset for video editing quality evaluation, and VEFX-Bench, +a standardized benchmark for systematic model comparison. VEFX-Dataset contains 5,049 editing examples— +4,200 for training and 849 for testing—covering 9 major categories and 32 subcategories, each annotated along +three decoupled quality dimensions: Instruction Following (IF), Rendering Quality (RQ), and Edit Exclusivity +(EE). VEFX-Bench contains 300 curated (raw video, editing prompt) pairs for evaluating and comparing video +editing models under a standardized protocol. This section describes the data collection process, annotation +protocol, reliability check, and key dataset statistics. +3 + +===== PAGE 4 ===== +Table1comparesVEFX-Dataset withexistingvideoeditingdatasetsalongthreepropertiesthatareparticularly +important for reward modeling: whether the dataset includes edited outputs, whether the scores come from +human annotation, and whether quality is decomposed into multiple dimensions. These properties matter +because reward-model training requires actual edited results, reliable human supervision, and labels that +distinguish different failure modes. Several recent resources provide prompts without edited outputs [13–15]; +others rely on automated filtering or judge models rather than trained annotators [14, 16]; and some collapse +editing quality into a single scalar. VEFX-Dataset is the only dataset in this comparison that satisfies all +three conditions simultaneously. +Table 1 Comparison of VEFX-Dataset with existing video editing datasets. In the “#Cate” column, entries such as +“8/35” denote 8 major categories and 35 subcategories. “Human Ann.” indicates whether quality scores are provided +by human annotators. “Multi-Dim.” indicates whether the evaluation is decomposed into multiple quality dimensions. +“Editing Systems” summarizes the diversity of models used to generate edited videos. +Dataset #Videos #Pairs #Cate Edited Videos Human Ann. Multi-Dim. Editing Systems +VE-Bench [17] 169 1,170 6 ✓ ✓ ✗ 8 SD-based open-source (2024) +EditBoard [13] – – 4 ✗– – – +FiVE [14]∼100 420 6 ✗– – – +OpenVE-3M [16] 1M 3M 8 ✓ ✗ ✓ Open-source + agentic (2025) +IVE-Bench [15] 600 – 8/35 ✗– – – +VEFX-Dataset (Ours) 1,988 5,049 9/32 ✓ ✓ ✓ 4 Commercial + Open + Agentic (2026) +3.1 Data Collection +Source videos. We curate source videos from open-source video datasets including Open-Sora [39] and +OpenVid-1M [40], supplemented with privately collected footage for additional diversity. We filter the initial +pool for quality and usability, including sufficient resolution, duration, and temporal continuity, remove NSFW +content, and then sample across scene categories and content types. The final set contains 1,419 source videos +spanning 10 scene categories, summarized in Figure 3(c). +Editing instructions. We design instructions to cover 9 major editing +categories and 32 subcategories, illustrated in Figure 2. To improve +task-video compatibility, we use Gemini 3 Flash [41] to analyze video +content, assign suitable editing categories, and generate matched +prompts. Low-confidence assignments are discarded. This process +yields broad task coverage while keeping the editing instructions +grounded in the source content. +Edited video generation. For each (source video, instruction) pair, we +collect edited videos from a diverse mixture of commercial systems, +open-source models, and agentic editing pipelines. This diversity +is important because it exposes the benchmark to a broad range +of quality levels and failure modes rather than the behavior of a +single model family. Detailed model lists and pipeline descriptions +Figure 2 Task hierarchy of the 9 main +are provided in Section C. +editing categories and 32 subcategories +in VEFX-Dataset. +3.2 Annotation Protocol +Each editing example is evaluated on a 4-point scale along three decoupled dimensions. +Instruction Following (IF). IF measures whether the edit satisfies the semantic requirements of the instruction. +A score of 4 indicates that all requested edits are completed correctly, while a score of 1 indicates failure, +contradiction, or an edit that is largely unrelated to the instruction. +Rendering Quality (RQ). RQ evaluates visual quality, including clarity, naturalness, temporal stability, and the +absence of artifacts such as flickering, ghosting, blur, or distortion. This dimension is scored independently of +whether the instruction is followed. +4 + +===== PAGE 5 ===== +Table 2 Summary of the 4-point scoring rubric for each annotation dimension. +Score 4 Score 3 Score 2 Score 1 +IF All requested edits com- +pleted correctly +Core edit completed with minor +deviation +Partial execution with major se- +mantic deviation +Failure, contradiction, +or unrelated edit +RQ Clear, stable, and artifact- +free +Minor but noticeable degrada- +tion +Clear quality failure with recur- +rent artifacts +Severe visual break- +down +EE No clear non-target +change +One clear non-target change Two–three non-target changes or +one large unintended change +Global or widespread +over-editing +Edit Exclusivity (EE). EE assesses whether the model changes only the intended target region without introducing +unnecessary modifications elsewhere. In our annotation guide, score 4 means that no clear non-target change +is introduced, score 3 corresponds to one localized non-target change, score 2 corresponds to two to three +clear non-target changes or one large unintended background change, and score 1 indicates widespread or +global over-editing. +A summary of the rubric is provided in Table 2, with the complete annotation guide in Section D. The key +principle of the protocol is that IF, RQ, and EE are scored independently. For example, if the instruction is +“turn the apple into a banana” but the model returns the unchanged video with excellent visual quality, the +correct labels are IF = 1, RQ = 4, and EE = 4. This decoupling prevents semantic success, visual fidelity, +and locality preservation from contaminating one another. All annotators complete a calibration phase with +detailed guidelines and reference examples before annotation begins. +3.3 Annotation Reliability +To assess annotation reliability, we conduct a targeted cross-check study. We randomly sample 550 examples +from the dataset and re-annotate them with a double-annotation strategy using a new group of annotators +independent of the original raters. Since the labels lie on a four-point ordinal scale, we report two direct +agreement measures: exact agreement and within-1-point agreement. +Table 3 shows strong agreement under this cross- +Table 3 Inter-annotator agreement on the 550-sample cross- +check protocol. Within-1 agreement exceeds 91% +check subset. Higher values indicate stronger agreement. +on all three dimensions, reaching 93.5% for IF, +Metric IF RQ EE +97.2% for RQ, and 91.7% for EE, while exact agree- +Exact Agreement (%) 75.2 87.2 72.2 +ment remains high at 75.2%, 87.2%, and 72.2%, +Within-1 Agreement (%) 93.5 97.2 91.7 +respectively. This pattern is intuitive: rendering +quality is the easiest dimension to align on, while instruction following and edit exclusivity involve more +borderline cases around partial success and acceptable non-target change. Although limited in scale, this +study provides a useful sanity check that the three-dimensional labels are stable enough for training and +evaluation. Additional details are provided in Section E. +3.4 Dataset Statistics and Analysis +We present several analyses of VEFX-Dataset to characterize the dataset and motivate its three-dimensional +design. Extended analysis is provided in Section F. +Score distributions and score patterns. Figure 3 shows that the three quality dimensions follow clearly different +distributions, which justifies decoupled evaluation. IF is the most polarized: 41.2% of samples receive score 1, +while 28.1% receive score 4, indicating that many edits either fail outright or satisfy the instruction well. RQ +is much more right-skewed, with 78.6% of samples receiving scores 3 or 4 and only 6.8% receiving score 1, +suggesting that visual plausibility is often easier to achieve than semantic correctness. EE is more balanced +across score levels. The common score-pattern panel reinforces this point: while (4,4,4) is the most frequent +triplet, several of the next most common patterns are cases such as (1,4,4) and (1,4,3), where the output +looks plausible but does not follow the instruction. +Task difficulty across editing types. The task-type heatmap reveals substantial variation in difficulty across +editing categories. Camera Angle Editing is the hardest category overall, with IF = 1.76 and an overall mean +of 2.46, while Quantity Editing is also challenging on IF at 2.09. By contrast, Style Editing reaches the +highest IF at 2.87, and Visual Effect Editing attains the highest overall mean at 2.93. RQ remains relatively +5 + +===== PAGE 6 ===== +(c) Video +Categories +Figure 3 Overview of dataset statistics for VEFX-Dataset. Panel (a) shows common IF–RQ–EE score patterns; (b) +reports pairwise dimension correlations; (c) summarizes video-category coverage; (d) shows the video-resolution +distribution; (e) reports mean scores by task type; and (f) shows score distributions across annotation dimensions. +Together they show that VEFX-Dataset spans diverse content and resolutions, exhibits heterogeneous task difficulty, +and captures clear variation in difficulty across editing tasks. +stable across task types, between 3.00 and 3.39, again suggesting that current systems are better at producing +visually plausible outputs than at satisfying complex instructions. EE varies more strongly, with Instance +Motion Editing reaching 3.06 while Creative Editing and Style Editing are lower at 2.22 and 2.23. +Coverage and dimension independence. Panels (c) and (d) show that VEFX-Dataset spans diverse scene types +and video formats rather than collapsing to a single narrow distribution. Large groups such as Nature, +People, and Street are well represented, while finer-grained content remains present in the long tail. The +resolution distribution is also broad: 1920×1080 is the largest bucket at 36.8%, 3840×2160 contributes 21.4%, +and portrait videos such as 1080×1920 remain substantial at 14.6%. This coverage matters because editing +difficulty depends on both semantic content and visual format. To verify that IF, RQ, and EE capture distinct +aspects of editing quality, we further compute pairwise correlations over the full dataset. All correlations +remain weak: IF–RQ is 0.241, IF–EE is 0.195, and RQ–EE is 0.327. These low correlations support the +three-axis annotation design and indicate that a single scalar score would obscure important failure modes. +4 VEFX-Reward: Human-Aligned Video Editing Reward Model +We present the design and training of VEFX-Reward, a reward model that predicts human-aligned quality +scores for video editing results. Unlike existing reward models that target either image editing or video +generation, VEFX-Reward is specifically designed for the video editing setting, where quality assessment must +jointly consider the original video, the editing instruction, and the edited output. +4.1 Problem Formulation +Given an original video Vo = {vt +o}T +t=1, an editing instruction P, and the corresponding edited video Ve = +{vt +e}T +t=1, our goal is to predict quality scores that align with human judgment along the three annotation +dimensions defined in Section 3.2: +[sIF,sRQ,sEE] = F(Vo,P,Ve), (1) +6 + +===== PAGE 7 ===== +where each score lies on the ordinal scale {1,2,3,4}. +The three dimensions require different reasoning. Instruction Following evaluates the semantic execution of +the requested edit. Rendering Quality measures visual fidelity and temporal consistency. Edit Exclusivity +compares the original and edited videos to detect unintended modifications outside the target region. A single +holistic score would obscure these distinct failure modes, which motivates the multi-dimensional formulation +of VEFX-Reward. +4.2 Architecture +VEFX-Reward is instantiated on the Qwen3-VL-Instruct family [42] at two scales, 4B and 32B, which correspond +to VEFX-Reward-4B and VEFX-Reward-32B in the experiments. In both variants, the model jointly processes +the original video, the edited video, and the editing instruction. This design allows the backbone to compare +the edited result against both the requested change and the source content, which is essential for assessing +semantic faithfulness, rendering quality, and unintended edits within one shared representation. +We introduce three learnable special tokens, <|IF_reward|>, <|RQ_reward|>, and <|EE_reward|>, to query +the three target dimensions. Their final hidden states are passed to a shared reward head, which produces +the ordinal logits used for prediction. This token-based design gives each dimension its own query while +preserving a single backbone for joint multimodal reasoning. +4.3 Ordinal Regression Objective +The bimodal distribution of IF scores (Section 3.4) and the ordinal nature of the 4-point scale motivate the +use of ordinal regression rather than standard L2 loss. We adopt ordinal regression [43], which models the +score as a sequence of ordered threshold decisions instead of an unconstrained scalar regression target. +For each dimension, the reward head predicts three ordered probabilities corresponding to whether the score +is greater than 1, 2, and 3. Training applies binary cross-entropy to these ordered threshold predictions under +the formulation: +L= +d +1 +K−1 +K−1 +k=1 +BCE σ(zk +d), 1[yd >k] yd ≥k , (2) +where the conditional constraint yd ≥k ensures that each threshold is trained only on relevant samples, +preserving the ordinal structure. +At inference, we convert these ordered probabilities into a continuous score on [1,4] by taking their expected +value: +ˆ +sd = 1 + +K−1 +k=1 +P(Y >k). (3) +This soft prediction is used in all reported experiments. +4.4 Training Details +Data and video processing. We train VEFX-Reward on the 4,200-example training split of VEFX-Dataset and +evaluate on the 849-example test split, with the split stratified across editing categories and pipelines. For +each example, we uniformly sample both the original and edited videos at 4 FPS and cap the frame resolution +at 399,360 pixels, approximately 632 ×632, while preserving native aspect ratios through Qwen3-VL’s +dynamic-resolution mechanism. The two videos are sampled with aligned temporal indices to support direct +comparison, and the maximum sequence length is set to 32,768 tokens. +Optimization. We use a two-stage training schedule. In the first stage, lasting 1 epoch, we freeze all pretrained +parameters and train only the newly introduced reward tokens and reward head. In the second stage, lasting +49 epochs, we unfreeze and fine-tune the language backbone and visual-language merger together with the +reward head and reward tokens, while keeping the vision tower frozen. We optimize with AdamW using +learning rates of 1 ×10−5 for the language-side parameters and 5 ×10−5 for the reward tokens, cosine decay, +and a 15% warmup ratio. Training is performed in bf16 on 8 GPUs with an effective batch size of 8, and all +three reward dimensions are optimized jointly with equal loss weights. +7 + +===== PAGE 8 ===== +5 Experiments +We conduct comprehensive experiments to evaluate VEFX-Reward as a video editing quality assessor. We +compare against generic VLM-as-judge baselines and prior reward models, analyze global agreement with +standard IQA/VQA metrics, and further test whether the learned scores preserve local human preferences +within directly comparable candidate sets. +5.1 Experimental Setup +Evaluation metrics. Our primary evaluation follows standard IQA/VQA protocol. We report Spearman Rank- +Order Correlation Coefficient (SRCC), Kendall Rank-Order Correlation Coefficient (KRCC), Pearson Linear +Correlation Coefficient (PLCC), and Root Mean Squared Error (RMSE) in Section 5.2. SRCC and KRCC +are computed on raw predictions, while PLCC and RMSE are computed after the standard four-parameter +logistic calibration. We complement these global correlation metrics with a group-wise preference metric, +Pairwise Accuracy, in Section 5.3. Detailed metric definitions and the calibration protocol are provided in +Section H.1. +Baselines. We compare VEFX-Reward against three types of baselines: +• VLM-as-a-Judge: Qwen3.5-397B, Qwen3.5-122B [42], Gemini-3.1-Pro, Gemini-3.1-Flash-Lite, Gemini-2.5- +Flash [41, 44], and Seed-2.0-Lite, Seed-1.6 [45]. Each model receives the source video, editing instruction, +and edited video, and is prompted to score editing quality on the same 1–4 rubric used in human annotation. +• EditReward : an image editing reward model with two output heads, one aligned with instruction following +and one aligned with generic visual quality [18]. +• VE-Bench: a video editing reward model that predicts a single scalar quality score [17]. +Implementation details. We instantiate VEFX-Reward at two scales, VEFX-Reward-4B and VEFX-Reward-32B, +using Qwen3-VL backbones at 4B and 32B with the same architecture and training objective. Both models +are trained on the 4,200-example training split and evaluated on the 849-example test split. We sample both +the original and edited videos at 4 FPS with a maximum frame resolution of 399,360 pixels while preserving +aspect ratio, and train in bf16 with an effective batch size of 8. For VLM-as-judge baselines, we use a shared +rubric-aligned prompt over the same source-video/instruction/edited-video triplet. In our evaluation, the +human overall score is defined as the arithmetic mean of IF, RQ, and EE. For VEFX-Reward and VLM-as-judge +baselines, the overall prediction is the mean of the three predicted dimension scores; for EditReward, it +is the mean of its two native heads; and for VE-Bench, it is the model’s native scalar output. Additional +implementation details are provided in Section B. +5.2 Results on Standard IQA/VQA Metrics +Following standard IQA/VQA practice, we evaluate all methods with SRCC, KRCC, PLCC, and RMSE. The +Overall columns in Table 4 report agreement on the human overall score rather than a separate learned target. +Overall results. Both VEFX-Reward variants clearly outperform prior reward-model baselines on the human +overall score. VEFX-Reward-32B is strongest overall, achieving 0.780 SRCC, 0.616 KRCC, 0.790 PLCC, and +0.475 RMSE, while VEFX-Reward-4B follows closely at 0.760, 0.595, 0.771, and 0.493. The margin over prior +reward models is substantial: EditReward reaches 0.558 overall SRCC and 0.631 RMSE, whereas VE-Bench +drops further to 0.214 SRCC and 0.752 RMSE. +Dimension-wise behavior. The two VEFX-Reward scales show complementary strengths. VEFX-Reward-32B is +best on IF and EE, with the strongest rank correlation and calibration on both dimensions. VEFX-Reward-4B +is slightly stronger on RQ across all four standard metrics, which suggests that larger scale mainly helps +instruction faithfulness and edit exclusivity, while rendering-quality prediction is already close to saturation +at 4B scale. This is consistent with the dataset statistics in Section 3.4: RQ is both less ambiguous and more +concentrated than IF. +Baseline comparison. Strong VLM judges remain competitive on a few individual columns, but they do not +8 + +===== PAGE 9 ===== +Table 4 Results on standard IQA/VQA metrics. SRCC, KRCC, and PLCC are higher-is-better; RMSE is lower-is-better. +PLCC and RMSE are computed after logistic calibration. Overall denotes correlation on the human overall score, +defined as the mean of IF, RQ, and EE. For VEFX-Reward and VLM-as-judge baselines, the overall prediction is the +mean of the three predicted dimension scores; EditReward uses the mean of its two native heads, and VE-Bench uses +its native scalar overall score. +Method SRCC↑ KRCC↑ PLCC↑ RMSE↓ +IF RQ EE Overall IF RQ EE Overall IF RQ EE Overall IF RQ EE Overall +VLM-as-a-Judge +Seed-1.6 Seed-2.0-Lite Qwen3.5-122B Qwen3.5-397B Gemini-3.1-Pro 0.686 0.618 0.504 0.630 0.605 0.573 0.447 0.508 0.684 0.608 0.591 0.701 0.918 0.798 0.917 0.565 +0.545 0.544 0.697 0.720 0.483 0.497 0.527 0.607 0.616 0.594 0.729 0.768 0.984 0.815 0.791 0.510 +0.379 0.563 0.658 0.631 0.327 0.523 0.573 0.520 0.378 0.663 0.601 0.685 1.165 0.752 0.893 0.578 +0.572 0.422 0.654 0.601 0.506 0.384 0.587 0.497 0.615 0.624 0.692 0.657 0.992 0.785 0.820 0.598 +0.731 0.518 0.681 0.752 0.559 0.459 0.584 0.608 0.754 0.510 0.644 0.726 0.826 0.864 0.788 0.546 +Gemini-3.1-Flash-Lite 0.309 0.302 0.661 0.574 0.283 0.277 0.555 0.436 0.316 0.425 0.673 0.505 1.194 0.910 0.840 0.685 +Gemini-2.5-Flash 0.256 0.217 0.581 0.383 0.236 0.195 0.544 0.296 0.256 0.491 0.569 0.478 1.216 0.875 0.934 0.697 +Previous Reward Models +EditReward [18] 0.453 -0.211 – 0.558 0.342 -0.164 – 0.411 0.455 0.317 – 0.580 1.113 0.844 – 0.631 +VE-Bench [17] – – – 0.214 – – – 0.150 – – – 0.238 – – – 0.752 +Ours +VEFX-Reward-4B 0.714 0.690 0.693 0.760 0.564 0.574 0.556 0.595 0.704 0.793 0.710 0.771 0.888 0.642 0.764 0.493 +VEFX-Reward-32B 0.754 0.681 0.717 0.780 0.612 0.567 0.597 0.616 0.751 0.792 0.732 0.790 0.825 0.643 0.740 0.475 +Figure 4 Predicted overall scores versus human overall scores for VEFX-Reward-32B, EditReward, and VE-Bench. Here +the human overall score is defined as the mean of IF, RQ, and EE. VEFX-Reward-32B exhibits a tight monotonic trend +that closely follows the human score axis, whereas EditReward shows a weaker and more nonlinear relationship, and +VE-Bench displays substantially larger dispersion with limited sensitivity to score differences. Additional scatter plots +are provided in Section H.1. +match the consistency of VEFX-Reward across dimensions and metrics. More importantly, the gap to previous +reward models is large and systematic. EditReward remains somewhat useful on IF, but its negative RQ +correlations indicate a clear mismatch between image-editing supervision and video-editing assessment; it +also has no dedicated EE head. VE-Bench predicts only a single scalar score and therefore cannot support +per-dimension analysis, while even its overall agreement remains weak. These results support the need for a +reward model that jointly reasons over the source video, the editing instruction, and the edited output. +Scatter-plot analysis. Figure 4 provides a qualitative comparison of the three reward models on the human +overall score. VEFX-Reward-32B shows a clear monotonic increase and a relatively tight concentration around +the fitted trend, indicating that its predictions preserve both ordering and score magnitude more faithfully. +EditReward still captures a coarse positive trend, but the response is more nonlinear and compressed. VE- +Bench exhibits the weakest alignment, with much larger dispersion at nearly every human score level. This +visual evidence is fully consistent with the quantitative results in Table 4. +5.3 Group-wise Preference Evaluation +Standard IQA/VQA metrics measure global correlation with human scores, but reward models are often used +in a more local setting: given several candidate edits for the same source video and instruction, the model +9 + +===== PAGE 10 ===== +should prefer the better one. We therefore add a group-wise preference evaluation that measures whether a +reward model preserves human ordering within directly comparable candidate sets. +Pairwise Accuracy. Each ranking group g contains all candidate edits that share the same raw video and +editing instruction; candidate edits may come from different editing systems, but comparisons are performed +only within the group and never across groups. We enumerate all candidate pairs in each group and compare +the predicted ordering with the ground-truth ordering. If the ground truth is tied, the pair is counted as +correct regardless of the prediction; if the prediction is tied but the ground truth is not, it receives a score of +0.5. The dataset-level Pairwise Accuracy is +PairAcc = +G +g=1 (i,j)∈Pg +Accij +G +g=1 |Pg|, (4) +where Accij = 1 if the predicted order matches the human order. Unlike the global IQA/VQA metrics above, +Pairwise Accuracy depends only on relative ordering within each candidate group and is therefore insensitive +to score-scale mismatch across models. +Table 5 Group-wise preference evaluation using Pairwise Accuracy. Overall denotes performance on the human overall +score, defined as the mean of IF, RQ, and EE. +Model IF RQ EE Overall +EditReward [18] 0.8283 0.5629 0.5317 0.7919 +VE-Bench [17] 0.7351 0.8127 0.7143 0.6651 +VEFX-Reward-4B 0.9120 0.9309 0.9167 0.8628 +VEFX-Reward-32B 0.9366 0.9111 0.9196 0.8723 +Preference results. Both VEFX-Reward variants substantially outperform previous reward models on group- +wise preference consistency. VEFX-Reward-32B achieves the best overall Pairwise Accuracy at 0.872, while +VEFX-Reward-4B remains close at 0.863, indicating that most relative preference signal is already captured +at 4B scale. EditReward remains somewhat competitive on IF because one of its heads is naturally aligned +with instruction following, but it performs poorly on RQ and EE because it is an image editing reward +model without video-native temporal reasoning or a dedicated EE concept. VE-Bench shows moderate +ordering ability, but its single-score design limits fine-grained candidate comparison. Together, these results +confirm that VEFX-Reward is not only better aligned with human scores globally, but also more reliable for +within-group candidate selection. +5.4 Validation of Key Design Choices +We keep the ablation study intentionally lightweight, since the main contribution of this work is the benchmark +and the reward-model formulation rather than a complex architectural recipe. The goal of this section is to +verify that the final configuration is supported by controlled development experiments. +Table 6 Summary of key design-choice validations for VEFX-Reward. +Study Compared settings Selected choice Observation +Loss function REG / CLS / ORD ORD Best alignment with human labels +Temporal sampling Spatial resolution 1 / 2 / 4 / 8 FPS 4 FPS Best balance of motion and redundancy +154K / 400K / 450K / 920K px∼400K px Best trade-off between detail and efficiency +Analysis. Ordinal regression is consistently the strongest choice in development, which is well aligned with +the ordered 1–4 label space. For video preprocessing, 4 FPS provides the best trade-off between temporal +coverage and redundant frames. Spatially, around 400K pixels per frame is the most effective operating point: +lower resolution removes subtle local editing cues, while higher resolution increases computation without +yielding clear gains. These trends support the default configuration used in the final VEFX-Reward models. +6 Benchmarking Existing Video Editing Models +Beyond baseline comparison, VEFX-Bench also enables a systematic evaluation of existing video editing models +with our learned evaluator. We score 10 representative models using VEFX-Reward-32B on the same 1–4 scale +10 + +===== PAGE 11 ===== +. (6) +as VEFX-Dataset, including the commercial systems Kling o3 omni [46], Kling o1 [47], Runway Gen-4.5 [48], +Seedance 2.0 [49], Grok Imagine [50], Luma ray 3 [51], Wan 2.6 [52], and Luma ray 2 [53], as well as the +open-source systems UniVideo [12] and VACE [11]. In this section, all reported metrics are computed from +soft expected predictions for IF, RQ, and EE. We report Overall (Mean) as the arithmetic mean of the three +dimensions, and use Overall (GeoAgg) as the primary ranking metric. +Following prior work on multiplicative multi-attribute aggregation, we define Overall (GeoAgg) as a weighted +geometric aggregate to reduce full compensability across dimensions and to penalize weak instruction following +more strongly [54, 55]. For each evaluated sample i from model m, we first normalize the predicted scores to +[0,1]: +IFm,i−1 +RQm,i−1 +im,i= +3 , rm,i= +3 , em,i= +We then compute the sample-level aggregate and average it over the evaluated set Ωm: +EEm,i−1 +3. (5) +Overall (GeoAgg)m += +1 +|Ωm|i∈Ωm +1 + 3 iα +m,irβ +m,ieγ +m,i +1 +α+β+γ +In all experiments in this section, we set (α,β,γ) = (2,1,1), so IF receives twice the weight of RQ and EE. We +compute GeoAgg before averaging because the geometric aggregate is nonlinear; applying it after averaging IF, +RQ, and EE would overestimate systems with high variance or unbalanced per-sample behavior. Compared +with an arithmetic mean, this multiplicative form is more sensitive to weak dimensions, which is desirable in +video editing evaluation because strong rendering quality or locality preservation should not fully offset poor +instruction following. +Adjusting incomplete model coverage. Some commercial systems impose inference constraints, resulting in +incomplete benchmark coverage for models such as Runway Gen-4.5 and Seedance 2.0. Rather than reporting +a naive mean over each observed subset, which can be biased when coverage correlates with item difficulty, +we treat incomplete coverage as a missing-data problem [56]. Our adjustment follows the standard inverse- +propensity weighting principle [57–59]. Let Rm,i = 1 indicate that model m has a valid evaluated output for +benchmark item i, and let xi denote item-level covariates such as task type, prompt length, and constraint +count. We estimate the observation propensityˆ +pm,i= Pr(Rm,i = 1 |m,xi) and weight each observed score +by a clipped inverse-propensity weight wm,i = 1/ˆ +pm,i. For each dimension d, we then fit a weighted linear +mixed-effects model +ym,i,d= µm,d + ui + ϵm,i,d, ui ∼N(0,σ2 +u), (7) +where ui captures item difficulty. The reported IF, RQ, and EE scores are coverage-adjusted model-level +estimatesˆ +µm,d under the assumption that coverage is explainable by observed item covariates. Overall (Mean) +is computed from these adjusted dimension scores, while Overall (GeoAgg) is computed from soft per-sample +IF/RQ/EE predictions and then averaged as in Equation (6). +Table 7 VEFX-Reward-32B-based evaluation of representative video editing systems using soft expected predictions. +IF, RQ, EE, and Overall (Mean) use coverage-adjusted estimates from inverse-propensity-weighted mixed-effects +estimation; Overall (GeoAgg) is averaged over sample-level GeoAgg scores. Higher is better on all columns.∗ denotes +adjusted results for models with incomplete benchmark coverage. +Model Overall (GeoAgg) Overall (Mean) IF RQ EE +Commercial +Kling o3 omni 3.057 3.221 3.033 3.588 3.043 +Kling o1 2.985 3.183 3.040 3.534 2.976 +Runway Gen-4.5∗ 2.912 3.020 2.817 3.319 2.923 +Seedance 2.0∗ 2.766 3.107 2.811 3.421 3.088 +Grok Imagine 2.723 3.109 2.606 3.346 3.376 +Luma ray 3 2.717 2.936 2.702 3.403 2.705 +Wan 2.6 2.146 2.592 2.012 3.317 2.446 +Luma ray 2 1.804 1.977 2.038 2.532 1.363 +Open-source +UniVideo [12] 2.516 2.883 2.294 3.266 3.091 +VACE [11] 1.775 2.126 2.027 3.172 1.180 +11 + +===== PAGE 12 ===== +Table analysis. As shown in Table 7, Kling o3 omni ranks first under Overall (GeoAgg), followed by Kling +o1. Both models combine strong IF and RQ with competitive EE, so their rankings remain high under the +per-sample multiplicative aggregate. Runway Gen-4.5 ranks third by GeoAgg, reflecting balanced per-sample +behavior despite a lower adjusted mean. Seedance 2.0 improves after the corrected result merge and ranks +fourth by GeoAgg, with strong RQ and EE but still weaker IF than the top systems. Grok Imagine achieves +the strongest EE score and a high arithmetic mean, but its lower IF reduces its Overall (GeoAgg). +Among the open-source systems, UniVideo is clearly stronger than VACE and remains competitive with +several commercial systems, especially on EE. Luma ray 3 and Wan 2.6 achieve strong RQ but are limited by +weaker IF or EE, while Luma ray 2 and VACE show the largest drops because of poor edit exclusivity. Overall, +the results suggest that modern systems often produce visually plausible videos, but reliable instruction +following and locality preservation still separate the strongest editing models from the rest. +Overall (GeoAgg) +Score +4 +3 +2 +1 +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Grok +Luma ray 3 +Seedance +Wan 2.6 +Rendering Quality +Luma ray 2 +Open-source +UniVideo +VACE +Observed score distributions grouped and ordered by per-sample GeoAgg +Overall (Mean) +Score +Instruction Following +Score +4 +3 +2 +1 +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Grok +Luma ray 3 +Seedance +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +Score +4 +3 +2 +1 +Kling o3 omni +4 +Kling o1 +Commercial Runway Gen-4.5 +Grok +Luma ray 3 +3 +2 +Seedance +Edit Exclusivity +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +1 +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Grok +Luma ray 3 +Seedance +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +Score +4 +3 +2 +1 +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Grok +Luma ray 3 +Seedance +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +Models +Kling o3 omni +Kling o1 +Runway Gen-4.5 +Grok +Luma ray 3 +Seedance +Wan 2.6 +Luma ray 2 +UniVideo +VACE +Figure 5 Observed soft-score VEFX-Reward-32B distributions for the benchmarked video editing systems across Overall +(GeoAgg), Overall (Mean), IF, RQ, and EE. Models are grouped by availability and ordered by per-sample Overall +(GeoAgg). +Figure analysis. Figure 5 complements the adjusted table with the distribution of observed per-item scores. +The top commercial systems have high medians but still show substantial prompt-level variance, indicating +that no model is uniformly reliable across editing tasks. RQ is generally higher and more concentrated than +IF, suggesting that visual plausibility is easier to achieve than instruction-faithful editing. EE provides the +clearest separation: Grok Imagine, UniVideo, Kling o3 omni, and Seedance 2.0 maintain relatively strong +locality, whereas VACE and Luma ray 2 concentrate near the bottom of the scale. The gap between Overall +(Mean) and Overall (GeoAgg) is most visible for models with unbalanced dimensions, illustrating why a +shortfall-sensitive aggregate is useful for benchmark ranking. +Task-wise analysis. Figure 6 shows that the strongest systems are not uniformly strong across all editing types. +Kling o3 omni and Kling o1 maintain broad coverage with clear advantages on quantity, attribute, instance, +and visual-effect editing, while Runway Gen-4.5 and Seedance 2.0 are more balanced but slightly lower overall. +Grok Imagine has a distinctive profile: it is strong on style, instance, and visual-effect editing, but weaker on +camera-control tasks. The lower-scoring models show smaller and more compressed profiles, suggesting that +their failures are not limited to a single task type. +12 + +===== PAGE 13 ===== +Visual +Effect +Instance +Instance +Motion +Visual +Effect +Instance +Instance +Motion +Kling o3 omni +Camera +Angle +4 +3 +2 +1 +Creative +Style +UniVideo +Camera +Angle +4 +3 +2 +1 +Creative +Style +Camera +Motion +Visual +Effect +Quantity +Attribute +Camera +Motion +Quantity +Attribute +Instance +Instance +Motion +Visual +Effect +Instance +Instance +Motion +Kling o1 +Camera +Angle +4 +3 +2 +1 +Creative +Style +Grok Imagine +Camera +Angle +4 +3 +2 +1 +Creative +Style +Visual +Effect +Camera +Motion +3 +Quantity +Attribute +Quantity +Attribute +Overall (GeoAgg) Profiles by Editing Task +Camera +Motion +Seedance 2.0 +Camera +Angle +4 +3 +2 +1 +Creative +Style +Wan 2.6 +Camera +Angle +4 +3 +2 +1 +Runway Gen-4.5 +Camera +Angle +4 +Visual +Effect +2 +1 +Creative +VACE +Camera +Angle +2 +1 +Camera +Motion +Visual +Effect +Camera +Motion +Quantity +Attribute +Instance +Instance +Motion +Visual +Effect +Instance +Instance +Motion +Camera +Motion +Quantity +Attribute +Instance +Instance +Motion +Visual +Effect +Instance +Instance +Motion +Quantity +Attribute +Style +4 +3 +Camera +Motion +Quantity +Attribute +Instance +Instance +Motion +Visual +Effect +Instance +Instance +Motion +Creative +Style +Creative +Style +Luma ray 3 +Camera +Angle +4 +3 +2 +1 +Creative +Style +Luma ray 2 +Camera +Angle +4 +3 +2 +1 +Creative +Style +Camera +Motion +Quantity +Attribute +Camera +Motion +Quantity +Attribute +Figure 6 Task-wise Overall (GeoAgg) profiles of the benchmarked video editing systems. Each radar plot uses the same +radial scale, allowing the profile shape and absolute score level of each model to be compared across editing tasks. +7 Conclusion +We introduced VEFX-Dataset, a human-annotated dataset of 5,049 video editing examples with decoupled +labels for Instruction Following, Rendering Quality, and Edit Exclusivity, together with VEFX-Reward for +automated evaluation and VEFX-Bench for standardized model comparison. Across both standard IQA/VQA +metrics and group-wise preference evaluation, VEFX-Reward consistently outperforms generic VLM judges +and prior reward-model baselines, showing the value of task-specific reward modeling for video editing. Using +VEFX-Reward as a scalable evaluator, we further benchmark representative commercial and open-source editing +systems and analyze their behavior across editing tasks. This analysis shows that current systems often +achieve plausible rendering quality without reliably satisfying instructions or preserving non-target content, +reinforcing the need for multi-dimensional evaluation rather than a single holistic score. We hope these +resources provide a practical foundation for benchmarking, model selection, and reward-driven optimization +in video editing. +13 + +===== PAGE 14 ===== +References +[1] T. Wan, A. Wang, B. Ai, B. Wen, C. Mao, C.-W. Xie, D. Chen, F. Yu, H. Zhao, J. Yang et al., “Wan: Open and +advanced large-scale video generative models,” arXiv preprint arXiv:2503.20314, 2025. +[2] S. Chen, C. Ge, Y. Zhang, Y. Zhang, F. Zhu, H. Yang, H. Hao, H. Wu, Z. Lai, Y. Hu et al., “Goku: Flow based +video generative foundation models,” in Proceedings of the Computer Vision and Pattern Recognition Conference, +2025, pp. 23516–23527. +[3] W. Kong, Q. Tian, Z. Zhang, R. Min, Z. Dai, J. Zhou, J. Xiong, X. Li, B. Wu, J. Zhang et al., “Hunyuanvideo: A +systematic framework for large video generative models,” arXiv preprint arXiv:2412.03603, 2024. +[4] A. Polyak, A. Zohar, A. Brown, A. Tjandra, A. Sinha, A. Lee, A. Vyas, B. Shi, C.-Y. Ma, C.-Y. Chuang et al., +“Movie gen: A cast of media foundation models,” arXiv preprint arXiv:2410.13720, 2024. +[5] OpenAI, “Sora: Creating video from text,” 2024. +[6] R. Li, P. Pan, B. Yang, D. Xu, S. Zhou, X. Zhang, Z. Li, A. Kadambi, Z. Wang, Z. Tu et al., “4k4dgen: Panoramic +4d generation at 4k resolution,” arXiv preprint arXiv:2406.13527, 2024. +[7] M. Wu, A. Mishra, S. Dey, S. Xing, N. Ravipati, H. Wu, B. Li, and Z. Tu, “Consid-gen: View-consistent and +identity-preserving image-to-video generation,” arXiv preprint arXiv:2602.10113, 2026. +[8] DeepMind, “Veo3 technical report,” DeepMind, Technical Report, 2025, accessed: 2026-02-18. [Online]. Available: +https://storage.googleapis.com/deepmind-media/veo/Veo-3-Tech-Report.pdf +[9] Kling AI, “Kling AI Omni / VIDEO O1 creative interface,” 2025. +[10] xAI, “Grok Imagine — ai image & video generation by xai,” 2026. +[11] Z. Jiang, Z. Han, C. Mao, J. Zhang, Y. Pan, and Y. Liu, “Vace: All-in-one video creation and editing,” arXiv +preprint arXiv:2503.07598, 2025. +[12] C. Wei, Q. Liu, Z. Ye, Q. Wang, X. Wang, P. Wan, K. Gai, and W. Chen, “Univideo: Unified understanding, +generation, and editing for videos,” arXiv preprint arXiv:2510.08377, 2025. +[13] Y. Chen, P. Chen, X. Zhang, Y. Huang, and Q. Xie, “Editboard: Towards a comprehensive evaluation benchmark +for text-based video editing models,” in Proceedings of the AAAI Conference on Artificial Intelligence, vol. 39, +no. 15, 2025, pp. 15975–15983. +[14] M. Li, C. Xie, Y. Wu, L. Zhang, and M. Wang, “Five: A fine-grained video editing benchmark for evaluating +emerging diffusion and rectified flow models,” arXiv preprint arXiv:2503.13684, 2025. +[15] Y. Chen, J. Zhang, T. Hu, Y. Zeng, Z. Xue, Q. He, C. Wang, Y. Liu, X. Hu, and S. Yan, “Ivebench: Modern +benchmark suite for instruction-guided video editing assessment,” arXiv preprint arXiv:2510.11647, 2025. +[16] H. He, J. Wang, J. Zhang, Z. Xue, X. Bu, Q. Yang, S. Wen, and L. Xie, “Openve-3m: A large-scale high-quality +dataset for instruction-guided video editing,” arXiv preprint arXiv:2512.07826, 2025. +[17] S. Sun, X. Liang, S. Fan, W. Gao, and W. Gao, “Ve-bench: Subjective-aligned benchmark suite for text-driven +video editing quality assessment,” arXiv preprint arXiv:2408.11481, 2024. +[18] K. Wu, S. Jiang, M. Ku, P. Nie, M. Liu, and W. Chen, “Editreward: A human-aligned reward model for +instruction-guided image editing,” arXiv preprint arXiv:2509.26346, 2025. +[19] J. Liu, G. Liu, J. Liang, Z. Yuan, X. Liu, M. Zheng, X. Wu, Q. Wang, M. Xia, X. Wang et al., “Improving video +generation with human feedback,” arXiv preprint arXiv:2501.13918, 2025. +[20] Z. Li, X. Chen, L. Jiang, D. Hou, F. Lin, K. Yamada, X. Gao, and Z. Tu, “Physics-aware video instance removal +benchmark,” arXiv preprint arXiv:2604.05898, 2026. +[21] S. Motamed, W. Harvey, B. Klein, L. Van Gool, Z. Yuan, and T.-Y. Cheng, “Void: Video object and interaction +deletion,” arXiv preprint arXiv:2604.02296, 2026. +[22] R. Burgert, C. Herrmann, F. Cole, M. S. Ryoo, N. Wadhwa, A. Voynov, and N. Ruiz, “Motionv2v: Editing motion +in a video,” arXiv preprint arXiv:2511.20640, 2025. +[23] X. Gao, R. Li, X. Chen, Y. Wu, S. Feng, Q. Yin, and Z. Tu, “Pisco: Precise video instance insertion with sparse +control,” arXiv preprint arXiv:2602.08277, 2026. +[24] Y. Guo, C. Yang, A. Rao, Z. Liang, Y. Wang, Y. Qiao, M. Agrawala, D. Lin, and B. Dai, “Animatediff: Animate +your personalized text-to-image diffusion models without specific tuning,” arXiv preprint arXiv:2307.04725, 2023. +[25] L. Yang, Z. Zhang, Y. Song, S. Hong, R. Xu, Y. Zhao, W. Zhang, B. Cui, and M.-H. Yang, “Diffusion models: A +comprehensive survey of methods and applications,” ACM computing surveys, vol. 56, no. 4, pp. 1–39, 2023. +14 + +===== PAGE 15 ===== +[26] G. Cheng, X. Gao, L. Hu, S. Hu, M. Huang, C. Ji, J. Li, D. Meng, J. Qi, P. Qiao et al., “Wan-animate: Unified +character animation and replacement with holistic replication,” arXiv preprint arXiv:2509.14055, 2025. +[27] Luma AI, “Luma ray2,” https://lumalabs.ai/ray2, 2025. +[28] A. Radford, J. W. Kim, C. Hallacy, A. Ramesh, G. Goh, S. Agarwal, G. Sastry, A. Askell, P. Mishkin, J. Clark +et al., “Learning transferable visual models from natural language supervision,” in ICML, 2021. +[29] R. Zhang, P. Isola, A. A. Efros, E. Shechtman, and O. Wang, “The unreasonable effectiveness of deep features as +a perceptual metric,” in Proceedings of the IEEE conference on computer vision and pattern recognition, 2018, pp. +586–595. +[30] Z. Huang, Y. He, J. Yu, F. Zhang, C. Si, Y. Jiang, Y. Zhang, T. Wu, Q. Jin, N. Chanpaisit et al., “Vbench: +Comprehensive benchmark suite for video generative models,” in Proceedings of the IEEE/CVF Conference on +Computer Vision and Pattern Recognition, 2024, pp. 21807–21818. +[31] Z. Huang, F. Zhang, X. Xu, Y. He, J. Yu, Z. Dong, Q. Ma, N. Chanpaisit, C. Si, Y. Jiang et al., “Vbench++: +Comprehensive and versatile benchmark suite for video generative models,” IEEE Transactions on Pattern +Analysis and Machine Intelligence, 2025. +[32] J. Xu, X. Liu, Y. Wu, Y. Tong, Q. Li, M. Ding, J. Tang, and Y. Dong, “Imagereward: Learning and evaluating +human preferences for text-to-image generation,” Advances in Neural Information Processing Systems, vol. 36, pp. +15903–15935, 2023. +[33] X. Wu, Y. Hao, K. Sun, Y. Chen, F. Zhu, R. Zhao, and H. Li, “Human preference score v2: A solid benchmark +for evaluating human preferences of text-to-image synthesis,” arXiv preprint arXiv:2306.09341, 2023. +[34] Y. Kirstain, A. Polyak, U. Singer, S. Matiana, J. Penna, and O. Levy, “Pick-a-pic: An open dataset of user +preferences for text-to-image generation,” Advances in neural information processing systems, vol. 36, pp. 36652– +36663, 2023. +[35] X. He, D. Jiang, G. Zhang, M. Ku, A. Soni, S. Siu, H. Chen, A. Chandra, Z. Jiang, A. Arulraj et al., “Videoscore: +Building automatic metrics to simulate fine-grained human feedback for video generation,” in Proceedings of the +2024 Conference on Empirical Methods in Natural Language Processing, 2024, pp. 2105–2123. +[36] Z.Wu, A.Kag, I.Skorokhodov, W.Menapace, A.Mirzaei, I.Gilitschenski, S.Tulyakov, andA.Siarohin, “Densedpo: +Fine-grained temporal preference optimization for video diffusion models,” arXiv preprint arXiv:2506.03517, 2025. +[37] H. Duan, H.-X. Yu, S. Chen, L. Fei-Fei, and J. Wu, “Worldscore: A unified evaluation benchmark for world +generation,” in Proceedings of the IEEE/CVF International Conference on Computer Vision, 2025, pp. 27713– +27724. +[38] X. Gao, M. Wu, S. Yang, J. Yu, P. Taghavi, F. Lin, and Z. Tu, “The pulse of motion: Measuring physical frame +rate from visual dynamics,” arXiv preprint arXiv:2603.14375, 2026. +[39] Z. Zheng et al., “Open-Sora: Democratizing efficient video production for all,” arXiv preprint arXiv:2412.20404, +2024. +[40] K. Nan et al., “OpenVid-1M: A large-scale high-quality dataset for text-to-video generation,” arXiv preprint +arXiv:2407.02371, 2024. +[41] Google DeepMind, “Gemini 3 Flash — deepmind ai model,” 2025. +[42] A. Yang, A. Li, B. Yang, B. Zhang, B. Hui, B. Zheng, B. Yu, C. Gao, C. Huang, C. Lv et al., “Qwen3 technical +report,” arXiv preprint arXiv:2505.09388, 2025. +[43] U. Shaham, I. Zaidman, and J. Svirsky, “Deep ordinal regression using optimal transport loss and unimodal +output probabilities,” arXiv preprint arXiv:2011.07607, 2020. +[44] Google DeepMind, “Gemini 3.1 Pro — deepmind ai model,” 2025. +[45] ByteDance Seed Team, “ByteDance Seed: Models and research,” https://seed.bytedance.com/, 2025, accessed: +2026-02-27. +[46] Kling AI, “Kling video 3.0 model user guide,” https://kling.ai/quickstart/klingai-video-3-model-user-guide, Feb. +2026, accessed: 2026-04-16. +[47] ——, “Kling video o1 user guide,” https://kling.ai/quickstart/klingai-video-o1-user-guide, Dec. 2025, accessed: +2026-04-16. +[48] Runway, “Introducing runway gen-4.5: A new frontier for video generation,” https://runwayml.com/research/ +introducing-runway-gen-4.5, Dec. 2025, accessed: 2026-04-16. +[49] ByteDance Seed Team, “Seedance 2.0 official launch,” https://seed.bytedance.com/en/blog/ +15 + +===== PAGE 16 ===== +official-launch-of-seedance-2-0, Feb. 2026, accessed: 2026-04-16. +[50] xAI, “Grok imagine api,” https://x.ai/news/grok-imagine-api, Jan. 2026, accessed: 2026-04-16. +[51] Luma AI, “Luma ai launches ray3,” https://lumalabs.ai/news/ray3, Sep. 2025, accessed: 2026-04-16. +[52] Alibaba Cloud, “Alibaba unveils wan2.6 series enabling everyone to star in videos,” https://www.alibabacloud.com/ +blog/alibaba-unveils-wan2-6-series-enabling-everyone-to-star-in-videos_602742, Dec. 2025, accessed: 2026-04-16. +[53] Luma AI, “Introducing ray2,” https://lumalabs.ai/changelog/introducing-ray2, Jan. 2025, accessed: 2026-04-16. +[54] R. L. Keeney and H. Raiffa, Decisions with Multiple Objectives: Preferences and Value Tradeoffs. Cambridge +University Press, 1993. +[55] R. L. Keeney, “Multiplicative utility functions,” Operations Research, vol. 22, no. 1, pp. 22–34, 1974. +[56] D. B. Rubin, “Inference and missing data,” Biometrika, vol. 63, no. 3, pp. 581–592, 1976. +[57] D. G. Horvitz and D. J. Thompson, “A generalization of sampling without replacement from a finite universe,” +Journal of the American Statistical Association, vol. 47, no. 260, pp. 663–685, 1952. +[58] J. M. Robins, A. Rotnitzky, and L. P. Zhao, “Estimation of regression coefficients when some regressors are not +always observed,” Journal of the American Statistical Association, vol. 89, no. 427, pp. 846–866, 1994. +[59] S. R. Seaman and I. R. White, “Review of inverse probability weighting for dealing with missing data,” Statistical +Methods in Medical Research, vol. 22, no. 3, pp. 278–295, 2013. +[60] N. Ravi et al., “SAM 2: Segment anything in images and videos,” arXiv preprint arXiv:2408.00714, 2024. +[61] C. Miao, Y. Feng, J. Zeng, Z. Gao, H. Liu, Y. Yan, D. Qi, X. Chen, B. Wang, and H. Zhao, “Rose: Remove +objects with side effects in videos,” arXiv preprint arXiv:2508.18633, 2025. +[62] Y. Xu, J. Zhang, Q. Zhang, and D. Tao, “ViTPose: Simple vision transformer baselines for human pose estimation,” +in NeurIPS, 2022. +[63] H. Lin, S. Chen, J. Liew, D. Y. Chen, Z. Li, G. Shi, J. Feng, and B. Kang, “Depth anything 3: Recovering the +visual space from any views,” arXiv preprint arXiv:2511.10647, 2025. +[64] J. He et al., “ReCamMaster: Camera-controlled generative rendering from a single video,” arXiv preprint +arXiv:2501.12007, 2025. +[65] T. Liu, Z. Chen, Z. Huang, S. Xu, S. Zhang, C. Ye, B. Li, Z. Cao, W. Li, H. Zhao et al., “Light-x: Generative 4d +video rendering with camera and illumination control,” arXiv preprint arXiv:2512.05115, 2025. +16 + +===== PAGE 17 ===== +Appendix +A Additional Training Details for VEFX-Reward +We provide the implementation details omitted from the main paper. VEFX-Reward is trained on the 4,200- +example training split of VEFX-Dataset and evaluated on the 849-example test split, with the split stratified +across editing categories and pipelines. +Video Processing. For each example, we uniformly sample both the original and edited videos at 4 FPS and +cap the frame resolution at 399,360 pixels, approximately 632 ×632, while preserving aspect ratio through +Qwen3-VL’s dynamic-resolution mechanism. The two videos are sampled with aligned temporal indices to +support direct comparison. The maximum sequence length is 32,768 tokens. +Optimization. We use a two-stage training schedule. In the first stage, lasting 1 epoch, we freeze all pretrained +parameters and train only the newly introduced reward tokens and reward head. In the second stage, lasting +49 epochs, we unfreeze and fine-tune the language backbone and visual-language merger together with the +reward head and reward tokens, while keeping the vision tower frozen. We use AdamW with learning rates +of 1 ×10−5 for the language-side parameters and 5 ×10−5 for the reward tokens, cosine decay, and a 15% +warmup ratio. Training is performed in bf16 on 8 GPUs with an effective batch size of 8. The three reward +dimensions are optimized jointly with equal loss weights. +B Additional Experimental Details +Model Variants. We evaluate two VEFX-Reward variants, VEFX-Reward-4B and VEFX-Reward-32B, which +instantiate the same reward-model design on Qwen3-VL backbones at 4B and 32B scales. +Evaluation Setup. Both variants are evaluated on the same 849-example test split. For VLM-as-judge baselines, +we use a shared prompt that presents the original video, editing instruction, and edited video, and asks the +model to score IF, RQ, and EE according to the same 1–4 rubric used in human annotation. In the main +paper, the human overall score is defined as the arithmetic mean of the three human dimension scores. For +VEFX-Reward and VLM-as-judge baselines, the overall prediction is defined as the mean of the three predicted +dimension scores. +External Reward Models. EditReward and VE-Bench are evaluated through their native outputs. For +EditReward, the overall prediction is defined as the mean of its two native heads; for VE-Bench, the overall +prediction is its native scalar output. SRCC and KRCC are computed directly from raw predictions, while +PLCC and RMSE use the same logistic calibration protocol as in the main paper when applicable. Since +EditReward lacks a dedicated EE head and VE-Bench predicts only a single overall score, unavailable entries +are marked with – +. +C Editing Pipeline Details +We describe the detailed procedures for each category of editing systems used in VEFX-Dataset. +C.1 Commercial Models +For generic instruction-guided video editing, we directly submit (source video, instruction) pairs to four +commercial APIs: Grok Imagine [10], Kling Omni [9], Wan 2.6 [26], and Luma Ray2 [27]. These systems +accept free-form text instructions and produce edited videos end-to-end. +C.2 Open-Source Specialized Models +Instance Removal. We first apply SAM 2 [60] to segment the target instance across all video frames, with +manual verification and correction of segmentation masks. The corrected masks are then fed to ROSE [61], +17 + +===== PAGE 18 ===== +using the removal model retrained on the ROSE dataset with the PISCO [23] framework to support 720p +resolution and 121-frame sequences. +Instance Insertion. We use NanoBanana-Pro to perform the desired edit on a single reference frame, then +extract the newly inserted object via SAM 2 segmentation. The extracted single-frame instance serves as a +spatial control signal for PISCO, which propagates the insertion consistently across all video frames while +preserving the background. +Instance Repositioning and Resizing. The target instance is extracted using SAM 2 with manual correction. +A VLM (Gemini-2.0-Flash [41]) interprets the editing instruction and provides guidance for the required +spatial transformation (translation, scaling, rotation) of the segmented instance. Simultaneously, the PISCO- +finetuned removal model inpaints the vacated region. Finally, PISCO-14B performs instance insertion using +the transformed instance as a spatial condition, composited onto the inpainted background video. +Human Motion Editing. We extract human pose keypoints using ViTPose [62] and modify them according +to Gemini-2.0-Flash’s interpretation of the editing instruction, with human-in-the-loop verification of pose +correctness. The modified pose sequence, together with additional control signals (Canny edges, depth maps +from Depth Anything V3 [63]), condition Wan-Animate to generate a new video from the original first frame. +Camera Motion and Angle Editing. Gemini-2.0-Flash maps the natural language instruction to predefined +camera trajectory parameters (pan, tilt, zoom, dolly, arc, etc.). ReCamMaster [64] and LightX [65] then +execute the specified camera transformation on the source video. +Style, Creative, Visual Effect, and Attribute Editing. For these categories, we apply NanoBanana-Pro to edit the +first frame according to the instruction, then use VACE [11] in first-frame-conditioned mode to propagate the +edit temporally across all frames. Additionally, for a subset of samples, we employ UniVideo [12] for direct +end-to-end text-conditioned video editing, similar to the commercial-model usage pattern. +D Complete Annotation Guide +This appendix provides the complete annotation guide used to train annotators for VEFX-Dataset. The guide +was provided in both English and Chinese; we present the English version here. +D.1 General Instructions +Annotators are presented with an original video, an editing instruction, and one or more edited videos +produced by different models. For each edited video, annotators independently score three dimensions on a +4-point scale (1–4). The three dimensions must be scored independently: the score on one dimension must +not influence the score on another. When a result matches multiple descriptions, annotators should assign the +lowest applicable score. This rule is especially important when a video has both good aspects and one clear +failure that crosses the boundary to a lower level. +D.2 Dimension 1: Instruction Following (IF) +This dimension evaluates whether the edited content accurately reflects the semantic requirements of the +instruction. +• Score 4 — Complete and Correct Execution. All requested edits are clearly completed, and no required +element is missing or incorrect. The target object, attribute, action, style, or camera change matches the +instruction without visible contradiction. +• Score 3 — Mostly Correct Execution. The core edit is completed, but one minor detail is wrong or missing. +Typical cases include correct target and edit type but slight mismatch in fine-grained attribute, appearance, +intensity, or local extent. The result should still be recognizably aligned with the instruction overall. +• Score 2 — Partial Execution with Major Deviation. The video shows some relationship to the instruction, but +the main requirement is only partially satisfied or is satisfied with a major semantic error. Typical cases +18 + +===== PAGE 19 ===== +include editing the correct region but producing the wrong object or attribute, executing only one part of a +multi-step instruction, or mixing the requested edit with an obviously incorrect alternative. +• Score 1 — Failure or Contradiction. The instruction is not executed, the edit is largely unrelated, or the result +directly contradicts the instruction. Examples include no visible edit, editing the wrong target, or changing +the scene in the opposite direction from the requested operation. +D.3 Dimension 2: Rendering Quality (RQ) +This dimension evaluates the visual quality of the edited video, including naturalness, clarity, physical +correctness of object movements, temporal consistency between frames, and the absence of artifacts. +• Score 4 — High Visual Fidelity. The video is clear, temporally stable, and visually natural throughout. +Artifacts are absent or only barely perceptible, object structure remains intact, and motion follows plausible +physical behavior. +• Score 3 — Minor but Noticeable Degradation. The video remains fully watchable, but there are visible quality +issues such as slight blur, local flicker, mild temporal inconsistency, or small artifact regions. These issues +are limited and do not damage the overall scene structure or object identity. +• Score 2 — Clear Quality Failure. Artifacts are obvious and recurrent, such as repeated flicker, deformation, +ghosting, severe blur, unstable boundaries, or unnatural motion. The content is still recognizable, but the +defects substantially reduce visual quality and viewing coherence. +• Score 1 — Severe Visual Breakdown. The result is visually unusable or close to unusable. Major regions are +corrupted, object identity collapses, temporal coherence is lost, or motion becomes physically implausible +to the point that the video no longer supports reliable evaluation of the intended edit. +D.4 Dimension 3: Edit Exclusivity (EE) +This dimension evaluates whether the model executed only the specified operation without unnecessary +changes to unrelated areas. A non-target change is defined as any clearly visible modification to an object, +region, or background element that is not required by the instruction. When counting non-target changes, +multiple altered instances in different semantic regions should be counted separately. +• Score 4 — Strict Preservation. No clearly visible non-target change is introduced. All regions outside +the intended edit remain visually unchanged, except for imperceptible pixel-level differences or negligible +rendering noise. +• Score 3 — One Clear Non-Target Change. The intended target is edited, but exactly one additional non-target +object or semantic region is also clearly altered. The overall scene layout is still preserved, and the error +remains localized. +• Score 2 — Two to Three Clear Non-Target Changes. Two or three non-target objects or semantic regions are +clearly altered, or one large unintended background change affects a substantial part of the scene. The +result still resembles the original video, but over-editing is obvious. +• Score 1 — Global or Widespread Over-Editing. More than three non-target objects or semantic regions are +clearly altered, or the scene is globally rewritten. The result looks like a substantially different video rather +than a localized edit. +D.5 Dimension Decoupling Principle +The three dimensions must be scored independently. Consider the following example: +Instruction: “Turn the apple into a banana.” +Result: The model completely fails and the apple remains unchanged. +• IF = 1 (complete failure to follow the instruction) +• RQ = score independently (if the video quality is excellent, this can still be 4) +19 + +===== PAGE 20 ===== +• EE = score independently (if no unintended changes occurred, this can still be 4) +This principle ensures that each dimension captures a distinct aspect of editing quality. +D.6 Annotation Examples +We provide all example cases from the annotation guide. Each figure shows the first frame of the original +video together with one or more edited results and their IF/RQ/EE scores. The scores are assigned from +the full video rather than from the displayed frame alone. These examples cover attribute editing, creative +editing, instance editing, visual effects, and style transfer, and illustrate how the same instruction can lead to +different score patterns across dimensions. +Figure 7 Annotation example 1. The instruction asks to turn only the blue foreground pens into emerald green while +preserving transparency, reflections, highlights, the black pen, and the blurred background. Kling Omni receives +IF/RQ/EE = 4/4/4 because it executes the requested color change cleanly, keeps the plastic appearance realistic, +and leaves non-target content untouched. Grok Imagine receives 3/4/3 because the target edit is mostly correct and +visually clean, but the green conversion is less precise and some non-target regions are also affected, reducing both IF +and EE. Wan 2.6 receives 2/3/2 because the requested color transformation is incomplete, the result looks less stable +and less realistic, and unintended color changes spill into regions that should have remained unchanged. +Figure 8 Annotation example 2. The instruction asks to replace the distant tropical islands and mountains with +glaciers and snow-covered peaks while leaving the rest of the scene intact. Grok Imagine and Kling Omni both receive +IF/RQ/EE = 4/4/4 because they fully carry out the requested background replacement, keep the water and boat-view +foreground natural, and introduce no obvious non-target distortions. Wan 2.6 receives 1/4/3 because it essentially fails +to perform the requested semantic edit: the original tropical background remains, so IF is 1. Its RQ is still 4 because +the video itself remains visually clean and artifact-free, which illustrates the intended decoupling between instruction +following and rendering quality. EE is 3 rather than 4 because, although the edit does not heavily corrupt the scene, +the output also does not faithfully realize the target modification. +20 + +===== PAGE 21 ===== +Figure 9 Annotation example 3. The instruction asks for a complete replacement of the white background with a +bustling construction-site interior, together with clean subject boundaries, stable depth, and relit foreground subjects. +All three edited results receive IF = 2 because they only partially satisfy the instruction: the construction-site +replacement is introduced, but the compositing and relighting are not fully convincing, so the overall request is only +partly achieved. Kling Omni receives the highest rendering score, RQ = 4, because its compositing is the cleanest and +most visually coherent over time. Grok Imagine and Wan 2.6 receive RQ = 3 because the inserted environment looks +less seamlessly integrated and shows weaker consistency. Grok Imagine and Kling Omni both receive EE = 4 because +the three people remain largely intact, whereas Wan 2.6 receives EE = 3 because the foreground subjects are altered +more noticeably during the edit. +Figure 10 Annotation example 4. The instruction asks for a heavy snowfall effect with visible accumulation on the mossy +ground and bare branches. Grok Imagine receives IF/RQ/EE = 4/4/3 because it clearly adds snow and accumulation +with strong visual quality, but it also alters parts of the scene beyond the requested effect. Kling Omni receives 3/4/4 +because the result is visually strong and preserves the scene structure well, but the snowfall effect is weaker than +requested, so the instruction is not fully satisfied. Wan 2.6 receives 4/3/3 because it does introduce the requested snow +effect, but the rendering is less realistic and less stable, and some non-target structure is also modified. +21 + +===== PAGE 22 ===== +Figure 11 Annotation example 5. The instruction asks to replace the shirt graphic with a detailed vintage red sports +car while keeping the rest of the person and scene unchanged. The edited result receives IF/RQ/EE = 3/2/4. IF is 3 +because the shirt graphic is changed to a red car, so the main semantic request is met, but the inserted graphic is not +fully convincing as a detailed vintage illustration across the clip. RQ is 2 because the edited graphic shows noticeable +temporal instability and tracking inconsistency over time, even though the displayed frame looks acceptable. EE is 4 +because the edit remains well localized to the shirt and does not introduce obvious unintended changes elsewhere in +the video. +Figure 12 Annotation example 6. The instruction asks to convert the video into a cyberpunk style. The edited result +receives IF/RQ/EE = 4/4/3. IF is 4 because the neon lighting, color palette, wardrobe styling, and overall atmosphere +clearly match the requested cyberpunk aesthetic. RQ is 4 because the stylization is visually coherent and clean. EE is +reduced to 3 because the transformation also modifies unrelated details, including text, facial appearance, and other +local elements beyond the minimal style change needed to satisfy the instruction. +E Inter-Annotator Agreement +E.1 Cross-Check Procedure +We randomly sample 550 examples from the annotated dataset and assign them to an independent group +of new annotators for re-annotation. The second group follows the same annotation protocol and training +procedure but has no access to the original annotations. This produces a double-annotation subset for a +focused consistency check. +22 + +===== PAGE 23 ===== +Figure 13 Annotation example 7. The instruction asks to replace the original black-rimmed glasses with gold-framed +aviator sunglasses while preserving the man’s facial features, expressions, head motion, reflections, and clean edges. +The edited result receives IF/RQ/EE = 3/3/2. IF is 3 because the target object is indeed changed into sunglasses, but +the replacement does not fully satisfy the requested appearance and realism. RQ is 3 because the local edit is usable +but not fully clean, with only moderate realism in the eyewear integration. EE is 2 because the edit also changes other +facial details, overall lighting, and background appearance, producing multiple unintended modifications outside the +requested eyewear replacement. +E.2 Agreement by Dimension +Table 8 reports the agreement statistics used in the main paper. +Table 8 Inter-annotator agreement on the 550-sample double-annotation subset. +Metric IF RQ EE +Exact Agreement (%) 75.2 87.2 72.2 +Within-1 Agreement (%) 93.5 97.2 91.7 +RQ achieves the strongest agreement, with 87.2% exact agreement and 97.2% within-1 agreement, indicating +that rendering quality is relatively stable across annotators. IF also shows strong consistency, with 75.2% +exact agreement and 93.5% within-1 agreement. EE remains the most challenging dimension, but still +reaches 72.2% exact agreement and 91.7% within-1 agreement, which suggests that judgments about non- +target changes are noisier yet still broadly consistent. Overall, these results support the reliability of the +three-dimensional annotation protocol while also reflecting the inherently subjective nature of fine-grained +video-editing assessment. +F Extended Dataset Analysis +We present additional analyses of VEFX-Dataset that complement the main text. +F.1 Task Type Difficulty Ranking +Table 9 ranks the 9 task types by IF difficulty, and Figure 14 provides a finer-grained view across all 32 +subcategories. +Camera Angle editing is the hardest task for IF, as it requires geometric and 3D scene reasoning that current +systems still handle poorly. Style Editing is the easiest for IF but has relatively low EE, reflecting the inherent +tension between global style transformation and strict locality preservation. Notably, RQ varies much less +23 + +===== PAGE 24 ===== +Table 9 Task type ranking by editing difficulty. Tasks are sorted by IF score in ascending order, so lower values indicate +harder semantic execution. +Task Type IF RQ EE N +Camera Angle 1.76 3.20 2.41 796 +Instance Motion 2.00 3.39 3.06 450 +Quantity 2.09 3.00 2.81 634 +Camera Motion 2.31 3.28 2.69 383 +Attribute 2.35 3.16 2.63 598 +Creative 2.41 3.21 2.22 542 +Instance 2.51 3.14 2.82 641 +Visual Effect 2.58 3.32 2.89 520 +Style 2.87 3.14 2.23 485 +Figure 14 Score breakdown across all 32 subcategories grouped by 9 main categories. Fine-grained subcategory variation +reveals which specific editing operations are most challenging. +across task types than IF or EE, which again suggests that current models find visual plausibility easier than +precise semantic execution. +F.2 Video Difficulty and Training Signal Quality +Figure 15 shows the distribution of per-video difficulty, measured as the mean score across pipelines, against +cross-pipeline score variance. Videos with high score variance are especially valuable for reward-model learning +because they provide strong preference signals: different pipelines succeed or fail on the same input, enabling +the reward model to learn discriminative features rather than a dataset-wide average. +24 + +===== PAGE 25 ===== +Figure 15 Per-video difficulty (mean score) versus cross-pipeline score variance. High-variance videos provide especially +informative supervision for reward modeling. +G Per-Category Detailed Results +We provide finer-grained results for the six representative editing systems benchmarked in Section 6. Each +heatmap-style table reports the mean VEFX-Reward-32B score for one dimension at the level of the 9 main +editing categories, using the same model ordering as the main-text benchmark. To keep the focus on +comparative behavior rather than coverage statistics, we intentionally omit sample-count details here. +Across the 9 main categories, IF shows the largest variation and remains the main source of separation between +models. Grok Imagine and Kling Omni are strongest on many attribute, style, and instance-editing tasks, +while camera-angle and camera-motion edits remain difficult for nearly all systems. RQ is comparatively stable +across categories, indicating that visually plausible outputs are often easier to produce than semantically +correct ones. EE reveals the sharpest locality gap: Grok Imagine and UniVideo remain relatively strong on +localized edits, whereas VACE and Luma Ray2 degrade more visibly when preserving non-target regions +becomes difficult. +Camera Angle +Quantity +Attribute +Style +Camera Motion +Instance Motion +Instance +Visual Effect +Creative Edit +Per-Category Instruction Following Scores +1.20 3.00 1.82 1.52 1.30 2.05 +2.81 3.14 2.00 1.88 1.80 2.24 +3.38 3.27 1.26 2.29 2.44 1.54 +3.65 3.68 1.85 1.79 3.20 1.81 +1.70 2.43 1.44 1.36 1.31 1.78 +1.37 2.05 2.33 1.44 1.68 2.01 +3.22 3.59 2.06 2.64 2.71 2.43 +3.50 3.07 1.91 2.22 2.78 2.23 +3.46 3.31 1.47 1.50 2.35 2.10 +Grok-Imagine +Kling o1 +Wan 2.6 +Luma Ray 2 +UniVideo +VACE +4 +3 +Mean score +2 +1 +Figure 16 Heatmap table of per-category Instruction Following scores for the six benchmarked video editing systems. +Darker colors indicate higher VEFX-Reward-32B scores. +25 + +===== PAGE 26 ===== +Camera Angle +Quantity +Attribute +Style +Camera Motion +Instance Motion +Instance +Visual Effect +Creative Edit +Per-Category Rendering Quality Scores +3.47 3.73 3.53 3.00 3.27 3.37 +3.19 3.45 3.37 2.94 3.25 2.94 +3.62 3.82 3.47 3.10 3.43 2.92 +3.76 3.68 3.44 2.58 3.25 2.88 +2.90 3.86 3.33 2.55 3.14 3.31 +3.21 3.33 3.33 3.00 3.26 3.04 +3.44 3.82 3.47 3.00 3.14 3.15 +3.38 3.47 3.45 2.78 3.50 3.00 +3.85 3.85 3.60 3.00 3.08 3.12 +Grok-Imagine +Kling o1 +Wan 2.6 +Luma Ray 2 +UniVideo +VACE +4 +3 +Mean score +2 +1 +Figure 17 Heatmap table of per-category Rendering Quality scores for the six benchmarked video editing systems. +Camera Angle +Quantity +Attribute +Style +Camera Motion +Instance Motion +Instance +Visual Effect +Creative Edit +Per-Category Edit Exclusivity Scores +3.60 1.68 2.35 1.05 3.19 1.20 +3.73 3.32 2.41 1.00 3.07 1.19 +3.81 3.91 2.05 1.48 3.28 1.15 +2.47 1.95 2.40 1.12 2.92 1.15 +3.30 1.86 2.56 1.00 3.04 1.19 +3.79 3.19 2.29 1.22 3.15 1.23 +3.67 3.65 2.71 1.00 2.85 1.24 +3.56 3.40 2.64 1.33 3.34 1.20 +2.08 2.00 2.27 1.17 2.51 1.24 +Grok-Imagine +Kling o1 +Wan 2.6 +Luma Ray 2 +UniVideo +VACE +4 +3 +Mean score +2 +1 +Figure 18 Heatmap table of per-category Edit Exclusivity scores for the six benchmarked video editing systems. +H Additional Evaluation Details +H.1 Definitions of Standard IQA/VQA Metrics +In Section 5.2, we report four standard IQA/VQA-style metrics. We summarize their definitions here for +completeness. +Spearman Rank-Order Correlation Coefficient (SRCC). SRCC measures monotonic agreement between predicted +scores and human labels: +6 n +i=1 d2 +SRCC = 1− +i +n(n2 +−1), (8) +where di is the rank difference between the i-th prediction and the corresponding human score. +Kendall Rank-Order Correlation Coefficient (KRCC). We use Kendall’s τ-b to account for ties in the discrete 1–4 +26 + +===== PAGE 27 ===== +human scores: +n +(xi−yi)2 +. (11) +i=1 +τ = +Nc−Nd +, (9) +n(n−1) +2−Tpred +n(n−1) +2−Thuman +where Nc and Nd denote the numbers of concordant and discordant pairs, and Tpred and Thuman denote the +numbers of tied pairs in the predicted and human rankings. +Pearson Linear Correlation Coefficient (PLCC). PLCC measures linear agreement after score calibration: +PLCC = +n +i=1(xi− +¯ +x)(yi− +¯ +y) +n +i=1(xi− +¯ +x)2 n +i=1(yi− +y)2 , (10) +¯ +where xi is the calibrated model prediction and yi is the human score. +Root Mean Squared Error (RMSE). RMSE measures the calibrated absolute deviation: +RMSE = 1 +n +Logistic calibration. Following common IQA/VQA protocol, we apply a four-parameter logistic mapping before +computing PLCC and RMSE: +q(x) = β1 +1 +1 +2− +1 + eβ2 (x−β3 ) + β4, (12) +where x is the raw model score and q(x) is the calibrated score. The parameters β1,...,β4 are fitted by +non-linear least squares on the evaluation set. +Supplementary scatter plot. Figure 19 directly compares VEFX-Reward-4B and VEFX-Reward-32B across IF, +RQ, EE, and Overall. Here Overall is defined as the mean of IF, RQ, and EE for both predictions and human +scores. The figure shows that scaling from 4B to 32B mainly improves IF, EE, and the overall score, where +the 32B predictions form visibly tighter trends around the human annotations. By contrast, RQ remains +relatively similar across scales, consistent with the main-text observation that rendering quality is already +easier to model than semantic faithfulness and edit locality. +Figure 19 Side-by-side comparison between VEFX-Reward-4B and VEFX-Reward-32B across IF, RQ, EE, and Overall. +H.2 Additional Benchmark Visualizations +We supplement Section 6 with two additional views of the six-model evaluation. The strip plot in Figure 20 +shows the distribution of individual VEFX-Reward-32B scores, while the violin plot in Figure 21 emphasizes the +27 + +===== PAGE 28 ===== +density shape for each model-dimension pair. These visualizations provide a more detailed view of score spread +and concentration, complementing the main-text box plot without repeating the same summary statistics. +Overall (GeoAgg) +Score +4 +3 +2 +1 +Observed score distributions grouped and ordered by per-sample GeoAgg +Overall (Mean) +Score +Instruction Following +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Rendering Quality +Luma ray 2 +Open-source +UniVideo +VACE +Score +4 +3 +2 +1 +Score +4 +3 +2 +1 +Commercial Open-source +Kling o3 omni +Kling o1 +Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +UniVideo +VACE +Edit Exclusivity +4 +3 +2 +1 +Score +4 +3 +2 +1 +Commercial Open-source +Kling o3 omni +Kling o1 +Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +UniVideo +VACE +Models +Kling o3 omni +Kling o1 +Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +UniVideo +VACE +Kling o3 omni +Kling o1 +Runway Commercial Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +Figure 20 Strip plot of the six-model evaluation, showing individual VEFX-Reward-32B scores for IF, RQ, and EE. +Overall (GeoAgg) +Score +4 +3 +2 +1 +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Rendering Quality +Luma ray 2 +Open-source +UniVideo +VACE +Observed score distributions grouped and ordered by per-sample GeoAgg +Overall (Mean) +Score +Instruction Following +Score +4 +3 +2 +1 +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +Score +4 +3 +2 +1 +Kling o3 omni +4 +Kling o1 +Commercial Runway Gen-4.5 +Seedance +Grok +3 +2 +Luma ray 3 +Edit Exclusivity +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +1 +Kling o3 omni +Kling o1 +Commercial Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +Open-source +UniVideo +VACE +4 +3 +Score +2 +1 +Commercial Open-source +Kling o3 omni +Kling o1 +Runway Gen-4.5 +Seedance +Grok +Luma ray 3 +Wan 2.6 +Luma ray 2 +UniVideo +VACE +Models +Kling o3 omni +Kling o1 +Runway Gen-4.5 +Luma ray 3 +Wan 2.6 +Luma ray 2 +Seedance +UniVideo +Grok +VACE +Figure 21 Violin plot of the six-model evaluation, showing VEFX-Reward-32B score density for each model and dimension. +28 + +===== PAGE 29 ===== +I Ethical Considerations +Annotator welfare. All annotators were compensated at fair market rates and were not exposed to harmful or +disturbing content. The annotation task involved evaluating video editing quality, which does not inherently +involve sensitive content. NSFW content was removed during the data curation stage. +Potential misuse. VEFX-Reward isdesignedtoevaluatevideoeditingquality. Whilethemodelcouldtheoretically +be used to optimize for high-scoring edits that game specific metrics, the multi-dimensional scoring design +mitigates this risk by requiring simultaneous high performance across orthogonal dimensions. The ordinal +nature of the output, discrete scores 1–4, further limits the ability to exploit continuous optimization against +the reward model. +29