diff --git a/MemGen-main/common/config.py b/MemGen-main/common/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad97d31d609722f89be96317558f46e4bb086d2d
--- /dev/null
+++ b/MemGen-main/common/config.py
@@ -0,0 +1,91 @@
+import json
+import logging
+
+from omegaconf import OmegaConf
+
+class Config:
+ def __init__(self, args):
+ self.config = {}
+
+ self.args = args
+
+ user_config = self._build_opt_list(self.args.options)
+
+ config = OmegaConf.load(self.args.cfg_path)
+ runner_config = self.build_runner_config(config, **user_config)
+ model_config = self.build_model_config(config, **user_config)
+ dataset_config = self.build_dataset_config(config, **user_config)
+
+ # Override the default configuration with user options.
+ self.config = OmegaConf.merge(
+ runner_config, model_config, dataset_config, user_config
+ )
+
+
+ def _build_opt_list(self, opts):
+ opts_dot_list = self._convert_to_dot_list(opts)
+ return OmegaConf.from_dotlist(opts_dot_list)
+
+ @staticmethod
+ def build_model_config(config, **kwargs):
+ return {"model": config.model}
+
+ @staticmethod
+ def build_runner_config(config, **kwargs):
+ return {"run": config.run}
+
+ @staticmethod
+ def build_dataset_config(config, **kwargs):
+ dataset = config.get("dataset", None)
+ if dataset is None:
+ raise KeyError(
+ "Expecting 'dataset' as the root key for dataset configuration."
+ )
+
+ return dict(dataset=dataset)
+
+ def _convert_to_dot_list(self, opts):
+ if opts is None:
+ opts = []
+
+ if len(opts) == 0:
+ return opts
+
+ has_equal = opts[0].find("=") != -1
+
+ if has_equal:
+ return opts
+
+ return [(opt + "=" + value) for opt, value in zip(opts[0::2], opts[1::2])]
+
+ def get_config(self):
+ return self.config
+
+ @property
+ def run_cfg(self):
+ return self.config.run
+
+ @property
+ def dataset_cfg(self):
+ return self.config.dataset
+
+ @property
+ def model_cfg(self):
+ return self.config.model
+
+ def pretty_print(self):
+ logging.info("\n===== Running Parameters =====")
+ logging.info(self._convert_node_to_json(self.config.run))
+
+ logging.info("\n====== Dataset Attributes ======")
+ logging.info(self._convert_node_to_json(self.config.dataset))
+
+ logging.info(f"\n====== Model Attributes ======")
+ logging.info(self._convert_node_to_json(self.config.model))
+
+ def _convert_node_to_json(self, node):
+ container = OmegaConf.to_container(node, resolve=True)
+ return json.dumps(container, indent=4, sort_keys=True)
+
+ def to_dict(self):
+ return OmegaConf.to_container(self.config)
\ No newline at end of file
diff --git a/MemGen-main/common/logger.py b/MemGen-main/common/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e767f4a423694d1783340b44aa66fbed8435e1b
--- /dev/null
+++ b/MemGen-main/common/logger.py
@@ -0,0 +1,10 @@
+import os
+import logging
+
+def setup_logger(output_dir):
+ os.makedirs(output_dir, exist_ok=True)
+ logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s [%(levelname)s] %(message)s",
+ handlers=[logging.StreamHandler(), logging.FileHandler(os.path.join(output_dir, 'log.txt'))],
+ )
\ No newline at end of file
diff --git a/MemGen-main/configs/latent_memory/gpqa.yaml b/MemGen-main/configs/latent_memory/gpqa.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7c66928e863806b54108c3ba0a912270cc90d453
--- /dev/null
+++ b/MemGen-main/configs/latent_memory/gpqa.yaml
@@ -0,0 +1,173 @@
+model:
+ # base llm
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ load_model_path: null
+
+ # max prompt/inference augmentation num
+ max_prompt_aug_num: 1 # single turn
+ max_inference_aug_num: 5
+
+ # weaver configs
+ weaver:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ prompt_latents_len: 8
+ inference_latents_len: 8
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+ # trigger configs
+ trigger:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ active: False
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+# dataset configs
+dataset:
+ name: gpqa
+ mode: sft # NOTE - options: ["sft", "grpo"], should manually keep align with the training method in `run` configs
+ sft:
+ valid_ratio: 0.1
+ grpo:
+ valid_ratio: 0.1
+
+# training/evaluation configs
+run:
+
+ seed: 42
+
+ # route
+ mode: train
+ train_weaver: True
+ train_weaver_method: sft # sft or grpo
+ train_trigger: False
+ train_trigger_method: grpo # grpo only
+
+ # processor training configs
+ weaver:
+
+ # sft configs
+ sft:
+ # epochs and batchsize
+ num_train_epochs: 2
+ per_device_train_batch_size: 4
+ per_device_eval_batch_size: 4
+ gradient_accumulation_steps: 1
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ assistant_only_loss: False # used only in conversational dataset
+ max_length: 1024 # max sequence length
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # grpo configs
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: grpo
+
+ max_prompt_length: 1024
+ max_completion_length: 512
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # trigger training configs
+ trigger:
+
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: bnpo
+
+ max_prompt_length: 1024
+ max_completion_length: 512
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ learning_rate: 1e-5
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # interaction config for evaluation
+ interaction:
+ max_turns: 1
+ max_start_length: 1024 # Maximum length of the initial prompt.
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
+ max_response_length: 1024
+ max_obs_length: 512
+ temperature: 1.0
+ batch_size: 8
+ weaver_do_sample: False
+ trigger_do_sample: False
diff --git a/MemGen-main/configs/latent_memory/gsm8k.yaml b/MemGen-main/configs/latent_memory/gsm8k.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c9608cba0c1359d1b99adba86a7f3f8839b315db
--- /dev/null
+++ b/MemGen-main/configs/latent_memory/gsm8k.yaml
@@ -0,0 +1,173 @@
+model:
+ # base llm
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ load_model_path: null
+
+ # max prompt/inference augmentation num
+ max_prompt_aug_num: 1 # single turn
+ max_inference_aug_num: 5
+
+ # weaver configs
+ weaver:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ prompt_latents_len: 8
+ inference_latents_len: 8
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+ # trigger configs
+ trigger:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ active: False
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+# dataset configs
+dataset:
+ name: gsm8k
+ mode: sft # options: ["sft", "grpo"], should manually keep align with the training method in `run` configs
+ sft:
+ val_ratio: 0.1
+ grpo:
+ val_ratio: 0.1
+
+# training/evaluation configs
+run:
+
+ seed: 42
+
+ # route
+ mode: train
+ train_weaver: True
+ train_weaver_method: sft # sft or grpo
+ train_trigger: False
+ train_trigger_method: grpo # grpo only
+
+ # processor training configs
+ weaver:
+
+ # sft configs
+ sft:
+ # epochs and batchsize
+ num_train_epochs: 2
+ per_device_train_batch_size: 4
+ per_device_eval_batch_size: 4
+ gradient_accumulation_steps: 1
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ assistant_only_loss: True
+ max_length: 1024 # max sequence length
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # grpo configs
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: bnpo
+
+ max_prompt_length: 1024
+ max_completion_length: 1024
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # trigger training configs
+ trigger:
+
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: bnpo
+
+ max_prompt_length: 1024
+ max_completion_length: 1024
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ learning_rate: 1e-6
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # interaction config for evaluation
+ interaction:
+ max_turns: 1
+ max_start_length: 1024 # Maximum length of the initial prompt.
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
+ max_response_length: 1024
+ max_obs_length: 512
+ temperature: 0.0
+ batch_size: 8
+ weaver_do_sample: False
+ trigger_do_sample: False
diff --git a/MemGen-main/configs/latent_memory/kodcode.yaml b/MemGen-main/configs/latent_memory/kodcode.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c44219e9b4c0809fad9c5cad409dfde149abda62
--- /dev/null
+++ b/MemGen-main/configs/latent_memory/kodcode.yaml
@@ -0,0 +1,176 @@
+model:
+ # base llm
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ load_model_path: null
+
+ # max prompt/inference augmentation num
+ max_prompt_aug_num: 1 # single turn
+ max_inference_aug_num: 5
+
+ # weaver configs
+ weaver:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ prompt_latents_len: 8
+ inference_latents_len: 8
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+ # trigger configs
+ trigger:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ active: False
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+dataset:
+ name: kodcode
+ mode: sft
+ sft:
+ train_ratio: 0.7
+ valid_ratio: 0.1
+ test_ratio: 0.2
+ grpo:
+ train_ratio: 0.7
+ valid_ratio: 0.1
+ test_ratio: 0.2
+
+# training/evaluation configs
+run:
+
+ seed: 42
+
+ # route
+ mode: train
+ train_weaver: True
+ train_weaver_method: sft # sft or grpo
+ train_trigger: False
+ train_trigger_method: grpo # grpo only
+
+ # processor training configs
+ weaver:
+
+ # sft configs
+ sft:
+ # epochs and batchsize
+ num_train_epochs: 2
+ per_device_train_batch_size: 4
+ per_device_eval_batch_size: 4
+ gradient_accumulation_steps: 1
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ assistant_only_loss: False # used only in conversational dataset
+ max_length: 1024 # max sequence length
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # grpo configs
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: bnpo
+
+ max_prompt_length: 1024
+ max_completion_length: 512
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # trigger training configs
+ trigger:
+
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: bnpo
+
+ max_prompt_length: 1024
+ max_completion_length: 512
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ learning_rate: 1e-5
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # interaction config for evaluation
+ interaction:
+ max_turns: 1
+ max_start_length: 1024 # Maximum length of the initial prompt.
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
+ max_response_length: 1024
+ max_obs_length: 512
+ temperature: 0.0
+ batch_size: 8
+ weaver_do_sample: False
+ trigger_do_sample: False
\ No newline at end of file
diff --git a/MemGen-main/configs/latent_memory/triviaqa.yaml b/MemGen-main/configs/latent_memory/triviaqa.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1c176230c4eb22cc5e2388158476016b99b02297
--- /dev/null
+++ b/MemGen-main/configs/latent_memory/triviaqa.yaml
@@ -0,0 +1,172 @@
+model:
+ # base llm
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ load_model_path: null
+
+ # max prompt/inference augmentation num
+ max_prompt_aug_num: 8 # single turn
+ max_inference_aug_num: 0
+
+ # weaver configs
+ weaver:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ prompt_latents_len: 8
+ inference_latents_len: 8
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+ # trigger configs
+ trigger:
+ model_name: Qwen/Qwen2.5-1.5B-Instruct
+ active: False
+
+ lora_config:
+ r: 16
+ lora_alpha: 32
+ target_modules: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
+ lora_dropout: 0.1
+ bias: "none"
+ task_type: "CAUSAL_LM"
+
+dataset:
+ name: triviaqa
+ mode: sft
+ sft:
+ valid_ratio: 0.1
+ grpo:
+ valid_ratio: 0.1
+
+
+# training/evaluation configs
+run:
+
+ seed: 42
+
+ # route
+ mode: train
+ train_weaver: True
+ train_weaver_method: sft # sft or grpo
+ train_trigger: False
+ train_trigger_method: grpo # grpo only
+
+ # processor training configs
+ weaver:
+
+ # sft configs
+ sft:
+ # epochs and batchsize
+ num_train_epochs: 2
+ per_device_train_batch_size: 4
+ per_device_eval_batch_size: 4
+ gradient_accumulation_steps: 1
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ assistant_only_loss: True # used only in conversational dataset
+ max_length: 1024 # max sequence length
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # grpo configs
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: grpo
+
+ max_prompt_length: 1024
+ max_completion_length: 512
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+ learning_rate: 1e-5
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ # trigger training configs
+ trigger:
+
+ grpo:
+ num_train_epochs: 1
+ per_device_train_batch_size: 8
+ per_device_eval_batch_size: 8
+ num_generations: 8
+ num_iterations: 1
+ gradient_accumulation_steps: 1
+ beta: 0.0
+ loss_type: bnpo
+
+ max_prompt_length: 1024
+ max_completion_length: 512
+ temperature: 1.0
+
+ # optimizer configs
+ optim: adamw_torch
+ learning_rate: 1e-5
+ lr_scheduler_type: cosine
+ warmup_ratio: 0.1
+
+ # duration
+ logging_strategy: steps
+ logging_steps: 1
+ eval_strategy: epoch
+ eval_steps: 100
+ save_strategy: epoch
+ save_steps: 100
+
+ remove_unused_columns: False
+ load_best_model_at_end: True
+ bf16: True
+ report_to:
+ - tensorboard
+
+ interaction:
+ max_turns: 5
+ max_start_length: 1024 # Maximum length of the initial prompt.
+ max_prompt_length: 4096 # Maximum prompt length during multi-turn interactions (includes all conversation history across turns).
+ max_response_length: 1024
+ max_obs_length: 512
+ temperature: 0.0
+ batch_size: 8
+ weaver_do_sample: False
+ trigger_do_sample: False
\ No newline at end of file
diff --git a/MemGen-main/configs/zero2.yaml b/MemGen-main/configs/zero2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7be6b0b094722dd6cae6ebc77a3acf065bc3ddc7
--- /dev/null
+++ b/MemGen-main/configs/zero2.yaml
@@ -0,0 +1,22 @@
+compute_environment: LOCAL_MACHINE
+debug: false
+deepspeed_config:
+ deepspeed_multinode_launcher: standard
+ offload_optimizer_device: none
+ offload_param_device: none
+ zero3_init_flag: false
+ zero_stage: 2
+distributed_type: DEEPSPEED
+downcast_bf16: 'no'
+machine_rank: 0
+main_training_function: main
+mixed_precision: 'no'
+num_machines: 1
+num_processes: 1 # 会被脚本自动覆盖,无需手动修改
+main_process_port: 44326
+rdzv_backend: static
+same_network: true
+tpu_env: []
+tpu_use_cluster: false
+tpu_use_sudo: false
+use_cpu: false
\ No newline at end of file
diff --git a/MemGen-main/data/__init__.py b/MemGen-main/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0220811e595e85d7829bad44adb3a39e0c0fad1b
--- /dev/null
+++ b/MemGen-main/data/__init__.py
@@ -0,0 +1,26 @@
+from data.base_builder import BaseBuilder
+from data.base_env import (
+ BaseEnv,
+ StaticEnv,
+ DynamicEnv,
+)
+from data.gpqa.builder import GPQABuilder
+from data.gsm8k.builder import GSM8KBuilder
+from data.kodcode.builder import KodCodeBuilder
+from data.triviaqa.builder import TriviaQABuilder
+
+_DATA_BUILDER_MAP = {
+ "gpqa": GPQABuilder,
+ "gsm8k": GSM8KBuilder,
+ "kodcode": KodCodeBuilder,
+ "triviaqa": TriviaQABuilder
+}
+
+def get_data_builder(dataset_cfg) -> BaseBuilder:
+ if dataset_cfg.get("name") not in _DATA_BUILDER_MAP:
+ raise ValueError("Unsupported dataset.")
+
+ builder_cls = _DATA_BUILDER_MAP[dataset_cfg.get("name")]
+ builder = builder_cls(dataset_cfg)
+
+ return builder
\ No newline at end of file
diff --git a/MemGen-main/data/base_builder.py b/MemGen-main/data/base_builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..edefae87bb64ee302829a17429ee4e52f3960e26
--- /dev/null
+++ b/MemGen-main/data/base_builder.py
@@ -0,0 +1,38 @@
+from abc import ABC, abstractmethod
+from typing import Type
+
+from datasets import DatasetDict
+
+from data.base_env import BaseEnv
+
+class BaseBuilder(ABC):
+
+ def __init__(self, cfg: dict = None):
+ super().__init__()
+
+ self.mode = cfg.get("mode", "sft")
+ self.config = cfg.get(self.mode)
+
+ def get_dataset_dict(self) -> DatasetDict:
+ method_builder_map = {
+ "sft": self._build_sft_datasets,
+ "grpo": self._build_rl_datasets,
+ }
+
+ if self.mode not in method_builder_map:
+ raise ValueError("Unsupported datasets mode")
+
+ return method_builder_map[self.mode]()
+
+ @abstractmethod
+ def get_env_cls(self) -> Type[BaseEnv]:
+ ...
+
+ @abstractmethod
+ def _build_sft_datasets(self) -> DatasetDict:
+ ...
+
+ @abstractmethod
+ def _build_rl_datasets(self) -> DatasetDict:
+ ...
+
diff --git a/MemGen-main/data/base_env.py b/MemGen-main/data/base_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ae11cee4cfe77d7a2703898bfc083d6ed5446ec
--- /dev/null
+++ b/MemGen-main/data/base_env.py
@@ -0,0 +1,38 @@
+from abc import ABC, abstractmethod
+from typing import Literal, Dict, Tuple
+
+class BaseEnv(ABC):
+ ENV_CARD: Literal["STATIC", "DYNAMIC"] = None
+
+ def __init__(self, config):
+ self.config = config
+
+ @classmethod
+ @abstractmethod
+ def compute_reward(cls, **kwargs):
+ ...
+
+
+class StaticEnv(BaseEnv):
+ ENV_CARD = "STATIC"
+
+
+class DynamicEnv(BaseEnv):
+ ENV_CARD = "DYNAMIC"
+
+ @abstractmethod
+ def set_env(self, task_config: Dict) -> Tuple[str, str]:
+ ...
+
+ @classmethod
+ @abstractmethod
+ def preprocess_action(self, action: str) -> str:
+ ...
+
+ @abstractmethod
+ def step(self, action: str) -> Tuple[str, bool]:
+ ...
+
+ @abstractmethod
+ def feedback(self) -> Tuple[float, bool]:
+ ...
\ No newline at end of file
diff --git a/MemGen-main/data/gpqa/builder.py b/MemGen-main/data/gpqa/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bccf6779aaf4de9af06c3b0c2d3867d1c136b0e
--- /dev/null
+++ b/MemGen-main/data/gpqa/builder.py
@@ -0,0 +1,102 @@
+import random
+from datasets import DatasetDict, load_dataset
+
+from data.base_builder import BaseBuilder
+from data.gpqa.env import GPQAEnv
+
+class GPQABuilder(BaseBuilder):
+
+ def get_env_cls(self):
+ return GPQAEnv
+
+ def _build_datasets(self) -> DatasetDict:
+ # download data
+ raw_train_dataset = load_dataset("Idavidrein/gpqa", "gpqa_main")["train"]
+ raw_test_dataset = load_dataset("Idavidrein/gpqa", "gpqa_diamond")["train"]
+ val_size = int(len(raw_train_dataset) * self.config.get("valid_ratio"))
+ split = raw_train_dataset.train_test_split(test_size=val_size, shuffle=True)
+ raw_train_dataset, raw_valid_dataset = split["train"], split["test"]
+
+ # preprocess
+ train_dataset = raw_train_dataset.map(self._preprocess).select_columns(self._keep_keys())
+ valid_dataset = raw_valid_dataset.map(self._preprocess).select_columns(self._keep_keys())
+ test_dataset = raw_test_dataset.map(self._preprocess).select_columns(self._keep_keys())
+
+ # build dataset
+ dataset_dict = DatasetDict()
+ dataset_dict["train"] = train_dataset
+ dataset_dict["valid"] = valid_dataset
+ dataset_dict["test"] = test_dataset
+
+ return dataset_dict
+
+ def _build_sft_datasets(self) -> DatasetDict:
+ return self._build_datasets()
+
+
+ def _build_rl_datasets(self) -> DatasetDict:
+ return self._build_datasets()
+
+ @classmethod
+ def _preprocess(cls, example: dict):
+
+ def build_answer_map(candidates: list[str]) -> dict[str, dict[str, object]]:
+
+ indices = list(range(len(candidates)))
+ random.shuffle(indices)
+
+ orders = [chr(ord("A") + i) for i in range(len(candidates))]
+
+ answer_map = {}
+ for idx, candidate_idx in enumerate(indices):
+ answer = candidates[candidate_idx]
+ answer_map[answer] = {
+ "order": orders[idx],
+ "is_correct": (candidate_idx == 0)
+ }
+
+ return answer_map
+
+ def build_question(question, answer_map: dict) -> str:
+ result = question.strip() + "\n\nPlease choose one of the following options:\n"
+
+ sorted_items = sorted(answer_map.items(), key=lambda x: x[1]["order"])
+
+ for answer, meta in sorted_items:
+ result += f"{meta['order']}. {answer}\n"
+
+ return result
+
+ def build_answer(rationale: str, answer_map: dict) -> str:
+ correct_answer = None
+ for key, value in answer_map.items():
+ if value.get("is_correct") is True:
+ correct_answer = value.get("order")
+ assert correct_answer is not None
+ return rationale + f"\n\nTherefore, the final answer is \\boxed{{{correct_answer}}}"
+
+ question = example["Question"].strip()
+ explanation = example["Explanation"].strip()
+ correct_answer = example["Correct Answer"].strip()
+ incorrect_answer1 = example["Incorrect Answer 1"].strip()
+ incorrect_answer2 = example["Incorrect Answer 2"].strip()
+ incorrect_answer3 = example["Incorrect Answer 3"].strip()
+
+ answers_map = build_answer_map([correct_answer, incorrect_answer1, incorrect_answer2, incorrect_answer3])
+ question = build_question(question, answers_map)
+ answer = build_answer(explanation, answers_map)
+
+ format_template = r"""Solve the problem with proper reasoning, and make sure to put the FINAL CHOICE inside \boxed{}."""
+ prompt_template = "Question: {prompt}\n"
+ processed_prompt = format_template + prompt_template.format(prompt=question)
+
+ text_output = {
+ "prompt": processed_prompt,
+ "completion": answer,
+ "solution": answer
+ }
+ return text_output
+
+ @classmethod
+ def _keep_keys(cls):
+ return ["prompt", "completion", "solution"]
\ No newline at end of file
diff --git a/MemGen-main/data/gpqa/env.py b/MemGen-main/data/gpqa/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..2327b0753269b9a7e5f555c9eeb5ffe988ae4145
--- /dev/null
+++ b/MemGen-main/data/gpqa/env.py
@@ -0,0 +1,14 @@
+from data.utils.math_utils import compute_score
+from data.base_env import StaticEnv
+
+class GPQAEnv(StaticEnv):
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ @classmethod
+ def compute_reward(cls, completions: list[str], solution: list[str], **kwargs) -> list[float]:
+
+ scores = [compute_score(completion=c, ground_truth=s) for c, s in zip(completions, solution)]
+ return scores
+
diff --git a/MemGen-main/data/gsm8k/builder.py b/MemGen-main/data/gsm8k/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f401ab1e58f2e29b47106f713436610fdc75d6
--- /dev/null
+++ b/MemGen-main/data/gsm8k/builder.py
@@ -0,0 +1,74 @@
+from datasets import DatasetDict, load_dataset
+from typing import Dict
+
+from data.base_builder import BaseBuilder
+from data.gsm8k.env import GSM8KEnv
+
+class GSM8KBuilder(BaseBuilder): # Env
+
+ def get_env_cls(self):
+ return GSM8KEnv
+
+ def _build_datasets(self) -> DatasetDict:
+
+ # download data
+ raw_dataset = load_dataset("gsm8k", "main")
+ raw_train_dataset, raw_test_dataset = raw_dataset['train'], raw_dataset['test']
+ val_size = int(len(raw_train_dataset) * self.config.get("val_ratio"))
+ split = raw_train_dataset.train_test_split(test_size=val_size, shuffle=True)
+ raw_train_dataset, raw_valid_dataset = split["train"], split["test"]
+
+ # preprocess
+ num_workers = 32
+ train_dataset = raw_train_dataset.map(self._preprocess, num_proc=num_workers).select_columns(self._keep_keys())
+ valid_dataset = raw_valid_dataset.map(self._preprocess, num_proc=num_workers).select_columns(self._keep_keys())
+ test_dataset = raw_test_dataset.map(self._preprocess, num_proc=num_workers).select_columns(self._keep_keys())
+
+ # build dataset
+ dataset_dict = DatasetDict()
+ dataset_dict["train"] = train_dataset
+ dataset_dict["valid"] = valid_dataset
+ dataset_dict["test"] = test_dataset
+
+ return dataset_dict
+
+ def _build_sft_datasets(self) -> DatasetDict:
+ return self._build_datasets()
+
+
+ def _build_rl_datasets(self) -> DatasetDict:
+ return self._build_datasets()
+
+ @classmethod
+ def _preprocess(cls, example: Dict):
+ def _preprocess_answer(answer: str) -> str:
+ raw_answer_list = answer.split("\n####")
+ rationale = raw_answer_list[0]
+ clean_answer = raw_answer_list[-1].strip()
+ boxed_answer = "\\boxed{" + clean_answer + "}"
+ new_string = rationale + boxed_answer
+ return new_string.strip()
+
+ format_template = r"""Solve the math problem with proper reasoning, and make sure to put the FINAL ANSWER inside \boxed{}."""
+ prompt_template = "Question: {prompt}\n"
+
+ question = example["question"].strip()
+ answer = example["answer"].strip()
+
+ processed_prompt = format_template + prompt_template.format(prompt=question)
+ processed_label = _preprocess_answer(answer)
+
+ text_output = {
+ "prompt": [{"role": "user", "content": processed_prompt}],
+ "completion": [{"role": "assistant", "content": processed_label}],
+ "solution": processed_label,
+ "test": processed_label,
+ }
+
+ # NOTE - To use the built-in tokenization mechanism of SFTTrainer,
+ # it is necessary to ensure that the prompt + completion is lossless.
+ return text_output
+
+ @classmethod
+ def _keep_keys(cls):
+ return ["prompt", "completion", "solution"]
\ No newline at end of file
diff --git a/MemGen-main/data/gsm8k/env.py b/MemGen-main/data/gsm8k/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..d93d741ad9fd5a2ee1921dde0576b4e3cb234c8f
--- /dev/null
+++ b/MemGen-main/data/gsm8k/env.py
@@ -0,0 +1,13 @@
+from data.utils.math_utils import compute_score
+from data.base_env import StaticEnv
+
+class GSM8KEnv(StaticEnv):
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ @classmethod
+ def compute_reward(cls, completions: list[str], solution: list[str], **kwargs) -> list[float]:
+
+ scores = [compute_score(completion=c, ground_truth=s) for c, s in zip(completions, solution)]
+ return scores
\ No newline at end of file
diff --git a/MemGen-main/data/kodcode/builder.py b/MemGen-main/data/kodcode/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f3c0f14bfbd297b9dd12fcde3ebbb16580b53c5
--- /dev/null
+++ b/MemGen-main/data/kodcode/builder.py
@@ -0,0 +1,76 @@
+from datasets import DatasetDict, load_dataset
+from typing import Dict
+
+from data.base_builder import BaseBuilder
+from data.kodcode.env import KodCodeEnv
+
+class KodCodeBuilder(BaseBuilder):
+
+ def get_env_cls(self):
+ return KodCodeEnv
+
+ def _build_datasets(self) -> DatasetDict:
+ # download dataset
+ all_dataset = load_dataset("KodCode/KodCode-Light-RL-10K")
+ all_correct_dataset = all_dataset["train"]
+
+ # train, valid, test dataset split
+ train_ratio, valid_ratio, test_ratio = self.config.get("train_ratio"), self.config.get("valid_ratio"), self.config.get("test_ratio")
+ assert train_ratio + valid_ratio + test_ratio == 1
+
+ all_size = len(all_correct_dataset)
+ test_size = int(all_size * test_ratio)
+ split = all_correct_dataset.train_test_split(test_size=test_size, shuffle=True)
+ train_valid_dataset, test_dataset = split["train"], split["test"]
+
+ valid_size = int(len(train_valid_dataset) * valid_ratio / (train_ratio + valid_ratio))
+ split = train_valid_dataset.train_test_split(test_size=valid_size, shuffle=True)
+ train_dataset, valid_dataset = split["train"], split["test"]
+
+ # preprocess
+ train_dataset = train_dataset.map(self._sft_preprocess).select_columns(self._sft_keep_keys())
+ valid_dataset = valid_dataset.map(self._sft_preprocess).select_columns(self._sft_keep_keys())
+ test_dataset = test_dataset.map(self._sft_preprocess).select_columns(self._sft_keep_keys())
+
+ # build dataset dict
+ dataset_dict = DatasetDict()
+ dataset_dict["train"] = train_dataset
+ dataset_dict["valid"] = valid_dataset
+ dataset_dict["test"] = test_dataset
+
+ return dataset_dict
+
+ def _build_sft_datasets(self) -> DatasetDict:
+ return self._build_datasets()
+
+
+ def _build_rl_datasets(self) -> DatasetDict:
+ return self._build_datasets()
+
+ @classmethod
+ def _sft_preprocess(cls, example: Dict):
+
+ format_template = r"Write an efficient and correct Python function to solve the following problem."
+ prompt_template = "Question: {prompt}\n"
+
+ question = example["question"].strip()
+ solution = example["solution"].strip()
+
+ processed_prompt = format_template + prompt_template.format(prompt=question)
+ processed_label = solution
+
+ text_output = {
+ "prompt": [{"role": "user", "content": processed_prompt}],
+ "completion": [{"role": "assistant", "content": processed_label}],
+ "solution": processed_label,
+ "test": example["test"].strip(),
+ "test_info": example["test_info"]
+ }
+
+ return text_output
+
+ @classmethod
+ def _sft_keep_keys(cls):
+ return ["prompt", "completion", "solution", "test", "test_info"]
+
+
diff --git a/MemGen-main/data/kodcode/env.py b/MemGen-main/data/kodcode/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..a576c44d3d7103c45161ca4d18e0f8d0a4de8ef7
--- /dev/null
+++ b/MemGen-main/data/kodcode/env.py
@@ -0,0 +1,36 @@
+import re
+
+from data.base_env import StaticEnv
+from data.utils.code_utils import PyExecutor, extract_python_code
+
+class KodCodeEnv(StaticEnv):
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ @classmethod
+ def _rename_func(cls, answer: str, function_name: str) -> str:
+ """
+ Replace the name of the first function in `answer` with `function_name`.
+ Only modifies the function name, keeps everything else intact.
+ """
+ pattern = r"def\s+(\w+)\s*\("
+
+ new_answer = re.sub(pattern, f"def {function_name}(", answer, count=1)
+ return new_answer
+
+ @classmethod
+ def compute_reward(cls, completions: list[str], test: list[str], test_info: list, **kwargs) -> list[float]:
+
+ py_executor = PyExecutor()
+ scores = []
+ for completion, t, tf in zip(completions, test, test_info):
+ func_blocks = extract_python_code(completion.strip())
+ collected_answer = '\n'.join(func_blocks)
+ renamed_answer = cls._rename_func(collected_answer, tf[0]["function_name"])
+ _, _, results = py_executor.execute(renamed_answer, [t])
+
+ score = sum(results) / len(results)
+ scores.append(score)
+
+ return scores
diff --git a/MemGen-main/data/triviaqa/builder.py b/MemGen-main/data/triviaqa/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..051b817f5bb0ccfe4bd401866a9779de49ca38c6
--- /dev/null
+++ b/MemGen-main/data/triviaqa/builder.py
@@ -0,0 +1,139 @@
+from datasets import DatasetDict, load_dataset
+from typing import Dict, List
+import re
+import copy
+
+from data.base_builder import BaseBuilder
+from data.triviaqa.env import TriviaQAEnv
+
+
+TRIVIAQA_SYSTEM_PROMPT = """Answer the given question. \
+You must conduct reasoning inside and first every time you get new information. \
+After reasoning, if you find you lack some knowledge, you can call a search engine by query and it will return the top searched results between and . \
+You can search as many times as your want. \
+If you find no further external knowledge needed, you can directly provide the answer inside and , without detailed illustrations. For example, Beijing . \
+"""
+
+class TriviaQABuilder(BaseBuilder): # Env
+
+ def get_env_cls(self):
+ return TriviaQAEnv
+
+ def _build_sft_datasets(self) -> DatasetDict:
+
+ # build train/valid dataset from agentbank
+ train_ds = load_dataset("Solaris99/AgentBank", "triviaqa")["train"]
+
+ valid_ratio = self.config.get("valid_ratio")
+ all_size = len(train_ds)
+ valid_size = int(all_size * valid_ratio)
+ split = train_ds.train_test_split(test_size=valid_size, shuffle=True)
+ raw_train_dataset, raw_valid_dataset = split["train"], split["test"]
+
+ # build test dataset from triviaqa
+ ds = load_dataset("mandarjoshi/trivia_qa", "rc.wikipedia.nocontext")
+ raw_test_dataset = ds["validation"]
+
+ # preprocess
+ num_workers = 32
+ train_dataset = raw_train_dataset.map(self._sft_preprocess, num_proc=num_workers).select_columns(self._sft_keep_keys())
+ valid_dataset = raw_valid_dataset.map(self._sft_preprocess, num_proc=num_workers).select_columns(self._sft_keep_keys())
+ test_dataset = raw_test_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
+
+ dataset_dict = DatasetDict()
+ dataset_dict["train"] = train_dataset
+ dataset_dict["valid"] = valid_dataset
+ dataset_dict["test"] = test_dataset
+
+ return dataset_dict
+
+ def _build_rl_datasets(self) -> DatasetDict:
+
+ ds = load_dataset("mandarjoshi/trivia_qa", "rc.wikipedia.nocontext")
+ raw_train_dataset = ds["train"]
+ raw_valid_dataset = ds["validation"]
+ raw_test_dataset = ds["test"]
+
+ num_workers = 32
+ train_dataset = raw_train_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
+ valid_dataset = raw_valid_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
+ test_dataset = raw_test_dataset.map(self._rl_preprocess, num_proc=num_workers).select_columns(self._rl_keep_keys())
+
+ dataset_dict = DatasetDict()
+ dataset_dict["train"] = train_dataset
+ dataset_dict["valid"] = valid_dataset
+ dataset_dict["test"] = test_dataset
+
+ return dataset_dict
+
+ @classmethod
+ def _sft_preprocess(cls, example: Dict):
+
+ def _add_user_special_tokens(content: str) -> str:
+ observation_match = re.search(r'Observation: (.*)', content)
+
+ if observation_match:
+ observation_content = f" {observation_match.group(1).strip()} "
+ else:
+ observation_content = content
+
+ return observation_content
+
+ def _add_assistant_special_tokens(content: str) -> str:
+ thought_match = re.search(r'Thought: (.*?)(?=\nAction:|\nFinal Answer:|$)', content, re.DOTALL)
+ action_match = re.search(r'Action: search\[(.*?)\]', content)
+ answer_match = re.search(r'Final Answer: (.*)', content)
+
+ parts = []
+
+ if thought_match:
+ thought_content = thought_match.group(1).strip()
+ parts.append(f" {thought_content} ")
+
+ if action_match:
+ action_content = action_match.group(1).strip()
+ parts.append(f" {action_content} ")
+
+ if answer_match:
+ answer_content = answer_match.group(1).strip()
+ parts.append(f" {answer_content} ")
+
+ aggregated_content = "\n".join(parts)
+ return aggregated_content
+
+ messages = []
+ system_prompt = {"role": "system", "content": TRIVIAQA_SYSTEM_PROMPT.strip()}
+ messages.append(system_prompt)
+
+ for sample in example["conversations"]:
+ message = {}
+ # role
+ if sample["from"] == "human":
+ message["role"] = "user"
+ message["content"] = _add_user_special_tokens(sample["value"])
+ elif sample["from"] == "gpt":
+ message["role"] = "assistant"
+ message["content"] = _add_assistant_special_tokens(sample["value"])
+ else:
+ raise ValueError("Unsupported Role type.")
+
+ messages.append(message)
+
+ return {
+ "messages": messages
+ }
+
+ @classmethod
+ def _sft_keep_keys(cls) -> List[str]:
+ return ["messages"]
+
+ @classmethod
+ def _rl_preprocess(cls, example: Dict) -> Dict:
+ output = copy.deepcopy(example)
+ output["answer"] = output["answer"]["normalized_aliases"]
+ output["prompt"] = output["question"]
+ return output
+
+ @classmethod
+ def _rl_keep_keys(cls) -> List[str]:
+ return ["prompt", "answer"]
\ No newline at end of file
diff --git a/MemGen-main/data/triviaqa/env.py b/MemGen-main/data/triviaqa/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..d85f6d75f68897302189060f27361e83edca362d
--- /dev/null
+++ b/MemGen-main/data/triviaqa/env.py
@@ -0,0 +1,120 @@
+from typing import List, Dict, Tuple
+import re
+
+from data.base_env import DynamicEnv
+from data.utils.retrieval_utils import Retriever
+
+class TriviaQAEnv(DynamicEnv):
+
+ def __init__(self, configs: Dict):
+ super().__init__(configs)
+ self.explorer = Retriever()
+
+ def set_env(self, task_config: Dict) -> None:
+ if task_config.get('answer') is None:
+ raise ValueError('Please provide the answer for the task')
+ if task_config.get("prompt") is None:
+ raise ValueError('Please provide the prompt for the task')
+
+ self.task_config = task_config
+
+ self._reset()
+
+ from data.triviaqa.builder import TRIVIAQA_SYSTEM_PROMPT
+ return TRIVIAQA_SYSTEM_PROMPT, task_config["prompt"]
+
+ def _reset(self):
+ self.done = False
+ self.reward = 0.0
+
+ def step(self, action: str) -> Tuple[str, float, bool]:
+ action = self.preprocess_action(action)
+ action_type, action_content = self._process_action(action)
+ observation = None
+
+ if action_type == "search":
+ try:
+ observation = self.explorer.batch_search([action_content])[0]
+ except Exception as e:
+ observation = f'Cannot find corresponding pages.'
+ self.done = False
+ self.reward = 0.0
+
+ elif action_type == "answer":
+ observation = ""
+ self.done = True
+ self.reward = 1.0 if self._check_answer(action_content, self.task_config["answer"]) else 0.0
+ else:
+ observation = "\nMy previous action is invalid. \
+If I want to search, I should put the query between and . \
+If I want to give the final answer, I should put the answer between and . Let me try again.\n"
+ self.done = False
+ self.reward = 0.0
+
+ return observation, self.reward, self.done
+
+ @classmethod
+ def preprocess_action(cls, action: str) -> str:
+ if "" in action:
+ return action.split("", 1)[0] + ""
+ elif "" in action:
+ return action.split("", 1)[0] + ""
+ else:
+ return action
+
+ @classmethod
+ def _process_action(cls, action: str):
+ action = action.strip()
+
+ if "" in action and "" in action:
+ start = action.index("") + len("")
+ end = action.index("")
+ content = action[start:end].strip().split("\n", 1)[0].strip()
+ return "search", content
+
+ if "" in action and "" in action:
+ start = action.index("") + len("")
+ end = action.index("")
+ content = action[start:end].strip().split("\n", 1)[0].strip()
+ return "answer", content
+
+ return "think", action
+
+ def _check_answer(self, answer: str, ground_truth: List[str]):
+ answer = answer.lower()
+ for gt in ground_truth:
+ if gt.lower() in answer:
+ return True
+
+ return False
+
+ def feedback(self) -> float:
+ return self.reward
+
+ @classmethod
+ def compute_reward(cls, completions: List[str], envs: List['TriviaQAEnv'], **kwargs) -> List[float]:
+ scores = []
+ for completion, env in zip(completions, envs):
+ solution = env.task_config['answer']
+
+ matches = re.findall(r"(.*?)", completion, re.DOTALL)
+
+ if not matches:
+ scores.append(0.0)
+ continue
+
+ extracted = matches[-1].strip()
+
+ correct = False
+ for s in solution:
+ if s.lower() in extracted.lower():
+ correct = True
+ break
+
+ if correct:
+ scores.append(1.0)
+ else:
+ scores.append(0.5)
+
+ return scores
+
diff --git a/MemGen-main/data/utils/code_utils.py b/MemGen-main/data/utils/code_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf21805c376627468a9bec49bbec51de53fe9af5
--- /dev/null
+++ b/MemGen-main/data/utils/code_utils.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+import os
+from typing import List, Tuple, Any, Optional
+import re
+import multiprocessing
+from multiprocessing.connection import Connection
+
+ExecuteResult = Tuple[bool, str, Tuple[bool]]
+
+
+def extract_python_code(text_string: str) -> List[str]:
+ code_blocks = re.findall(r"```python(.*?)```", text_string, re.DOTALL)
+ if not code_blocks:
+ code_blocks = [text_string]
+
+ results = []
+ for block in code_blocks:
+ imports = re.findall(r"^(?:from\s+\S+\s+import\s+\S+|import\s+\S+.*)$", block, re.MULTILINE)
+
+ funcs = re.findall(r"(def\s+\w+\(.*?:[\s\S]*?)(?=^def\s|\Z)", block.strip(), re.MULTILINE)
+
+ if imports:
+ import_block = "\n".join(imports)
+ if funcs:
+ funcs = [import_block] + funcs
+ else:
+ funcs = [import_block]
+
+ results.extend(funcs)
+
+ return results
+
+def rename_function(function: str, function_name: str) -> str:
+ """
+ Replace the name of the first function in `answer` with `function_name`.
+ Only modifies the function name, keeps everything else intact.
+ """
+ pattern = r"def\s+(\w+)\s*\("
+
+ new_answer = re.sub(pattern, f"def {function_name}(", function, count=1)
+ return new_answer
+
+
+def _exec_code_and_capture(code: str, conn: Connection, work_dir: Optional[str] = None):
+ try:
+ if work_dir is not None:
+ os.makedirs(work_dir, exist_ok=True)
+ os.chdir(work_dir)
+
+ local_ns = {}
+ exec(code, local_ns)
+
+ for name, func in local_ns.items():
+ if callable(func) and name.startswith("test_"):
+ func()
+ conn.send(True)
+ except Exception as e:
+ conn.send(e)
+ finally:
+ conn.close()
+
+
+class PyExecutor:
+
+ def _run_with_timeout(self, code: str, timeout: int, work_dir: Optional[str] = "./code_stuff") -> Any:
+ parent_conn, child_conn = multiprocessing.Pipe()
+ p = multiprocessing.Process(
+ target=_exec_code_and_capture,
+ args=(code, child_conn, work_dir)
+ )
+
+ p.start()
+ p.join(timeout)
+
+ if p.is_alive():
+ p.kill()
+ p.join()
+ raise TimeoutError("Test execution timed out")
+
+ if parent_conn.poll():
+ result = parent_conn.recv()
+ if isinstance(result, Exception):
+ raise result
+ return result
+ else:
+ raise RuntimeError("Child process terminated unexpectedly without sending a result.")
+
+ def execute(self, func: str, tests: List[str], timeout: int = 5, verbose: bool = True) -> ExecuteResult:
+ success_tests = []
+ failed_tests = []
+ is_passing = True
+
+ for test_code in tests:
+ cleaned_test = re.sub(r"^\s*from\s+solution\s+import\s+\w+\s*", "", test_code, flags=re.MULTILINE)
+ code_to_run = func + "\n" + cleaned_test
+ try:
+ self._run_with_timeout(code_to_run, timeout)
+ success_tests.append(test_code)
+ except Exception as e:
+ failed_tests.append(f"{test_code} # output: {e}")
+ is_passing = False
+
+ state = tuple(test in success_tests for test in tests)
+ feedback = (
+ "Tests passed:\n" + "\n".join(success_tests)
+ + "\n\nTests failed:\n" + "\n".join(failed_tests)
+ )
+ return is_passing, feedback, state
+
+ def evaluate(self, name: str, func: str, test: str, timeout: int = 5) -> bool:
+ cleaned_test = re.sub(r"^\s*from\s+solution\s+import\s+\w+\s*", "", test, flags=re.MULTILINE)
+ code_to_run = func + "\n" + cleaned_test
+ try:
+ self._run_with_timeout(code_to_run, timeout)
+ return True
+ except Exception:
+ return False
+
+ def check_code_report(self, completions: list[str], tests: list[str], timeout: int = 5) -> tuple[list[str], list[float]]:
+ def extract_failed_tests(text: str) -> str:
+ match = re.search(r"Tests failed:\s*(.*)", text, re.DOTALL)
+ return match.group(1).strip() if match else ""
+
+ def extract_correct_function_name(text: str) -> str:
+ match = re.search(r"from\s+solution\s+import\s+([a-zA-Z_]\w*)", text)
+ return match.group(1) if match else ""
+
+ reports = []
+ avg_scores = []
+
+ for completion, test_code_str in zip(completions, tests):
+ func_blocks = extract_python_code(completion.strip())
+ collected_answer = '\n'.join(func_blocks)
+
+ correct_function_name = extract_correct_function_name(test_code_str)
+ if correct_function_name != "":
+ collected_answer = rename_function(collected_answer, correct_function_name)
+
+ test_block = extract_python_code(test_code_str.strip())
+ test_list = [test_block[0] + "\n\n" + block for block in test_block[1:]]
+
+ report_lines = []
+ success_examples = 0
+
+ for test in test_list:
+ func_name_match = re.search(r"def\s+(test_\w+)\s*\(", test)
+ func_name = func_name_match.group(1) if func_name_match else "unknown_test"
+
+ is_passing, feedback, _ = self.execute(collected_answer, [test], timeout=timeout)
+
+ if is_passing:
+ success_examples += 1
+ report_lines.append(f"✅ Test passed for '{func_name}'")
+ else:
+ report_lines.append(f"❌ Test failed for '{func_name}': \n{extract_failed_tests(feedback)}")
+
+ if len(test_list) != 0:
+ avg_score = success_examples / len(test_list)
+ else:
+ avg_score = 1.0
+ avg_scores.append(avg_score)
+ report_lines.append(f"\nAverage correctness: {avg_score:.2f}")
+
+ reports.append("\n".join(report_lines))
+
+ return reports, avg_scores
+
+
\ No newline at end of file
diff --git a/MemGen-main/data/utils/dynamic_padding.py b/MemGen-main/data/utils/dynamic_padding.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6d68b3b9174b876f279b20d02bef3a86af2776a
--- /dev/null
+++ b/MemGen-main/data/utils/dynamic_padding.py
@@ -0,0 +1,78 @@
+import torch
+from transformers import PreTrainedTokenizerBase
+from typing import Dict, List, Any
+
+class DynamicPaddingDataCollater:
+ def __init__(self, tokenizer: PreTrainedTokenizerBase):
+
+ self.tokenizer = tokenizer
+
+ if tokenizer.pad_token_id is None:
+ print("Warning: Tokenizer does not have a pad_token_id. Using 0 for input_ids and attention_mask padding.")
+ self.padding_value_input = 0
+ else:
+ self.padding_value_input = tokenizer.pad_token_id
+
+ # labels 的填充值
+ self.padding_value_label = tokenizer.pad_token_id
+
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, torch.Tensor]:
+
+ processed_features = []
+ for feature in features:
+ input_ids = feature["input_ids"]
+ completion_mask = feature["completion_mask"]
+
+ prompt_ids = [token for token, is_completion in zip(input_ids, completion_mask) if not is_completion]
+
+ label_ids = [token for token, is_completion in zip(input_ids, completion_mask) if is_completion]
+
+ processed_features.append({
+ "prompt_ids": prompt_ids,
+ "label_ids": label_ids,
+
+ "original": feature
+ })
+
+ max_prompt_len = max(len(f["prompt_ids"]) for f in processed_features)
+ max_label_len = max(len(f["label_ids"]) for f in processed_features)
+
+ padded_prompt_ids = []
+ padded_input_attention_mask = []
+ padded_label_ids = []
+ padded_labels_attention_mask = []
+
+ for feature in processed_features:
+
+ prompt_ids = feature["prompt_ids"]
+ label_ids = feature["label_ids"]
+
+
+ num_input_pads = max_prompt_len - len(prompt_ids)
+ padded_prompt_ids.append([self.padding_value_input] * num_input_pads + prompt_ids)
+
+ input_attention_mask = [1] * len(prompt_ids)
+ num_input_mask_pads = max_prompt_len - len(input_attention_mask)
+ padded_input_attention_mask.append([0] * num_input_mask_pads + input_attention_mask)
+
+ num_label_pads = max_label_len - len(label_ids)
+ padded_label_ids.append(label_ids + [self.padding_value_label] * num_label_pads)
+
+ labels_attention_mask = [1] * len(label_ids)
+ num_label_mask_pads = max_label_len - len(labels_attention_mask)
+ padded_labels_attention_mask.append(labels_attention_mask + [0] * num_label_mask_pads)
+
+ batch = {
+ "prompt_ids": torch.tensor(padded_prompt_ids, dtype=torch.long),
+ "prompt_attention_mask": torch.tensor(padded_input_attention_mask, dtype=torch.long),
+ "label_ids": torch.tensor(padded_label_ids, dtype=torch.long),
+ "label_attention_mask": torch.tensor(padded_labels_attention_mask, dtype=torch.long),
+ }
+
+ batch["raw_samples"] = [f["original"] for f in processed_features]
+
+ return batch
+
+
+
+
diff --git a/MemGen-main/data/utils/math_utils.py b/MemGen-main/data/utils/math_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..45f06347936b11ab1d33d78ddd72a0239fc93ce9
--- /dev/null
+++ b/MemGen-main/data/utils/math_utils.py
@@ -0,0 +1,254 @@
+# Copyright 2024 Bytedance Ltd. and/or its affiliates
+# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# Adapted from https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/hendrycks_math/utils.py
+
+
+def compute_score(completion, ground_truth) -> float:
+ retval = 0.0
+ try:
+ # string_in_last_boxed = last_boxed_only_string(solution_str)
+ string_in_first_boxed = first_boxed_only_string(completion)
+ ground_truth_in_last_boxed = last_boxed_only_string(ground_truth)
+ if string_in_first_boxed is not None:
+ answer = remove_boxed(string_in_first_boxed)
+ ground_truth = remove_boxed(ground_truth_in_last_boxed)
+ if is_equiv(answer, ground_truth):
+ retval = 1.0
+ except Exception as e:
+ print(e)
+
+ return retval
+
+
+# string normalization from https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/hendrycks_math.py
+def is_equiv(str1, str2, verbose=False):
+ if str1 is None and str2 is None:
+ print("WARNING: Both None")
+ return True
+ if str1 is None or str2 is None:
+ return False
+
+ try:
+ ss1 = strip_string(str1)
+ ss2 = strip_string(str2)
+ if verbose:
+ print(ss1, ss2)
+ return ss1 == ss2
+ except Exception:
+ return str1 == str2
+
+
+def remove_boxed(s):
+ if "\\boxed " in s:
+ left = "\\boxed "
+ assert s[: len(left)] == left
+ return s[len(left) :]
+
+ left = "\\boxed{"
+
+ assert s[: len(left)] == left
+ assert s[-1] == "}"
+
+ return s[len(left) : -1]
+
+def first_boxed_only_string(string):
+ if "\\boxed " in string:
+ return "\\boxed " + string.split("\\boxed ")[1].split("$")[0]
+
+ idx = string.find("\\boxed")
+ if idx < 0:
+ idx = string.find("\\fbox")
+ if idx < 0:
+ return None
+
+ i = idx
+ right_brace_idx = None
+ num_left_braces_open = 0
+ while i < len(string):
+ if string[i] == "{":
+ num_left_braces_open += 1
+ if string[i] == "}":
+ num_left_braces_open -= 1
+ if num_left_braces_open == 0:
+ right_brace_idx = i
+ break
+ i += 1
+
+ retval = None if right_brace_idx is None else string[idx : right_brace_idx + 1]
+
+ return retval
+
+
+def last_boxed_only_string(string):
+ idx = string.rfind("\\boxed")
+ if "\\boxed " in string:
+ return "\\boxed " + string.split("\\boxed ")[-1].split("$")[0]
+ if idx < 0:
+ idx = string.rfind("\\fbox")
+ if idx < 0:
+ return None
+
+ i = idx
+ right_brace_idx = None
+ num_left_braces_open = 0
+ while i < len(string):
+ if string[i] == "{":
+ num_left_braces_open += 1
+ if string[i] == "}":
+ num_left_braces_open -= 1
+ if num_left_braces_open == 0:
+ right_brace_idx = i
+ break
+ i += 1
+
+ retval = None if right_brace_idx is None else string[idx : right_brace_idx + 1]
+
+ return retval
+
+
+def fix_fracs(string):
+ substrs = string.split("\\frac")
+ new_str = substrs[0]
+ if len(substrs) > 1:
+ substrs = substrs[1:]
+ for substr in substrs:
+ new_str += "\\frac"
+ if substr[0] == "{":
+ new_str += substr
+ else:
+ try:
+ assert len(substr) >= 2
+ except: # noqa: E722
+ return string
+ a = substr[0]
+ b = substr[1]
+ if b != "{":
+ if len(substr) > 2:
+ post_substr = substr[2:]
+ new_str += "{" + a + "}{" + b + "}" + post_substr
+ else:
+ new_str += "{" + a + "}{" + b + "}"
+ else:
+ if len(substr) > 2:
+ post_substr = substr[2:]
+ new_str += "{" + a + "}" + b + post_substr
+ else:
+ new_str += "{" + a + "}" + b
+ string = new_str
+ return string
+
+
+def fix_a_slash_b(string):
+ if len(string.split("/")) != 2:
+ return string
+ a = string.split("/")[0]
+ b = string.split("/")[1]
+ try:
+ a = int(a)
+ b = int(b)
+ assert string == "{}/{}".format(a, b)
+ new_string = "\\frac{" + str(a) + "}{" + str(b) + "}"
+ return new_string
+ except: # noqa: E722
+ return string
+
+
+def remove_right_units(string):
+ # "\\text{ " only ever occurs (at least in the val set) when describing units
+ if "\\text{ " in string:
+ splits = string.split("\\text{ ")
+ assert len(splits) == 2
+ return splits[0]
+ else:
+ return string
+
+
+def fix_sqrt(string):
+ if "\\sqrt" not in string:
+ return string
+ splits = string.split("\\sqrt")
+ new_string = splits[0]
+ for split in splits[1:]:
+ if split[0] != "{":
+ a = split[0]
+ new_substr = "\\sqrt{" + a + "}" + split[1:]
+ else:
+ new_substr = "\\sqrt" + split
+ new_string += new_substr
+ return new_string
+
+
+def strip_string(string):
+ # linebreaks
+ string = string.replace("\n", "")
+
+ # remove inverse spaces
+ string = string.replace("\\!", "")
+
+ # replace \\ with \
+ string = string.replace("\\\\", "\\")
+
+ # replace tfrac and dfrac with frac
+ string = string.replace("tfrac", "frac")
+ string = string.replace("dfrac", "frac")
+
+ # remove \left and \right
+ string = string.replace("\\left", "")
+ string = string.replace("\\right", "")
+
+ # Remove circ (degrees)
+ string = string.replace("^{\\circ}", "")
+ string = string.replace("^\\circ", "")
+
+ # remove dollar signs
+ string = string.replace("\\$", "")
+
+ # remove units (on the right)
+ string = remove_right_units(string)
+
+ # remove percentage
+ string = string.replace("\\%", "")
+ string = string.replace("\%", "") # noqa: W605
+
+ # " 0." equivalent to " ." and "{0." equivalent to "{." Alternatively, add "0" if "." is the start of the string
+ string = string.replace(" .", " 0.")
+ string = string.replace("{.", "{0.")
+ # if empty, return empty string
+ if len(string) == 0:
+ return string
+ if string[0] == ".":
+ string = "0" + string
+
+ # to consider: get rid of e.g. "k = " or "q = " at beginning
+ if len(string.split("=")) == 2 and len(string.split("=")[0]) <= 2:
+ string = string.split("=")[1]
+
+ # fix sqrt3 --> sqrt{3}
+ string = fix_sqrt(string)
+
+ # remove spaces
+ string = string.replace(" ", "")
+
+ # \frac1b or \frac12 --> \frac{1}{b} and \frac{1}{2}, etc. Even works with \frac1{72} (but not \frac{72}1).
+ # Also does a/b --> \\frac{a}{b}
+ string = fix_fracs(string)
+
+ # manually change 0.5 --> \frac{1}{2}
+ if string == "0.5":
+ string = "\\frac{1}{2}"
+
+ # NOTE: X/Y changed to \frac{X}{Y} in dataset, but in simple cases fix in case the model output is X/Y
+ string = fix_a_slash_b(string)
+
+ return string
\ No newline at end of file
diff --git a/MemGen-main/data/utils/processor.py b/MemGen-main/data/utils/processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..e84c54aa9c9052eef4442d25f25f49b644cbb646
--- /dev/null
+++ b/MemGen-main/data/utils/processor.py
@@ -0,0 +1,39 @@
+from typing import Dict
+
+def add_eos(example, eos_token):
+ """在 labels 部分末尾添加 eos token
+ """
+ if "text" in example and not example["text"].endswith(eos_token):
+ example["text"] = example["text"] + eos_token
+ elif "completion" in example and not example["completion"].endswith(eos_token):
+ example["completion"] = example["completion"] + eos_token
+ return example
+
+def tokenize(example, processing_class) -> Dict:
+
+ output = dict(example)
+ prompt_ids = processing_class(
+ text=example["prompt"], add_special_tokens=False
+ )["input_ids"]
+ completion_ids = processing_class(
+ text=example["completion"], add_special_tokens=False
+ )["input_ids"]
+ input_ids = prompt_ids + completion_ids
+
+ # Create a completion mask
+ completion_mask = [0] * len(prompt_ids) + [1] * len(completion_ids)
+ output["input_ids"] = input_ids
+ output["completion_mask"] = completion_mask
+
+ return output
+
+def tokenize_instruction_example(example: Dict, processing_class) -> Dict:
+ eos_token = processing_class.eos_token
+ eos_example = add_eos(example, eos_token)
+ tokenized_example = tokenize(eos_example, processing_class)
+
+ return tokenized_example
+
+
+def tokenize_conversation_example(example: Dict, processing_class) -> Dict:
+ ...
\ No newline at end of file
diff --git a/MemGen-main/data/utils/retrieval_utils.py b/MemGen-main/data/utils/retrieval_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..08a609e7abbe8d1028a0a7638cadb3752e17cfc5
--- /dev/null
+++ b/MemGen-main/data/utils/retrieval_utils.py
@@ -0,0 +1,43 @@
+from typing import List
+import requests
+
+class Retriever:
+
+ def __init__(self):
+ self.config = {
+ "search_url": "http://127.0.0.1:8001/retrieve",
+ "topk": 3
+ }
+
+ def batch_search(self, queries: List[str] = None) -> List[str]:
+ """
+ Batchified search for queries.
+ Args:
+ queries: queries to call the search engine
+ Returns:
+ search results which is concatenated into a string
+ """
+ results = self._batch_search(queries)['result']
+
+ return [self._passages2string(result) for result in results]
+
+ def _batch_search(self, queries):
+
+ payload = {
+ "queries": queries,
+ "topk": self.config["topk"],
+ "return_scores": True
+ }
+
+ return requests.post(self.config["search_url"], json=payload).json()
+
+ def _passages2string(self, retrieval_result):
+ format_reference = ''
+ for idx, doc_item in enumerate(retrieval_result):
+
+ content = doc_item['document']['contents']
+ title = content.split("\n")[0]
+ text = "\n".join(content.split("\n")[1:])
+ format_reference += f"Doc {idx+1}(Title: {title}) {text}\n"
+
+ return format_reference
\ No newline at end of file
diff --git a/MemGen-main/data/utils/search_utils.py b/MemGen-main/data/utils/search_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7a75677e1684c2af77198aff987d5aae9b6c0db
--- /dev/null
+++ b/MemGen-main/data/utils/search_utils.py
@@ -0,0 +1,70 @@
+from typing import Optional, Union
+from langchain.docstore.document import Document
+import wikipedia
+
+class LangChainWiki:
+
+ def __init__(self) -> None:
+ self.document: Optional[Document] = None
+ self.lookup_str = ""
+ self.lookup_index = 0
+
+ def search(self, search: str) -> Union[str, Document]:
+ def _try_search(term: str) -> Union[str, Document]:
+ try:
+ page_content = wikipedia.page(search).content
+ url = wikipedia.page(search).url
+ result: Union[str, Document] = Document( page_content=page_content, metadata={"page": url} )
+ return result
+ except wikipedia.PageError:
+ return f"Could not find [{term}]. Similar: {wikipedia.search(term)}"
+ except wikipedia.DisambiguationError:
+ return f"Could not find [{term}]. Similar: {wikipedia.search(term)}"
+ except Exception:
+ return f"Could not find [{term}]. Similar: {wikipedia.search(term)}"
+
+ result = _try_search(search)
+
+ if isinstance(result, str) and "Similar:" in result:
+ try:
+ similar = wikipedia.search(search)
+ if similar:
+ fallback = similar[0]
+ print(f"[INFO] Falling back to similar term: {fallback}")
+ result = _try_search(fallback)
+ except Exception as e:
+ print(f"[ERROR] Could not fetch similar terms: {e}")
+
+ if isinstance(result, Document):
+ self.document = result
+ return self._sumary
+ else:
+ self.document = None
+ return result
+
+ def lookup(self, term: str):
+ if self.document is None:
+ raise ValueError("Cannot lookup without a successful search first")
+ if term.lower() != self.lookup_str:
+ self.lookup_str = term.lower()
+ self.lookup_index = 0
+ else:
+ self.lookup_index += 1
+ lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()]
+ if len(lookups) == 0:
+ return "No Results"
+ elif self.lookup_index >= len(lookups):
+ return "No More Results"
+ else:
+ result_prefix = f"(Result {self.lookup_index + 1}/{len(lookups)})"
+ return f"{result_prefix} {lookups[self.lookup_index]}"
+
+ @property
+ def _sumary(self) -> str:
+ return self._paragraphs[0]
+
+ @property
+ def _paragraphs(self) -> list[str]:
+ if self.document is None:
+ raise ValueError("Cannot get paragraphs without a document")
+ return self.document.page_content.split("\n\n")
diff --git a/MemGen-main/interactions/base_interaction.py b/MemGen-main/interactions/base_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..de370df7315a4b97afc0c74ffe735cc3242ba69a
--- /dev/null
+++ b/MemGen-main/interactions/base_interaction.py
@@ -0,0 +1,67 @@
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+import logging
+from typing import Optional
+
+from transformers import GenerationConfig
+
+from interactions.tensor_utils import TensorHelper, TensorConfig
+
+
+@dataclass
+class InteractionConfig:
+ max_turns: int = 1
+ max_start_length: int = 1024
+ max_prompt_length: int = 4096
+ max_response_length: int = 512
+ max_obs_length: int = 512
+ # do_sample: bool = False
+ temperature: float = 1.0
+ batch_size: int = 8
+ output_dir: Optional[str] = None
+ weaver_do_sample: bool = False
+ trigger_do_sample: bool = False
+
+@dataclass
+class InteractionDataProto:
+ batch: dict = field(default_factory=dict)
+ no_tensor_batch: dict = field(default_factory=dict)
+
+class InteractionManager(ABC):
+
+ def __init__(
+ self,
+ tokenizer,
+ actor_rollout_wg,
+ config: InteractionConfig,
+ is_validation: bool = False,
+ ):
+ self.tokenizer = tokenizer
+ self.tokenizer.padding_side = "left"
+ self.actor_rollout_wg = actor_rollout_wg
+ self.config = config
+ self.is_validation = is_validation
+
+ assert tokenizer.pad_token_id is not None
+ self.tensor_fn = TensorHelper(TensorConfig(
+ pad_token_id=tokenizer.pad_token_id,
+ max_prompt_length=config.max_prompt_length,
+ max_obs_length=config.max_obs_length,
+ max_start_length=config.max_start_length
+ ))
+
+ # generation configs for agent
+ self.generation_config = GenerationConfig(
+ max_new_tokens=self.config.max_response_length,
+ temperature=self.config.temperature,
+ pad_token_id=self.tokenizer.pad_token_id,
+ eos_token_id=self.tokenizer.eos_token_id
+ )
+ self.generation_config.weaver_do_sample = self.config.weaver_do_sample
+ self.generation_config.trigger_do_sample = self.config.trigger_do_sample
+
+ logging.info(f"Weaver do sample: {self.generation_config.weaver_do_sample}, Trigger do sample: {self.generation_config.trigger_do_sample}")
+
+ @abstractmethod
+ def run_agent_loop(self, gen_batch: InteractionDataProto) -> InteractionDataProto:
+ ...
\ No newline at end of file
diff --git a/MemGen-main/interactions/multiturn_interaction.py b/MemGen-main/interactions/multiturn_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e43579477654b4bb28b2941dcc12be3a1df47b9
--- /dev/null
+++ b/MemGen-main/interactions/multiturn_interaction.py
@@ -0,0 +1,263 @@
+import torch
+from typing import Dict, List, Tuple
+import copy
+
+from interactions.base_interaction import (
+ InteractionDataProto,
+ InteractionConfig,
+ InteractionManager
+)
+
+
+class MultiTurnInteractionManager(InteractionManager):
+ def __init__(
+ self,
+ tokenizer,
+ actor_rollout_wg,
+ config: InteractionConfig,
+ is_validation: bool = False,
+ ):
+ super().__init__(
+ tokenizer, actor_rollout_wg, config, is_validation
+ )
+
+ def _batch_tokenize(self, responses: List[str]) -> torch.Tensor:
+ """Tokenize a batch of responses."""
+ return self.tokenizer(
+ responses,
+ add_special_tokens=False,
+ return_tensors='pt',
+ padding="longest"
+ )['input_ids']
+
+ def _build_chat_history(self, rollings: Dict) -> List[Dict]:
+
+ init_prompts = rollings.get("init_prompts")
+ if init_prompts is None:
+ raise ValueError("")
+
+ inter_histories = rollings.get("inter_histories")
+ if inter_histories is None:
+ raise ValueError("")
+
+ chat_histories: List[List[Dict]] = []
+ for init_prompt, inter_history in zip(init_prompts, inter_histories):
+ chat_histories.append(init_prompt + inter_history)
+
+ return chat_histories
+
+ def _update_interaction_history(self, rollings: InteractionDataProto, responses: List[str], observations: List[str]) -> List[List[Dict]]:
+
+ inter_histories = copy.deepcopy(rollings.no_tensor_batch.get("inter_histories"))
+ assert len(inter_histories) == len(responses) == len(observations)
+ for inter_history, response, observation in zip(inter_histories, responses, observations):
+ assistant_info = {"role": "assistant", "content": response}
+ user_info = {"role": "user", "content": observation}
+
+ inter_history.append(assistant_info)
+ inter_history.append(user_info)
+
+ return inter_histories
+
+ def _postprocess_responses(self, responses: torch.Tensor, envs: List) -> torch.Tensor:
+
+ responses_str = self.tokenizer.batch_decode(
+ responses,
+ skip_special_tokens=True
+ )
+
+ processed_responses_str = []
+ for r, env in zip(responses_str, envs):
+ processed_r = env.preprocess_action(r)
+ processed_responses_str.append(processed_r)
+
+ responses = self._batch_tokenize(processed_responses_str)
+ return responses, processed_responses_str
+
+
+ def _example_level_pad(
+ self, responses_ids: torch.Tensor, responses_str: List[str], active_mask: torch.Tensor
+ ) -> Tuple[torch.Tensor, List[str]]:
+
+ assert active_mask.sum() == responses_ids.shape[0]
+ # Create masked responses tensor
+ batch_size = active_mask.shape[0]
+ seq_len = responses_ids.shape[1]
+ padded_responses = torch.full(
+ (batch_size, seq_len), self.tokenizer.pad_token_id,
+ dtype=responses_ids.dtype, device=responses_ids.device
+ )
+ padded_responses[active_mask] = responses_ids
+
+ # Create masked response strings
+ padded_responses_str = [""] * batch_size
+
+ s = 0
+ for i, is_active in enumerate(active_mask):
+ if is_active:
+ padded_responses_str[i] = responses_str[s]
+ s += 1
+
+ return padded_responses, padded_responses_str
+
+ def run_agent_loop(self, gen_batch: InteractionDataProto) -> InteractionDataProto:
+ """Run main LLM generation loop (conversation format)."""
+ assert "init_prompts" in gen_batch.no_tensor_batch
+ assert "envs" in gen_batch.no_tensor_batch
+ batch_size = len(gen_batch.no_tensor_batch["init_prompts"])
+
+ rollings = gen_batch
+ rollings.no_tensor_batch["inter_histories"] = [[] for _ in range(batch_size)]
+
+ active_mask = torch.ones(batch_size, dtype=torch.bool)
+ active_num_list = [active_mask.sum().item()]
+
+ for step in range(self.config.max_turns):
+ if not active_mask.sum():
+ break
+
+ mask_list = active_mask.tolist()
+ rollings_active = {
+ k: [item for item, keep in zip(v, mask_list) if keep]
+ for k, v in rollings.no_tensor_batch.items()
+ }
+ # use tokenizer to add chat template and encode text to tokens: input_ids, attention_mask
+ messages = self._build_chat_history(rollings_active)
+ self.tokenizer.padding_side = "left"
+ inputs = self.tokenizer.apply_chat_template(
+ messages, tokenize=True,
+ add_generation_prompt=True,
+ padding=True, return_tensors="pt", return_dict=True
+ )
+
+ # agent rollout
+ gen_output = self.actor_rollout_wg.generate(
+ input_ids=inputs["input_ids"],
+ attention_mask=inputs["attention_mask"],
+ generation_config=self.generation_config,
+ ).to("cpu")
+
+ # postprocess
+ prompt_len = inputs["input_ids"].size(1)
+ responses = gen_output[:, prompt_len:]
+ responses = self.tensor_fn.erase_after_first_eos(responses, self.tokenizer.eos_token_id)
+ responses_ids, responses_str = self._postprocess_responses(responses, rollings_active["envs"])
+ all_responses_ids, all_responses_str = self._example_level_pad(responses_ids, responses_str, active_mask)
+
+ next_obs, dones = self._execute_predictions(rollings, all_responses_str, active_mask)
+ processed_obs = self._postprocess_observations(next_obs)
+
+ # post process interaction states
+ curr_active_mask = torch.tensor([not done for done in dones], dtype=torch.bool)
+ active_mask = active_mask * curr_active_mask
+ active_num_list.append(active_mask.sum().item())
+
+ interaction_histories = self._update_interaction_history(rollings, all_responses_str, processed_obs)
+ rollings.no_tensor_batch["inter_histories"] = interaction_histories
+
+ # build final outputs
+ final_outputs = self._build_final_outputs(rollings)
+ return final_outputs
+
+ def _execute_predictions(self, rollings: InteractionDataProto, responses: List[str], active_mask: torch.Tensor) -> Tuple[List[str], List[str]]:
+ observations = []
+ dones = []
+ for response, env, is_active in zip(responses, rollings.no_tensor_batch["envs"], active_mask):
+ if is_active:
+ observation, _, done = env.step(response)
+ else:
+ observation = ""
+ done = True
+ observations.append(observation)
+ dones.append(done)
+
+ return observations, dones
+
+
+ def _postprocess_observations(self, observations: List[str]) -> List[str]:
+ self.tokenizer.padding_side = "right"
+ next_obs_ids = self._batch_tokenize(observations)
+
+ max_len = self.config.max_obs_length
+ if next_obs_ids.shape[1] > max_len:
+ extra_text = "..."
+ extra_ids = self.tokenizer.encode(
+ extra_text, add_special_tokens=False, return_tensors="pt"
+ ).to(next_obs_ids.device)
+ extra_len = extra_ids.shape[1]
+
+ new_obs_ids = []
+ for row in next_obs_ids:
+ valid_len = (row != self.tokenizer.pad_token_id).sum().item()
+
+ if valid_len > max_len:
+ truncated = row[: max_len - extra_len]
+ new_row = torch.cat([truncated, extra_ids.squeeze(0)], dim=0)
+ else:
+ new_row = row[:max_len]
+
+ new_obs_ids.append(new_row.unsqueeze(0))
+
+ next_obs_ids = torch.cat(new_obs_ids, dim=0)
+ observations = self.tokenizer.batch_decode(next_obs_ids, skip_special_tokens=True)
+
+ return observations
+
+ def _build_final_outputs(self, rollings: InteractionDataProto) -> InteractionDataProto:
+
+ init_prompts: List[List[Dict]] = rollings.no_tensor_batch["init_prompts"]
+ inter_histories: List[List[Dict]] = rollings.no_tensor_batch["inter_histories"]
+
+ output = InteractionDataProto()
+
+ output.no_tensor_batch["inter_histories"] = [
+ prompt + inter for prompt, inter in zip(init_prompts, inter_histories)
+ ]
+
+ # ---------- prompts ----------
+ self.tokenizer.padding_side = "left"
+ prompt_ids = self.tokenizer.apply_chat_template(
+ init_prompts, tokenize=True,
+ add_generation_prompt=False,
+ padding=True, return_tensors="pt", return_dict=True
+ )
+ output.batch["prompts"] = prompt_ids["input_ids"]
+ prompt_attn_mask = prompt_ids["attention_mask"]
+
+ # ---------- responses ----------
+ self.tokenizer.padding_side = "right"
+ response_ids = self.tokenizer.apply_chat_template(
+ inter_histories,
+ tokenize=True,
+ padding=True,
+ return_assistant_tokens_mask=True,
+ add_generation_prompt=False,
+ return_tensors="pt", return_dict=True
+ )
+ output.batch["responses"] = response_ids["input_ids"]
+ response_attn_mask = response_ids["attention_mask"]
+
+ completion_info_mask = response_ids["assistant_masks"]
+
+ # ---------- input_ids ----------
+ output.batch["input_ids"] = torch.cat(
+ [prompt_ids["input_ids"], response_ids["input_ids"]], dim=1
+ )
+ output.batch["attention_mask"] = torch.cat(
+ [prompt_attn_mask, response_attn_mask], dim=1
+ )
+
+ # ---------- info_mask ----------
+ prompt_info_mask = torch.zeros(
+ prompt_ids["input_ids"].shape,
+ dtype=completion_info_mask.dtype,
+ device=completion_info_mask.device
+ )
+
+ output.batch["info_mask"] = torch.cat(
+ [prompt_info_mask, completion_info_mask], dim=1
+ )
+
+ self.tokenizer.padding_side = "left"
+
+ return output
\ No newline at end of file
diff --git a/MemGen-main/interactions/singleturn_interaction.py b/MemGen-main/interactions/singleturn_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aa805725c0c9cce1754c553ac50d896d6ff9c03
--- /dev/null
+++ b/MemGen-main/interactions/singleturn_interaction.py
@@ -0,0 +1,144 @@
+import torch
+from typing import Dict, List
+
+from interactions.base_interaction import (
+ InteractionConfig,
+ InteractionManager,
+ InteractionDataProto
+)
+
+
+class SingleTurnInteractionManager(InteractionManager):
+ def __init__(
+ self,
+ tokenizer,
+ actor_rollout_wg,
+ config: InteractionConfig,
+ is_validation: bool = False,
+ ):
+ super().__init__(
+ tokenizer, actor_rollout_wg, config, is_validation
+ )
+
+ def _batch_tokenize(self, responses: List[str]) -> torch.Tensor:
+ """Tokenize a batch of responses."""
+ return self.tokenizer(
+ responses,
+ add_special_tokens=False,
+ return_tensors='pt',
+ padding="longest"
+ )['input_ids']
+
+ def _info_masked_concatenate_with_padding(self,
+ prompt: torch.Tensor,
+ prompt_with_mask: torch.Tensor,
+ response: torch.Tensor,
+ info: torch.Tensor = None,
+ pad_to_left: bool = True
+ ) -> torch.Tensor:
+ """Concatenate tensors and handle padding. Additionally, create a mask (info_mask) to cover the information block if it exists."""
+ pad_id = self.tokenizer.pad_token_id
+ tensors = [prompt, response]
+ tensors_with_mask = [prompt_with_mask, response]
+ if info is not None:
+ tensors.append(info)
+ info_mask = torch.full(info.size(), pad_id, dtype=info.dtype, device=info.device) # information mask
+ tensors_with_mask.append(info_mask)
+
+ concatenated = torch.cat(tensors, dim=1)
+ concatenated_with_info = torch.cat(tensors_with_mask, dim=1)
+ mask = concatenated != pad_id if pad_to_left else concatenated == pad_id
+ sorted_indices = mask.to(torch.int64).argsort(dim=1, stable=True)
+ padded_tensor = concatenated.gather(1, sorted_indices)
+ padded_tensor_with_info = concatenated_with_info.gather(1, sorted_indices)
+
+ return padded_tensor, padded_tensor_with_info
+
+ def _update_right_side(
+ self, right_side: Dict,
+ cur_responses: torch.Tensor,
+ next_obs_ids: torch.Tensor = None
+ ) -> Dict:
+ """Update right side state."""
+ if next_obs_ids != None:
+ responses, responses_with_info_mask = self._info_masked_concatenate_with_padding(
+ right_side['responses'],
+ right_side['responses_with_info_mask'],
+ cur_responses,
+ next_obs_ids,
+ pad_to_left=False
+ )
+ else:
+ responses, responses_with_info_mask = self._info_masked_concatenate_with_padding(
+ right_side['responses'],
+ right_side['responses_with_info_mask'],
+ cur_responses,
+ pad_to_left=False
+ )
+ effective_len = self.tensor_fn.create_attention_mask(responses).sum(dim=1).max()
+ max_len = min(self.config.max_prompt_length, effective_len)
+
+ return {'responses': responses[:, :max_len], 'responses_with_info_mask': responses_with_info_mask[:, :max_len]}
+
+ def run_agent_loop(self, gen_batch: InteractionDataProto) -> InteractionDataProto:
+
+ initial_input_ids = gen_batch.batch["input_ids"]
+ original_left_side = {'input_ids': initial_input_ids[:, -self.config.max_start_length:]}
+ original_right_side = {'responses': initial_input_ids[:, []], 'responses_with_info_mask': initial_input_ids[:, []]}
+
+ # postprocess model inputs
+ rollings = gen_batch
+ rollings.batch = self.tensor_fn.cut_to_effective_len(
+ rollings.batch,
+ keys=['input_ids', 'attention_mask']
+ )
+ rollings_active = {
+ k: v for k, v in rollings.batch.items()
+ }
+
+ # model generation
+ gen_output = self.actor_rollout_wg.generate(
+ rollings_active["input_ids"],
+ rollings_active["attention_mask"],
+ generation_config=self.generation_config,
+ )
+ responses_ids = gen_output[:, rollings_active["input_ids"].size(1):]
+ responses_ids = self.tensor_fn.erase_after_first_eos(responses_ids, self.tokenizer.eos_token_id)
+
+ # update right side
+ original_right_side = self._update_right_side(original_right_side, responses_ids, next_obs_ids=None)
+
+ # construct final output
+ return self._compose_final_output(original_left_side, original_right_side)
+
+ def _compose_final_output(
+ self, left_side: Dict,
+ right_side: Dict,
+ ) -> InteractionDataProto:
+ """Compose final generation output."""
+
+ final_output_batch = right_side.copy()
+ final_output_batch['prompts'] = left_side['input_ids']
+ final_output_batch["responses"] = right_side['responses']
+
+ # Combine input IDs: input_ids + responses
+ final_output_batch['input_ids'] = torch.cat([
+ left_side['input_ids'],
+ right_side['responses']
+ ], dim=1)
+
+ # Create attention mask
+ final_output_batch['attention_mask'] = torch.cat([
+ self.tensor_fn.create_attention_mask(left_side['input_ids']),
+ self.tensor_fn.create_attention_mask(final_output_batch['responses'])
+ ], dim=1)
+
+ final_output_batch['info_mask'] = torch.cat([
+ self.tensor_fn.create_attention_mask(left_side['input_ids']),
+ self.tensor_fn.create_attention_mask(final_output_batch['responses_with_info_mask'])
+ ], dim=1)
+
+ final_output = InteractionDataProto(batch=final_output_batch)
+
+ return final_output
+
\ No newline at end of file
diff --git a/MemGen-main/interactions/tensor_utils.py b/MemGen-main/interactions/tensor_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dd2dcd806ef8ba19ed62600c147fd1966fc5a02
--- /dev/null
+++ b/MemGen-main/interactions/tensor_utils.py
@@ -0,0 +1,85 @@
+import torch
+from typing import Dict, Tuple, List
+from dataclasses import dataclass
+
+@dataclass
+class TensorConfig:
+ pad_token_id: int
+ max_prompt_length: int
+ max_obs_length: int
+ max_start_length: int
+
+class TensorHelper:
+ def __init__(self, config: TensorConfig):
+ self.config = config
+
+ def cut_to_effective_len(self, tensor_dict: Dict[str, torch.Tensor],
+ keys: List[str], cut_left: bool = True) -> Dict[str, torch.Tensor]:
+ """Cut tensors to their effective length based on attention mask."""
+ effective_len = tensor_dict['attention_mask'].sum(dim=1).max()
+ result = tensor_dict.copy()
+
+ for key in keys:
+ if cut_left: # 裁剪左侧
+ result[key] = tensor_dict[key][:, -effective_len:]
+ else:
+ result[key] = tensor_dict[key][:, :effective_len]
+ return result
+
+ def convert_pad_structure(self, tensor: torch.Tensor, pad_to_left: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Convert padding structure and return sorted tensor with indices."""
+ mask = tensor != self.config.pad_token_id if pad_to_left else tensor == self.config.pad_token_id
+ sorted_indices = mask.to(torch.int64).argsort(dim=1, stable=True)
+ return tensor.gather(1, sorted_indices), sorted_indices
+
+ def create_attention_mask(self, input_ids: torch.Tensor) -> torch.Tensor:
+ """Create attention mask from input ids."""
+ return torch.where(input_ids != self.config.pad_token_id, 1, 0)
+
+ def create_position_ids(self, attention_mask: torch.Tensor) -> torch.Tensor:
+ """Create position ids from attention mask."""
+ return (torch.cumsum(attention_mask, dim=1) - 1) * attention_mask
+
+ def concatenate_with_padding(
+ self, tensors: List[torch.Tensor],
+ pad_to_left: bool = True
+ )-> torch.Tensor:
+ """Concatenate tensors and handle padding."""
+ concatenated = torch.cat(tensors, dim=1)
+ padded_tensor, _ = self.convert_pad_structure(concatenated, pad_to_left)
+ return padded_tensor
+
+ def example_level_pad(
+ self, responses: torch.Tensor,
+ responses_str: List[str],
+ active_mask: torch.Tensor
+ ) -> Tuple[torch.Tensor, List[str]]:
+ assert active_mask.sum() == responses.shape[0]
+ # Create masked responses tensor
+ batch_size = active_mask.shape[0]
+ seq_len = responses.shape[1]
+ padded_responses = torch.full(
+ (batch_size, seq_len), self.config.pad_token_id,
+ dtype=responses.dtype, device=responses.device
+ )
+ padded_responses[active_mask] = responses
+
+ # Create masked response strings
+ padded_responses_str = [""] * batch_size
+
+ s = 0
+ for i, is_active in enumerate(active_mask):
+ if is_active:
+ padded_responses_str[i] = responses_str[s]
+ s += 1
+
+ return padded_responses, padded_responses_str
+
+ def erase_after_first_eos(self, completion_ids: torch.Tensor, eos_token_id: int) -> torch.Tensor:
+ is_eos_mask = (completion_ids == eos_token_id)
+ first_eos_indices = torch.argmax(is_eos_mask.int(), dim=1)
+ seq_len = completion_ids.size(1)
+ col_indices = torch.arange(seq_len, device=completion_ids.device)
+ mask_to_replace = (col_indices > first_eos_indices.unsqueeze(1)) & is_eos_mask.any(dim=1).unsqueeze(1)
+ completion_ids[mask_to_replace] = eos_token_id
+ return completion_ids
\ No newline at end of file
diff --git a/MemGen-main/memgen/__init__.py b/MemGen-main/memgen/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea75f95439c4909ef90747f3bcc2c17e88b84db7
--- /dev/null
+++ b/MemGen-main/memgen/__init__.py
@@ -0,0 +1,7 @@
+from .model.modeling_memgen import MemGenModel
+from .runner import MemGenRunner
+
+__all__ = [
+ "MemGenModel",
+ "MemGenRunner",
+]
\ No newline at end of file
diff --git a/MemGen-main/memgen/model/__init__.py b/MemGen-main/memgen/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..daebc6d83c36c06c7bf02e79dd207f3c63d08898
--- /dev/null
+++ b/MemGen-main/memgen/model/__init__.py
@@ -0,0 +1 @@
+from memgen.model.modeling_memgen import MemGenModel
\ No newline at end of file
diff --git a/MemGen-main/memgen/model/configuration_memgen.py b/MemGen-main/memgen/model/configuration_memgen.py
new file mode 100644
index 0000000000000000000000000000000000000000..743d30298953c368210132cd2f3721d6392e8d6b
--- /dev/null
+++ b/MemGen-main/memgen/model/configuration_memgen.py
@@ -0,0 +1,32 @@
+from transformers import PretrainedConfig
+from typing import Optional
+
+
+class MemGenConfig(PretrainedConfig):
+ model_type = "memgen"
+
+ def __init__(
+ self,
+ # weaver configs
+ weaver_lora_config: Optional[dict] = None,
+ prompt_latents_len: int = 0,
+ inference_latents_len: int = 0,
+ # trigger configs
+ trigger_active: bool = False,
+ trigger_lora_config: Optional[dict] = None,
+ max_prompt_aug_num: int = 1,
+ max_inference_aug_num: int = 5,
+ **kwargs
+ ):
+ super().__init__(**kwargs)
+
+ # weaver configs
+ self.weaver_lora_config = weaver_lora_config
+ self.prompt_latents_len = prompt_latents_len
+ self.inference_latents_len = inference_latents_len
+
+ # trigger configs
+ self.trigger_active = trigger_active
+ self.trigger_lora_config = trigger_lora_config
+ self.max_prompt_aug_num = max_prompt_aug_num
+ self.max_inference_aug_num = max_inference_aug_num
diff --git a/MemGen-main/memgen/model/modeling_memgen.py b/MemGen-main/memgen/model/modeling_memgen.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd5b8987dc36cced517f3f6e8a6d992a65f70795
--- /dev/null
+++ b/MemGen-main/memgen/model/modeling_memgen.py
@@ -0,0 +1,787 @@
+import logging
+import os
+import random
+from typing import Union
+
+from peft import PeftModel
+import torch
+import torch.nn as nn
+from transformers import (
+ AutoModelForCausalLM,
+ AutoTokenizer,
+ GenerationConfig,
+ DynamicCache
+)
+from transformers.modeling_utils import PreTrainedModel
+
+from memgen.model.configuration_memgen import MemGenConfig
+from memgen.model.modeling_utils import (
+ MemGenOutputWithPast,
+ MemGenLoraSwitchMixin,
+ MemGenGenerationMixin,
+)
+from memgen.model.trigger import MemGenTrigger
+from memgen.model.weaver import MemGenWeaver
+from memgen.utils import (
+ CONVERSATION_TEMPLATE,
+ fix_model_parameters,
+ log_trainable_params
+)
+
+class MemGenModel(PreTrainedModel, MemGenLoraSwitchMixin, MemGenGenerationMixin):
+ config_class = MemGenConfig
+ INSTRUCTION_STATE = 0
+ CONVERSATION_STATE = 1
+
+ def __init__(
+ self,
+ config: MemGenConfig,
+ base_tokenizer,
+ reasoner_base_model: PreTrainedModel,
+ weaver_base_model: PreTrainedModel,
+ trigger_base_model: PreTrainedModel,
+ ):
+ super().__init__(config)
+
+ self.config = config
+
+ # insert lora adapters into weaver and trigger
+ weaver_model_w_lora, trigger_model_w_lora = self._insert_lora_adapters(
+ weaver_base_model, config.weaver_lora_config, trigger_base_model, config.trigger_lora_config,
+ )
+
+ # use base model with lora adapters to initiate weaver and trigger
+ self.weaver = MemGenWeaver(weaver_model_w_lora, config.prompt_latents_len, config.inference_latents_len)
+ self.trigger = MemGenTrigger(trigger_model_w_lora, config.trigger_active)
+
+ # base reasoner
+ self.reasoner = reasoner_base_model
+ self.tokenizer = base_tokenizer
+
+ # projection layers for mapping embeddings between reasoner and weaver
+ reasoner_hidden_size = reasoner_base_model.config.hidden_size
+ weaver_hidden_size = weaver_base_model.config.hidden_size
+ self.reasoner_to_weaver = nn.Linear(reasoner_hidden_size, weaver_hidden_size) # map reasoner input embeddings to weaver input embeddings
+ self.weaver_to_reasoner = nn.Linear(weaver_hidden_size, reasoner_hidden_size) # Map weaver hidden states to reasoner input embeddings
+
+ # delimiters for detecting augmentation points
+ self.delimiters: list[str] = [",", ".", "\n"]
+
+ self.state = None
+
+ # postprocess
+ self._postprocess_models()
+ logging.info("##### MemGen Initialization #####")
+ log_trainable_params(self)
+
+ def _postprocess_models(self):
+ # fix base model parameters
+ fix_model_parameters(self.reasoner)
+
+ # Ensure tokenizer has a pad token
+ if self.tokenizer.pad_token is None:
+ self.tokenizer.pad_token = self.tokenizer.eos_token
+ self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
+ self.tokenizer.padding_side = "left"
+ logging.info(
+ f"Tokenizer has no pad token. Using EOS token ({self.tokenizer.eos_token}) as pad token."
+ )
+
+ # Normalize the tokenizer's chat template
+ self.tokenizer.chat_template = CONVERSATION_TEMPLATE
+
+
+ @property
+ def device(self):
+ return self.reasoner.device
+
+ def _forward(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor,
+ labels: torch.Tensor,
+ **kwargs
+ ) -> torch.Tensor:
+ # preprocess inputs
+ assert input_ids.shape == attention_mask.shape == labels.shape
+
+ tokenizer = self.tokenizer
+ reasoner = self.reasoner
+ weaver = self.weaver
+ delimiters = self.delimiters
+ max_augment_num = self.config.max_inference_aug_num # Limit the number of inference augmentation points to avoid excessive augmentation
+ device = self.device
+ embeds_dtype = reasoner.get_input_embeddings().weight.dtype
+ B, _ = input_ids.shape
+ hidden_size = self.config.hidden_size
+
+ # select augment idx
+ augmentation_indices = self._select_augment_points_after_delimiter(
+ input_ids, labels, delimiters, tokenizer, max_augment_num
+ )
+
+ # origin inputs embeds
+ inputs_embeds = reasoner.get_input_embeddings()(input_ids)
+
+ # Initialize the start index and empty tensors for accumulating processed segments
+ current_start_idx = 0
+ current_inputs_embeds = torch.empty((B, 0, hidden_size), device=device, dtype=embeds_dtype)
+ current_attention_mask = torch.empty((B, 0), device=device, dtype=attention_mask.dtype)
+ current_latents_mask = torch.empty((B, 0), device=device, dtype=torch.bool)
+
+ # Iterate over the selected augmentation points
+ for aug_point_idx in augmentation_indices:
+ # Slice the current segment of original embeddings and attention mask
+ segment_inputs_embeds = inputs_embeds[:, current_start_idx:aug_point_idx]
+ segment_attention_mask = attention_mask[:, current_start_idx:aug_point_idx]
+ segment_latents_mask = torch.zeros((B, segment_inputs_embeds.size(1)), device=device, dtype=torch.bool)
+
+ # Concatenate the current segment to the accumulated embeddings and masks
+ current_inputs_embeds = torch.cat([current_inputs_embeds, segment_inputs_embeds], dim=1)
+ current_attention_mask = torch.cat([current_attention_mask, segment_attention_mask], dim=1)
+ current_position_ids = self._generate_position_ids(current_attention_mask)
+ current_latents_mask = torch.cat([current_latents_mask, segment_latents_mask], dim=1)
+
+ # Map reasoner embeddings to weaver embeddings for augmentation
+ weaver_inputs_embeds = self.reasoner_to_weaver(current_inputs_embeds)
+
+ # Determine whether this point is the end of the prompt (prompt augmentation)
+ is_prompt_end_aug = (labels[:, aug_point_idx] != -100).all() and (labels[:, aug_point_idx-1] == -100).all().item()
+
+ # Depending on type, use weaver to augment prompt or inference
+ if is_prompt_end_aug:
+ weaver_hidden_states, attn_mask, pos_ids = weaver.augment_prompt(
+ weaver_inputs_embeds, current_attention_mask, current_position_ids
+ )
+ else:
+ weaver_hidden_states, attn_mask, pos_ids = weaver.augment_inference(
+ weaver_inputs_embeds, current_attention_mask, current_position_ids
+ )
+
+ # Map weaver hidden states back to reasoner embeddings
+ latent_inputs_embeds = self.weaver_to_reasoner(weaver_hidden_states)
+
+ # Update accumulated embeddings and masks with the newly augmented segment
+ current_inputs_embeds = torch.cat([current_inputs_embeds, latent_inputs_embeds], dim=1)
+ current_attention_mask = torch.cat([current_attention_mask, attn_mask], dim=1)
+ current_start_idx = aug_point_idx
+
+ # Update latent mask for the newly added latent embeddings
+ latent_mask = torch.ones((B, latent_inputs_embeds.size(1)), device=device, dtype=torch.bool)
+ current_latents_mask = torch.cat([current_latents_mask, latent_mask], dim=1)
+
+ # Process the remaining segment after the last augmentation point
+ remaining_inputs_embeds = inputs_embeds[:, current_start_idx:]
+ remaining_attention_mask = attention_mask[:, current_start_idx:]
+ latent_mask = torch.zeros((B, remaining_attention_mask.size(1)), device=device, dtype=torch.bool)
+
+ current_inputs_embeds = torch.cat([current_inputs_embeds, remaining_inputs_embeds], dim=1)
+ current_attention_mask = torch.cat([current_attention_mask, remaining_attention_mask], dim=1)
+ current_position_ids = self._generate_position_ids(current_attention_mask)
+ current_latents_mask = torch.cat([current_latents_mask, latent_mask], dim=1)
+
+ reasoner_outputs = reasoner(
+ inputs_embeds=current_inputs_embeds,
+ attention_mask=current_attention_mask,
+ position_ids=current_position_ids
+ )
+ logits = reasoner_outputs.logits
+
+ # Identify valid positions in logits (positions that should contribute to loss)
+ shifted = torch.zeros_like(current_latents_mask)
+ shifted[:, :-1] = current_latents_mask[:, 1:]
+ valid_mask = ~shifted
+
+ valid_logits = logits[valid_mask].view(logits.size(0), -1, logits.size(2))
+ # assert shifted.sum() == current_latents_mask.sum()
+ # assert valid_logits.shape[:2] == input_ids.shape
+ return valid_logits
+
+ def _instructional_forward(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor,
+ labels: torch.Tensor,
+ **kwargs
+ ) -> tuple[torch.FloatTensor, torch.LongTensor]:
+ """
+ Forward pass for single-turn instructional data (no multi-turn conversation required).
+
+ This method is used for instruction-following tasks (SFT), where the input
+ consists of a single instruction and the corresponding labels. It directly
+ delegates to the single-turn forward method `_forward`.
+
+ Args:
+ input_ids (torch.Tensor): Tensor of shape (batch_size, seq_len) containing input token IDs.
+ attention_mask (torch.Tensor): Tensor indicating padding positions.
+ labels (torch.Tensor): Tensor containing the target labels for supervised fine-tuning.
+ **kwargs: Additional keyword arguments passed to `_forward`.
+
+ Returns:
+ tuple[torch.Tensor, torch.Tensor]:
+ - logits: The output logits from the model for each input token.
+ - labels: The same as input labels, used for loss computation.
+ """
+ # raise RuntimeError()
+ logits = self._forward(input_ids, attention_mask, labels, **kwargs)
+ # For Instruction SFT, labels remain the same as input
+ return logits, labels
+
+ def _conversational_forward(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor,
+ labels: torch.Tensor,
+ **kwargs
+ ) -> tuple[torch.FloatTensor, torch.LongTensor]:
+ """
+ Forward pass for conversational (multi-turn) data.
+
+ Multi-turn forward is constructed by sequentially calling the single-turn forward
+ for each conversation turn. Latents inserted in turn i-1 are not visible to turn i.
+
+ Args:
+ input_ids (torch.Tensor): Input token IDs, shape (1, seq_len). Batch size must be 1.
+ attention_mask (torch.Tensor): Attention mask for input tokens.
+ labels (torch.Tensor): Target labels for supervised fine-tuning (-100 for ignore positions).
+ **kwargs: Additional arguments passed to `_forward`.
+
+ Returns:
+ tuple[torch.Tensor, torch.Tensor]:
+ - all_logits: Logits for the entire sequence, with zeros for unsupervised positions.
+ - all_labels: Labels for the entire sequence, with -100 for unsupervised positions.
+ """
+ assert input_ids.shape[0] == 1, "Conversational SFT currently only supports batch_size = 1"
+ seq_len = input_ids.shape[1]
+ vocab_size = self.config.vocab_size
+ device = input_ids.device
+
+ # Identify single-turn segments within the conversation based on labels
+ label_row = labels[0]
+ should_supervise = label_row != -100
+ if not should_supervise.any():
+ raise ValueError("At least one completion segment is required")
+
+ # Compute the start and end indices of valid supervised segments
+ valid_mask = should_supervise.int()
+ diff = torch.diff(torch.cat([torch.tensor([0], device=device), valid_mask]))
+ valid_starts = (diff == 1).nonzero(as_tuple=True)[0].tolist() # Transition 0 -> 1
+ ends = (diff == -1).nonzero(as_tuple=True)[0].tolist() # Transition 1 -> 0
+ if len(ends) < len(valid_starts):
+ ends.append(seq_len) # 自动补充最后一个 token 的 (index + 1) 作为最后一个序列的末尾
+ assert len(valid_starts) == len(ends)
+
+ # Build triplets (start of previous segment, start of supervised segment, end of supervised segment)
+ triplets = []
+ start = 0
+ for s, e in zip(valid_starts, ends):
+ triplets.append((start, s, e))
+ start = e
+
+ # If there are more segments than allowed, randomly select self.max_prompt_aug_num segments
+ if len(triplets) <= self.config.max_prompt_aug_num:
+ select_turns = [1] * len(triplets)
+ else:
+ triplets_num = len(triplets)
+ selected_indices = set(random.sample(range(triplets_num), self.config.max_prompt_aug_num))
+ select_turns = [1 if i in selected_indices else 0 for i in range(triplets_num)]
+
+ # Initialize tensors to store logits and labels for the entire sequence
+ all_logits = torch.zeros(1, seq_len, vocab_size, device=device)
+ all_labels = torch.full((1, seq_len), -100, device=device)
+
+ # Loop over each conversation turn and perform single-turn forward if supervised
+ for triplet, should_supervise in zip(triplets, select_turns):
+ start, valid_start, end = triplet
+ if should_supervise:
+ cur_input_ids = input_ids[0, :end].unsqueeze(0)
+ cur_attention = attention_mask[0, :end].unsqueeze(0)
+ # cur_labels only used for _forward, does not represent the true supervision range
+ # cur_labels = labels[0, :end].clone().unsqueeze(0)
+ # cur_labels[0, :valid_start] = -100 # Mask tokens before supervision start
+ cur_labels = torch.full((1, end), -100, device=device)
+ cur_labels[0, valid_start:end] = labels[0, valid_start:end]
+
+ # Single-turn forward for the current conversation segment
+ logits = self._forward(cur_input_ids, cur_attention, cur_labels, **kwargs)
+
+ # Update overall logits and labels with the results of this segment
+ all_logits[0, start:end, :] = logits[0, start:end, :]
+ all_labels[0, start:end] = labels[0, start:end]
+
+ # Return logits and labels:
+ # - supervised positions retain computed logits and original labels
+ # - unsupervised positions have logits = 0 and labels = -100
+ return all_logits, all_labels
+
+ def forward(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor,
+ labels: torch.Tensor,
+ **kwargs
+ ) -> MemGenOutputWithPast:
+ tokenizer = self.tokenizer
+
+ # Ensure labels are provided, required for training the reasoning processor
+ assert labels is not None, "Reasoning Processor requires input labels for training"
+
+ # Determine whether the input is single-turn (instruction) or multi-turn (conversation)
+ labels = self._postprocess_assistant_labels(input_ids, labels, tokenizer)
+
+ # Use only the first data sample of each dataset to determine the model state
+ if self.state is None:
+ self.state = MemGenModel.CONVERSATION_STATE if self._is_conversation(input_ids, tokenizer) else MemGenModel.INSTRUCTION_STATE
+
+ if self.state == MemGenModel.INSTRUCTION_STATE:
+ forward_func = self._instructional_forward
+ elif self.state == MemGenModel.CONVERSATION_STATE:
+ forward_func = self._conversational_forward
+ else:
+ raise RuntimeError(f"Unexpected model state: {self.state}")
+
+ batch_size = 1 # Currently process one sequence per batch
+ iter_num = input_ids.size(0) // batch_size
+
+ # Forward pass per batch
+ logits, supervised_labels = [], []
+ for i in range(iter_num):
+ batch_input_ids = input_ids[i * batch_size: (i + 1) * batch_size]
+ batch_attention_mask = attention_mask[i * batch_size: (i + 1) * batch_size]
+ batch_labels = labels[i * batch_size: (i + 1) * batch_size]
+
+ # Call the appropriate forward function (instruction or conversation)
+ batch_logits, batch_supervised_labels = forward_func(
+ input_ids=batch_input_ids,
+ attention_mask=batch_attention_mask,
+ labels=batch_labels,
+ **kwargs
+ )
+ logits.append(batch_logits)
+ supervised_labels.append(batch_supervised_labels)
+
+ # Concatenate results from all batches
+ all_logits = torch.concat(logits, dim=0)
+ all_labels = torch.concat(supervised_labels, dim=0)
+
+ # Compute causal language modeling loss (shifted by one)
+ shift_logits = all_logits[..., :-1, :].contiguous()
+ shift_labels = all_labels[..., 1:].contiguous()
+ # assert shift_logits.shape[:-1] == shift_labels.shape
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
+
+ # Return model outputs
+ outputs = MemGenOutputWithPast(loss=loss, logits=all_logits)
+ outputs.supervised_labels = all_labels # Positions in input_ids that are supervised
+ return outputs
+
+ # @torch.no_grad()
+ # def generate(
+ # self,
+ # input_ids: torch.Tensor,
+ # attention_mask: torch.Tensor,
+ # generation_config: GenerationConfig = None,
+ # return_augmentation_mask: bool = False,
+ # **kwargs
+ # ) -> Union[torch.LongTensor, tuple[torch.LongTensor, torch.LongTensor]]:
+
+ # tokenizer = self.tokenizer
+ # reasoner = self.reasoner
+ # weaver = self.weaver
+ # max_augment_num = self.config.max_inference_aug_num
+ # invalid_token_id = -100
+
+ # # preproecess inputs
+ # input_ids = input_ids.to(self.device)
+ # attention_mask = attention_mask.to(self.device)
+ # max_new_tokens = generation_config.max_new_tokens
+ # pad_token_id = tokenizer.pad_token_id
+ # eos_token_id = tokenizer.eos_token_id
+ # prompt_len = input_ids.size(1)
+
+ # inputs_embeds = reasoner.get_input_embeddings()(input_ids)
+ # B, _, hidden_size = inputs_embeds.shape
+ # device = inputs_embeds.device
+
+ # # --- generation loop ---
+ # current_inputs_embeds = inputs_embeds
+ # current_attention_mask = attention_mask
+ # current_position_ids = self._generate_position_ids(current_attention_mask)
+ # current_input_ids = input_ids
+ # current_cache: DynamicCache = None
+
+ # # Generation Loop Initialization
+ # sentence_augment_count = torch.zeros(B, dtype=torch.int, device=device)
+
+ # # NOTE - Whether to call the trigger and insert latent memory before generating the token at this position
+ # # - augmentation_pos[b][i] == -100: For the b-th sequence, no augmentation was sampled before generating the i-th token
+ # # - augmentation_pos[b][i] == 0: For the b-th sequence, augmentation was sampled before generating the i-th token, but the trigger decided NOT to insert latent memory
+ # # - augmentation_pos[b][i] == 1: For the b-th sequence, augmentation was sampled before generating the i-th token, and the trigger decided to insert latent memory
+ # augmentation_pos = torch.full((B, max_new_tokens), fill_value=invalid_token_id, device=device)
+
+ # generation_config = GenerationConfig(
+ # do_sample=False,
+ # pad_token_id=pad_token_id,
+ # eos_token_id=eos_token_id,
+ # use_cache=False,
+ # max_new_tokens=max_new_tokens
+ # )
+ # # Perform generation for the remaining tokens using the reasoner
+ # generated = reasoner.generate(
+ # inputs_embeds=current_inputs_embeds,
+ # attention_mask=current_attention_mask,
+ # generation_config=generation_config
+ # )
+ # current_input_ids = torch.cat([current_input_ids, generated], dim=1)
+
+ # # postprocess
+ # new_generated_len = current_input_ids.size(1) - prompt_len
+ # augmentation_pos = augmentation_pos[:, :new_generated_len]
+
+ # self._check_generate(
+ # current_input_ids[:, prompt_len:],
+ # augmentation_pos
+ # )
+
+ # if return_augmentation_mask:
+ # return (current_input_ids, augmentation_pos)
+ # else:
+ # return current_input_ids
+
+ @torch.no_grad()
+ def generate(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor,
+ generation_config: GenerationConfig = None,
+ return_augmentation_mask: bool = False,
+ **kwargs
+ ) -> Union[torch.LongTensor, tuple[torch.LongTensor, torch.LongTensor]]:
+
+ tokenizer = self.tokenizer
+ reasoner = self.reasoner
+ weaver = self.weaver
+ max_augment_num = self.config.max_inference_aug_num
+ invalid_token_id = -100
+
+ # preproecess inputs
+ input_ids = input_ids.to(self.device)
+ attention_mask = attention_mask.to(self.device)
+ max_new_tokens = generation_config.max_new_tokens
+ pad_token_id = tokenizer.pad_token_id
+ eos_token_id = tokenizer.eos_token_id
+ prompt_len = input_ids.size(1)
+
+ inputs_embeds = reasoner.get_input_embeddings()(input_ids)
+ B, _, hidden_size = inputs_embeds.shape
+ device = inputs_embeds.device
+
+ # --- generation loop ---
+ current_inputs_embeds = inputs_embeds
+ current_attention_mask = attention_mask
+ current_position_ids = self._generate_position_ids(current_attention_mask)
+ current_input_ids = input_ids
+ current_cache: DynamicCache = None
+
+ # Generation Loop Initialization
+ sentence_augment_count = torch.zeros(B, dtype=torch.int, device=device)
+
+ # NOTE - Whether to call the trigger and insert latent memory before generating the token at this position
+ # - augmentation_pos[b][i] == -100: For the b-th sequence, no augmentation was sampled before generating the i-th token
+ # - augmentation_pos[b][i] == 0: For the b-th sequence, augmentation was sampled before generating the i-th token, but the trigger decided NOT to insert latent memory
+ # - augmentation_pos[b][i] == 1: For the b-th sequence, augmentation was sampled before generating the i-th token, and the trigger decided to insert latent memory
+ augmentation_pos = torch.full((B, max_new_tokens), fill_value=invalid_token_id, device=device)
+
+ for i in range(max_new_tokens):
+
+ assert current_inputs_embeds.shape[:2] == current_attention_mask.shape == current_position_ids.shape
+ augment_decision = self._should_augment(
+ current_input_ids,
+ sentence_augment_count=sentence_augment_count,
+ do_sample=generation_config.trigger_do_sample,
+ temperature=generation_config.temperature,
+ is_prompt=(i==0)
+ )
+ augmentation_pos[:, i] = augment_decision
+ augment_indices = torch.where(augment_decision == 1)[0]
+
+ # If there are sentences to augment, apply augmentation; others remain with left padding
+ if len(augment_indices) > 0:
+ # Increment the augmentation count for sentences that are being augmented
+ if i != 0:
+ sentence_augment_count[augment_indices] += 1
+
+ # Select embeddings, attention masks, and position IDs for sentences to be augmented
+ candidate_inputs_embeds = current_inputs_embeds[augment_indices]
+ candidate_attention_mask = current_attention_mask[augment_indices]
+ candidate_position_ids = current_position_ids[augment_indices]
+
+ # Perform inference augmentation using the weaver
+ weaver_inputs_embeds = self.reasoner_to_weaver(candidate_inputs_embeds)
+ if i == 0:
+ weaver_hidden_states, attn_mask, _ = weaver.augment_prompt(
+ weaver_inputs_embeds, candidate_attention_mask, candidate_position_ids
+ )
+ else:
+ weaver_hidden_states, attn_mask, _ = weaver.augment_inference(
+ weaver_inputs_embeds, candidate_attention_mask, candidate_position_ids
+ )
+ latent_inputs_embeds = self.weaver_to_reasoner(weaver_hidden_states)
+
+ candidate_inputs_embeds = torch.cat([candidate_inputs_embeds, latent_inputs_embeds], dim=1)
+ candidate_attention_mask = torch.cat([candidate_attention_mask, attn_mask], dim=1)
+
+ # Create a single merged tensor for all sequences
+ new_len = candidate_inputs_embeds.size(1)
+ merged_inputs_embeds = torch.zeros((B, new_len, hidden_size), device=device, dtype=current_inputs_embeds.dtype)
+ merged_attention_mask = torch.zeros((B, new_len), device=device, dtype=current_attention_mask.dtype)
+
+ # Directly place augmented and non-augmented sequences
+ merged_inputs_embeds[augment_indices] = candidate_inputs_embeds
+ merged_attention_mask[augment_indices] = candidate_attention_mask
+
+ # Non-augmented sequences now include both -100 and 0
+ non_augment_indices = torch.where(augment_decision != 1)[0]
+ if len(non_augment_indices) > 0:
+ # dynamic left padding
+ non_aug_inputs_embeds = current_inputs_embeds[non_augment_indices]
+ non_aug_attention_mask = current_attention_mask[non_augment_indices]
+ pad_len = weaver.prompt_latents_num if i == 0 else weaver.inference_latents_num
+ non_aug_inputs_embeds, non_aug_attention_mask, _ = self._left_pad(
+ non_aug_inputs_embeds, non_aug_attention_mask, None, pad_len
+ )
+
+ merged_inputs_embeds[non_augment_indices] = non_aug_inputs_embeds
+ merged_attention_mask[non_augment_indices] = non_aug_attention_mask
+
+ current_inputs_embeds = merged_inputs_embeds
+ current_attention_mask = merged_attention_mask
+ current_position_ids = self._generate_position_ids(current_attention_mask)
+ current_cache = None
+
+ # Check if all sequences have reached the maximum number of augmentations
+ if (sentence_augment_count >= max_augment_num).all():
+ # Adjust the remaining generation length
+ generation_config_continue = GenerationConfig(
+ do_sample=generation_config.weaver_do_sample,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ use_cache=False,
+ max_new_tokens=max_new_tokens-i
+ )
+ # Perform generation for the remaining tokens using the reasoner
+ generated = reasoner.generate(
+ inputs_embeds=current_inputs_embeds,
+ attention_mask=current_attention_mask,
+ generation_config=generation_config_continue
+ )
+ current_input_ids = torch.cat([current_input_ids, generated], dim=1)
+ break
+
+ if current_cache is not None:
+ assert current_inputs_embeds.size(1) == current_cache.get_seq_length() + 1
+ reasoner_inputs_embeds = current_inputs_embeds[:, -1:]
+ reasoner_position_ids = current_position_ids[:, -1:]
+ else:
+ reasoner_inputs_embeds = current_inputs_embeds
+ reasoner_position_ids = current_position_ids
+
+ outputs = reasoner(
+ inputs_embeds=reasoner_inputs_embeds,
+ attention_mask=current_attention_mask,
+ position_ids=reasoner_position_ids,
+ output_hidden_states=False,
+ use_cache=True,
+ past_key_values=current_cache
+ )
+ current_inputs_embeds, current_attention_mask, current_position_ids, current_input_ids = self._append_one_step(
+ outputs,
+ current_inputs_embeds,
+ current_attention_mask,
+ current_position_ids,
+ current_input_ids,
+ do_sample=generation_config.weaver_do_sample,
+ temperature=generation_config.temperature
+ )
+ current_cache = outputs.past_key_values
+
+ # If all sequences in the batch have already generated an EOS token, stop early
+ if (current_input_ids[:, -1] == eos_token_id).all():
+ break
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ del outputs
+
+ # postprocess
+ new_generated_len = current_input_ids.size(1) - prompt_len
+ augmentation_pos = augmentation_pos[:, :new_generated_len]
+
+ self._check_generate(
+ current_input_ids[:, prompt_len:],
+ augmentation_pos
+ )
+
+ if return_augmentation_mask:
+ return (current_input_ids, augmentation_pos)
+ else:
+ return current_input_ids
+
+ @classmethod
+ def from_config(cls, config_dict: dict):
+ # base LLM
+ model_name = config_dict.get("model_name")
+
+ # max augment numbers
+ max_prompt_aug_num = config_dict.get("max_prompt_aug_num", 1)
+ max_inference_aug_num = config_dict.get("max_inference_aug_num", 5)
+
+ # weaver configs
+ weaver_config = config_dict.get("weaver", {})
+ prompt_latents_len = weaver_config.get("prompt_latents_len", 8)
+ inference_latents_len = weaver_config.get("inference_latents_len", 8)
+ weaver_lora_config_dict = weaver_config.get("lora_config", None)
+ weaver_model_name = weaver_config.get("model_name", None)
+
+ # trigger configs
+ trigger_config = config_dict.get("trigger", {})
+ trigger_active = trigger_config.get("active", False)
+ trigger_lora_config_dict = trigger_config.get("lora_config", None)
+ trigger_model_name = trigger_config.get("model_name", None)
+
+ # build MemGenConfig
+ from transformers import AutoConfig
+ memgen_config = AutoConfig.from_pretrained(model_name)
+ memgen_config = MemGenConfig.from_pretrained(
+ model_name,
+ max_prompt_aug_num=max_prompt_aug_num,
+ max_inference_aug_num=max_inference_aug_num,
+ prompt_latents_len=prompt_latents_len,
+ inference_latents_len=inference_latents_len,
+ weaver_lora_config=weaver_lora_config_dict,
+ trigger_active=trigger_active,
+ trigger_lora_config=trigger_lora_config_dict
+ )
+
+ # load pretrained base models
+ base_tokenizer = AutoTokenizer.from_pretrained(model_name)
+ reasoner_base_model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
+ weaver_base_model = AutoModelForCausalLM.from_pretrained(weaver_model_name, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
+ trigger_base_model = AutoModelForCausalLM.from_pretrained(trigger_model_name, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
+
+ # instantiate MemGen Model
+ load_model_path = config_dict.get("load_model_path", None)
+
+ if not load_model_path:
+ model = cls(
+ config=memgen_config,
+ base_tokenizer=base_tokenizer,
+ reasoner_base_model=reasoner_base_model,
+ weaver_base_model=weaver_base_model,
+ trigger_base_model=trigger_base_model
+ )
+ else:
+ model = cls.from_pretrained(
+ load_model_path,
+ config=memgen_config,
+ base_tokenizer=base_tokenizer,
+ reasoner_base_model=reasoner_base_model,
+ weaver_base_model=weaver_base_model,
+ trigger_base_model=trigger_base_model
+ )
+
+ return model
+
+ def save_pretrained(self, save_directory: str, **kwargs):
+ os.makedirs(save_directory, exist_ok=True)
+
+ self.config.save_pretrained(save_directory)
+
+ torch.save(
+ {
+ "reasoner_to_weaver": self.reasoner_to_weaver.state_dict(),
+ "weaver_to_reasoner": self.weaver_to_reasoner.state_dict(),
+ },
+ os.path.join(save_directory, "projs.bin"),
+ )
+
+ torch.save(
+ {
+ "prompt_query_latents": self.weaver.prompt_query_latents.data,
+ "inference_query_latents": self.weaver.inference_query_latents.data,
+ "prompt_latent_ln": self.weaver.prompt_latent_ln.state_dict(),
+ "inference_latent_ln": self.weaver.inference_latent_ln.state_dict(),
+ "prompt_latent_scale": self.weaver.prompt_latent_scale.data,
+ "inference_latent_scale": self.weaver.inference_latent_scale.data,
+ },
+ os.path.join(save_directory, "weaver.bin"),
+ )
+
+ torch.save(
+ {
+ "output_layer": self.trigger.output_layer.state_dict(),
+ },
+ os.path.join(save_directory, "trigger.bin"),
+ )
+
+ self.weaver.model.save_pretrained(os.path.join(save_directory, "weaver"))
+ self.trigger.model.save_pretrained(os.path.join(save_directory, "trigger"))
+
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ load_directory: str,
+ *,
+ config,
+ base_tokenizer,
+ reasoner_base_model,
+ weaver_base_model,
+ trigger_base_model,
+ ):
+ model = cls(
+ config=config,
+ base_tokenizer=base_tokenizer,
+ reasoner_base_model=reasoner_base_model,
+ weaver_base_model=weaver_base_model,
+ trigger_base_model=trigger_base_model,
+ )
+
+ proj_path = os.path.join(load_directory, "projs.bin")
+ proj_state = torch.load(proj_path, map_location="cpu")
+ model.reasoner_to_weaver.load_state_dict(proj_state["reasoner_to_weaver"])
+ model.weaver_to_reasoner.load_state_dict(proj_state["weaver_to_reasoner"])
+
+ weaver_path = os.path.join(load_directory, "weaver.bin")
+ weaver_state = torch.load(weaver_path, map_location="cpu")
+ model.weaver.prompt_query_latents.data.copy_(weaver_state["prompt_query_latents"])
+ model.weaver.inference_query_latents.data.copy_(weaver_state["inference_query_latents"])
+ model.weaver.prompt_latent_ln.load_state_dict(weaver_state["prompt_latent_ln"])
+ model.weaver.inference_latent_ln.load_state_dict(weaver_state["inference_latent_ln"])
+ model.weaver.prompt_latent_scale.data.copy_(weaver_state["prompt_latent_scale"])
+ model.weaver.inference_latent_scale.data.copy_(weaver_state["inference_latent_scale"])
+
+ trigger_path = os.path.join(load_directory, "trigger.bin")
+ trigger_state = torch.load(trigger_path, map_location="cpu")
+ model.trigger.output_layer.load_state_dict(trigger_state["output_layer"])
+
+ model.weaver.model = PeftModel.from_pretrained(
+ model.weaver.model.base_model,
+ os.path.join(load_directory, "weaver", "weaver"),
+ adapter_name=MemGenWeaver.adapter_name,
+ )
+ model.weaver.model.set_adapter(MemGenWeaver.adapter_name)
+
+ model.trigger.model = PeftModel.from_pretrained(
+ model.trigger.model.base_model,
+ os.path.join(load_directory, "trigger", "trigger"),
+ adapter_name=MemGenTrigger.adapter_name,
+ )
+ model.trigger.model.set_adapter(MemGenTrigger.adapter_name)
+
+ logging.info("##### MemGen from Pretrained #####")
+ log_trainable_params(model)
+
+ return model
+
diff --git a/MemGen-main/memgen/model/modeling_utils.py b/MemGen-main/memgen/model/modeling_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..03f7122f53a477d5073b631bc48130e5b5d72f77
--- /dev/null
+++ b/MemGen-main/memgen/model/modeling_utils.py
@@ -0,0 +1,430 @@
+from dataclasses import dataclass
+import logging
+import os
+from typing import Optional, Literal, Set
+
+from peft import PeftModel, LoraConfig
+import torch
+import torch.nn.functional as F
+from transformers import PreTrainedTokenizerBase
+from transformers.generation.utils import GenerationMixin
+from transformers.modeling_outputs import CausalLMOutputWithPast
+from transformers.modeling_utils import PreTrainedModel
+
+from memgen.model.trigger import MemGenTrigger
+from memgen.model.weaver import MemGenWeaver
+from memgen.utils import (
+ CONVERSATION_TEMPLATE,
+ fix_model_parameters,
+ open_model_parameters
+)
+
+@dataclass
+class MemGenOutputWithPast(CausalLMOutputWithPast):
+ supervised_labels: Optional[torch.LongTensor] = None
+
+class MemGenLoraSwitchMixin:
+
+ def _insert_lora_adapters(
+ self,
+ weaver_model: PreTrainedModel,
+ weaver_lora_config: dict,
+ trigger_model: PreTrainedModel,
+ trigger_lora_config: dict
+ ) -> tuple[PeftModel, PeftModel]:
+ # insert lora adapters into weaver and trigger
+ weaver_lora_config = LoraConfig(**weaver_lora_config)
+ trigger_lora_config = LoraConfig(**trigger_lora_config)
+
+ weaver_model_with_lora = PeftModel(
+ weaver_model, weaver_lora_config, adapter_name=MemGenWeaver.adapter_name
+ )
+ trigger_model_with_lora = PeftModel(
+ trigger_model, trigger_lora_config, adapter_name=MemGenTrigger.adapter_name
+ )
+
+ return weaver_model_with_lora, trigger_model_with_lora
+
+ def fix_component(self, name: Literal["weaver", "trigger"]):
+ # frozen parameters of weaver or trigger
+ component = getattr(self, name)
+ fix_model_parameters(component)
+ if name == "weaver":
+ fix_model_parameters(self.weaver_to_reasoner)
+ fix_model_parameters(self.reasoner_to_weaver)
+
+ def open_component(self, name: Literal["weaver", "trigger"]):
+ # open parameters of weaver or trigger
+ component = getattr(self, name)
+ open_model_parameters(component)
+ if name == "weaver":
+ open_model_parameters(self.weaver_to_reasoner)
+ open_model_parameters(self.reasoner_to_weaver)
+
+ fix_model_parameters(component.model.base_model) # only finetune the lora adapters of the specific component
+
+ for n, p in component.model.named_parameters():
+ if "lora_A" in n or "lora_B" in n:
+ if name in n:
+ assert p.requires_grad, f"{n} should be trainable"
+ else:
+ assert not p.requires_grad, f"{n} should be frozen"
+
+
+class MemGenGenerationMixin(GenerationMixin):
+
+ def _get_next_token(
+ self,
+ next_token_logits: torch.Tensor,
+ do_sample: bool,
+ temperature: Optional[float] = 0.0
+ ) -> torch.Tensor:
+ if len(next_token_logits.shape) != 2:
+ raise ValueError("Input logits must be a 2D tensor [batch_size, vocab_size]")
+
+ if do_sample and temperature != 0: # Apply temperature scaling and sample from the resulting probability distribution
+ probs = F.softmax(next_token_logits / temperature, dim=-1)
+ return torch.multinomial(probs, num_samples=1)
+ else: # Greedy decoding: pick the token with the highest probability
+ return torch.argmax(next_token_logits, dim=-1, keepdim=True)
+
+ def _generate_position_ids(self, attention_mask: torch.Tensor) -> torch.Tensor:
+ position_ids = (attention_mask.cumsum(-1) - 1).clamp(min=0)
+ position_ids.masked_fill_(attention_mask == 0, 0)
+ return position_ids
+
+ def _is_conversation(self, input_ids: torch.Tensor, tokenizer) -> bool:
+ # if the input_ids has more than one <|im_start|>assistant\n, then it will be considered as a conversation
+ if len(input_ids.shape) != 2:
+ raise ValueError("input_ids must be a 2D tensor of shape (batch_size, seq_len)")
+
+ seq = input_ids[0].tolist()
+
+ im_start_ids = tokenizer.encode("<|im_start|>", add_special_tokens=False)
+ assistant_ids = tokenizer.encode("assistant", add_special_tokens=False)
+
+ target_seq = im_start_ids + assistant_ids
+
+ count = 0
+ for i in range(len(seq) - len(target_seq) + 1):
+ if seq[i:i+len(target_seq)] == target_seq:
+ count += 1
+
+ return count > 1
+
+
+ def _postprocess_assistant_labels(
+ self,
+ input_ids: torch.Tensor,
+ labels: torch.Tensor,
+ tokenizer
+ ) -> torch.Tensor:
+ if tokenizer.chat_template != CONVERSATION_TEMPLATE:
+ raise ValueError(
+ "Invalid tokenizer.chat_template detected.\n"
+ f"Expected:\n{CONVERSATION_TEMPLATE}\n\n"
+ f"Got:\n{tokenizer.chat_template}\n\n"
+ "Please ensure that you are using the correct conversation template."
+ )
+
+ # Encode the token sequence for "<|im_start|>assistant\n"
+ pattern_ids: list[int] = tokenizer.encode("<|im_start|>assistant\n", add_special_tokens=False)
+
+ batch_size, seq_len = input_ids.shape
+ new_labels = labels.clone()
+
+ for b in range(batch_size):
+ seq = input_ids[b].tolist()
+ for i in range(len(seq) - len(pattern_ids) + 1):
+ # Mask positions matching the pattern
+ if seq[i : i + len(pattern_ids)] == pattern_ids:
+ new_labels[b, i : i + len(pattern_ids)] = -100
+
+ return new_labels
+
+ def _get_delimiter_token_ids(self, tokenizer, delimiters: list[str]) -> Set[int]:
+ """预计算 delimiter 对应的 token ids (在 __init__ 后调用一次)"""
+ delimiter_token_ids = set()
+ for d in delimiters:
+ ids = tokenizer.encode(d, add_special_tokens=False)
+ delimiter_token_ids.update(ids)
+ return delimiter_token_ids
+
+ def _check_ends_with_delimiter(
+ self, input_ids: torch.Tensor, tokenizer, delimiters: list[str]
+ ) -> torch.Tensor:
+ """检查每个序列的最后一个 token 是否是 delimiter token (O(1) 每序列,无 decode)"""
+ batch_size = input_ids.size(0)
+ device = input_ids.device
+
+ # 获取最后一个有效 token (跳过 padding)
+ pad_token_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
+ mask = input_ids != pad_token_id
+ last_positions = mask.sum(dim=1).clamp(min=1) - 1
+ last_tokens = input_ids[torch.arange(batch_size, device=device), last_positions]
+
+ # 预计算并缓存 delimiter token ids tensor (只执行一次)
+ cache_key = '_delimiter_token_tensor'
+ if not hasattr(self, cache_key):
+ token_ids = self._get_delimiter_token_ids(tokenizer, delimiters)
+ setattr(self, cache_key, torch.tensor(list(token_ids), device=device))
+
+ delimiter_tensor = getattr(self, cache_key)
+ is_delimiter = (last_tokens.unsqueeze(1) == delimiter_tensor).any(dim=1)
+
+ return is_delimiter.unsqueeze(1)
+
+ def _select_augment_points_after_delimiter(
+ self,
+ input_ids: torch.Tensor,
+ labels: torch.Tensor,
+ delimiters: list[str],
+ tokenizer: PreTrainedTokenizerBase,
+ max_num: int = 10,
+ ) -> list[int]:
+
+ assert input_ids.shape == labels.shape
+ B, seq_len = input_ids.size(0), input_ids.size(1)
+
+ prompt_augment_idx = []
+ inference_augment_idx = []
+
+ for i in range(1, seq_len): # Skip the first token and last token for augmentation
+ # Detect the boundary between prompt and label for prompt augmentation
+ if (labels[:, i] != -100).all() and (labels[:, i - 1] == -100).all():
+ prompt_augment_idx.append(i)
+
+ # Detect valid label regions for inference augmentation
+ elif (labels[:, i] != -100).all() and (labels[:, i - 1] != -100).all():
+ batch_tokens_before_i = input_ids[:, :i]
+ # Fast token-level check (no decode)
+ if self._check_ends_with_delimiter(batch_tokens_before_i, tokenizer, delimiters).any():
+ inference_augment_idx.append(i)
+
+ # Ensure exactly one prompt augmentation point exists for single-turn processing
+ if len(prompt_augment_idx) != 1:
+ logging.error("❌ Unexpected number of prompt augment indices: %s", prompt_augment_idx)
+ logging.error("The inference_augment_idx: %s", inference_augment_idx)
+ logging.error("Batch size = %d, seq_len = %d", B, seq_len)
+
+ for b in range(B):
+ ids = input_ids[b].tolist()
+ labs = labels[b].tolist()
+ toks = tokenizer.convert_ids_to_tokens(ids)
+
+ logging.error("---- Sample %d ----", b)
+ logging.error("Decoded text:\n%s", tokenizer.decode(ids, skip_special_tokens=False))
+
+ vis = []
+ for t, l in zip(toks, labs):
+ tag = "MASK" if l == -100 else "LAB"
+ vis.append(f"{t}<{tag}>")
+
+ logging.error("Token-level view:\n%s", " ".join(vis))
+
+ boundaries = []
+ for i in range(1, seq_len):
+ if labs[i] != -100 and labs[i - 1] == -100:
+ boundaries.append(i)
+ logging.error("Detected prompt→label boundaries at positions: %s", boundaries)
+ raise ValueError("Single-turn forward must have exactly one prompt augment index")
+
+ final_points = prompt_augment_idx[:1]
+
+ # Limit the number of inference augmentation points to max_num
+ if len(inference_augment_idx) > max_num:
+ inference_augment_idx = inference_augment_idx[:max_num]
+
+ final_points.extend(inference_augment_idx)
+
+ if len(final_points) == 0:
+ raise RuntimeError("No valid augmentation points found")
+
+ final_points.sort()
+ return final_points
+
+ @torch.no_grad()
+ def _should_augment(
+ self,
+ input_ids: torch.LongTensor,
+ sentence_augment_count: torch.LongTensor,
+ do_sample: bool,
+ temperature: float,
+ is_prompt: bool = False
+ ) -> torch.LongTensor:
+
+ tokenizer = self.tokenizer
+ delimiters = self.delimiters
+ trigger = self.trigger
+ max_augment_num = self.config.max_inference_aug_num
+
+ batch_size = input_ids.size(0)
+
+ if is_prompt:
+ attention_mask = (input_ids != tokenizer.pad_token_id).long()
+ position_ids = self._generate_position_ids(attention_mask)
+ aug_vector = torch.zeros((batch_size,), dtype=torch.long, device=input_ids.device)
+ trigger_indices = (aug_vector != -100).nonzero(as_tuple=True)[0]
+
+ else:
+ attention_mask = (input_ids != tokenizer.pad_token_id).long()
+ position_ids = self._generate_position_ids(attention_mask)
+ aug_vector = torch.full((batch_size,), -100, dtype=torch.long, device=input_ids.device)
+ ends_with_delimiters = self._check_ends_with_delimiter(input_ids, tokenizer, delimiters).squeeze(1)
+ aug_vector[ends_with_delimiters] = 0
+ over_limit = (sentence_augment_count >= max_augment_num)
+ aug_vector[over_limit] = -100
+ trigger_indices = (aug_vector != -100).nonzero(as_tuple=True)[0]
+
+ if trigger_indices.numel() > 0:
+ trigger_logits = trigger(
+ input_ids=input_ids[trigger_indices],
+ attention_mask=attention_mask[trigger_indices],
+ position_ids=position_ids[trigger_indices]
+ )
+ last_token_logits = trigger_logits[:, -1] # [batch, 2]
+
+ next_tokens = self._get_next_token(
+ last_token_logits,
+ do_sample=do_sample,
+ temperature=temperature
+ ).view(-1)
+
+ aug_vector[trigger_indices] = next_tokens
+
+ return aug_vector
+
+
+ @torch.no_grad()
+ def _append_one_step(
+ self,
+ reasoner_outputs,
+ current_inputs_embeds: torch.Tensor,
+ current_attention_mask: torch.Tensor,
+ current_position_ids: torch.Tensor,
+ current_input_ids: torch.Tensor,
+ do_sample: bool,
+ temperature: float
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ B = current_inputs_embeds.size(0)
+
+ # Append next token
+ next_token_logits = reasoner_outputs.logits[:, -1]
+ next_token_ids = self._get_next_token(next_token_logits, do_sample=do_sample, temperature=temperature)
+ current_input_ids = torch.cat([current_input_ids, next_token_ids], dim=1)
+
+ # Append next token embeds
+ next_token_embeds = self.reasoner.get_input_embeddings()(next_token_ids)
+ current_inputs_embeds = torch.cat([current_inputs_embeds, next_token_embeds], dim=1)
+
+ # Append attention mask
+ attn_mask = torch.ones((B, 1), dtype=current_attention_mask.dtype, device=current_attention_mask.device)
+ current_attention_mask = torch.cat([current_attention_mask, attn_mask], dim=1)
+
+ # Append position ids
+ next_position_id = current_position_ids[:, -1:] + 1
+ current_position_ids = torch.cat([current_position_ids, next_position_id], dim=1)
+
+ return current_inputs_embeds, current_attention_mask, current_position_ids, current_input_ids
+
+
+ @torch.no_grad()
+ def _left_pad(
+ self,
+ input_embeds: torch.FloatTensor,
+ attention_mask: torch.LongTensor,
+ position_ids: torch.LongTensor,
+ pad_num: int
+ ) -> tuple[torch.FloatTensor, torch.LongTensor, torch.LongTensor]:
+
+ if input_embeds is not None:
+ B, L, D = input_embeds.shape
+ pad_embeds = torch.zeros((B, pad_num, D), dtype=input_embeds.dtype, device=input_embeds.device)
+ input_embeds = torch.cat([pad_embeds, input_embeds], dim=1) # [B, pad_num + L, D]
+
+ if attention_mask is not None:
+ B = attention_mask.size(0)
+ pad_mask = torch.zeros((B, pad_num), dtype=attention_mask.dtype, device=attention_mask.device)
+ attention_mask = torch.cat([pad_mask, attention_mask], dim=1) # [B, pad_num + L]
+
+ if position_ids is not None:
+ B = position_ids.size(0)
+ pad_pos = torch.zeros((B, pad_num), dtype=position_ids.dtype, device=position_ids.device)
+ position_ids = torch.cat([pad_pos, position_ids], dim=1) # [B, pad_num + L]
+
+ return input_embeds, attention_mask, position_ids
+
+ @torch.no_grad()
+ def _left_clip_pad_tokens(
+ self, inputs_embeds: torch.FloatTensor, attention_mask: torch.LongTensor, position_ids: torch.LongTensor
+ ) -> tuple[torch.FloatTensor, torch.LongTensor, torch.LongTensor]:
+
+ B, L, D = inputs_embeds.shape
+
+ # Find the index of the first non-padding token in each sequence
+ first_nonpad_idx = []
+ for b in range(B):
+ nonzero = (attention_mask[b] != 0).nonzero(as_tuple=True)[0]
+ if len(nonzero) == 0:
+ # Entire row is padding; can potentially trim the whole sequence
+ first_nonpad_idx.append(L)
+ else:
+ first_nonpad_idx.append(nonzero[0].item())
+
+ # Determine the minimum number of left-padding tokens across the batch
+ min_pad = min(first_nonpad_idx)
+
+ # If no padding on the left, return original tensors
+ if min_pad == 0:
+ return inputs_embeds, attention_mask, position_ids
+
+ # Trim the left-padding from all sequences in the batch
+ inputs_embeds = inputs_embeds[:, min_pad:, :]
+ attention_mask = attention_mask[:, min_pad:]
+ position_ids = position_ids[:, min_pad:]
+
+ return inputs_embeds, attention_mask, position_ids
+
+ @torch.no_grad()
+ def _check_generate(self, input_ids: torch.LongTensor, augmentation_pos: torch.LongTensor):
+ """检查 augmentation_pos[b][i] == 1 的位置, input_ids[b][:i] (不包括第 i 位) 对应的字符串是否以 delimiters 结尾
+ 仅在 DEBUG_MODE 下启用,避免训练时的性能开销
+ """
+ # 仅在 DEBUG 模式下执行验证,避免训练时的大量 decode 开销
+ if os.environ.get('DEBUG_MODE', '').lower() != 'true':
+ return
+
+ delimiters = self.delimiters
+ tokenizer = self.tokenizer
+
+ B, L = input_ids.shape
+ assert augmentation_pos.shape == input_ids.shape
+
+ for b in range(B):
+ for i in range(1, L):
+ is_augment_point = augmentation_pos[b, i].item()
+
+ if is_augment_point == -100:
+ continue
+
+ if is_augment_point == 1 or is_augment_point == 0:
+ prefix_input_ids = input_ids[b, :i].unsqueeze(0)
+
+ ends_with_delimiter = self._check_ends_with_delimiter(
+ prefix_input_ids, tokenizer, delimiters
+ ).item()
+
+ if not ends_with_delimiter:
+ decoded_prefix = tokenizer.decode(prefix_input_ids.squeeze(0), skip_special_tokens=False)
+
+ raise ValueError(
+ f"Augmentation position error at batch {b}, index {i}. "
+ f"augmentation_pos is 1, but the prefix does NOT end with a delimiter.\n"
+ f"Prefix: '...{decoded_prefix[-50:]}'\n"
+ f"Delimiters: {delimiters}"
+ )
+ else:
+ raise ValueError(
+ f"Invalid value in augmentation_pos at batch {b}, index {i}: {is_augment_point}. "
+ "Expected 1, 0, or -100."
+ )
diff --git a/MemGen-main/memgen/model/trigger.py b/MemGen-main/memgen/model/trigger.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf06560dc97cfe4417e40a1ddc0a502b4c64b1c7
--- /dev/null
+++ b/MemGen-main/memgen/model/trigger.py
@@ -0,0 +1,45 @@
+from peft import PeftModel
+import torch
+import torch.nn as nn
+
+
+class MemGenTrigger(nn.Module):
+ adapter_name = "trigger"
+
+ def __init__(
+ self,
+ model: PeftModel,
+ active: bool,
+ ):
+ super().__init__()
+
+ self.active = active
+ self.model = model
+ self.output_layer = nn.Linear(model.base_model.config.hidden_size, 2)
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: torch.LongTensor,
+ position_ids: torch.Tensor
+ ) -> torch.FloatTensor:
+
+ if self.active:
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_hidden_states=True,
+ )
+ hidden_states = outputs.hidden_states[-1]
+ logits = self.output_layer(hidden_states)
+
+ else:
+ batch_size, seq_len = input_ids.shape
+ logits = torch.zeros(batch_size, seq_len, 2, device=input_ids.device) # logits: [batch_size, seq_len, 2]
+ logits[..., 1] = 1.0
+
+ return logits
+
+
+
diff --git a/MemGen-main/memgen/model/weaver.py b/MemGen-main/memgen/model/weaver.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f907c5f222988ef6cc8a8e600fd2e9641a54d4f
--- /dev/null
+++ b/MemGen-main/memgen/model/weaver.py
@@ -0,0 +1,125 @@
+from peft import PeftModel
+import torch
+import torch.nn as nn
+
+
+class MemGenWeaver(nn.Module):
+
+ adapter_name = "weaver"
+
+ def __init__(
+ self,
+ model: PeftModel,
+ prompt_latents_len: int,
+ inference_latents_len: int,
+ ):
+ super().__init__()
+
+ self.model = model
+ hidden_size = model.base_model.config.hidden_size
+
+ # prompt augmentation
+ self.prompt_query_latents = nn.Parameter(
+ torch.randn(prompt_latents_len, hidden_size),
+ requires_grad=True
+ )
+
+ # inference augmentation
+ self.inference_query_latents = nn.Parameter(
+ torch.randn(inference_latents_len, hidden_size),
+ requires_grad=True
+ )
+
+ # latent normalization + scale
+ self.prompt_latent_ln = nn.LayerNorm(hidden_size)
+ self.inference_latent_ln = nn.LayerNorm(hidden_size)
+ self.prompt_latent_scale = nn.Parameter(torch.ones(1))
+ self.inference_latent_scale = nn.Parameter(torch.ones(1))
+
+ @property
+ def prompt_latents_num(self) -> int:
+ return self.prompt_query_latents.size(0)
+
+ @property
+ def inference_latents_num(self) -> int:
+ return self.inference_query_latents.size(0)
+
+ @property
+ def device(self):
+ assert self.prompt_query_latents.device == self.inference_query_latents.device
+ return self.prompt_query_latents.device
+
+ def _augment(
+ self,
+ latents: torch.Tensor,
+ latent_ln: nn.LayerNorm,
+ latent_scale: torch.Tensor,
+ inputs_embeds: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_ids: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+
+ batch_size = attention_mask.shape[0]
+ latents_num = latents.size(0)
+
+ # normalize + scale
+ latents = latent_ln(latents) * latent_scale
+ latents = latents.unsqueeze(0).repeat(batch_size, 1, 1)
+
+ # inputs_embeds
+ inputs_embeds = torch.cat([inputs_embeds, latents], dim=1)
+
+ # attention_mask: (B, L_total)
+ latents_mask = torch.ones(latents.shape[:-1], dtype=attention_mask.dtype, device=attention_mask.device)
+ attention_mask = torch.cat([attention_mask, latents_mask], dim=1)
+
+ # get position ids
+ last_position_ids = position_ids.max(dim=1)[0]
+ latents_relative_positions = torch.arange(latents_num, device=attention_mask.device)
+ latents_position_ids = last_position_ids.unsqueeze(1) + latents_relative_positions + 1
+ position_ids = torch.cat([position_ids.long(), latents_position_ids.long()], dim=1)
+
+ # the processor only outputs the hidden states
+ assert inputs_embeds.shape[:2] == attention_mask.shape == position_ids.shape
+
+ outputs = self.model(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_hidden_states=True,
+ )
+ hidden_states = outputs.hidden_states[-1]
+ latents_hidden_states = hidden_states[:, -latents_num:, :]
+
+ return latents_hidden_states, latents_mask, latents_position_ids
+
+ def augment_prompt(
+ self,
+ inputs_embeds: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_ids: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ return self._augment(
+ latents=self.prompt_query_latents,
+ latent_ln=self.prompt_latent_ln,
+ latent_scale=self.prompt_latent_scale,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ position_ids=position_ids
+ )
+
+
+ def augment_inference(
+ self,
+ inputs_embeds: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_ids: torch.Tensor
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ return self._augment(
+ latents=self.inference_query_latents,
+ latent_ln=self.inference_latent_ln,
+ latent_scale=self.inference_latent_scale,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ position_ids=position_ids
+ )
diff --git a/MemGen-main/memgen/runner.py b/MemGen-main/memgen/runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..de35642ed33069f37545b206dcd8dc8688e4f9f4
--- /dev/null
+++ b/MemGen-main/memgen/runner.py
@@ -0,0 +1,446 @@
+import os
+import random
+
+from accelerate import Accelerator
+from datasets import Dataset
+import torch
+from torch.utils.data import DataLoader
+from tqdm import tqdm
+from trl import SFTTrainer, SFTConfig, GRPOConfig
+from trl.models import unwrap_model_for_generation
+
+from data import (
+ BaseBuilder,
+)
+from interactions.base_interaction import (
+ InteractionConfig,
+ InteractionManager,
+ InteractionDataProto
+)
+from interactions.singleturn_interaction import SingleTurnInteractionManager
+from interactions.multiturn_interaction import MultiTurnInteractionManager
+
+from memgen.model.modeling_memgen import MemGenModel
+from memgen.trainer.weaver_grpo_trainer import WeaverGRPOTrainer
+from memgen.trainer.trigger_grpo_trainer import TriggerGRPOTrainer
+from memgen.utils import (
+ StaticEvalRecorder,
+ DynamicEvalRecorder,
+ create_tensorboard,
+ log_trainable_params,
+ gather_objects
+)
+
+
+class MemGenRunner:
+
+ def __init__(
+ self,
+ model: MemGenModel,
+ data_builder: BaseBuilder,
+ config: dict,
+ working_dir: str,
+ ):
+ # parse configs
+ self.config = config
+ self.working_dir = working_dir
+
+ self._parse_configs(config.get("run"))
+
+ # parse model
+ self.processing_class = model.tokenizer
+ self.model = model
+
+ # initialize envs and generation managers
+ self.dataset_dict = data_builder.get_dataset_dict()
+ self.env_cls = data_builder.get_env_cls()
+ self.env = self.env_cls(config.get("dataset"))
+
+ # partition datasets
+ self.weaver_train_dataset, self.trigger_train_dataset = self._parse_train_dataset(self.dataset_dict["train"])
+ self.weaver_valid_dataset, self.trigger_valid_dataset = self._parse_valid_dataset(self.dataset_dict["valid"])
+ self.test_dataset = self.dataset_dict["test"]
+
+ self.weaver_train_dataset = self._filter_dataset(self.weaver_train_dataset)
+ self.trigger_train_dataset = self._filter_dataset(self.trigger_train_dataset)
+ self.weaver_valid_dataset = self._filter_dataset(self.weaver_valid_dataset)
+ self.trigger_valid_dataset = self._filter_dataset(self.trigger_valid_dataset)
+
+ # initialize generation manager
+ if self.env_cls.ENV_CARD == "STATIC":
+ self.inter_cls = SingleTurnInteractionManager
+ elif self.env_cls.ENV_CARD == "DYNAMIC":
+ self.inter_cls = MultiTurnInteractionManager
+ else:
+ raise ValueError("Unsupported environment type.")
+
+ self.generation_manager: InteractionManager = self.inter_cls(
+ self.processing_class, self.model, self.interaction_config
+ )
+
+ def _parse_train_dataset(self, train_dataset: Dataset) -> tuple[Dataset, Dataset]:
+ # use half size of the datatset to train the trigger
+ trigger_trainset_size = min(len(train_dataset) // 3, len(train_dataset))
+ rand_indices = random.sample(range(len(train_dataset)), trigger_trainset_size)
+ return train_dataset, train_dataset.select(rand_indices)
+
+ def _parse_valid_dataset(self, valid_dataset: Dataset) -> tuple[Dataset, Dataset]:
+
+ trigger_validset_size = min(len(valid_dataset) // 3, len(valid_dataset))
+ rand_indices = random.sample(range(len(valid_dataset)), trigger_validset_size)
+ return valid_dataset, valid_dataset.select(rand_indices)
+
+ def _filter_dataset(self, dataset: Dataset) -> Dataset:
+ tokenizer = self.processing_class
+
+ # Determine max length based on training mode
+ max_len = 1024
+ if self.train_weaver and self.train_weaver_method == "sft":
+ max_len = self.weaver_sft_training_args.max_length
+ elif self.train_weaver and self.train_weaver_method == "grpo":
+ max_len = self.weaver_grpo_training_args.max_prompt_length
+ elif self.train_trigger and self.train_trigger_method == "grpo":
+ max_len = self.trigger_grpo_training_args.max_prompt_length
+ else:
+ raise ValueError("Wrong training mode.")
+
+ # Function to filter out samples exceeding max length
+ def filter_func(sample):
+ if "prompt" in sample and sample["prompt"] is not None:
+ prompt = tokenizer.apply_chat_template(sample["prompt"], tokenize=True)
+ return len(prompt) < max_len
+ elif "messages" in sample and sample["messages"] is not None:
+ conversation = tokenizer.apply_chat_template(sample["messages"][:2], tokenize=True)
+ return len(conversation) < max_len
+ return True
+
+ # Apply filtering
+ dataset = dataset.filter(filter_func)
+
+ return dataset
+
+ # ===== train weaver =====
+ def _create_weaver_trainer(self):
+
+ # SFT Trainer
+ if self.train_weaver_method == "sft":
+
+ weaver_trainer = SFTTrainer(
+ model=self.model,
+ args=self.weaver_sft_training_args,
+ train_dataset=self.weaver_train_dataset,
+ eval_dataset=self.weaver_valid_dataset,
+ processing_class=self.processing_class,
+ )
+
+ # GRPO Trainer
+ elif self.train_weaver_method == 'grpo':
+ self.weaver_grpo_training_args.do_eval = False
+ self.weaver_grpo_training_args.eval_strategy = 'no'
+ self.generation_manager.generation_config.weaver_do_sample = True
+ self.generation_manager.generation_config.trigger_do_sample = False
+ self.generation_manager.generation_config.temperature = self.weaver_grpo_training_args.temperature
+ self.generation_manager.generation_config.max_new_tokens = self.weaver_grpo_training_args.max_completion_length
+
+ # self.weaver_train_dataset = self.weaver_train_dataset.select(range(1600))
+
+ weaver_trainer = WeaverGRPOTrainer(
+ model=self.model,
+ reward_funcs=[self.env_cls.compute_reward],
+ args=self.weaver_grpo_training_args,
+ train_dataset=self.weaver_train_dataset,
+ eval_dataset=self.weaver_valid_dataset,
+ processing_class=self.processing_class,
+ # --- add env into trainer ---
+ env_class=self.env_cls,
+ env_main_config=self.config.get("dataset"),
+ generation_manager=self.generation_manager,
+ )
+ else:
+ raise ValueError("Unsupported weaver training method.")
+
+ return weaver_trainer
+
+ # ===== train trigger =====
+ def _create_trigger_trainer(self):
+
+ if self.train_trigger_method == "grpo":
+ self.trigger_grpo_training_args.do_eval = False
+ self.trigger_grpo_training_args.eval_strategy = 'no'
+
+ self.generation_manager.generation_config.trigger_do_sample = True
+ self.generation_manager.generation_config.weaver_do_sample = False
+ self.generation_manager.generation_config.temperature = self.weaver_grpo_training_args.temperature
+ self.generation_manager.generation_config.max_new_tokens = self.weaver_grpo_training_args.max_completion_length
+
+ trigger_trainer = TriggerGRPOTrainer(
+ model=self.model,
+ processing_class=self.processing_class,
+ train_dataset=self.trigger_train_dataset,
+ eval_dataset=self.trigger_valid_dataset,
+ reward_funcs=[self.env_cls.compute_reward],
+ args=self.trigger_grpo_training_args
+ )
+ else:
+ raise ValueError("Unsupported trigger training method.")
+
+ return trigger_trainer
+
+ # ===== train weaver/trigger =====
+ def train(self):
+
+ if self.train_weaver:
+ trainer = self._create_weaver_trainer()
+ self.model.fix_component('trigger')
+
+ if self.train_trigger:
+ trainer = self._create_trigger_trainer()
+ self.model.fix_component('weaver')
+
+ log_trainable_params(self.model)
+
+ try:
+ trainer.train()
+ trainer.save_model()
+ except RuntimeError as e:
+ # 检查是否是 OOM 相关的错误
+ if "OOM" in str(e) or "out of memory" in str(e).lower():
+ logging.error(f"[Runner] Training stopped due to OOM: {e}")
+ # 尝试最后一次保存
+ try:
+ oom_dir = os.path.join(self.working_dir, "model_oom_final")
+ logging.info(f"[Runner] Attempting to save final checkpoint to {oom_dir}")
+ trainer.save_model(oom_dir)
+ logging.info(f"[Runner] Final checkpoint saved successfully")
+ except Exception as save_e:
+ logging.error(f"[Runner] Failed to save final checkpoint: {save_e}")
+ raise
+ else:
+ # 非 OOM 错误,直接抛出
+ raise
+
+
+ # ===== evaluate =====
+ def evaluate(self):
+ self.model = self.model.to(torch.bfloat16)
+
+ evaluate_func_mapping = {
+ "STATIC": self._static_evaluate,
+ "DYNAMIC": self._dynamic_evaluate
+ }
+ evaluate_func = evaluate_func_mapping.get(self.env.ENV_CARD)
+ if evaluate_func is None:
+ raise ValueError("The env has unrecogonized ENV_CARD attribute")
+
+ return evaluate_func()
+
+ def _static_evaluate(self):
+
+ accelerator = Accelerator()
+
+ if accelerator.is_main_process:
+ writer = create_tensorboard(save_dir=self.working_dir)
+ save_file = os.path.join(self.interaction_config.output_dir, "answer.json")
+ recorder = StaticEvalRecorder(
+ compute_metrics=[self.env_cls.compute_reward],
+ writer=writer,
+ log_file=save_file
+ )
+ else:
+ writer = None
+ recorder = None
+
+ batch_size = self.interaction_config.batch_size
+
+ test_dataloader = accelerator.prepare(DataLoader(
+ dataset=self.test_dataset,
+ batch_size=batch_size,
+ shuffle=False,
+ collate_fn=lambda batch: batch
+ ))
+
+ model_wrapped = accelerator.prepare_model(model=self.model, evaluation_mode=True)
+ model_wrapped.eval()
+
+ for test_batch in tqdm(test_dataloader, disable=not accelerator.is_main_process):
+ with unwrap_model_for_generation(model_wrapped, accelerator) as unwrapped_model:
+ prompts = [x["prompt"] for x in test_batch]
+ prompt_inputs = self.processing_class.apply_chat_template(
+ prompts,
+ add_generation_prompt=True,
+ return_tensors="pt",
+ padding=True,
+ padding_side="left",
+ add_special_tokens=True,
+ return_dict=True
+ )
+ prompt_ids, prompt_mask = prompt_inputs["input_ids"], prompt_inputs["attention_mask"]
+ gen_batch = InteractionDataProto()
+ gen_batch.batch["input_ids"] = prompt_ids.to(accelerator.device)
+ gen_batch.batch["attention_mask"] = prompt_mask.to(accelerator.device)
+ gen_batch.no_tensor_batch["initial_prompts"] = prompts
+
+ self.generation_manager.actor_rollout_wg = unwrapped_model
+ gen_output = self.generation_manager.run_agent_loop(gen_batch)
+
+ completion_ids = gen_output.batch["responses"]
+ completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
+
+ # only main rank can write the json
+ local_completions = completions
+ local_batches = test_batch
+
+ all_completions = gather_objects(local_completions)
+ all_batches = gather_objects(local_batches)
+
+ if accelerator.is_main_process:
+ for comps, batch in zip(all_completions, all_batches):
+ recorder.record_batch(comps, batch)
+
+ accelerator.wait_for_everyone()
+
+ if accelerator.is_main_process:
+ recorder.finalize()
+ writer.close()
+
+ def _dynamic_evaluate(self):
+
+ def _set_batch_envs(batch: list) -> tuple[list[str], list[str], list]: # batch set envs
+ system_prompts, init_user_prompts, envs = [], [], []
+ for task_config in batch:
+ env = self.env_cls(self.config.get("dataset"))
+ system_prompt, init_user_prompt = env.set_env(task_config)
+
+ system_prompts.append(system_prompt)
+ init_user_prompts.append(init_user_prompt)
+ envs.append(env)
+
+ return system_prompts, init_user_prompts, envs
+
+ def _build_data_proto(
+ system_prompts: list[str], init_user_prompts: list[str], envs: list
+ ) -> InteractionDataProto:
+ messages = []
+ for system_prmopt, init_user_prompt in zip(system_prompts, init_user_prompts):
+ system_message = {"role": "system", "content": system_prmopt}
+ user_message = {"role": "user", "content": init_user_prompt}
+ init_messages = [system_message, user_message]
+ messages.append(init_messages)
+
+ data_proto = InteractionDataProto()
+ data_proto.no_tensor_batch["init_prompts"] = messages
+ data_proto.no_tensor_batch["envs"] = envs
+
+ return data_proto
+
+ # ===== body =====
+ accelerator = Accelerator()
+
+ if accelerator.is_main_process:
+ writer = create_tensorboard(save_dir=self.working_dir)
+ save_file = os.path.join(self.interaction_config.output_dir, "conversations.txt")
+ recorder = DynamicEvalRecorder(writer=writer, log_file=save_file)
+ else:
+ writer = None
+ recorder = None
+
+ batch_size = self.interaction_config.batch_size
+
+ # prepare dataset and dataloader
+ test_dataloader = accelerator.prepare(DataLoader(
+ dataset=self.test_dataset,
+ batch_size=batch_size,
+ shuffle=False,
+ collate_fn=lambda batch: batch # use the identity function
+ ))
+
+ # prepare model
+ model_wrapped = accelerator.prepare_model(model=self.model, evaluation_mode=True)
+ model_wrapped.eval()
+
+ # batch generate
+ for step, test_batch in tqdm(enumerate(test_dataloader), desc="Evaluation"):
+ with unwrap_model_for_generation(
+ model_wrapped, accelerator
+ ) as unwrapped_model:
+ system_prompts, init_user_prompts, envs = _set_batch_envs(test_batch)
+ input_data_proto = _build_data_proto(system_prompts, init_user_prompts, envs)
+
+ self.generation_manager.actor_rollout_wg = unwrapped_model
+ outputs: InteractionDataProto = self.generation_manager.run_agent_loop(input_data_proto)
+
+ inter_histories = outputs.no_tensor_batch["inter_histories"]
+ inter_context = self.processing_class.apply_chat_template(inter_histories, tokenize=False)
+
+ # calculate batch rewards
+ rewards = []
+ for env in input_data_proto.no_tensor_batch["envs"]:
+ reward = env.feedback()
+ rewards.append(reward)
+
+ all_contexts = gather_objects(inter_context)
+ all_rewards = gather_objects(rewards)
+
+ if accelerator.is_main_process:
+ for conts, rs in zip(all_contexts, all_rewards):
+ recorder.record_batch(conts, rs)
+
+ accelerator.wait_for_everyone()
+
+ if accelerator.is_main_process:
+ recorder.finalize()
+ writer.close()
+
+ def _parse_configs(self, configs):
+
+ self.train_weaver = configs.get("train_weaver", True)
+ self.train_trigger = configs.get("train_trigger", False)
+
+ # --- Parse weaver training args ---
+ self.train_weaver_method = configs.get("train_weaver_method", "sft")
+ if self.train_weaver_method not in ["sft", "grpo"]:
+ raise ValueError("Unsupported weaver training method.")
+
+ # parse weaver sft training args
+ weaver_config = configs.get("weaver", dict())
+ weaver_sft_config = weaver_config.get("sft", dict())
+ self.weaver_sft_training_args = SFTConfig(**weaver_sft_config)
+
+ # parse weaver grpo training args
+ weaver_grpo_config = weaver_config.get("grpo", dict())
+ self.weaver_grpo_training_args = GRPOConfig(**weaver_grpo_config)
+
+ # --- Parse trigger training args ---
+ trigger_config = configs.get("trigger", dict())
+ self.train_trigger_method = configs.get("train_trigger_method", "grpo")
+ if self.train_trigger_method not in ["grpo"]:
+ raise ValueError("Unsupported trigger training method.")
+
+ trigger_grpo_config = trigger_config.get("grpo", dict())
+ self.trigger_grpo_training_args = GRPOConfig(**trigger_grpo_config)
+
+ # --- update training args ---
+ updated_args = {
+ "output_dir": os.path.join(self.working_dir, "model"),
+ "logging_dir": os.path.join(self.working_dir, "run"),
+ "save_strategy": "no"
+ }
+ for k, v in updated_args.items():
+ setattr(self.weaver_sft_training_args, k, v)
+ setattr(self.weaver_grpo_training_args, k, v)
+ setattr(self.trigger_grpo_training_args, k, v)
+
+ # --- parse interaction args ---
+ interaction_configs = configs.get("interaction", {})
+ self.interaction_config = InteractionConfig(
+ max_turns=interaction_configs.get("max_turns", 30),
+ max_start_length=interaction_configs.get("max_start_length", 1024),
+ max_prompt_length=interaction_configs.get("max_prompt_length", 4096),
+ max_response_length=interaction_configs.get("max_response_length", 512),
+ max_obs_length=interaction_configs.get("max_obs_length", 512),
+ temperature=interaction_configs.get("temperature", 0.0),
+ batch_size=interaction_configs.get("batch_size", 32),
+ output_dir=os.path.join(self.working_dir, "evaluate"),
+ weaver_do_sample=interaction_configs.get("weaver_do_sample", False),
+ trigger_do_sample=interaction_configs.get("trigger_do_sample", False),
+ )
\ No newline at end of file
diff --git a/MemGen-main/memgen/trainer/__init__.py b/MemGen-main/memgen/trainer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/MemGen-main/memgen/trainer/trigger_grpo_trainer.py b/MemGen-main/memgen/trainer/trigger_grpo_trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b08cfebabbb6f4d17478d81ed983773158313809
--- /dev/null
+++ b/MemGen-main/memgen/trainer/trigger_grpo_trainer.py
@@ -0,0 +1,390 @@
+from trl import GRPOTrainer, GRPOConfig
+from trl.data_utils import maybe_apply_chat_template
+from trl.models import unwrap_model_for_generation, create_reference_model
+from trl.trainer.utils import selective_log_softmax
+from transformers import (
+ PreTrainedModel,
+ PreTrainedTokenizerBase,
+ TrainerCallback
+)
+from peft import PeftConfig
+
+from typing import Union, Callable, Optional, Any
+from contextlib import nullcontext
+import torch
+from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+from torch.utils.data import Dataset
+from accelerate.utils import gather_object
+
+from interactions.base_interaction import InteractionDataProto
+from interactions.tensor_utils import TensorHelper, TensorConfig
+
+from memgen.trainer.utils import (
+ nanstd,
+ nanmax,
+ nanmin,
+ generate_position_ids
+)
+from memgen.model.modeling_memgen import MemGenModel
+
+RewardFunc = Union[str, PreTrainedModel, Callable[[list, list], list[float]]]
+
+class TriggerGRPOTrainer(GRPOTrainer):
+ def __init__(
+ self,
+ model: MemGenModel,
+ processing_class: PreTrainedTokenizerBase,
+ train_dataset: Dataset,
+ eval_dataset: Dataset,
+ reward_funcs: Union[RewardFunc, list[RewardFunc]],
+ reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None,
+ args: Optional[GRPOConfig] = None,
+ callbacks: Optional[list[TrainerCallback]] = None,
+ optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
+ peft_config: Optional[PeftConfig] = None,
+ ):
+ # NOTE - Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
+ # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
+ # self.model_accepts_loss_kwargs to False to enable scaling.
+ self.model_accepts_loss_kwargs = False
+
+ super().__init__(
+ model=model,
+ args=args,
+ reward_funcs=reward_funcs,
+ reward_processing_classes=reward_processing_classes,
+ train_dataset=train_dataset,
+ eval_dataset=eval_dataset,
+ processing_class=processing_class,
+ callbacks=callbacks,
+ optimizers=optimizers,
+ peft_config=peft_config
+ )
+
+ # If PEFT configuration is not provided, create a reference model based on the initial model.
+ ref_model = create_reference_model(model.trigger)
+ self.ref_model = self.accelerator.prepare_model(ref_model, evaluation_mode=True)
+ self.tensor_fn = TensorHelper(TensorConfig(
+ pad_token_id=self.processing_class.pad_token_id,
+ max_prompt_length=self.max_prompt_length,
+ max_obs_length=None,
+ max_start_length=None
+ ))
+
+ def _set_signature_columns_if_needed(self):
+ # NOTE - If `self.args.remove_unused_columns` is True, non-signature columns are removed.
+ # By default, this method sets `self._signature_columns` to the model's expected inputs.
+ # In LatentProcessorSFTTrainer, we preprocess data, so using the model's signature columns doesn't work.
+ # Instead, we set them to the columns expected by the `training_step` method, hence the override.
+ pass
+
+ def _get_per_token_logps(
+ self,
+ model,
+ input_ids: torch.LongTensor,
+ attention_mask: torch.LongTensor,
+ augmentation_mask: torch.LongTensor
+ ) -> torch.Tensor:
+ prompt_len = attention_mask.size(1) - augmentation_mask.size(1)
+
+ assert input_ids.shape == attention_mask.shape
+ position_ids = generate_position_ids(attention_mask)
+ augmentation_logits = model.trigger(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids
+ )
+ clipped_logits = augmentation_logits[:, prompt_len - 1 : -1]
+ assert clipped_logits.shape[:-1] == augmentation_mask.shape
+
+ temp_mask = augmentation_mask.clone()
+ augmentation_valid_mask = (temp_mask == -100).clone()
+
+ temp_mask[augmentation_valid_mask] = 0
+ logps = selective_log_softmax(clipped_logits, temp_mask)
+ logps[augmentation_valid_mask] = 0
+
+ return logps
+
+ def _generate_and_score_completions(
+ self, inputs: list[dict[str, Union[torch.Tensor, Any]]]
+ ) -> dict[str, Union[torch.Tensor, Any]]:
+
+ device = self.accelerator.device
+ mode = "train" if self.model.training else "eval"
+
+ prompts = [x["prompt"] for x in inputs]
+ invalid_augmentation_id = -100
+
+ # modified: pop those keys for generation
+ batch_gen_keys = []
+ if "prompt" in inputs[0]: # text-based raw prompt
+ batch_gen_keys.append("prompt")
+ if "tools_kwargs" in inputs[0]: # tool-integrated
+ batch_gen_keys.append("tools_kwargs")
+ if "interaction_kwargs" in inputs[0]: # interaction args
+ batch_gen_keys.append("interaction_kwargs")
+ if "agent_name" in inputs[0]: # agent name
+ batch_gen_keys.append("agent_name")
+ if "env" in inputs[0]:
+ batch_gen_keys.append("env")
+
+ # build generation batch
+ gen_batch = InteractionDataProto()
+ for key in batch_gen_keys:
+ gen_batch.no_tensor_batch[key] = [x[key] for x in inputs]
+
+ prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
+ prompt_inputs = self.processing_class(
+ text=prompts_text, return_tensors="pt", padding=True, padding_side="left", add_special_tokens=False
+ )
+
+ prompt_ids, prompt_mask = prompt_inputs["input_ids"], prompt_inputs["attention_mask"]
+ if self.max_prompt_length is not None:
+ prompt_ids = prompt_ids[:, -self.max_prompt_length :]
+ prompt_mask = prompt_mask[:, -self.max_prompt_length :]
+
+ gen_batch.batch["input_ids"] = prompt_ids.to(device)
+ gen_batch.batch["attention_mask"] = prompt_mask.to(device)
+
+ # Regular generation path
+ with unwrap_model_for_generation(
+ self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
+ ) as unwrapped_model:
+ with (
+ FSDP.summon_full_params(self.model_wrapped, recurse=False)
+ if self.is_fsdp_enabled
+ else nullcontext()
+ ):
+ prompt_ids = gen_batch.batch["input_ids"]
+ prompt_mask = gen_batch.batch["attention_mask"]
+ prompt_completion_ids, augmentation_mask = unwrapped_model.generate(
+ prompt_ids, prompt_mask, generation_config=self.generation_config, return_augmentation_mask=True
+ )
+ # Compute prompt length and extract completion ids
+ prompt_length = prompt_ids.size(1)
+ prompt_ids = prompt_completion_ids[:, :prompt_length]
+ completion_ids = prompt_completion_ids[:, prompt_length:]
+ assert completion_ids.shape == augmentation_mask.shape
+
+ # Mask everything after the first EOS token
+ is_eos = completion_ids == self.processing_class.eos_token_id
+ eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
+ eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
+ sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
+ completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
+ completion_ids = torch.where(
+ completion_mask.bool(),
+ completion_ids,
+ torch.full_like(completion_ids, self.processing_class.eos_token_id)
+ )
+
+ augmentation_valid_mask = completion_mask * (augmentation_mask != invalid_augmentation_id)
+ augmentation_mask = torch.where(
+ augmentation_valid_mask.bool(),
+ augmentation_mask,
+ torch.full_like(augmentation_mask, invalid_augmentation_id)
+ )
+
+ # If a truncation-based output strategy is used,
+ # then for any sequence that has not generated an EOS token, its loss will be ignored during computation.
+ if self.mask_truncated_completions:
+ truncated_completions = ~is_eos.any(dim=1)
+ completion_mask = completion_mask * (~truncated_completions).unsqueeze(1).int()
+
+ # Concatenate prompt_mask with completion_mask for logit computation
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P + C)
+
+ with torch.no_grad():
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
+ # old_per_token_logps == per_token_logps, so we can skip it's computation here, and use
+ # per_token_logps.detach() instead.
+ if self.num_iterations > 1 or self.args.steps_per_generation > self.args.gradient_accumulation_steps:
+ old_per_token_logps = self._get_per_token_logps(
+ self.model.trigger, prompt_completion_ids, attention_mask, augmentation_mask
+ )
+ else:
+ old_per_token_logps = None
+
+ # Compute the per-token log probabilities for the reference model
+ if self.beta != 0.0:
+ if self.ref_model is not None:
+ ref_per_token_logps = self._get_per_token_logps(
+ self.ref_model, prompt_completion_ids, attention_mask, augmentation_mask
+ )
+ else:
+ with self.accelerator.unwrap_model(self.model).disable_adapter():
+ ref_per_token_logps = self._get_per_token_logps(
+ self.model.trigger, prompt_completion_ids, attention_mask, augmentation_mask
+ )
+ else:
+ ref_per_token_logps = None
+
+ # Decode the generated completions
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
+ completions = completions_text
+
+ for i in range(len(inputs)):
+ inputs[i]["augmentation_mask"] = augmentation_mask[i]
+
+ # Convert tensor to a list of lists of token IDs. This will be passed to the reward function, avoiding the need
+ # to re-tokenize completions if the reward is computed from tokens.
+ completion_ids_list = [
+ [id.item() for id, m in zip(row, mask_row) if m] for row, mask_row in zip(completion_ids, completion_mask)
+ ]
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
+
+ # Apply weights to each reward function's output and sum
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
+
+ # Compute grouped-wise rewards
+ mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
+ std_grouped_rewards = rewards.view(-1, self.num_generations).std(dim=1)
+ is_std_zero = torch.isclose(std_grouped_rewards, torch.zeros_like(std_grouped_rewards))
+
+ # Normalize the rewards to compute the advantages
+ mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
+ std_grouped_rewards = std_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
+ advantages = rewards - mean_grouped_rewards
+ if self.scale_rewards:
+ advantages = advantages / (std_grouped_rewards + 1e-4)
+
+ # Slice to keep only the local part of the data
+ process_slice = slice(
+ self.accelerator.process_index * len(prompts),
+ (self.accelerator.process_index + 1) * len(prompts),
+ )
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
+ advantages = advantages[process_slice]
+
+ # Log the metrics
+ if mode == "train":
+ self.state.num_input_tokens_seen += self.accelerator.gather(attention_mask.sum()).sum().item()
+ self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
+
+ # Log completion lengths, mean, min, max
+ completion_lengths = completion_mask.sum(1)
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
+
+ # Log augmentation lengths, mean, min, max
+ augmentation_lengths = (augmentation_mask == 1).sum(dim=1)
+ agg_augmentation_lengths = self.accelerator.gather(augmentation_lengths)
+ self._metrics[mode]["augmentations/mean_length"].append(agg_augmentation_lengths.float().mean().item())
+ self._metrics[mode]["augmentations/min_length"].append(agg_augmentation_lengths.float().min().item())
+ self._metrics[mode]["augmentations/max_length"].append(agg_augmentation_lengths.float().max().item())
+
+ # Identify sequences that terminated with EOS and log their lengths
+ agg_terminated_with_eos = self.accelerator.gather(is_eos.any(dim=1))
+ term_completion_lengths = agg_completion_lengths[agg_terminated_with_eos]
+ clipped_completions_ratio = 1 - len(term_completion_lengths) / len(agg_completion_lengths)
+ self._metrics[mode]["completions/clipped_ratio"].append(clipped_completions_ratio)
+ if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found
+ term_completion_lengths = torch.zeros(1, device=device)
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
+
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
+ for i, reward_func_name in enumerate(self.reward_func_names):
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
+ std_rewards = nanstd(rewards_per_func[:, i]).item()
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_rewards)
+ self._metrics[mode]["reward"].append(mean_grouped_rewards.mean().item())
+ self._metrics[mode]["reward_std"].append(std_grouped_rewards.mean().item())
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
+
+ # Log prompt and completion texts
+ self._logs["prompt"].extend(gather_object(prompts_text))
+ self._logs["completion"].extend(gather_object(completions_text))
+ for i, name in enumerate(self.reward_func_names):
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
+ self._logs["advantages"].extend(all_process_advantages.tolist())
+
+ return {
+ "prompt_ids": prompt_ids,
+ "prompt_mask": prompt_mask,
+ "completion_ids": completion_ids,
+ "completion_mask": completion_mask,
+ "augmentation_mask": augmentation_mask,
+ "advantages": advantages,
+ "old_per_token_logps": old_per_token_logps,
+ "ref_per_token_logps": ref_per_token_logps,
+ }
+
+ def _compute_loss(self, model, inputs):
+ # Compute the per-token log probabilities for the model
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
+ augmentation_mask = inputs["augmentation_mask"]
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
+
+ per_token_logps = self._get_per_token_logps(model, input_ids, attention_mask, augmentation_mask)
+
+ # Compute the KL divergence between the model and the reference model
+ if self.beta != 0.0:
+ ref_per_token_logps = inputs["ref_per_token_logps"]
+ per_token_kl = (
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
+ )
+
+ # Compute the loss
+ advantages = inputs["advantages"]
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
+ # old_per_token_logps == per_token_logps, so we can skip it's computation
+ # (see _generate_and_score_completions) and use per_token_logps.detach() instead.
+ old_per_token_logps = (
+ per_token_logps.detach() if inputs["old_per_token_logps"] is None else inputs["old_per_token_logps"]
+ )
+ coef_1 = torch.exp(per_token_logps - old_per_token_logps)
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
+
+ # Two-sided clipping
+ if self.args.delta is not None:
+ coef_1 = torch.clamp(coef_1, max=self.args.delta)
+
+ per_token_loss1 = coef_1 * advantages.unsqueeze(1)
+ per_token_loss2 = coef_2 * advantages.unsqueeze(1)
+ per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
+ if self.beta != 0.0:
+ per_token_loss = per_token_loss + self.beta * per_token_kl
+
+ augmentation_valid_mask = (augmentation_mask != -100)
+ if self.loss_type == "grpo":
+ loss = ((per_token_loss * augmentation_valid_mask).sum(-1) / augmentation_valid_mask.sum(-1).clamp(min=1.0)).mean()
+ elif self.loss_type == "bnpo":
+ loss = (per_token_loss * augmentation_valid_mask).sum() / augmentation_valid_mask.sum().clamp(min=1.0)
+ elif self.loss_type == "dr_grpo":
+ loss = (per_token_loss * augmentation_valid_mask).sum() / (augmentation_valid_mask.size(0) * self.max_completion_length)
+ else:
+ raise ValueError(f"Unknown loss type: {self.loss_type}")
+
+ # Log the metrics
+ mode = "train" if self.model.training else "eval"
+
+ if self.beta != 0.0:
+ mean_kl = (per_token_kl * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
+
+ # Compute the clipped probability ratios
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0)
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0)
+ is_region_clipped = is_low_clipped | is_high_clipped
+
+ low_clip = (is_low_clipped * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
+ high_clip = (is_high_clipped * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
+ clip_ratio = (is_region_clipped * augmentation_valid_mask).sum() / augmentation_valid_mask.sum()
+
+ gathered_low_clip = self.accelerator.gather(low_clip)
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
+ gathered_high_clip = self.accelerator.gather(high_clip)
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
+ gathered_clip_ratio = self.accelerator.gather(clip_ratio)
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
+ return loss
\ No newline at end of file
diff --git a/MemGen-main/memgen/trainer/utils.py b/MemGen-main/memgen/trainer/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c4e7d509b653f15b4471ab69c9550923515c6c9
--- /dev/null
+++ b/MemGen-main/memgen/trainer/utils.py
@@ -0,0 +1,52 @@
+import torch
+
+# torch.nanstd doesn't exist, so we define it here
+def nanstd(tensor: torch.Tensor) -> torch.Tensor:
+ """
+ Compute the standard deviation of a tensor, ignoring NaNs. This function only supports 1D tensors.
+
+ Args:
+ tensor (`torch.Tensor`):
+ Input tensor of shape `(N,)`.
+
+ Returns:
+ `torch.Tensor`:
+ Standard deviation of the tensor, ignoring NaNs.
+ """
+ variance = torch.nanmean((tensor - torch.nanmean(tensor, keepdim=True)) ** 2) # Compute variance ignoring NaNs
+ count = torch.sum(~torch.isnan(tensor)) # Count of non-NaN values
+ variance *= count / (count - 1) # Bessel's correction
+ return torch.sqrt(variance)
+
+def nanmax(tensor: torch.Tensor) -> torch.Tensor:
+ """
+ Compute the maximum value of a tensor, ignoring NaNs. This function only supports 1D tensors.
+
+ Args:
+ tensor (`torch.Tensor`): Input tensor of shape `(N,)`.
+
+ Returns:
+ `torch.Tensor`: Maximum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN.
+ """
+ if torch.isnan(tensor).all():
+ return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device)
+ return torch.max(tensor[~torch.isnan(tensor)])
+
+def nanmin(tensor: torch.Tensor) -> torch.Tensor:
+ """
+ Compute the minimum value of a tensor, ignoring NaNs. This function only supports 1D tensors.
+
+ Args:
+ tensor (`torch.Tensor`): Input tensor of shape `(N,)`.
+
+ Returns:
+ `torch.Tensor`: Minimum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN.
+ """
+ if torch.isnan(tensor).all():
+ return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device)
+ return torch.min(tensor[~torch.isnan(tensor)])
+
+def generate_position_ids(attention_mask):
+ position_ids = (attention_mask.cumsum(-1) - 1).clamp(min=0)
+ position_ids.masked_fill_(attention_mask == 0, 0)
+ return position_ids
\ No newline at end of file
diff --git a/MemGen-main/memgen/trainer/weaver_grpo_trainer.py b/MemGen-main/memgen/trainer/weaver_grpo_trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b9ae280ab6c0b975b50a669d9ee5b7c8d5d9c01
--- /dev/null
+++ b/MemGen-main/memgen/trainer/weaver_grpo_trainer.py
@@ -0,0 +1,466 @@
+from contextlib import nullcontext
+import logging
+import os
+from typing import Any, Callable, Optional, Union
+
+import torch
+from accelerate.utils import gather_object
+from datasets import Dataset, IterableDataset
+from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+from transformers import (
+ PreTrainedModel,
+ PreTrainedTokenizerBase,
+ ProcessorMixin,
+ TrainerCallback,
+)
+from transformers.utils import is_peft_available
+from trl import GRPOTrainer, GRPOConfig
+from trl.trainer.utils import selective_log_softmax
+from trl.data_utils import maybe_apply_chat_template
+from trl.models import unwrap_model_for_generation
+if is_peft_available():
+ from peft import PeftConfig
+
+from interactions.base_interaction import (
+ InteractionManager, InteractionDataProto
+)
+from data.base_env import StaticEnv, DynamicEnv
+
+from .utils import (
+ nanstd, nanmax, nanmin
+)
+from ..model.modeling_memgen import MemGenModel
+
+# What we call a reward function is a callable that takes a list of prompts and completions and returns a list of
+# rewards. When it's a string, it's a model ID, so it's loaded as a pretrained model.
+RewardFunc = Union[str, PreTrainedModel, Callable[[list, list], list[float]]]
+
+class WeaverGRPOTrainer(GRPOTrainer):
+
+ def __init__(
+ self,
+ model: MemGenModel,
+ reward_funcs: Union[RewardFunc, list[RewardFunc]],
+ args: Optional[GRPOConfig] = None,
+ train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
+ eval_dataset: Optional[Union[Dataset, IterableDataset, dict[str, Union[Dataset, IterableDataset]]]] = None,
+ processing_class: Optional[Union[PreTrainedTokenizerBase, ProcessorMixin]] = None,
+ reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None,
+ callbacks: Optional[list[TrainerCallback]] = None,
+ optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
+ peft_config: Optional["PeftConfig"] = None,
+ env_class = None, # env main class
+ env_main_config = None, # configs to initialize an env object
+ generation_manager: InteractionManager = None # manage the interaction between agent and env
+ ):
+ super().__init__(
+ model,
+ reward_funcs,
+ args,
+ train_dataset,
+ eval_dataset,
+ processing_class,
+ reward_processing_classes,
+ callbacks,
+ optimizers,
+ peft_config
+ )
+
+ self.env_class = env_class
+ self.env_main_config = env_main_config
+ self.generation_manager = generation_manager
+
+ self.generation_manager.config.max_prompt_length
+
+ # assert self.max_prompt_length == generation_manager.config.max_start_length
+ # assert self.max_completion_length == generation_manager.config.max_response_length
+ # assert self.temperature == generation_manager.config.temperature
+
+ def _build_multiturn_envs(self, inputs: list[dict[str, Union[torch.Tensor, Any]]]) -> tuple[list[list[dict]], list]:
+ init_messages, envs = [], []
+
+ for task_config in inputs:
+ env: DynamicEnv = self.env_class(self.env_main_config)
+ system_prompt, init_user_prompt = env.set_env(task_config)
+
+ system_message = {"role": "system", "content": system_prompt}
+ init_user_message = {"role": "user", "content": init_user_prompt}
+
+ init_messages.append([system_message, init_user_message])
+ envs.append(env)
+
+ return init_messages, envs
+
+ def _get_per_token_logps(
+ self, model,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor,
+ labels: torch.Tensor,
+ logits_to_keep: int,
+ batch_size: int = None
+ ) -> torch.Tensor:
+ batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak
+ all_logps = []
+ supervise_masks = []
+ for start in range(0, input_ids.size(0), batch_size):
+ input_ids_batch = input_ids[start : start + batch_size]
+ attention_mask_batch = attention_mask[start : start + batch_size]
+
+ # Build model inputs - check if the model supports logits_to_keep (some models and VLMs don't)
+ model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch, "labels": labels}
+
+ # Only add logits_to_keep if the model supports it
+ if "logits_to_keep" in self.model_kwarg_keys:
+ # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
+ model_inputs["logits_to_keep"] = logits_to_keep + 1
+
+ outputs = model(**model_inputs)
+ logits = outputs.logits
+ labels = outputs.supervised_labels
+
+ # Exclude the last value: it corresponds to the next token pred
+ logits = logits[:, :-1, :] # (B, L-1, H)
+ # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op.
+ logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H)
+ # Divide logits by sampling temperature.
+ # See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details
+ logits = logits / self.temperature
+
+ completion_ids = input_ids_batch[:, -logits_to_keep:]
+ logps = selective_log_softmax(logits, completion_ids) # compute logprobs
+ all_logps.append(logps)
+
+ labels = labels[:, -logits_to_keep:]
+ mask = (labels != -100).long()
+ supervise_masks.append(mask)
+
+ logps = torch.cat(all_logps, dim=0)
+ masks = torch.cat(supervise_masks, dim=0)
+ return logps, masks
+
+
+ # NOTE - currently we only deal with text input and leave multimodal as a feature work
+ def _generate_and_score_completions(
+ self, inputs: list[dict[str, Union[torch.Tensor, Any]]] # batch_size * num_generations
+ ) -> dict[str, Union[torch.Tensor, Any]]:
+
+ device = self.accelerator.device
+ mode = "train" if self.model.training else "eval"
+
+ # build no-tensor part
+ batch_gen_keys = []
+ if "prompt" in inputs[0]: # text-based raw prompt
+ batch_gen_keys.append("prompt")
+ if "tools_kwargs" in inputs[0]: # tool-integrated
+ batch_gen_keys.append("tools_kwargs")
+ if "interaction_kwargs" in inputs[0]: # interaction args
+ batch_gen_keys.append("interaction_kwargs")
+ if "agent_name" in inputs[0]: # agent name
+ batch_gen_keys.append("agent_name")
+
+ gen_batch = InteractionDataProto()
+ for key in batch_gen_keys:
+ gen_batch.no_tensor_batch[key] = [x[key] for x in inputs]
+
+ # Single-turn env
+ if issubclass(self.env_class, StaticEnv):
+ prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs]
+ prompt_inputs = self.processing_class(
+ text=prompts_text, return_tensors="pt", padding=True, padding_side="left", add_special_tokens=False
+ )
+
+ prompts, prompt_mask = prompt_inputs["input_ids"].to(device), prompt_inputs["attention_mask"].to(device)
+ if self.max_prompt_length is not None:
+ prompts = prompts[:, -self.max_prompt_length :]
+ prompt_mask = prompt_mask[:, -self.max_prompt_length :]
+
+ gen_batch.batch["input_ids"] = prompts
+ gen_batch.batch["attention_mask"] = prompt_mask
+ # Multi-turn env
+ elif issubclass(self.env_class, DynamicEnv):
+ init_prompts, envs = self._build_multiturn_envs(inputs)
+ gen_batch.no_tensor_batch["init_prompts"] = init_prompts
+ gen_batch.no_tensor_batch["envs"] = envs
+
+ for example, env in zip(inputs, envs):
+ example["envs"] = env
+ else:
+ raise ValueError("Unsupported environment type")
+
+ # Regular generation path
+ with unwrap_model_for_generation(
+ self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
+ ) as unwrapped_model:
+ with (
+ FSDP.summon_full_params(self.model_wrapped, recurse=False)
+ if self.is_fsdp_enabled
+ else nullcontext()
+ ):
+ # Use GenerationManager to coordinate the interaction between the agent and the environment
+ self.generation_manager.actor_rollout_wg = unwrapped_model
+ final_gen_batch_output = self.generation_manager.run_agent_loop(gen_batch=gen_batch)
+
+ # parse outputs
+ prompts = final_gen_batch_output.batch["prompts"].to(device) # prompt ids
+ completion_ids = final_gen_batch_output.batch["responses"].to(device) # completion ids
+ prompt_completion_ids = final_gen_batch_output.batch["input_ids"].to(device) # prompt and completion ids
+ attention_mask = final_gen_batch_output.batch["attention_mask"].to(device) # attention_mask on prompt and response
+ prompt_mask = attention_mask[:, :prompts.size(1)]
+ completion_mask = final_gen_batch_output.batch["info_mask"][:, prompts.size(1):].to(device)
+ is_eos = completion_ids == self.eos_token_id
+ assert completion_ids.shape == completion_mask.shape
+
+ # Construct labels: Supervise only the agent response portion.
+ prompt_labels = torch.full(prompt_mask.shape, -100, device=device)
+ completion_labels = torch.where(completion_mask == 1, completion_ids, -100)
+ labels = torch.cat([prompt_labels, completion_labels], dim=1)
+
+ # Convert tensor to a list of lists of token IDs. This will be passed to the reward function, avoiding the need
+ # to re-tokenize completions if the reward is computed from tokens.
+ completion_ids_list = [
+ [id.item() for id, m in zip(row, mask_row) if m] for row, mask_row in zip(completion_ids, completion_mask)
+ ]
+
+ # Sum along sequence dimension (dim=1) to get completion length per sequence, used for logging
+ completion_lengths = completion_mask.sum(1)
+
+ logits_to_keep = completion_mask.size(1)
+
+ # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
+ if self.mask_truncated_completions:
+ truncated_completions = ~is_eos.any(dim=1)
+ completion_mask = completion_mask * (~truncated_completions).unsqueeze(1).int()
+
+ with torch.no_grad():
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
+ # old_per_token_logps == per_token_logps, so we can skip it's computation here, and use
+ # per_token_logps.detach() instead.
+ if self.num_iterations > 1 or self.args.steps_per_generation > self.args.gradient_accumulation_steps:
+ old_per_token_logps, old_supervise_mask = self._get_per_token_logps(
+ self.model, prompt_completion_ids, attention_mask, labels, logits_to_keep
+ )
+ else:
+ old_per_token_logps, old_supervise_mask = None, None
+
+ # Compute the per-token log probabilities for the reference model
+ if self.beta != 0.0:
+ if self.ref_model is not None:
+ ref_per_token_logps, ref_supervise_mask = self._get_per_token_logps(
+ self.ref_model, prompt_completion_ids, attention_mask, labels, logits_to_keep
+ )
+ else:
+ with self.accelerator.unwrap_model(self.model).disable_adapter():
+ ref_per_token_logps, ref_supervise_mask = self._get_per_token_logps(
+ self.model, prompt_completion_ids, attention_mask, labels, logits_to_keep
+ )
+ else:
+ ref_per_token_logps, ref_supervise_mask = None, None
+
+ # Decode the generated completions
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
+ completions = completions_text
+
+ # compute rewards
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
+
+ # Apply weights to each reward function's output and sum
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
+
+ # Compute grouped-wise rewards
+ mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
+ std_grouped_rewards = rewards.view(-1, self.num_generations).std(dim=1)
+ is_std_zero = torch.isclose(std_grouped_rewards, torch.zeros_like(std_grouped_rewards))
+
+ # Normalize the rewards to compute the advantages
+ mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
+ std_grouped_rewards = std_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
+ advantages = rewards - mean_grouped_rewards
+ if self.scale_rewards:
+ advantages = advantages / (std_grouped_rewards + 1e-4)
+
+ # Slice to keep only the local part of the data
+ process_slice = slice(
+ self.accelerator.process_index * len(prompts),
+ (self.accelerator.process_index + 1) * len(prompts),
+ )
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
+ advantages = advantages[process_slice]
+
+ # Log the metrics
+ if mode == "train":
+ self.state.num_input_tokens_seen += self.accelerator.gather(attention_mask.sum()).sum().item()
+ self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
+
+ # Log completion lengths, mean, min, max
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
+
+ # Identify sequences that terminated with EOS and log their lengths
+ agg_terminated_with_eos = self.accelerator.gather(is_eos.any(dim=1))
+ term_completion_lengths = agg_completion_lengths[agg_terminated_with_eos]
+ clipped_completions_ratio = 1 - len(term_completion_lengths) / len(agg_completion_lengths)
+ self._metrics[mode]["completions/clipped_ratio"].append(clipped_completions_ratio)
+ if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found
+ term_completion_lengths = torch.zeros(1, device=device)
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
+
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
+ for i, reward_func_name in enumerate(self.reward_func_names):
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
+ std_rewards = nanstd(rewards_per_func[:, i]).item()
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_rewards)
+ self._metrics[mode]["reward"].append(mean_grouped_rewards.mean().item())
+ self._metrics[mode]["reward_std"].append(std_grouped_rewards.mean().item())
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
+
+ # Log prompt and completion texts
+ # self._logs["prompt"].extend(gather_object(prompts_text))
+ self._logs["completion"].extend(gather_object(completions_text))
+ for i, name in enumerate(self.reward_func_names):
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
+ self._logs["advantages"].extend(all_process_advantages.tolist())
+
+ return {
+ "prompt_ids": prompts,
+ "prompt_mask": prompt_mask,
+ "completion_ids": completion_ids,
+ "completion_mask": completion_mask,
+ "advantages": advantages,
+ "old_per_token_logps": old_per_token_logps,
+ "old_supervise_mask": old_supervise_mask,
+ "ref_per_token_logps": ref_per_token_logps,
+ "ref_supervise_mask": ref_supervise_mask
+ }
+
+
+ def _compute_loss(self, model, inputs):
+ device = self.accelerator.device
+
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
+ old_supervise_mask, ref_supervise_mask = inputs["old_supervise_mask"], inputs["ref_supervise_mask"]
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
+
+ prompt_labels = torch.full(prompt_mask.shape, -100, device=device)
+ completion_labels = torch.where(completion_mask == 1, completion_ids, -100)
+ labels = torch.cat([prompt_labels, completion_labels], dim=1)
+ logits_to_keep = completion_labels.size(1)
+
+ assert prompt_ids.shape == prompt_mask.shape
+ assert completion_ids.shape == completion_mask.shape
+ assert input_ids.shape == attention_mask.shape == labels.shape
+ per_token_logps, supervise_mask = self._get_per_token_logps(model, input_ids, attention_mask, labels, logits_to_keep)
+
+ # Compute the KL divergence between the model and the reference model
+ if self.beta != 0.0:
+ ref_per_token_logps = inputs["ref_per_token_logps"]
+ per_token_kl = (
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
+ )
+
+ # Compute the loss
+ advantages = inputs["advantages"]
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
+ # old_per_token_logps == per_token_logps, so we can skip it's computation
+ # (see _generate_and_score_completions) and use per_token_logps.detach() instead.
+ old_per_token_logps = (
+ per_token_logps.detach() if inputs["old_per_token_logps"] is None else inputs["old_per_token_logps"]
+ )
+ coef_1 = torch.exp(per_token_logps - old_per_token_logps)
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
+
+ # Two-sided clipping
+ if self.args.delta is not None:
+ coef_1 = torch.clamp(coef_1, max=self.args.delta)
+
+ per_token_loss1 = coef_1 * advantages.unsqueeze(1)
+ per_token_loss2 = coef_2 * advantages.unsqueeze(1)
+ per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
+ if self.beta != 0.0:
+ per_token_loss = per_token_loss + self.beta * per_token_kl
+
+ if old_supervise_mask is None:
+ old_supervise_mask = supervise_mask
+ if ref_supervise_mask is None:
+ ref_supervise_mask = supervise_mask
+ # Consistency check: The positions that are supervised must be a subset of the completion mask.
+ assert (
+ torch.all(supervise_mask <= completion_mask) and
+ torch.all(old_supervise_mask <= completion_mask) and
+ torch.all(ref_supervise_mask <= completion_mask)
+ )
+ supervised_mask = completion_mask * supervise_mask * old_supervise_mask * ref_supervise_mask
+
+ if self.loss_type == "grpo":
+ loss = ((per_token_loss * supervised_mask).sum(-1) / supervised_mask.sum(-1).clamp(min=1.0)).mean()
+ elif self.loss_type == "bnpo":
+ loss = (per_token_loss * supervised_mask).sum() / supervised_mask.sum().clamp(min=1.0)
+ elif self.loss_type == "dr_grpo":
+ loss = (per_token_loss * supervised_mask).sum() / (supervised_mask.size(0) * self.max_completion_length)
+ else:
+ raise ValueError(f"Unknown loss type: {self.loss_type}")
+
+ # Log the metrics
+ mode = "train" if self.model.training else "eval"
+
+ if self.beta != 0.0:
+ mean_kl = (per_token_kl * supervised_mask).sum() / supervised_mask.sum()
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
+
+ # Compute the clipped probability ratios
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0)
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0)
+ is_region_clipped = is_low_clipped | is_high_clipped
+
+ low_clip = (is_low_clipped * supervised_mask).sum() / supervised_mask.sum()
+ high_clip = (is_high_clipped * supervised_mask).sum() / supervised_mask.sum()
+ clip_ratio = (is_region_clipped * supervised_mask).sum() / supervised_mask.sum()
+
+ gathered_low_clip = self.accelerator.gather(low_clip)
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
+ gathered_high_clip = self.accelerator.gather(high_clip)
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
+ gathered_clip_ratio = self.accelerator.gather(clip_ratio)
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
+ return loss
+
+ def training_step(self, model, inputs, num_items_in_batch=None):
+ """
+ 重写 training_step 以捕获 OOM 异常并保存 checkpoint
+ """
+ try:
+ # 调用父类的 training_step
+ loss = super().training_step(model, inputs, num_items_in_batch)
+ return loss
+ except torch.cuda.OutOfMemoryError as e:
+ # OOM 发生时保存 checkpoint
+ logging.error(f"[OOM] CUDA OutOfMemoryError occurred at step {self.state.global_step}")
+ logging.error(f"[OOM] Error message: {str(e)}")
+
+ # 清理缓存以释放内存
+ torch.cuda.empty_cache()
+
+ # 保存 emergency checkpoint
+ oom_ckpt_dir = os.path.join(self.args.output_dir, f"oom_checkpoint_step_{self.state.global_step}")
+ logging.info(f"[OOM] Saving emergency checkpoint to {oom_ckpt_dir}")
+
+ try:
+ self.save_model(oom_ckpt_dir)
+ logging.info(f"[OOM] Emergency checkpoint saved successfully")
+ except Exception as save_error:
+ logging.error(f"[OOM] Failed to save checkpoint: {save_error}")
+
+ # 重新抛出异常,让训练停止
+ raise RuntimeError(
+ f"Training stopped due to OOM at step {self.state.global_step}. "
+ f"Emergency checkpoint saved to {oom_ckpt_dir}. "
+ f"You can resume training from this checkpoint."
+ ) from e
\ No newline at end of file
diff --git a/MemGen-main/memgen/utils.py b/MemGen-main/memgen/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3746dd3543ae053eda430e105b394a0ae36dead
--- /dev/null
+++ b/MemGen-main/memgen/utils.py
@@ -0,0 +1,268 @@
+from dataclasses import dataclass, field
+import glob
+import json
+import logging
+import os
+import shutil
+from typing import Optional, Callable, Dict, List
+
+from safetensors import safe_open
+import torch.nn as nn
+from torch.utils.tensorboard import SummaryWriter
+
+
+# ===== chat template =====
+
+# from https://huggingface.co/HuggingFaceTB/SmolLM3-3B/blob/main/chat_template.jinja
+CONVERSATION_TEMPLATE = r"""
+{# ───── main loop ───── #}
+{%- for message in messages -%}
+ {%- set content = message.content if message.content is string else "" -%}
+ {%- if (message.role == "user") or (message.role == "system") -%}
+ {{ "<|im_start|>" + message.role + "\n" + content + "<|im_end|>\n" }}
+ {%- elif message.role == "assistant" -%}
+ {%- generation -%}
+ {{ "<|im_start|>assistant\n" + content + "<|im_end|>\n" }}
+ {%- endgeneration -%}
+ {%- elif message.role == "tool" -%}
+ {{ "<|im_start|>" + "user\n" + content + "<|im_end|>\n" }}
+ {%- endif -%}
+{%- endfor -%}
+{# ───── generation prompt ───── #}
+{%- if add_generation_prompt -%}
+ {{ "<|im_start|>assistant\n" }}
+{%- endif -%}
+""".strip()
+
+# ===== torch part =====
+def load_state_dict_from_safetensor(model_path) -> Dict:
+ """Load a safetensor file from the given path and return a state_dict.
+
+ Args:
+ model_path (str): Path to the safetensor file.
+
+ Returns:
+ Dict[str, torch.Tensor]: A dictionary of model parameters,
+ where keys are parameter names and values are corresponding tensors.
+ """
+ model_state_dict = {}
+ with safe_open(model_path, framework="pt") as f:
+ for key in f.keys():
+ model_state_dict[key] = f.get_tensor(key)
+ return model_state_dict
+
+def fix_model_parameters(model: nn.Module):
+ """Freeze all parameters of the given model.
+
+ Args:
+ model (nn.Module): The PyTorch model whose parameters will be frozen.
+ """
+ for parameter in model.parameters():
+ parameter.requires_grad = False
+
+def open_model_parameters(model: nn.Module):
+ """Unfreeze all parameters of the given model.
+
+ Args:
+ model (nn.Module): The PyTorch model whose parameters will be unfrozen.
+ """
+ for parameter in model.parameters():
+ parameter.requires_grad = True
+
+def log_trainable_params(model: nn.Module):
+ """Log all trainable parameters of the given model.
+
+ Args:
+ model (nn.Module): The PyTorch model to inspect.
+ """
+ logging.info("Trainable parameters in the model:")
+ for name, param in model.named_parameters():
+ if param.requires_grad:
+ logging.info(f" {name}: {param.numel()} params, shape={param.shape}")
+
+
+
+# ===== Eval Part =====
+@dataclass
+class StaticEvalRecorder:
+ compute_metrics: List[Callable[[str, str, str], float]] = field(default_factory=list)
+ log_file: Optional[str] = None
+ writer: Optional[object] = None
+
+ # Internal storage
+ metric_sums: Dict[str, float] = field(init=False)
+ metric_counts: Dict[str, int] = field(init=False)
+
+ def __post_init__(self):
+ self.metric_sums = {metric.__name__: 0.0 for metric in self.compute_metrics}
+ self.metric_counts = {metric.__name__: 0 for metric in self.compute_metrics}
+ if self.log_file:
+ os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
+ with open(self.log_file, 'w') as f:
+ f.write('') # Clear file
+
+ def record_batch(self, completions: List[str], examples: List[Dict]):
+ """Record results for a batch of model outputs.
+
+ Args:
+ completions (List[str]): The model's answers (outputs).
+ examples (List[Dict]): Each completion's corresponding question and related attributes.
+ Each example is expected to contain the keys: "prompt" and "solution".
+ """
+ # Extract all keys from the first example
+ keys = [key for key in examples[0]]
+ # Build kwargs for metrics computation (one list per field)
+ reward_kwargs = {key: [example[key] for example in examples] for key in keys}
+ reward_kwargs['completions'] = completions
+
+ # Compute all metrics in batch
+ batched_results = {}
+ for metric in self.compute_metrics: # iterate over each metric function
+ metric_name = metric.__name__ # use function name as metric name
+ batched_scores = metric(**reward_kwargs) # compute scores for the entire batch
+ batched_results[metric_name] = batched_scores
+
+ # Record experiment results for each example
+ for i, (completion, example) in enumerate(zip(completions, examples)):
+ # Collect the metric results for this specific example
+ metrics_result = {
+ metric_name: batched_results[metric_name][i]
+ for metric_name in batched_results
+ }
+
+ # Update running totals for metrics
+ for metric_name, score in metrics_result.items():
+ self.metric_sums[metric_name] += score
+ self.metric_counts[metric_name] += 1
+
+ # Create a log record with prompt, solution, completion, and metrics
+ prompt = example.get("prompt", "")
+ solution = example.get("solution", "")
+ record = {
+ 'prompt': prompt,
+ 'solution': solution,
+ 'completion': completion,
+ 'metrics': metrics_result
+ }
+
+ # Write the record into a log file (if available)
+ if self.log_file:
+ with open(self.log_file, 'a') as f:
+ f.write(json.dumps(record, ensure_ascii=False) + '\n')
+
+ # Update TensorBoard metrics (if writer is available)
+ if self.writer:
+ mean_metrics = self.get_mean_metrics() # get average metrics across all data so far
+ for name, value in mean_metrics.items():
+ self.writer.add_scalar(name, value, global_step=self.metric_counts[name])
+
+
+ def get_mean_metrics(self) -> Dict[str, float]:
+ return {
+ name: (self.metric_sums[name] / self.metric_counts[name]) if self.metric_counts[name] > 0 else 0.0
+ for name in self.metric_sums
+ }
+
+ def finalize(self):
+ mean_metrics = self.get_mean_metrics()
+ final_record = {
+ 'summary_metrics': mean_metrics
+ }
+
+ if self.log_file:
+ with open(self.log_file, 'a', encoding='utf-8') as f:
+ f.write(json.dumps(final_record, ensure_ascii=False) + '\n')
+
+ if self.writer:
+ mean_metrics = self.get_mean_metrics()
+ for name, value in mean_metrics.items():
+ self.writer.add_scalar(name + "_final", value, global_step=self.metric_counts[name])
+
+
+@dataclass
+class DynamicEvalRecorder:
+ log_file: Optional[str] = None # path to the txt log file
+ writer: object = field(default=None) # TensorBoard SummaryWriter
+
+ def __post_init__(self):
+ if self.log_file is None:
+ raise ValueError("log_file path must be provided")
+
+ # Ensure the directory for the log file exists
+ os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
+ self.logger = logging.getLogger("DynamicEvalRecorder")
+
+ # Internal counters
+ self._total_reward = 0.0
+ self._count = 0
+
+ # Initialize the file (clear previous content if any)
+ with open(self.log_file, "w", encoding="utf-8") as f:
+ f.write("DynamicEvalRecorder Log\n\n")
+
+ def record_batch(self, conversations: List[str], rewards: List[float]):
+ """Record a batch of conversations and their associated rewards.
+
+ Args:
+ conversations (List[str]): List of conversation texts.
+ rewards (List[float]): List of reward values corresponding to conversations.
+ """
+ if len(conversations) != len(rewards):
+ raise ValueError("conversations and rewards must have the same length")
+
+ # Append batch results to the log file
+ with open(self.log_file, "a", encoding="utf-8") as f:
+ for conv, rew in zip(conversations, rewards):
+ f.write(f"Conversation:\n{conv}\n")
+ f.write(f"Reward: {rew:.4f}\n")
+ f.write("-" * 40 + "\n")
+
+ # Update statistics
+ self._total_reward += rew
+ self._count += 1
+
+ # Compute running average reward
+ avg_reward = self._total_reward / self._count if self._count > 0 else 0.0
+
+ # Write running average to TensorBoard
+ if self.writer is not None:
+ self.writer.add_scalar("reward/avg", avg_reward, self._count)
+
+ # Log summary info
+ self.logger.info(f"Recorded {len(conversations)} items, avg_reward={avg_reward:.4f}")
+
+ def finalize(self):
+ """Finalize evaluation: write final average reward to both log file and TensorBoard."""
+ # Compute final average reward
+ avg_reward = self._total_reward / self._count if self._count > 0 else 0.0
+
+ # Append final result to log file
+ with open(self.log_file, "a", encoding="utf-8") as f:
+ f.write("\nFinal Results\n")
+ f.write("=" * 40 + "\n")
+ f.write(f"Average Reward: {avg_reward:.4f}\n")
+
+ # Write final result to TensorBoard
+ if self.writer:
+ self.writer.add_scalar("ave_reward_final", avg_reward, global_step=self._count)
+
+
+# --- helper functions ---
+def create_tensorboard(save_dir: str):
+ log_dir = os.path.join(save_dir, "runs")
+ writer = SummaryWriter(log_dir=log_dir)
+ return writer
+
+def remove_trainer_checkpoints(trainer_output_dir):
+ ckpt_paths = glob.glob(os.path.join(trainer_output_dir, "checkpoint-*"))
+ for ckpt in ckpt_paths:
+ shutil.rmtree(ckpt, ignore_errors=True)
+
+import torch.distributed as dist
+
+def gather_objects(obj):
+ if not dist.is_initialized():
+ return obj
+ gathered = [None for _ in range(dist.get_world_size())]
+ dist.all_gather_object(gathered, obj)
+ return gathered
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval.sh b/MemGen-main/scripts/eval.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9a6d92296885166e391cc27edd5c87784230d46a
--- /dev/null
+++ b/MemGen-main/scripts/eval.sh
@@ -0,0 +1,63 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+# options:
+# - Qwen/Qwen2.5-1.5B-Instruct
+# - HuggingFaceTB/SmolLM3-3B
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+
+# Dataset configs
+DATASET_NAME="kodcode" # gsm8k, gpqa, kodcode, triviaqa
+
+# MemGen configs
+
+# Augmentation configs:
+# - For gsm8k, gpqa, kodcode: MAX_PROMPT_AUG_NUM=1, MAX_INFERENCE_AUG_NUM=5
+# - For triviaqa: MAX_PROMPT_AUG_NUM=8, MAX_INFERENCE_AUG_NUM=0
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=16
+INFERENCE_LATENTS_LEN=16
+
+BATCH_SIZE=4
+
+# Trained model path:
+# - Must point to a checkpoint file ending with .safetensors (e.g. /model.safetensors)
+# - Required when evaluating the model
+LOAD_MODEL_PATH=""
+
+# evaluate
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval/qwen2_5_gsm8k_grpo.sh b/MemGen-main/scripts/eval/qwen2_5_gsm8k_grpo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..24e39e47b1b4435adca8478878143ef8cfbd95fe
--- /dev/null
+++ b/MemGen-main/scripts/eval/qwen2_5_gsm8k_grpo.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+DATASET_NAME="gsm8k"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=4
+
+LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/gsm8k/weaver-grpo/pn=1_pl=8_in=0_il=8"
+
+# evaluate
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval/qwen2_5_gsm8k_sft.sh b/MemGen-main/scripts/eval/qwen2_5_gsm8k_sft.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5179e903ed377fe06152f2d6cf9231e224deafdb
--- /dev/null
+++ b/MemGen-main/scripts/eval/qwen2_5_gsm8k_sft.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+DATASET_NAME="gsm8k"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=3
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=4
+
+LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/gsm8k/weaver-sft/pn=1_pl=8_in=3_il=8"
+
+# evaluate
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval/qwen2_5_kodcode_grpo.sh b/MemGen-main/scripts/eval/qwen2_5_kodcode_grpo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..cd3e29929dcaea6d438041db4741814cb59a433a
--- /dev/null
+++ b/MemGen-main/scripts/eval/qwen2_5_kodcode_grpo.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+DATASET_NAME="kodcode"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=4
+
+LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/kodcode/weaver-grpo/pn=1_pl=8_in=0_il=8"
+
+# evaluate
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval/qwen2_5_kodcode_sft.sh b/MemGen-main/scripts/eval/qwen2_5_kodcode_sft.sh
new file mode 100644
index 0000000000000000000000000000000000000000..32cbd5279bfd2ad83d7e774f015c2729001ee74c
--- /dev/null
+++ b/MemGen-main/scripts/eval/qwen2_5_kodcode_sft.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+DATASET_NAME="kodcode"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=5
+PROMPT_LATENTS_LEN=4
+INFERENCE_LATENTS_LEN=4
+
+BATCH_SIZE=4
+
+LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/kodcode/weaver-sft/pn=1_pl=4_in=5_il=4"
+
+# evaluate
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval/qwen2_5_triviaqa.sh b/MemGen-main/scripts/eval/qwen2_5_triviaqa.sh
new file mode 100644
index 0000000000000000000000000000000000000000..bba574df7f986ba32824b3309579380e75d34b83
--- /dev/null
+++ b/MemGen-main/scripts/eval/qwen2_5_triviaqa.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+DATASET_NAME="triviaqa"
+
+MAX_PROMPT_AUG_NUM=8
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=4
+
+LOAD_MODEL_PATH="MemGen/Qwen2.5-1.5B-Instruct/triviaqa/weaver-sft/pn=8_pl=8_in=0_il=8"
+
+# evaluate
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval/smollm_kodcode.sh b/MemGen-main/scripts/eval/smollm_kodcode.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6c192985759282d13a96c23cd244dfb2bea6ae48
--- /dev/null
+++ b/MemGen-main/scripts/eval/smollm_kodcode.sh
@@ -0,0 +1,50 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="HuggingFaceTB/SmolLM3-3B"
+WEAVER_MODEL="HuggingFaceTB/SmolLM3-3B"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+DATASET_NAME="kodcode"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=5
+PROMPT_LATENTS_LEN=4
+INFERENCE_LATENTS_LEN=4
+
+BATCH_SIZE=4
+
+LOAD_MODEL_PATH="MemGen/SmolLM3-3B/kodcode/weaver-sft/pn=1_pl=4_in=5_il=4"
+
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/eval/smollm_triviaqa.sh b/MemGen-main/scripts/eval/smollm_triviaqa.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4134a47eb5e643ffa04b72456d442f8e4c2bca4e
--- /dev/null
+++ b/MemGen-main/scripts/eval/smollm_triviaqa.sh
@@ -0,0 +1,50 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="HuggingFaceTB/SmolLM3-3B"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_ACTIVE=False
+
+DATASET_NAME="triviaqa"
+
+MAX_PROMPT_AUG_NUM=8
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=4
+INFERENCE_LATENTS_LEN=4
+
+BATCH_SIZE=4
+
+LOAD_MODEL_PATH="MemGen/SmolLM3-3B/triviaqa/weaver-sft/pn=8_pl=4_in=0_il=4"
+
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active ${TRIGGER_ACTIVE} \
+ run.mode evaluate \
+ run.interaction.batch_size ${BATCH_SIZE} \
+ run.interaction.temperature 0.0 \
+ run.interaction.max_response_length 1024 \
\ No newline at end of file
diff --git a/MemGen-main/scripts/train/qwen2_5_gsm8k_grpo.sh b/MemGen-main/scripts/train/qwen2_5_gsm8k_grpo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..f9a96b3ca591159bf36ed6dc4998a0740f50b381
--- /dev/null
+++ b/MemGen-main/scripts/train/qwen2_5_gsm8k_grpo.sh
@@ -0,0 +1,58 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+DATASET_NAME="gsm8k"
+
+TRAIN_METHOD="grpo"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=""
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/train/qwen2_5_gsm8k_sft.sh b/MemGen-main/scripts/train/qwen2_5_gsm8k_sft.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4506ad74887619329db001ee55ccadfe7d74facf
--- /dev/null
+++ b/MemGen-main/scripts/train/qwen2_5_gsm8k_sft.sh
@@ -0,0 +1,58 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+DATASET_NAME="gsm8k"
+
+TRAIN_METHOD="sft"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=3
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=null
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/train/qwen2_5_kodcode_grpo.sh b/MemGen-main/scripts/train/qwen2_5_kodcode_grpo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c639df6a2862a232cf0f25f2326c3fea6b84b21c
--- /dev/null
+++ b/MemGen-main/scripts/train/qwen2_5_kodcode_grpo.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+DATASET_NAME="kodcode"
+
+TRAIN_METHOD="grpo"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=""
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/train/qwen2_5_kodcode_sft.sh b/MemGen-main/scripts/train/qwen2_5_kodcode_sft.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8361161300860db53014d2b1ffecebef5bba85f6
--- /dev/null
+++ b/MemGen-main/scripts/train/qwen2_5_kodcode_sft.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+DATASET_NAME="kodcode"
+
+TRAIN_METHOD="sft"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=5
+PROMPT_LATENTS_LEN=4
+INFERENCE_LATENTS_LEN=4
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=null
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/train/qwen2_5_triviaqa.sh b/MemGen-main/scripts/train/qwen2_5_triviaqa.sh
new file mode 100644
index 0000000000000000000000000000000000000000..336ed4a1dd6c1c65b1c251d539a177832b755f87
--- /dev/null
+++ b/MemGen-main/scripts/train/qwen2_5_triviaqa.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+DATASET_NAME="triviaqa"
+
+TRAIN_METHOD="sft"
+
+MAX_PROMPT_AUG_NUM=8
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=null
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/train/smollm_kodcode.sh b/MemGen-main/scripts/train/smollm_kodcode.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3707a5f913f45c1333804b3568915f316715fd69
--- /dev/null
+++ b/MemGen-main/scripts/train/smollm_kodcode.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+
+REASONER_MODEL="HuggingFaceTB/SmolLM3-3B"
+WEAVER_MODEL="HuggingFaceTB/SmolLM3-3B"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+DATASET_NAME="kodcode"
+
+TRAIN_METHOD="sft"
+
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=5
+PROMPT_LATENTS_LEN=4
+INFERENCE_LATENTS_LEN=4
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=null
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/train/smollm_triviaqa.sh b/MemGen-main/scripts/train/smollm_triviaqa.sh
new file mode 100644
index 0000000000000000000000000000000000000000..33724986562c1bb328a3de8fb7775d48e916d408
--- /dev/null
+++ b/MemGen-main/scripts/train/smollm_triviaqa.sh
@@ -0,0 +1,59 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+
+REASONER_MODEL="HuggingFaceTB/SmolLM3-3B"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+DATASET_NAME="triviaqa"
+
+TRAIN_METHOD="sft"
+
+MAX_PROMPT_AUG_NUM=8
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=4
+INFERENCE_LATENTS_LEN=4
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=null
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/trigger_train.sh b/MemGen-main/scripts/trigger_train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ff0914ab1b8faef03b98f1c74690b98e5dec6e81
--- /dev/null
+++ b/MemGen-main/scripts/trigger_train.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+# options:
+# - Qwen/Qwen2.5-1.5B-Instruct
+# - HuggingFaceTB/SmolLM3-3B
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+# Dataset configs
+DATASET_NAME="kodcode" # options: gsm8k, gpqa, kodcode, triviaqa
+
+# MemGen configs
+TRAIN_METHOD="grpo" # options: sft or grpo
+
+# Augmentation configs:
+# - For gsm8k, gpqa, kodcode: MAX_PROMPT_AUG_NUM=1, MAX_INFERENCE_AUG_NUM=5
+# - For triviaqa: MAX_PROMPT_AUG_NUM=6, MAX_INFERENCE_AUG_NUM=0
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=5
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+
+LOAD_WEAVER_PATH=""
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_WEAVER_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active True \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver False \
+ run.train_trigger True \
+ run.train_trigger_method ${TRAIN_METHOD} \
+ run.trigger.grpo.per_device_train_batch_size 8 \
+ run.trigger.grpo.per_device_eval_batch_size 8 \
+ run.trigger.grpo.num_train_epochs 1 \
+ run.trigger.grpo.num_generations 8 \
+ run.trigger.grpo.gradient_accumulation_steps 4 \
+
+
+
+
+
diff --git a/MemGen-main/scripts/weaver_grpo.sh b/MemGen-main/scripts/weaver_grpo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..545fcaf597ee994eaf960fca1a622deb2a0dfca3
--- /dev/null
+++ b/MemGen-main/scripts/weaver_grpo.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+
+export DEBUG_MODE=false
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29508
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+# options:
+# - Qwen/Qwen2.5-1.5B-Instruct
+# - HuggingFaceTB/SmolLM3-3B
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+# Dataset configs
+DATASET_NAME="kodcode" # options: gsm8k, gpqa, kodcode, triviaqa
+
+# MemGen configs
+TRAIN_METHOD="grpo" # options: sft or grpo
+
+# Augmentation configs:
+# - For gsm8k, gpqa, kodcode: MAX_PROMPT_AUG_NUM=1, MAX_INFERENCE_AUG_NUM=5
+# - For triviaqa: MAX_PROMPT_AUG_NUM=6, MAX_INFERENCE_AUG_NUM=0
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=16
+INFERENCE_LATENTS_LEN=16
+
+GROUP_SIZE=8
+
+LOAD_MODEL_PATH=""
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.grpo.max_completion_length 512 \
+ run.weaver.grpo.num_train_epochs 1 \
+ run.weaver.grpo.per_device_train_batch_size ${GROUP_SIZE} \
+ run.weaver.grpo.per_device_eval_batch_size ${GROUP_SIZE} \
+ run.weaver.grpo.num_generations ${GROUP_SIZE} \
+ run.weaver.grpo.gradient_accumulation_steps 1 \
diff --git a/MemGen-main/scripts/weaver_sft.sh b/MemGen-main/scripts/weaver_sft.sh
new file mode 100644
index 0000000000000000000000000000000000000000..897463caaa696212d7884e9345696fbfdcf03d78
--- /dev/null
+++ b/MemGen-main/scripts/weaver_sft.sh
@@ -0,0 +1,66 @@
+#!/bin/bash
+
+export DEBUG_MODE=true
+export LOG_PATH="./debug_log_2b.txt"
+export CUDA_VISIBLE_DEVICES=0
+export MAIN_PROCESS_PORT=29507
+
+# 自动计算 GPU 数量
+NUM_GPUS=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
+echo "Using $NUM_GPUS GPU(s): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+export NCCL_DEBUG=INFO
+export NCCL_IB_DISABLE=1
+export NCCL_P2P_DISABLE=1
+export NCCL_ASYNC_DISABLE=1
+
+# options:
+# - Qwen/Qwen2.5-1.5B-Instruct
+# - HuggingFaceTB/SmolLM3-3B
+REASONER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+WEAVER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+TRIGGER_MODEL="Qwen/Qwen2.5-1.5B-Instruct"
+
+# Dataset configs
+DATASET_NAME="kodcode" # options: gsm8k, gpqa, kodcode, triviaqa
+
+# MemGen configs
+TRAIN_METHOD="sft" # options: sft or grpo
+
+# Augmentation configs:
+# - For gsm8k, gpqa, kodcode: MAX_PROMPT_AUG_NUM=1, MAX_INFERENCE_AUG_NUM=5
+# - For triviaqa: MAX_PROMPT_AUG_NUM=6, MAX_INFERENCE_AUG_NUM=0
+MAX_PROMPT_AUG_NUM=1
+MAX_INFERENCE_AUG_NUM=0
+PROMPT_LATENTS_LEN=8
+INFERENCE_LATENTS_LEN=8
+
+BATCH_SIZE=1
+
+LOAD_MODEL_PATH=null
+
+
+# train
+python -m accelerate.commands.launch \
+ --config_file=configs/zero2.yaml \
+ --num_processes=${NUM_GPUS} \
+ main.py \
+ --cfg-path configs/latent_memory/${DATASET_NAME}.yaml \
+ --options \
+ model.model_name ${REASONER_MODEL} \
+ model.load_model_path ${LOAD_MODEL_PATH} \
+ model.max_prompt_aug_num ${MAX_PROMPT_AUG_NUM} \
+ model.max_inference_aug_num ${MAX_INFERENCE_AUG_NUM} \
+ model.weaver.model_name ${WEAVER_MODEL} \
+ model.weaver.prompt_latents_len ${PROMPT_LATENTS_LEN} \
+ model.weaver.inference_latents_len ${INFERENCE_LATENTS_LEN} \
+ model.trigger.model_name ${TRIGGER_MODEL} \
+ model.trigger.active False \
+ datasets.mode ${TRAIN_METHOD} \
+ run.mode train \
+ run.train_weaver True \
+ run.train_trigger False \
+ run.train_weaver_method ${TRAIN_METHOD} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.per_device_train_batch_size ${BATCH_SIZE} \
+ run.weaver.sft.bf16 True \
+ run.weaver.sft.gradient_accumulation_steps 1 \
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/GroundingDINO_SwinB_cfg.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/GroundingDINO_SwinB_cfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..f490c4bbd598a35de43d36ceafcbd769e7ff21bf
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/GroundingDINO_SwinB_cfg.py
@@ -0,0 +1,43 @@
+batch_size = 1
+modelname = "groundingdino"
+backbone = "swin_B_384_22k"
+position_embedding = "sine"
+pe_temperatureH = 20
+pe_temperatureW = 20
+return_interm_indices = [1, 2, 3]
+backbone_freeze_keywords = None
+enc_layers = 6
+dec_layers = 6
+pre_norm = False
+dim_feedforward = 2048
+hidden_dim = 256
+dropout = 0.0
+nheads = 8
+num_queries = 900
+query_dim = 4
+num_patterns = 0
+num_feature_levels = 4
+enc_n_points = 4
+dec_n_points = 4
+two_stage_type = "standard"
+two_stage_bbox_embed_share = False
+two_stage_class_embed_share = False
+transformer_activation = "relu"
+dec_pred_bbox_embed_share = True
+dn_box_noise_scale = 1.0
+dn_label_noise_ratio = 0.5
+dn_label_coef = 1.0
+dn_bbox_coef = 1.0
+embed_init_tgt = True
+dn_labelbook_size = 2000
+max_text_len = 256
+text_encoder_type = "bert-base-uncased"
+use_text_enhancer = True
+use_fusion_layer = True
+use_checkpoint = True
+use_transformer_ckpt = True
+use_text_cross_attention = True
+text_dropout = 0.0
+fusion_dropout = 0.0
+fusion_droppath = 0.1
+sub_sentence_present = True
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/GroundingDINO_SwinT_OGC.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/GroundingDINO_SwinT_OGC.py
new file mode 100644
index 0000000000000000000000000000000000000000..9158d5f6260ec74bded95377d382387430d7cd70
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/GroundingDINO_SwinT_OGC.py
@@ -0,0 +1,43 @@
+batch_size = 1
+modelname = "groundingdino"
+backbone = "swin_T_224_1k"
+position_embedding = "sine"
+pe_temperatureH = 20
+pe_temperatureW = 20
+return_interm_indices = [1, 2, 3]
+backbone_freeze_keywords = None
+enc_layers = 6
+dec_layers = 6
+pre_norm = False
+dim_feedforward = 2048
+hidden_dim = 256
+dropout = 0.0
+nheads = 8
+num_queries = 900
+query_dim = 4
+num_patterns = 0
+num_feature_levels = 4
+enc_n_points = 4
+dec_n_points = 4
+two_stage_type = "standard"
+two_stage_bbox_embed_share = False
+two_stage_class_embed_share = False
+transformer_activation = "relu"
+dec_pred_bbox_embed_share = True
+dn_box_noise_scale = 1.0
+dn_label_noise_ratio = 0.5
+dn_label_coef = 1.0
+dn_bbox_coef = 1.0
+embed_init_tgt = True
+dn_labelbook_size = 2000
+max_text_len = 256
+text_encoder_type = "bert-base-uncased"
+use_text_enhancer = True
+use_fusion_layer = True
+use_checkpoint = True
+use_transformer_ckpt = True
+use_text_cross_attention = True
+text_dropout = 0.0
+fusion_dropout = 0.0
+fusion_droppath = 0.1
+sub_sentence_present = True
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/cocogrounding_eval.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/cocogrounding_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..7693a182d86fcb2b7f707d28371849f019b883c3
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/cocogrounding_eval.py
@@ -0,0 +1,269 @@
+# ------------------------------------------------------------------------
+# Grounding DINO. Midified by Shilong Liu.
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+COCO evaluator that works in distributed mode.
+
+Mostly copy-paste from https://github.com/pytorch/vision/blob/edfd5a7/references/detection/coco_eval.py
+The difference is that there is less copy-pasting from pycocotools
+in the end of the file, as python3 can suppress prints with contextlib
+"""
+import contextlib
+import copy
+import os
+
+import numpy as np
+import pycocotools.mask as mask_util
+import torch
+from pycocotools.coco import COCO
+from pycocotools.cocoeval import COCOeval
+
+from groundingdino.util.misc import all_gather
+
+
+class CocoGroundingEvaluator(object):
+ def __init__(self, coco_gt, iou_types, useCats=True):
+ assert isinstance(iou_types, (list, tuple))
+ coco_gt = copy.deepcopy(coco_gt)
+ self.coco_gt = coco_gt
+
+ self.iou_types = iou_types
+ self.coco_eval = {}
+ for iou_type in iou_types:
+ self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type)
+ self.coco_eval[iou_type].useCats = useCats
+
+ self.img_ids = []
+ self.eval_imgs = {k: [] for k in iou_types}
+ self.useCats = useCats
+
+ def update(self, predictions):
+ img_ids = list(np.unique(list(predictions.keys())))
+ self.img_ids.extend(img_ids)
+
+ for iou_type in self.iou_types:
+ results = self.prepare(predictions, iou_type)
+
+ # suppress pycocotools prints
+ with open(os.devnull, "w") as devnull:
+ with contextlib.redirect_stdout(devnull):
+ coco_dt = COCO.loadRes(self.coco_gt, results) if results else COCO()
+
+ coco_eval = self.coco_eval[iou_type]
+
+ coco_eval.cocoDt = coco_dt
+ coco_eval.params.imgIds = list(img_ids)
+ coco_eval.params.useCats = self.useCats
+ img_ids, eval_imgs = evaluate(coco_eval)
+
+ self.eval_imgs[iou_type].append(eval_imgs)
+
+ def synchronize_between_processes(self):
+ for iou_type in self.iou_types:
+ self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2)
+ create_common_coco_eval(self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type])
+
+ def accumulate(self):
+ for coco_eval in self.coco_eval.values():
+ coco_eval.accumulate()
+
+ def summarize(self):
+ for iou_type, coco_eval in self.coco_eval.items():
+ print("IoU metric: {}".format(iou_type))
+ coco_eval.summarize()
+
+ def prepare(self, predictions, iou_type):
+ if iou_type == "bbox":
+ return self.prepare_for_coco_detection(predictions)
+ elif iou_type == "segm":
+ return self.prepare_for_coco_segmentation(predictions)
+ elif iou_type == "keypoints":
+ return self.prepare_for_coco_keypoint(predictions)
+ else:
+ raise ValueError("Unknown iou type {}".format(iou_type))
+
+ def prepare_for_coco_detection(self, predictions):
+ coco_results = []
+ for original_id, prediction in predictions.items():
+ if len(prediction) == 0:
+ continue
+
+ boxes = prediction["boxes"]
+ boxes = convert_to_xywh(boxes).tolist()
+ scores = prediction["scores"].tolist()
+ labels = prediction["labels"].tolist()
+
+ coco_results.extend(
+ [
+ {
+ "image_id": original_id,
+ "category_id": labels[k],
+ "bbox": box,
+ "score": scores[k],
+ }
+ for k, box in enumerate(boxes)
+ ]
+ )
+ return coco_results
+
+ def prepare_for_coco_segmentation(self, predictions):
+ coco_results = []
+ for original_id, prediction in predictions.items():
+ if len(prediction) == 0:
+ continue
+
+ scores = prediction["scores"]
+ labels = prediction["labels"]
+ masks = prediction["masks"]
+
+ masks = masks > 0.5
+
+ scores = prediction["scores"].tolist()
+ labels = prediction["labels"].tolist()
+
+ rles = [
+ mask_util.encode(np.array(mask[0, :, :, np.newaxis], dtype=np.uint8, order="F"))[0]
+ for mask in masks
+ ]
+ for rle in rles:
+ rle["counts"] = rle["counts"].decode("utf-8")
+
+ coco_results.extend(
+ [
+ {
+ "image_id": original_id,
+ "category_id": labels[k],
+ "segmentation": rle,
+ "score": scores[k],
+ }
+ for k, rle in enumerate(rles)
+ ]
+ )
+ return coco_results
+
+ def prepare_for_coco_keypoint(self, predictions):
+ coco_results = []
+ for original_id, prediction in predictions.items():
+ if len(prediction) == 0:
+ continue
+
+ boxes = prediction["boxes"]
+ boxes = convert_to_xywh(boxes).tolist()
+ scores = prediction["scores"].tolist()
+ labels = prediction["labels"].tolist()
+ keypoints = prediction["keypoints"]
+ keypoints = keypoints.flatten(start_dim=1).tolist()
+
+ coco_results.extend(
+ [
+ {
+ "image_id": original_id,
+ "category_id": labels[k],
+ "keypoints": keypoint,
+ "score": scores[k],
+ }
+ for k, keypoint in enumerate(keypoints)
+ ]
+ )
+ return coco_results
+
+
+def convert_to_xywh(boxes):
+ xmin, ymin, xmax, ymax = boxes.unbind(1)
+ return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1)
+
+
+def merge(img_ids, eval_imgs):
+ all_img_ids = all_gather(img_ids)
+ all_eval_imgs = all_gather(eval_imgs)
+
+ merged_img_ids = []
+ for p in all_img_ids:
+ merged_img_ids.extend(p)
+
+ merged_eval_imgs = []
+ for p in all_eval_imgs:
+ merged_eval_imgs.append(p)
+
+ merged_img_ids = np.array(merged_img_ids)
+ merged_eval_imgs = np.concatenate(merged_eval_imgs, 2)
+
+ # keep only unique (and in sorted order) images
+ merged_img_ids, idx = np.unique(merged_img_ids, return_index=True)
+ merged_eval_imgs = merged_eval_imgs[..., idx]
+
+ return merged_img_ids, merged_eval_imgs
+
+
+def create_common_coco_eval(coco_eval, img_ids, eval_imgs):
+ img_ids, eval_imgs = merge(img_ids, eval_imgs)
+ img_ids = list(img_ids)
+ eval_imgs = list(eval_imgs.flatten())
+
+ coco_eval.evalImgs = eval_imgs
+ coco_eval.params.imgIds = img_ids
+ coco_eval._paramsEval = copy.deepcopy(coco_eval.params)
+
+
+#################################################################
+# From pycocotools, just removed the prints and fixed
+# a Python3 bug about unicode not defined
+#################################################################
+
+
+def evaluate(self):
+ """
+ Run per image evaluation on given images and store results (a list of dict) in self.evalImgs
+ :return: None
+ """
+ # tic = time.time()
+ # print('Running per image evaluation...')
+ p = self.params
+ # add backward compatibility if useSegm is specified in params
+ if p.useSegm is not None:
+ p.iouType = "segm" if p.useSegm == 1 else "bbox"
+ print("useSegm (deprecated) is not None. Running {} evaluation".format(p.iouType))
+ # print('Evaluate annotation type *{}*'.format(p.iouType))
+ p.imgIds = list(np.unique(p.imgIds))
+ if p.useCats:
+ p.catIds = list(np.unique(p.catIds))
+ p.maxDets = sorted(p.maxDets)
+ self.params = p
+
+ self._prepare()
+ # loop through images, area range, max detection number
+ catIds = p.catIds if p.useCats else [-1]
+
+ if p.iouType == "segm" or p.iouType == "bbox":
+ computeIoU = self.computeIoU
+ elif p.iouType == "keypoints":
+ computeIoU = self.computeOks
+ self.ious = {
+ (imgId, catId): computeIoU(imgId, catId)
+ for imgId in p.imgIds
+ for catId in catIds}
+
+ evaluateImg = self.evaluateImg
+ maxDet = p.maxDets[-1]
+ evalImgs = [
+ evaluateImg(imgId, catId, areaRng, maxDet)
+ for catId in catIds
+ for areaRng in p.areaRng
+ for imgId in p.imgIds
+ ]
+ # this is NOT in the pycocotools code, but could be done outside
+ evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds))
+ self._paramsEval = copy.deepcopy(self.params)
+ # toc = time.time()
+ # print('DONE (t={:0.2f}s).'.format(toc-tic))
+ return p.imgIds, evalImgs
+
+
+#################################################################
+# end of straight copy from pycocotools, just removing the prints
+#################################################################
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/transforms.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..91cf9269e4b31008a3ddca34a19b038a9b399991
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/datasets/transforms.py
@@ -0,0 +1,311 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+Transforms and data augmentation for both image + bbox.
+"""
+import os
+import random
+
+import PIL
+import torch
+import torchvision.transforms as T
+import torchvision.transforms.functional as F
+
+from groundingdino.util.box_ops import box_xyxy_to_cxcywh
+from groundingdino.util.misc import interpolate
+
+
+def crop(image, target, region):
+ cropped_image = F.crop(image, *region)
+
+ target = target.copy()
+ i, j, h, w = region
+
+ # should we do something wrt the original size?
+ target["size"] = torch.tensor([h, w])
+
+ fields = ["labels", "area", "iscrowd", "positive_map"]
+
+ if "boxes" in target:
+ boxes = target["boxes"]
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i])
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
+ cropped_boxes = cropped_boxes.clamp(min=0)
+ area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
+ target["boxes"] = cropped_boxes.reshape(-1, 4)
+ target["area"] = area
+ fields.append("boxes")
+
+ if "masks" in target:
+ # FIXME should we update the area here if there are no boxes?
+ target["masks"] = target["masks"][:, i : i + h, j : j + w]
+ fields.append("masks")
+
+ # remove elements for which the boxes or masks that have zero area
+ if "boxes" in target or "masks" in target:
+ # favor boxes selection when defining which elements to keep
+ # this is compatible with previous implementation
+ if "boxes" in target:
+ cropped_boxes = target["boxes"].reshape(-1, 2, 2)
+ keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1)
+ else:
+ keep = target["masks"].flatten(1).any(1)
+
+ for field in fields:
+ if field in target:
+ target[field] = target[field][keep]
+
+ if os.environ.get("IPDB_SHILONG_DEBUG", None) == "INFO":
+ # for debug and visualization only.
+ if "strings_positive" in target:
+ target["strings_positive"] = [
+ _i for _i, _j in zip(target["strings_positive"], keep) if _j
+ ]
+
+ return cropped_image, target
+
+
+def hflip(image, target):
+ flipped_image = F.hflip(image)
+
+ w, h = image.size
+
+ target = target.copy()
+ if "boxes" in target:
+ boxes = target["boxes"]
+ boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor(
+ [w, 0, w, 0]
+ )
+ target["boxes"] = boxes
+
+ if "masks" in target:
+ target["masks"] = target["masks"].flip(-1)
+
+ return flipped_image, target
+
+
+def resize(image, target, size, max_size=None):
+ # size can be min_size (scalar) or (w, h) tuple
+
+ def get_size_with_aspect_ratio(image_size, size, max_size=None):
+ w, h = image_size
+ if max_size is not None:
+ min_original_size = float(min((w, h)))
+ max_original_size = float(max((w, h)))
+ if max_original_size / min_original_size * size > max_size:
+ size = int(round(max_size * min_original_size / max_original_size))
+
+ if (w <= h and w == size) or (h <= w and h == size):
+ return (h, w)
+
+ if w < h:
+ ow = size
+ oh = int(size * h / w)
+ else:
+ oh = size
+ ow = int(size * w / h)
+
+ return (oh, ow)
+
+ def get_size(image_size, size, max_size=None):
+ if isinstance(size, (list, tuple)):
+ return size[::-1]
+ else:
+ return get_size_with_aspect_ratio(image_size, size, max_size)
+
+ size = get_size(image.size, size, max_size)
+ rescaled_image = F.resize(image, size)
+
+ if target is None:
+ return rescaled_image, None
+
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size))
+ ratio_width, ratio_height = ratios
+
+ target = target.copy()
+ if "boxes" in target:
+ boxes = target["boxes"]
+ scaled_boxes = boxes * torch.as_tensor(
+ [ratio_width, ratio_height, ratio_width, ratio_height]
+ )
+ target["boxes"] = scaled_boxes
+
+ if "area" in target:
+ area = target["area"]
+ scaled_area = area * (ratio_width * ratio_height)
+ target["area"] = scaled_area
+
+ h, w = size
+ target["size"] = torch.tensor([h, w])
+
+ if "masks" in target:
+ target["masks"] = (
+ interpolate(target["masks"][:, None].float(), size, mode="nearest")[:, 0] > 0.5
+ )
+
+ return rescaled_image, target
+
+
+def pad(image, target, padding):
+ # assumes that we only pad on the bottom right corners
+ padded_image = F.pad(image, (0, 0, padding[0], padding[1]))
+ if target is None:
+ return padded_image, None
+ target = target.copy()
+ # should we do something wrt the original size?
+ target["size"] = torch.tensor(padded_image.size[::-1])
+ if "masks" in target:
+ target["masks"] = torch.nn.functional.pad(target["masks"], (0, padding[0], 0, padding[1]))
+ return padded_image, target
+
+
+class ResizeDebug(object):
+ def __init__(self, size):
+ self.size = size
+
+ def __call__(self, img, target):
+ return resize(img, target, self.size)
+
+
+class RandomCrop(object):
+ def __init__(self, size):
+ self.size = size
+
+ def __call__(self, img, target):
+ region = T.RandomCrop.get_params(img, self.size)
+ return crop(img, target, region)
+
+
+class RandomSizeCrop(object):
+ def __init__(self, min_size: int, max_size: int, respect_boxes: bool = False):
+ # respect_boxes: True to keep all boxes
+ # False to tolerence box filter
+ self.min_size = min_size
+ self.max_size = max_size
+ self.respect_boxes = respect_boxes
+
+ def __call__(self, img: PIL.Image.Image, target: dict):
+ init_boxes = len(target["boxes"])
+ max_patience = 10
+ for i in range(max_patience):
+ w = random.randint(self.min_size, min(img.width, self.max_size))
+ h = random.randint(self.min_size, min(img.height, self.max_size))
+ region = T.RandomCrop.get_params(img, [h, w])
+ result_img, result_target = crop(img, target, region)
+ if (
+ not self.respect_boxes
+ or len(result_target["boxes"]) == init_boxes
+ or i == max_patience - 1
+ ):
+ return result_img, result_target
+ return result_img, result_target
+
+
+class CenterCrop(object):
+ def __init__(self, size):
+ self.size = size
+
+ def __call__(self, img, target):
+ image_width, image_height = img.size
+ crop_height, crop_width = self.size
+ crop_top = int(round((image_height - crop_height) / 2.0))
+ crop_left = int(round((image_width - crop_width) / 2.0))
+ return crop(img, target, (crop_top, crop_left, crop_height, crop_width))
+
+
+class RandomHorizontalFlip(object):
+ def __init__(self, p=0.5):
+ self.p = p
+
+ def __call__(self, img, target):
+ if random.random() < self.p:
+ return hflip(img, target)
+ return img, target
+
+
+class RandomResize(object):
+ def __init__(self, sizes, max_size=None):
+ assert isinstance(sizes, (list, tuple))
+ self.sizes = sizes
+ self.max_size = max_size
+
+ def __call__(self, img, target=None):
+ size = random.choice(self.sizes)
+ return resize(img, target, size, self.max_size)
+
+
+class RandomPad(object):
+ def __init__(self, max_pad):
+ self.max_pad = max_pad
+
+ def __call__(self, img, target):
+ pad_x = random.randint(0, self.max_pad)
+ pad_y = random.randint(0, self.max_pad)
+ return pad(img, target, (pad_x, pad_y))
+
+
+class RandomSelect(object):
+ """
+ Randomly selects between transforms1 and transforms2,
+ with probability p for transforms1 and (1 - p) for transforms2
+ """
+
+ def __init__(self, transforms1, transforms2, p=0.5):
+ self.transforms1 = transforms1
+ self.transforms2 = transforms2
+ self.p = p
+
+ def __call__(self, img, target):
+ if random.random() < self.p:
+ return self.transforms1(img, target)
+ return self.transforms2(img, target)
+
+
+class ToTensor(object):
+ def __call__(self, img, target):
+ return F.to_tensor(img), target
+
+
+class RandomErasing(object):
+ def __init__(self, *args, **kwargs):
+ self.eraser = T.RandomErasing(*args, **kwargs)
+
+ def __call__(self, img, target):
+ return self.eraser(img), target
+
+
+class Normalize(object):
+ def __init__(self, mean, std):
+ self.mean = mean
+ self.std = std
+
+ def __call__(self, image, target=None):
+ image = F.normalize(image, mean=self.mean, std=self.std)
+ if target is None:
+ return image, None
+ target = target.copy()
+ h, w = image.shape[-2:]
+ if "boxes" in target:
+ boxes = target["boxes"]
+ boxes = box_xyxy_to_cxcywh(boxes)
+ boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32)
+ target["boxes"] = boxes
+ return image, target
+
+
+class Compose(object):
+ def __init__(self, transforms):
+ self.transforms = transforms
+
+ def __call__(self, image, target):
+ for t in self.transforms:
+ image, target = t(image, target)
+ return image, target
+
+ def __repr__(self):
+ format_string = self.__class__.__name__ + "("
+ for t in self.transforms:
+ format_string += "\n"
+ format_string += " {0}".format(t)
+ format_string += "\n)"
+ return format_string
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2af819d61d589cfec2e0ca46612a7456f42b831a
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/__init__.py
@@ -0,0 +1,15 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copied from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+from .groundingdino import build_groundingdino
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e4b272b479a26c63d120c818c140870cd8c287
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/__init__.py
@@ -0,0 +1 @@
+from .backbone import build_backbone
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/backbone.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8340c723fad8e07e2fc62daaa3912487498814b
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/backbone.py
@@ -0,0 +1,221 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copied from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+"""
+Backbone modules.
+"""
+
+from typing import Dict, List
+
+import torch
+import torch.nn.functional as F
+import torchvision
+from torch import nn
+from torchvision.models._utils import IntermediateLayerGetter
+
+from groundingdino.util.misc import NestedTensor, clean_state_dict, is_main_process
+
+from .position_encoding import build_position_encoding
+from .swin_transformer import build_swin_transformer
+
+
+class FrozenBatchNorm2d(torch.nn.Module):
+ """
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
+
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt,
+ without which any other models than torchvision.models.resnet[18,34,50,101]
+ produce nans.
+ """
+
+ def __init__(self, n):
+ super(FrozenBatchNorm2d, self).__init__()
+ self.register_buffer("weight", torch.ones(n))
+ self.register_buffer("bias", torch.zeros(n))
+ self.register_buffer("running_mean", torch.zeros(n))
+ self.register_buffer("running_var", torch.ones(n))
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ num_batches_tracked_key = prefix + "num_batches_tracked"
+ if num_batches_tracked_key in state_dict:
+ del state_dict[num_batches_tracked_key]
+
+ super(FrozenBatchNorm2d, self)._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ def forward(self, x):
+ # move reshapes to the beginning
+ # to make it fuser-friendly
+ w = self.weight.reshape(1, -1, 1, 1)
+ b = self.bias.reshape(1, -1, 1, 1)
+ rv = self.running_var.reshape(1, -1, 1, 1)
+ rm = self.running_mean.reshape(1, -1, 1, 1)
+ eps = 1e-5
+ scale = w * (rv + eps).rsqrt()
+ bias = b - rm * scale
+ return x * scale + bias
+
+
+class BackboneBase(nn.Module):
+ def __init__(
+ self,
+ backbone: nn.Module,
+ train_backbone: bool,
+ num_channels: int,
+ return_interm_indices: list,
+ ):
+ super().__init__()
+ for name, parameter in backbone.named_parameters():
+ if (
+ not train_backbone
+ or "layer2" not in name
+ and "layer3" not in name
+ and "layer4" not in name
+ ):
+ parameter.requires_grad_(False)
+
+ return_layers = {}
+ for idx, layer_index in enumerate(return_interm_indices):
+ return_layers.update(
+ {"layer{}".format(5 - len(return_interm_indices) + idx): "{}".format(layer_index)}
+ )
+
+ # if len:
+ # if use_stage1_feature:
+ # return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
+ # else:
+ # return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"}
+ # else:
+ # return_layers = {'layer4': "0"}
+ self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
+ self.num_channels = num_channels
+
+ def forward(self, tensor_list: NestedTensor):
+ xs = self.body(tensor_list.tensors)
+ out: Dict[str, NestedTensor] = {}
+ for name, x in xs.items():
+ m = tensor_list.mask
+ assert m is not None
+ mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0]
+ out[name] = NestedTensor(x, mask)
+ # import ipdb; ipdb.set_trace()
+ return out
+
+
+class Backbone(BackboneBase):
+ """ResNet backbone with frozen BatchNorm."""
+
+ def __init__(
+ self,
+ name: str,
+ train_backbone: bool,
+ dilation: bool,
+ return_interm_indices: list,
+ batch_norm=FrozenBatchNorm2d,
+ ):
+ if name in ["resnet18", "resnet34", "resnet50", "resnet101"]:
+ backbone = getattr(torchvision.models, name)(
+ replace_stride_with_dilation=[False, False, dilation],
+ pretrained=is_main_process(),
+ norm_layer=batch_norm,
+ )
+ else:
+ raise NotImplementedError("Why you can get here with name {}".format(name))
+ # num_channels = 512 if name in ('resnet18', 'resnet34') else 2048
+ assert name not in ("resnet18", "resnet34"), "Only resnet50 and resnet101 are available."
+ assert return_interm_indices in [[0, 1, 2, 3], [1, 2, 3], [3]]
+ num_channels_all = [256, 512, 1024, 2048]
+ num_channels = num_channels_all[4 - len(return_interm_indices) :]
+ super().__init__(backbone, train_backbone, num_channels, return_interm_indices)
+
+
+class Joiner(nn.Sequential):
+ def __init__(self, backbone, position_embedding):
+ super().__init__(backbone, position_embedding)
+
+ def forward(self, tensor_list: NestedTensor):
+ xs = self[0](tensor_list)
+ out: List[NestedTensor] = []
+ pos = []
+ for name, x in xs.items():
+ out.append(x)
+ # position encoding
+ pos.append(self[1](x).to(x.tensors.dtype))
+
+ return out, pos
+
+
+def build_backbone(args):
+ """
+ Useful args:
+ - backbone: backbone name
+ - lr_backbone:
+ - dilation
+ - return_interm_indices: available: [0,1,2,3], [1,2,3], [3]
+ - backbone_freeze_keywords:
+ - use_checkpoint: for swin only for now
+
+ """
+ position_embedding = build_position_encoding(args)
+ train_backbone = True
+ if not train_backbone:
+ raise ValueError("Please set lr_backbone > 0")
+ return_interm_indices = args.return_interm_indices
+ assert return_interm_indices in [[0, 1, 2, 3], [1, 2, 3], [3]]
+ args.backbone_freeze_keywords
+ use_checkpoint = getattr(args, "use_checkpoint", False)
+
+ if args.backbone in ["resnet50", "resnet101"]:
+ backbone = Backbone(
+ args.backbone,
+ train_backbone,
+ args.dilation,
+ return_interm_indices,
+ batch_norm=FrozenBatchNorm2d,
+ )
+ bb_num_channels = backbone.num_channels
+ elif args.backbone in [
+ "swin_T_224_1k",
+ "swin_B_224_22k",
+ "swin_B_384_22k",
+ "swin_L_224_22k",
+ "swin_L_384_22k",
+ ]:
+ pretrain_img_size = int(args.backbone.split("_")[-2])
+ backbone = build_swin_transformer(
+ args.backbone,
+ pretrain_img_size=pretrain_img_size,
+ out_indices=tuple(return_interm_indices),
+ dilation=False,
+ use_checkpoint=use_checkpoint,
+ )
+
+ bb_num_channels = backbone.num_features[4 - len(return_interm_indices) :]
+ else:
+ raise NotImplementedError("Unknown backbone {}".format(args.backbone))
+
+ assert len(bb_num_channels) == len(
+ return_interm_indices
+ ), f"len(bb_num_channels) {len(bb_num_channels)} != len(return_interm_indices) {len(return_interm_indices)}"
+
+ model = Joiner(backbone, position_embedding)
+ model.num_channels = bb_num_channels
+ assert isinstance(
+ bb_num_channels, List
+ ), "bb_num_channels is expected to be a List but {}".format(type(bb_num_channels))
+ # import ipdb; ipdb.set_trace()
+ return model
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/position_encoding.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/position_encoding.py
new file mode 100644
index 0000000000000000000000000000000000000000..eac7e896bbe85a670824bfe8ef487d0535d5bd99
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/position_encoding.py
@@ -0,0 +1,186 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# DINO
+# Copyright (c) 2022 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copied from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+"""
+Various positional encodings for the transformer.
+"""
+import math
+
+import torch
+from torch import nn
+
+from groundingdino.util.misc import NestedTensor
+
+
+class PositionEmbeddingSine(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one
+ used by the Attention is all you need paper, generalized to work on images.
+ """
+
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
+ super().__init__()
+ self.num_pos_feats = num_pos_feats
+ self.temperature = temperature
+ self.normalize = normalize
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ if scale is None:
+ scale = 2 * math.pi
+ self.scale = scale
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+ mask = tensor_list.mask
+ assert mask is not None
+ not_mask = ~mask
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
+ if self.normalize:
+ eps = 1e-6
+ # if os.environ.get("SHILONG_AMP", None) == '1':
+ # eps = 1e-4
+ # else:
+ # eps = 1e-6
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
+
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
+
+ pos_x = x_embed[:, :, :, None] / dim_t
+ pos_y = y_embed[:, :, :, None] / dim_t
+ pos_x = torch.stack(
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos_y = torch.stack(
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+ return pos
+
+
+class PositionEmbeddingSineHW(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one
+ used by the Attention is all you need paper, generalized to work on images.
+ """
+
+ def __init__(
+ self, num_pos_feats=64, temperatureH=10000, temperatureW=10000, normalize=False, scale=None
+ ):
+ super().__init__()
+ self.num_pos_feats = num_pos_feats
+ self.temperatureH = temperatureH
+ self.temperatureW = temperatureW
+ self.normalize = normalize
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ if scale is None:
+ scale = 2 * math.pi
+ self.scale = scale
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+ mask = tensor_list.mask
+ assert mask is not None
+ not_mask = ~mask
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
+
+ # import ipdb; ipdb.set_trace()
+
+ if self.normalize:
+ eps = 1e-6
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
+
+ dim_tx = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
+ dim_tx = self.temperatureW ** (2 * (torch.div(dim_tx, 2, rounding_mode='floor')) / self.num_pos_feats)
+ pos_x = x_embed[:, :, :, None] / dim_tx
+
+ dim_ty = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
+ dim_ty = self.temperatureH ** (2 * (torch.div(dim_ty, 2, rounding_mode='floor')) / self.num_pos_feats)
+ pos_y = y_embed[:, :, :, None] / dim_ty
+
+ pos_x = torch.stack(
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos_y = torch.stack(
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+
+ # import ipdb; ipdb.set_trace()
+
+ return pos
+
+
+class PositionEmbeddingLearned(nn.Module):
+ """
+ Absolute pos embedding, learned.
+ """
+
+ def __init__(self, num_pos_feats=256):
+ super().__init__()
+ self.row_embed = nn.Embedding(50, num_pos_feats)
+ self.col_embed = nn.Embedding(50, num_pos_feats)
+ self.reset_parameters()
+
+ def reset_parameters(self):
+ nn.init.uniform_(self.row_embed.weight)
+ nn.init.uniform_(self.col_embed.weight)
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+ h, w = x.shape[-2:]
+ i = torch.arange(w, device=x.device)
+ j = torch.arange(h, device=x.device)
+ x_emb = self.col_embed(i)
+ y_emb = self.row_embed(j)
+ pos = (
+ torch.cat(
+ [
+ x_emb.unsqueeze(0).repeat(h, 1, 1),
+ y_emb.unsqueeze(1).repeat(1, w, 1),
+ ],
+ dim=-1,
+ )
+ .permute(2, 0, 1)
+ .unsqueeze(0)
+ .repeat(x.shape[0], 1, 1, 1)
+ )
+ return pos
+
+
+def build_position_encoding(args):
+ N_steps = args.hidden_dim // 2
+ if args.position_embedding in ("v2", "sine"):
+ # TODO find a better way of exposing other arguments
+ position_embedding = PositionEmbeddingSineHW(
+ N_steps,
+ temperatureH=args.pe_temperatureH,
+ temperatureW=args.pe_temperatureW,
+ normalize=True,
+ )
+ elif args.position_embedding in ("v3", "learned"):
+ position_embedding = PositionEmbeddingLearned(N_steps)
+ else:
+ raise ValueError(f"not supported {args.position_embedding}")
+
+ return position_embedding
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/swin_transformer.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/swin_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c66194deb5dd370e797e57e2712f44303e568cc
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/backbone/swin_transformer.py
@@ -0,0 +1,802 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# DINO
+# Copyright (c) 2022 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# --------------------------------------------------------
+# modified from https://github.com/SwinTransformer/Swin-Transformer-Object-Detection/blob/master/mmdet/models/backbones/swin_transformer.py
+# --------------------------------------------------------
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as checkpoint
+from timm.models.layers import DropPath, to_2tuple, trunc_normal_
+
+from groundingdino.util.misc import NestedTensor
+
+
+class Mlp(nn.Module):
+ """Multilayer perceptron."""
+
+ def __init__(
+ self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
+ B, H, W, C = x.shape
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
+ return windows
+
+
+def window_reverse(windows, window_size, H, W):
+ """
+ Args:
+ windows: (num_windows*B, window_size, window_size, C)
+ window_size (int): Window size
+ H (int): Height of image
+ W (int): Width of image
+ Returns:
+ x: (B, H, W, C)
+ """
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
+ return x
+
+
+class WindowAttention(nn.Module):
+ """Window based multi-head self attention (W-MSA) module with relative position bias.
+ It supports both of shifted and non-shifted window.
+ Args:
+ dim (int): Number of input channels.
+ window_size (tuple[int]): The height and width of the window.
+ num_heads (int): Number of attention heads.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
+ """
+
+ def __init__(
+ self,
+ dim,
+ window_size,
+ num_heads,
+ qkv_bias=True,
+ qk_scale=None,
+ attn_drop=0.0,
+ proj_drop=0.0,
+ ):
+
+ super().__init__()
+ self.dim = dim
+ self.window_size = window_size # Wh, Ww
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = qk_scale or head_dim**-0.5
+
+ # define a parameter table of relative position bias
+ self.relative_position_bias_table = nn.Parameter(
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
+ ) # 2*Wh-1 * 2*Ww-1, nH
+
+ # get pair-wise relative position index for each token inside the window
+ coords_h = torch.arange(self.window_size[0])
+ coords_w = torch.arange(self.window_size[1])
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
+ relative_coords[:, :, 1] += self.window_size[1] - 1
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
+ self.register_buffer("relative_position_index", relative_position_index)
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ trunc_normal_(self.relative_position_bias_table, std=0.02)
+ self.softmax = nn.Softmax(dim=-1)
+
+ def forward(self, x, mask=None):
+ """Forward function.
+ Args:
+ x: input features with shape of (num_windows*B, N, C)
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
+ """
+ B_, N, C = x.shape
+ qkv = (
+ self.qkv(x)
+ .reshape(B_, N, 3, self.num_heads, C // self.num_heads)
+ .permute(2, 0, 3, 1, 4)
+ )
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
+
+ q = q * self.scale
+ attn = q @ k.transpose(-2, -1)
+
+ relative_position_bias = self.relative_position_bias_table[
+ self.relative_position_index.view(-1)
+ ].view(
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
+ ) # Wh*Ww,Wh*Ww,nH
+ relative_position_bias = relative_position_bias.permute(
+ 2, 0, 1
+ ).contiguous() # nH, Wh*Ww, Wh*Ww
+ attn = attn + relative_position_bias.unsqueeze(0)
+
+ if mask is not None:
+ nW = mask.shape[0]
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
+ attn = attn.view(-1, self.num_heads, N, N)
+ attn = self.softmax(attn)
+ else:
+ attn = self.softmax(attn)
+
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+
+class SwinTransformerBlock(nn.Module):
+ """Swin Transformer Block.
+ Args:
+ dim (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ window_size (int): Window size.
+ shift_size (int): Shift size for SW-MSA.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(
+ self,
+ dim,
+ num_heads,
+ window_size=7,
+ shift_size=0,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop=0.0,
+ attn_drop=0.0,
+ drop_path=0.0,
+ act_layer=nn.GELU,
+ norm_layer=nn.LayerNorm,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.shift_size = shift_size
+ self.mlp_ratio = mlp_ratio
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
+
+ self.norm1 = norm_layer(dim)
+ self.attn = WindowAttention(
+ dim,
+ window_size=to_2tuple(self.window_size),
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop=attn_drop,
+ proj_drop=drop,
+ )
+
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.norm2 = norm_layer(dim)
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = Mlp(
+ in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop
+ )
+
+ self.H = None
+ self.W = None
+
+ def forward(self, x, mask_matrix):
+ """Forward function.
+ Args:
+ x: Input feature, tensor size (B, H*W, C).
+ H, W: Spatial resolution of the input feature.
+ mask_matrix: Attention mask for cyclic shift.
+ """
+ B, L, C = x.shape
+ H, W = self.H, self.W
+ assert L == H * W, "input feature has wrong size"
+
+ shortcut = x
+ x = self.norm1(x)
+ x = x.view(B, H, W, C)
+
+ # pad feature maps to multiples of window size
+ pad_l = pad_t = 0
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
+ _, Hp, Wp, _ = x.shape
+
+ # cyclic shift
+ if self.shift_size > 0:
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
+ attn_mask = mask_matrix
+ else:
+ shifted_x = x
+ attn_mask = None
+
+ # partition windows
+ x_windows = window_partition(
+ shifted_x, self.window_size
+ ) # nW*B, window_size, window_size, C
+ x_windows = x_windows.view(
+ -1, self.window_size * self.window_size, C
+ ) # nW*B, window_size*window_size, C
+
+ # W-MSA/SW-MSA
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
+
+ # merge windows
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
+
+ # reverse cyclic shift
+ if self.shift_size > 0:
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
+ else:
+ x = shifted_x
+
+ if pad_r > 0 or pad_b > 0:
+ x = x[:, :H, :W, :].contiguous()
+
+ x = x.view(B, H * W, C)
+
+ # FFN
+ x = shortcut + self.drop_path(x)
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
+
+ return x
+
+
+class PatchMerging(nn.Module):
+ """Patch Merging Layer
+ Args:
+ dim (int): Number of input channels.
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
+ super().__init__()
+ self.dim = dim
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
+ self.norm = norm_layer(4 * dim)
+
+ def forward(self, x, H, W):
+ """Forward function.
+ Args:
+ x: Input feature, tensor size (B, H*W, C).
+ H, W: Spatial resolution of the input feature.
+ """
+ B, L, C = x.shape
+ assert L == H * W, "input feature has wrong size"
+
+ x = x.view(B, H, W, C)
+
+ # padding
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
+ if pad_input:
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
+
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
+
+ x = self.norm(x)
+ x = self.reduction(x)
+
+ return x
+
+
+class BasicLayer(nn.Module):
+ """A basic Swin Transformer layer for one stage.
+ Args:
+ dim (int): Number of feature channels
+ depth (int): Depths of this stage.
+ num_heads (int): Number of attention head.
+ window_size (int): Local window size. Default: 7.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
+ """
+
+ def __init__(
+ self,
+ dim,
+ depth,
+ num_heads,
+ window_size=7,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop=0.0,
+ attn_drop=0.0,
+ drop_path=0.0,
+ norm_layer=nn.LayerNorm,
+ downsample=None,
+ use_checkpoint=False,
+ ):
+ super().__init__()
+ self.window_size = window_size
+ self.shift_size = window_size // 2
+ self.depth = depth
+ self.use_checkpoint = use_checkpoint
+
+ # build blocks
+ self.blocks = nn.ModuleList(
+ [
+ SwinTransformerBlock(
+ dim=dim,
+ num_heads=num_heads,
+ window_size=window_size,
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop,
+ attn_drop=attn_drop,
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
+ norm_layer=norm_layer,
+ )
+ for i in range(depth)
+ ]
+ )
+
+ # patch merging layer
+ if downsample is not None:
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
+ else:
+ self.downsample = None
+
+ def forward(self, x, H, W):
+ """Forward function.
+ Args:
+ x: Input feature, tensor size (B, H*W, C).
+ H, W: Spatial resolution of the input feature.
+ """
+
+ # calculate attention mask for SW-MSA
+ Hp = int(np.ceil(H / self.window_size)) * self.window_size
+ Wp = int(np.ceil(W / self.window_size)) * self.window_size
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
+ h_slices = (
+ slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None),
+ )
+ w_slices = (
+ slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None),
+ )
+ cnt = 0
+ for h in h_slices:
+ for w in w_slices:
+ img_mask[:, h, w, :] = cnt
+ cnt += 1
+
+ mask_windows = window_partition(
+ img_mask, self.window_size
+ ) # nW, window_size, window_size, 1
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
+ attn_mask == 0, float(0.0)
+ )
+
+ for blk in self.blocks:
+ blk.H, blk.W = H, W
+ if self.use_checkpoint:
+ x = checkpoint.checkpoint(blk, x, attn_mask)
+ else:
+ x = blk(x, attn_mask)
+ if self.downsample is not None:
+ x_down = self.downsample(x, H, W)
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
+ return x, H, W, x_down, Wh, Ww
+ else:
+ return x, H, W, x, H, W
+
+
+class PatchEmbed(nn.Module):
+ """Image to Patch Embedding
+ Args:
+ patch_size (int): Patch token size. Default: 4.
+ in_chans (int): Number of input image channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
+ """
+
+ def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
+ super().__init__()
+ patch_size = to_2tuple(patch_size)
+ self.patch_size = patch_size
+
+ self.in_chans = in_chans
+ self.embed_dim = embed_dim
+
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
+ if norm_layer is not None:
+ self.norm = norm_layer(embed_dim)
+ else:
+ self.norm = None
+
+ def forward(self, x):
+ """Forward function."""
+ # padding
+ _, _, H, W = x.size()
+ if W % self.patch_size[1] != 0:
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
+ if H % self.patch_size[0] != 0:
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
+
+ x = self.proj(x) # B C Wh Ww
+ if self.norm is not None:
+ Wh, Ww = x.size(2), x.size(3)
+ x = x.flatten(2).transpose(1, 2)
+ x = self.norm(x)
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
+
+ return x
+
+
+class SwinTransformer(nn.Module):
+ """Swin Transformer backbone.
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
+ https://arxiv.org/pdf/2103.14030
+ Args:
+ pretrain_img_size (int): Input image size for training the pretrained model,
+ used in absolute postion embedding. Default 224.
+ patch_size (int | tuple(int)): Patch size. Default: 4.
+ in_chans (int): Number of input image channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ depths (tuple[int]): Depths of each Swin Transformer stage.
+ num_heads (tuple[int]): Number of attention head of each stage.
+ window_size (int): Window size. Default: 7.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
+ drop_rate (float): Dropout rate.
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
+ out_indices (Sequence[int]): Output from which stages.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters.
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
+ dilation (bool): if True, the output size if 16x downsample, ow 32x downsample.
+ """
+
+ def __init__(
+ self,
+ pretrain_img_size=224,
+ patch_size=4,
+ in_chans=3,
+ embed_dim=96,
+ depths=[2, 2, 6, 2],
+ num_heads=[3, 6, 12, 24],
+ window_size=7,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop_rate=0.0,
+ attn_drop_rate=0.0,
+ drop_path_rate=0.2,
+ norm_layer=nn.LayerNorm,
+ ape=False,
+ patch_norm=True,
+ out_indices=(0, 1, 2, 3),
+ frozen_stages=-1,
+ dilation=False,
+ use_checkpoint=False,
+ ):
+ super().__init__()
+
+ self.pretrain_img_size = pretrain_img_size
+ self.num_layers = len(depths)
+ self.embed_dim = embed_dim
+ self.ape = ape
+ self.patch_norm = patch_norm
+ self.out_indices = out_indices
+ self.frozen_stages = frozen_stages
+ self.dilation = dilation
+
+ # if use_checkpoint:
+ # print("use_checkpoint!!!!!!!!!!!!!!!!!!!!!!!!")
+
+ # split image into non-overlapping patches
+ self.patch_embed = PatchEmbed(
+ patch_size=patch_size,
+ in_chans=in_chans,
+ embed_dim=embed_dim,
+ norm_layer=norm_layer if self.patch_norm else None,
+ )
+
+ # absolute position embedding
+ if self.ape:
+ pretrain_img_size = to_2tuple(pretrain_img_size)
+ patch_size = to_2tuple(patch_size)
+ patches_resolution = [
+ pretrain_img_size[0] // patch_size[0],
+ pretrain_img_size[1] // patch_size[1],
+ ]
+
+ self.absolute_pos_embed = nn.Parameter(
+ torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])
+ )
+ trunc_normal_(self.absolute_pos_embed, std=0.02)
+
+ self.pos_drop = nn.Dropout(p=drop_rate)
+
+ # stochastic depth
+ dpr = [
+ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
+ ] # stochastic depth decay rule
+
+ # build layers
+ self.layers = nn.ModuleList()
+ # prepare downsample list
+ downsamplelist = [PatchMerging for i in range(self.num_layers)]
+ downsamplelist[-1] = None
+ num_features = [int(embed_dim * 2**i) for i in range(self.num_layers)]
+ if self.dilation:
+ downsamplelist[-2] = None
+ num_features[-1] = int(embed_dim * 2 ** (self.num_layers - 1)) // 2
+ for i_layer in range(self.num_layers):
+ layer = BasicLayer(
+ # dim=int(embed_dim * 2 ** i_layer),
+ dim=num_features[i_layer],
+ depth=depths[i_layer],
+ num_heads=num_heads[i_layer],
+ window_size=window_size,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop_rate,
+ attn_drop=attn_drop_rate,
+ drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],
+ norm_layer=norm_layer,
+ # downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
+ downsample=downsamplelist[i_layer],
+ use_checkpoint=use_checkpoint,
+ )
+ self.layers.append(layer)
+
+ # num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
+ self.num_features = num_features
+
+ # add a norm layer for each output
+ for i_layer in out_indices:
+ layer = norm_layer(num_features[i_layer])
+ layer_name = f"norm{i_layer}"
+ self.add_module(layer_name, layer)
+
+ self._freeze_stages()
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+
+ if self.frozen_stages >= 1 and self.ape:
+ self.absolute_pos_embed.requires_grad = False
+
+ if self.frozen_stages >= 2:
+ self.pos_drop.eval()
+ for i in range(0, self.frozen_stages - 1):
+ m = self.layers[i]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ # def init_weights(self, pretrained=None):
+ # """Initialize the weights in backbone.
+ # Args:
+ # pretrained (str, optional): Path to pre-trained weights.
+ # Defaults to None.
+ # """
+
+ # def _init_weights(m):
+ # if isinstance(m, nn.Linear):
+ # trunc_normal_(m.weight, std=.02)
+ # if isinstance(m, nn.Linear) and m.bias is not None:
+ # nn.init.constant_(m.bias, 0)
+ # elif isinstance(m, nn.LayerNorm):
+ # nn.init.constant_(m.bias, 0)
+ # nn.init.constant_(m.weight, 1.0)
+
+ # if isinstance(pretrained, str):
+ # self.apply(_init_weights)
+ # logger = get_root_logger()
+ # load_checkpoint(self, pretrained, strict=False, logger=logger)
+ # elif pretrained is None:
+ # self.apply(_init_weights)
+ # else:
+ # raise TypeError('pretrained must be a str or None')
+
+ def forward_raw(self, x):
+ """Forward function."""
+ x = self.patch_embed(x)
+
+ Wh, Ww = x.size(2), x.size(3)
+ if self.ape:
+ # interpolate the position embedding to the corresponding size
+ absolute_pos_embed = F.interpolate(
+ self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"
+ )
+ x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C
+ else:
+ x = x.flatten(2).transpose(1, 2)
+ x = self.pos_drop(x)
+
+ outs = []
+ for i in range(self.num_layers):
+ layer = self.layers[i]
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
+ # import ipdb; ipdb.set_trace()
+
+ if i in self.out_indices:
+ norm_layer = getattr(self, f"norm{i}")
+ x_out = norm_layer(x_out)
+
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
+ outs.append(out)
+ # in:
+ # torch.Size([2, 3, 1024, 1024])
+ # outs:
+ # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \
+ # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])]
+ return tuple(outs)
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+
+ """Forward function."""
+ x = self.patch_embed(x)
+
+ Wh, Ww = x.size(2), x.size(3)
+ if self.ape:
+ # interpolate the position embedding to the corresponding size
+ absolute_pos_embed = F.interpolate(
+ self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"
+ )
+ x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C
+ else:
+ x = x.flatten(2).transpose(1, 2)
+ x = self.pos_drop(x)
+
+ outs = []
+ for i in range(self.num_layers):
+ layer = self.layers[i]
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
+
+ if i in self.out_indices:
+ norm_layer = getattr(self, f"norm{i}")
+ x_out = norm_layer(x_out)
+
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
+ outs.append(out)
+ # in:
+ # torch.Size([2, 3, 1024, 1024])
+ # out:
+ # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \
+ # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])]
+
+ # collect for nesttensors
+ outs_dict = {}
+ for idx, out_i in enumerate(outs):
+ m = tensor_list.mask
+ assert m is not None
+ mask = F.interpolate(m[None].float(), size=out_i.shape[-2:]).to(torch.bool)[0]
+ outs_dict[idx] = NestedTensor(out_i, mask)
+
+ return outs_dict
+
+ def train(self, mode=True):
+ """Convert the model into training mode while keep layers freezed."""
+ super(SwinTransformer, self).train(mode)
+ self._freeze_stages()
+
+
+def build_swin_transformer(modelname, pretrain_img_size, **kw):
+ assert modelname in [
+ "swin_T_224_1k",
+ "swin_B_224_22k",
+ "swin_B_384_22k",
+ "swin_L_224_22k",
+ "swin_L_384_22k",
+ ]
+
+ model_para_dict = {
+ "swin_T_224_1k": dict(
+ embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7
+ ),
+ "swin_B_224_22k": dict(
+ embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7
+ ),
+ "swin_B_384_22k": dict(
+ embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12
+ ),
+ "swin_L_224_22k": dict(
+ embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=7
+ ),
+ "swin_L_384_22k": dict(
+ embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12
+ ),
+ }
+ kw_cgf = model_para_dict[modelname]
+ kw_cgf.update(kw)
+ model = SwinTransformer(pretrain_img_size=pretrain_img_size, **kw_cgf)
+ return model
+
+
+if __name__ == "__main__":
+ model = build_swin_transformer("swin_L_384_22k", 384, dilation=True)
+ x = torch.rand(2, 3, 1024, 1024)
+ y = model.forward_raw(x)
+ import ipdb
+
+ ipdb.set_trace()
+ x = torch.rand(2, 3, 384, 384)
+ y = model.forward_raw(x)
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/bertwarper.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/bertwarper.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0cf9779b270e1aead32845006f8b881fcba37ad
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/bertwarper.py
@@ -0,0 +1,273 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+
+import torch
+import torch.nn.functional as F
+import torch.utils.checkpoint as checkpoint
+from torch import Tensor, nn
+from torchvision.ops.boxes import nms
+from transformers import BertConfig, BertModel, BertPreTrainedModel
+from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
+
+
+class BertModelWarper(nn.Module):
+ def __init__(self, bert_model):
+ super().__init__()
+ # self.bert = bert_modelc
+
+ self.config = bert_model.config
+ self.embeddings = bert_model.embeddings
+ self.encoder = bert_model.encoder
+ self.pooler = bert_model.pooler
+
+ self.get_extended_attention_mask = bert_model.get_extended_attention_mask
+ self.invert_attention_mask = bert_model.invert_attention_mask
+ self.get_head_mask = bert_model.get_head_mask
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ token_type_ids=None,
+ position_ids=None,
+ head_mask=None,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
+ use_cache (:obj:`bool`, `optional`):
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
+ decoding (see :obj:`past_key_values`).
+ """
+ output_attentions = (
+ output_attentions if output_attentions is not None else self.config.output_attentions
+ )
+ output_hidden_states = (
+ output_hidden_states
+ if output_hidden_states is not None
+ else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_shape = input_ids.size()
+ batch_size, seq_length = input_shape
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ batch_size, seq_length = input_shape
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ # past_key_values_length
+ past_key_values_length = (
+ past_key_values[0][0].shape[2] if past_key_values is not None else 0
+ )
+
+ if attention_mask is None:
+ attention_mask = torch.ones(
+ ((batch_size, seq_length + past_key_values_length)), device=device
+ )
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
+ attention_mask, input_shape, device
+ )
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+class TextEncoderShell(nn.Module):
+ def __init__(self, text_encoder):
+ super().__init__()
+ self.text_encoder = text_encoder
+ self.config = self.text_encoder.config
+
+ def forward(self, **kw):
+ # feed into text encoder
+ return self.text_encoder(**kw)
+
+
+def generate_masks_with_special_tokens(tokenized, special_tokens_list, tokenizer):
+ """Generate attention mask between each pair of special tokens
+ Args:
+ input_ids (torch.Tensor): input ids. Shape: [bs, num_token]
+ special_tokens_mask (list): special tokens mask.
+ Returns:
+ torch.Tensor: attention mask between each special tokens.
+ """
+ input_ids = tokenized["input_ids"]
+ bs, num_token = input_ids.shape
+ # special_tokens_mask: bs, num_token. 1 for special tokens. 0 for normal tokens
+ special_tokens_mask = torch.zeros((bs, num_token), device=input_ids.device).bool()
+ for special_token in special_tokens_list:
+ special_tokens_mask |= input_ids == special_token
+
+ # idxs: each row is a list of indices of special tokens
+ idxs = torch.nonzero(special_tokens_mask)
+
+ # generate attention mask and positional ids
+ attention_mask = (
+ torch.eye(num_token, device=input_ids.device).bool().unsqueeze(0).repeat(bs, 1, 1)
+ )
+ position_ids = torch.zeros((bs, num_token), device=input_ids.device)
+ previous_col = 0
+ for i in range(idxs.shape[0]):
+ row, col = idxs[i]
+ if (col == 0) or (col == num_token - 1):
+ attention_mask[row, col, col] = True
+ position_ids[row, col] = 0
+ else:
+ attention_mask[row, previous_col + 1 : col + 1, previous_col + 1 : col + 1] = True
+ position_ids[row, previous_col + 1 : col + 1] = torch.arange(
+ 0, col - previous_col, device=input_ids.device
+ )
+
+ previous_col = col
+
+ # # padding mask
+ # padding_mask = tokenized['attention_mask']
+ # attention_mask = attention_mask & padding_mask.unsqueeze(1).bool() & padding_mask.unsqueeze(2).bool()
+
+ return attention_mask, position_ids.to(torch.long)
+
+
+def generate_masks_with_special_tokens_and_transfer_map(tokenized, special_tokens_list, tokenizer):
+ """Generate attention mask between each pair of special tokens
+ Args:
+ input_ids (torch.Tensor): input ids. Shape: [bs, num_token]
+ special_tokens_mask (list): special tokens mask.
+ Returns:
+ torch.Tensor: attention mask between each special tokens.
+ """
+ input_ids = tokenized["input_ids"]
+ bs, num_token = input_ids.shape
+ # special_tokens_mask: bs, num_token. 1 for special tokens. 0 for normal tokens
+ special_tokens_mask = torch.zeros((bs, num_token), device=input_ids.device).bool()
+ for special_token in special_tokens_list:
+ special_tokens_mask |= input_ids == special_token
+
+ # idxs: each row is a list of indices of special tokens
+ idxs = torch.nonzero(special_tokens_mask)
+
+ # generate attention mask and positional ids
+ attention_mask = (
+ torch.eye(num_token, device=input_ids.device).bool().unsqueeze(0).repeat(bs, 1, 1)
+ )
+ position_ids = torch.zeros((bs, num_token), device=input_ids.device)
+ cate_to_token_mask_list = [[] for _ in range(bs)]
+ previous_col = 0
+ for i in range(idxs.shape[0]):
+ row, col = idxs[i]
+ if (col == 0) or (col == num_token - 1):
+ attention_mask[row, col, col] = True
+ position_ids[row, col] = 0
+ else:
+ attention_mask[row, previous_col + 1 : col + 1, previous_col + 1 : col + 1] = True
+ position_ids[row, previous_col + 1 : col + 1] = torch.arange(
+ 0, col - previous_col, device=input_ids.device
+ )
+ c2t_maski = torch.zeros((num_token), device=input_ids.device).bool()
+ c2t_maski[previous_col + 1 : col] = True
+ cate_to_token_mask_list[row].append(c2t_maski)
+ previous_col = col
+
+ cate_to_token_mask_list = [
+ torch.stack(cate_to_token_mask_listi, dim=0)
+ for cate_to_token_mask_listi in cate_to_token_mask_list
+ ]
+
+ # # padding mask
+ # padding_mask = tokenized['attention_mask']
+ # attention_mask = attention_mask & padding_mask.unsqueeze(1).bool() & padding_mask.unsqueeze(2).bool()
+
+ return attention_mask, position_ids.to(torch.long), cate_to_token_mask_list
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.h b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.h
new file mode 100644
index 0000000000000000000000000000000000000000..eef05e2eb8f3db8a4ab60701933b4c333ad04603
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.h
@@ -0,0 +1,92 @@
+/*!
+ **************************************************************************************************
+ * Deformable DETR
+ * Copyright (c) 2020 SenseTime. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+ **************************************************************************************************
+ * Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+ **************************************************************************************************
+ */
+
+#pragma once
+
+#include "ms_deform_attn_cpu.h"
+
+#ifdef WITH_CUDA
+#include "ms_deform_attn_cuda.h"
+#endif
+
+namespace groundingdino {
+
+/**
+ * Forward interface (CPU + CUDA) for the deformable attention operator.
+ *
+ * 参数说明(保持与原代码一致):
+ * - value: (N, S, nhead, C) 输入特征
+ * - spatial_shapes: (nlevel, 2) 每个特征层的 (H, W)
+ * - level_start_index: (nlevel) 每层在拼接后 feature map 的起始位置
+ * - sampling_loc: (N, Lq, nhead, nlevel, npoint, 2) 采样坐标
+ * - attn_weight: (N, Lq, nhead, nlevel, npoint) attention 权重
+ * - im2col_step: 计算时的 batch 子块大小(默认 = min(N, 64))
+ *
+ * 该函数会根据 Tensor 是否在 CUDA 上自动分派到对应实现。
+ */
+static inline at::Tensor
+ms_deform_attn_forward(const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step) {
+ // 使用新版 API 检查是否在 CUDA 上(已在 PyTorch 2.x 中废弃 .type())
+ if (value.is_cuda()) {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_forward(value,
+ spatial_shapes,
+ level_start_index,
+ sampling_loc,
+ attn_weight,
+ im2col_step);
+#else
+ AT_ERROR("GroundingDINO was compiled without CUDA support");
+#endif
+ }
+
+ // 这里保留原来的 “CPU not implemented” 报错,防止误用
+ AT_ERROR("GroundingDINO ms_deform_attn_forward CPU implementation is not provided");
+}
+
+/**
+ * Backward interface (CPU + CUDA) for the deformable attention operator.
+ *
+ * 与 forward 对称,返回三个梯度:
+ * - grad_value
+ * - grad_sampling_loc
+ * - grad_attn_weight
+ */
+static inline std::vector
+ms_deform_attn_backward(const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step) {
+ if (value.is_cuda()) {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_backward(value,
+ spatial_shapes,
+ level_start_index,
+ sampling_loc,
+ attn_weight,
+ grad_output,
+ im2col_step);
+#else
+ AT_ERROR("GroundingDINO was compiled without CUDA support");
+#endif
+ }
+
+ AT_ERROR("GroundingDINO ms_deform_attn_backward CPU implementation is not provided");
+}
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cpp b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..551243fdadfd1682b5dc6628623b67a79b3f6c74
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cpp
@@ -0,0 +1,43 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+namespace groundingdino {
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+} // namespace groundingdino
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..b2b88e8c46f19b6db0933163e57ccdb51180f517
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h
@@ -0,0 +1,35 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+namespace groundingdino {
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
+} // namespace groundingdino
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cu b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..0c8a9eb2091c8aed02fdf9487d4d159c99881ba7
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cu
@@ -0,0 +1,207 @@
+
+
+#include
+#include "ms_deform_im2col_cuda.cuh"
+
+#include
+#include
+#include
+#include
+
+namespace groundingdino {
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step) {
+ // ------------------- sanity checks -------------------
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(),
+ "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(),
+ "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(),
+ "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(),
+ "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(),
+ "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(),
+ "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(),
+ "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(),
+ "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+ const int num_levels = spatial_shapes.size(0);
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+ AT_ASSERTM(batch % im2col_step_ == 0,
+ "batch(%d) must be divisible by im2col_step(%d)",
+ batch,
+ im2col_step_);
+
+ // ------------------- output -------------------
+ auto output = at::zeros({batch, num_query, num_heads, channels},
+ value.options());
+
+ const int batch_n = im2col_step_;
+ // shape: (batch/im2col_step_, batch_n, num_query, num_heads, channels)
+ auto output_n = output.view(
+ {batch / im2col_step_, batch_n, num_query, num_heads, channels});
+
+ const int64_t per_value_size =
+ static_cast(spatial_size) * num_heads * channels;
+ const int64_t per_sample_loc_size =
+ static_cast(num_query) * num_heads * num_levels * num_point * 2;
+ const int64_t per_attn_weight_size =
+ static_cast(num_query) * num_heads * num_levels * num_point;
+
+ for (int n = 0; n < batch / im2col_step_; ++n) {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(
+ value.scalar_type(),
+ "ms_deform_attn_forward_cuda",
+ ([&] {
+ ms_deformable_im2col_cuda(
+ at::cuda::getCurrentCUDAStream(),
+ value.data_ptr() +
+ n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() +
+ n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() +
+ n * im2col_step_ * per_attn_weight_size,
+ batch_n,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ columns.data_ptr());
+ }));
+ }
+
+ // collapse head & channel dimensions
+ output = output.view({batch, num_query, num_heads * channels});
+ return output;
+}
+
+// ---------------------------------------------------------------------
+// Backward
+// ---------------------------------------------------------------------
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step) {
+ // ------------------- sanity checks -------------------
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(),
+ "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(),
+ "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(),
+ "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(),
+ "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(),
+ "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(),
+ "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(),
+ "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(),
+ "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(),
+ "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.is_cuda(),
+ "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+ const int num_levels = spatial_shapes.size(0);
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+ AT_ASSERTM(batch % im2col_step_ == 0,
+ "batch(%d) must be divisible by im2col_step(%d)",
+ batch,
+ im2col_step_);
+
+ // ------------------- allocate grads -------------------
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+
+ const int64_t per_value_size =
+ static_cast(spatial_size) * num_heads * channels;
+ const int64_t per_sample_loc_size =
+ static_cast(num_query) * num_heads * num_levels * num_point * 2;
+ const int64_t per_attn_weight_size =
+ static_cast(num_query) * num_heads * num_levels * num_point;
+
+ // grad_output shape -> (batch/im2col_step_, batch_n, num_query, num_heads, channels)
+ auto grad_output_n = grad_output.view(
+ {batch / im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch / im2col_step_; ++n) {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(
+ value.scalar_type(),
+ "ms_deform_attn_backward_cuda",
+ ([&] {
+ ms_deformable_col2im_cuda(
+ at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data_ptr(),
+ value.data_ptr() +
+ n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() +
+ n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() +
+ n * im2col_step_ * per_attn_weight_size,
+ batch_n,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value.data_ptr() +
+ n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data_ptr() +
+ n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data_ptr() +
+ n * im2col_step_ * per_attn_weight_size);
+ }));
+ }
+
+ return {grad_value, grad_sampling_loc, grad_attn_weight};
+}
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..ad1311a78f61303616504eb991aaa9c4a93d9948
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h
@@ -0,0 +1,33 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+namespace groundingdino {
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuh b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..6bc2acb7aea0eab2e9e91e769a16861e1652c284
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuh
@@ -0,0 +1,1327 @@
+/*!
+**************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************
+* Modified from DCN (https://github.com/msracver/Deformable-ConvNets)
+* Copyright (c) 2018 Microsoft
+**************************************************************************
+*/
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ default:
+ if (channels < 64)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/cuda_version.cu b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/cuda_version.cu
new file mode 100644
index 0000000000000000000000000000000000000000..64569e34ffb250964de27e33e7a53f3822270b9e
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/cuda_version.cu
@@ -0,0 +1,7 @@
+#include
+
+namespace groundingdino {
+int get_cudart_version() {
+ return CUDART_VERSION;
+}
+} // namespace groundingdino
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/vision.cpp b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/vision.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c1f2c50c82909bbd5492c163d634af77a3ba1781
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/csrc/vision.cpp
@@ -0,0 +1,58 @@
+// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+
+#include "MsDeformAttn/ms_deform_attn.h"
+
+namespace groundingdino {
+
+#ifdef WITH_CUDA
+extern int get_cudart_version();
+#endif
+
+std::string get_cuda_version() {
+#ifdef WITH_CUDA
+ std::ostringstream oss;
+
+ // copied from
+ // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/cuda/detail/CUDAHooks.cpp#L231
+ auto printCudaStyleVersion = [&](int v) {
+ oss << (v / 1000) << "." << (v / 10 % 100);
+ if (v % 10 != 0) {
+ oss << "." << (v % 10);
+ }
+ };
+ printCudaStyleVersion(get_cudart_version());
+ return oss.str();
+#else
+ return std::string("not available");
+#endif
+}
+
+// similar to
+// https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Version.cpp
+std::string get_compiler_version() {
+ std::ostringstream ss;
+#if defined(__GNUC__)
+#ifndef __clang__
+ { ss << "GCC " << __GNUC__ << "." << __GNUC_MINOR__; }
+#endif
+#endif
+
+#if defined(__clang_major__)
+ {
+ ss << "clang " << __clang_major__ << "." << __clang_minor__ << "."
+ << __clang_patchlevel__;
+ }
+#endif
+
+#if defined(_MSC_VER)
+ { ss << "MSVC " << _MSC_FULL_VER; }
+#endif
+ return ss.str();
+}
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("ms_deform_attn_forward", &ms_deform_attn_forward, "ms_deform_attn_forward");
+ m.def("ms_deform_attn_backward", &ms_deform_attn_backward, "ms_deform_attn_backward");
+}
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/fuse_modules.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/fuse_modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..2753b3ddee43c7a9fe28d1824db5d786e7e1ad59
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/fuse_modules.py
@@ -0,0 +1,297 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from timm.models.layers import DropPath
+
+
+class FeatureResizer(nn.Module):
+ """
+ This class takes as input a set of embeddings of dimension C1 and outputs a set of
+ embedding of dimension C2, after a linear transformation, dropout and normalization (LN).
+ """
+
+ def __init__(self, input_feat_size, output_feat_size, dropout, do_ln=True):
+ super().__init__()
+ self.do_ln = do_ln
+ # Object feature encoding
+ self.fc = nn.Linear(input_feat_size, output_feat_size, bias=True)
+ self.layer_norm = nn.LayerNorm(output_feat_size, eps=1e-12)
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(self, encoder_features):
+ x = self.fc(encoder_features)
+ if self.do_ln:
+ x = self.layer_norm(x)
+ output = self.dropout(x)
+ return output
+
+
+def l1norm(X, dim, eps=1e-8):
+ """L1-normalize columns of X"""
+ norm = torch.abs(X).sum(dim=dim, keepdim=True) + eps
+ X = torch.div(X, norm)
+ return X
+
+
+def l2norm(X, dim, eps=1e-8):
+ """L2-normalize columns of X"""
+ norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
+ X = torch.div(X, norm)
+ return X
+
+
+def func_attention(query, context, smooth=1, raw_feature_norm="softmax", eps=1e-8):
+ """
+ query: (n_context, queryL, d)
+ context: (n_context, sourceL, d)
+ """
+ batch_size_q, queryL = query.size(0), query.size(1)
+ batch_size, sourceL = context.size(0), context.size(1)
+
+ # Get attention
+ # --> (batch, d, queryL)
+ queryT = torch.transpose(query, 1, 2)
+
+ # (batch, sourceL, d)(batch, d, queryL)
+ # --> (batch, sourceL, queryL)
+ attn = torch.bmm(context, queryT)
+ if raw_feature_norm == "softmax":
+ # --> (batch*sourceL, queryL)
+ attn = attn.view(batch_size * sourceL, queryL)
+ attn = nn.Softmax()(attn)
+ # --> (batch, sourceL, queryL)
+ attn = attn.view(batch_size, sourceL, queryL)
+ elif raw_feature_norm == "l2norm":
+ attn = l2norm(attn, 2)
+ elif raw_feature_norm == "clipped_l2norm":
+ attn = nn.LeakyReLU(0.1)(attn)
+ attn = l2norm(attn, 2)
+ else:
+ raise ValueError("unknown first norm type:", raw_feature_norm)
+ # --> (batch, queryL, sourceL)
+ attn = torch.transpose(attn, 1, 2).contiguous()
+ # --> (batch*queryL, sourceL)
+ attn = attn.view(batch_size * queryL, sourceL)
+ attn = nn.Softmax()(attn * smooth)
+ # --> (batch, queryL, sourceL)
+ attn = attn.view(batch_size, queryL, sourceL)
+ # --> (batch, sourceL, queryL)
+ attnT = torch.transpose(attn, 1, 2).contiguous()
+
+ # --> (batch, d, sourceL)
+ contextT = torch.transpose(context, 1, 2)
+ # (batch x d x sourceL)(batch x sourceL x queryL)
+ # --> (batch, d, queryL)
+ weightedContext = torch.bmm(contextT, attnT)
+ # --> (batch, queryL, d)
+ weightedContext = torch.transpose(weightedContext, 1, 2)
+
+ return weightedContext, attnT
+
+
+class BiMultiHeadAttention(nn.Module):
+ def __init__(self, v_dim, l_dim, embed_dim, num_heads, dropout=0.1, cfg=None):
+ super(BiMultiHeadAttention, self).__init__()
+
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.head_dim = embed_dim // num_heads
+ self.v_dim = v_dim
+ self.l_dim = l_dim
+
+ assert (
+ self.head_dim * self.num_heads == self.embed_dim
+ ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
+ self.scale = self.head_dim ** (-0.5)
+ self.dropout = dropout
+
+ self.v_proj = nn.Linear(self.v_dim, self.embed_dim)
+ self.l_proj = nn.Linear(self.l_dim, self.embed_dim)
+ self.values_v_proj = nn.Linear(self.v_dim, self.embed_dim)
+ self.values_l_proj = nn.Linear(self.l_dim, self.embed_dim)
+
+ self.out_v_proj = nn.Linear(self.embed_dim, self.v_dim)
+ self.out_l_proj = nn.Linear(self.embed_dim, self.l_dim)
+
+ self.stable_softmax_2d = True
+ self.clamp_min_for_underflow = True
+ self.clamp_max_for_overflow = True
+
+ self._reset_parameters()
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def _reset_parameters(self):
+ nn.init.xavier_uniform_(self.v_proj.weight)
+ self.v_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.l_proj.weight)
+ self.l_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.values_v_proj.weight)
+ self.values_v_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.values_l_proj.weight)
+ self.values_l_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.out_v_proj.weight)
+ self.out_v_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.out_l_proj.weight)
+ self.out_l_proj.bias.data.fill_(0)
+
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
+ """_summary_
+
+ Args:
+ v (_type_): bs, n_img, dim
+ l (_type_): bs, n_text, dim
+ attention_mask_v (_type_, optional): _description_. bs, n_img
+ attention_mask_l (_type_, optional): _description_. bs, n_text
+
+ Returns:
+ _type_: _description_
+ """
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ bsz, tgt_len, _ = v.size()
+
+ query_states = self.v_proj(v) * self.scale
+ key_states = self._shape(self.l_proj(l), -1, bsz)
+ value_v_states = self._shape(self.values_v_proj(v), -1, bsz)
+ value_l_states = self._shape(self.values_l_proj(l), -1, bsz)
+
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
+ key_states = key_states.view(*proj_shape)
+ value_v_states = value_v_states.view(*proj_shape)
+ value_l_states = value_l_states.view(*proj_shape)
+
+ src_len = key_states.size(1)
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) # bs*nhead, nimg, ntxt
+
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
+ )
+
+ if self.stable_softmax_2d:
+ attn_weights = attn_weights - attn_weights.max()
+
+ if self.clamp_min_for_underflow:
+ attn_weights = torch.clamp(
+ attn_weights, min=-50000
+ ) # Do not increase -50000, data type half has quite limited range
+ if self.clamp_max_for_overflow:
+ attn_weights = torch.clamp(
+ attn_weights, max=50000
+ ) # Do not increase 50000, data type half has quite limited range
+
+ attn_weights_T = attn_weights.transpose(1, 2)
+ attn_weights_l = attn_weights_T - torch.max(attn_weights_T, dim=-1, keepdim=True)[0]
+ if self.clamp_min_for_underflow:
+ attn_weights_l = torch.clamp(
+ attn_weights_l, min=-50000
+ ) # Do not increase -50000, data type half has quite limited range
+ if self.clamp_max_for_overflow:
+ attn_weights_l = torch.clamp(
+ attn_weights_l, max=50000
+ ) # Do not increase 50000, data type half has quite limited range
+
+ # mask vison for language
+ if attention_mask_v is not None:
+ attention_mask_v = (
+ attention_mask_v[:, None, None, :].repeat(1, self.num_heads, 1, 1).flatten(0, 1)
+ )
+ attn_weights_l.masked_fill_(attention_mask_v, float("-inf"))
+
+ attn_weights_l = attn_weights_l.softmax(dim=-1)
+
+ # mask language for vision
+ if attention_mask_l is not None:
+ attention_mask_l = (
+ attention_mask_l[:, None, None, :].repeat(1, self.num_heads, 1, 1).flatten(0, 1)
+ )
+ attn_weights.masked_fill_(attention_mask_l, float("-inf"))
+ attn_weights_v = attn_weights.softmax(dim=-1)
+
+ attn_probs_v = F.dropout(attn_weights_v, p=self.dropout, training=self.training)
+ attn_probs_l = F.dropout(attn_weights_l, p=self.dropout, training=self.training)
+
+ attn_output_v = torch.bmm(attn_probs_v, value_l_states)
+ attn_output_l = torch.bmm(attn_probs_l, value_v_states)
+
+ if attn_output_v.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output_v` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output_v.size()}"
+ )
+
+ if attn_output_l.size() != (bsz * self.num_heads, src_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output_l` should be of size {(bsz, self.num_heads, src_len, self.head_dim)}, but is {attn_output_l.size()}"
+ )
+
+ attn_output_v = attn_output_v.view(bsz, self.num_heads, tgt_len, self.head_dim)
+ attn_output_v = attn_output_v.transpose(1, 2)
+ attn_output_v = attn_output_v.reshape(bsz, tgt_len, self.embed_dim)
+
+ attn_output_l = attn_output_l.view(bsz, self.num_heads, src_len, self.head_dim)
+ attn_output_l = attn_output_l.transpose(1, 2)
+ attn_output_l = attn_output_l.reshape(bsz, src_len, self.embed_dim)
+
+ attn_output_v = self.out_v_proj(attn_output_v)
+ attn_output_l = self.out_l_proj(attn_output_l)
+
+ return attn_output_v, attn_output_l
+
+
+# Bi-Direction MHA (text->image, image->text)
+class BiAttentionBlock(nn.Module):
+ def __init__(
+ self,
+ v_dim,
+ l_dim,
+ embed_dim,
+ num_heads,
+ dropout=0.1,
+ drop_path=0.0,
+ init_values=1e-4,
+ cfg=None,
+ ):
+ """
+ Inputs:
+ embed_dim - Dimensionality of input and attention feature vectors
+ hidden_dim - Dimensionality of hidden layer in feed-forward network
+ (usually 2-4x larger than embed_dim)
+ num_heads - Number of heads to use in the Multi-Head Attention block
+ dropout - Amount of dropout to apply in the feed-forward network
+ """
+ super(BiAttentionBlock, self).__init__()
+
+ # pre layer norm
+ self.layer_norm_v = nn.LayerNorm(v_dim)
+ self.layer_norm_l = nn.LayerNorm(l_dim)
+ self.attn = BiMultiHeadAttention(
+ v_dim=v_dim, l_dim=l_dim, embed_dim=embed_dim, num_heads=num_heads, dropout=dropout
+ )
+
+ # add layer scale for training stability
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.gamma_v = nn.Parameter(init_values * torch.ones((v_dim)), requires_grad=True)
+ self.gamma_l = nn.Parameter(init_values * torch.ones((l_dim)), requires_grad=True)
+
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
+ v = self.layer_norm_v(v)
+ l = self.layer_norm_l(l)
+ delta_v, delta_l = self.attn(
+ v, l, attention_mask_v=attention_mask_v, attention_mask_l=attention_mask_l
+ )
+ # v, l = v + delta_v, l + delta_l
+ v = v + self.drop_path(self.gamma_v * delta_v)
+ l = l + self.drop_path(self.gamma_l * delta_l)
+ return v, l
+
+ # def forward(self, v:List[torch.Tensor], l, attention_mask_v=None, attention_mask_l=None)
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/groundingdino.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/groundingdino.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd97028df679f89e5e7518e27ab620f2d6b1861d
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/groundingdino.py
@@ -0,0 +1,412 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR model and criterion classes.
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Modified from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
+# Copyright (c) 2020 SenseTime. All Rights Reserved.
+# ------------------------------------------------------------------------
+import copy
+from typing import List
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torchvision.ops.boxes import nms
+from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
+
+from groundingdino.util import box_ops, get_tokenlizer
+from groundingdino.util.misc import (
+ NestedTensor,
+ accuracy,
+ get_world_size,
+ interpolate,
+ inverse_sigmoid,
+ is_dist_avail_and_initialized,
+ nested_tensor_from_tensor_list,
+)
+from groundingdino.util.utils import get_phrases_from_posmap
+from groundingdino.util.visualizer import COCOVisualizer
+from groundingdino.util.vl_utils import create_positive_map_from_span
+
+from ..registry import MODULE_BUILD_FUNCS
+from .backbone import build_backbone
+from .bertwarper import (
+ BertModelWarper,
+ generate_masks_with_special_tokens,
+ generate_masks_with_special_tokens_and_transfer_map,
+)
+from .transformer import build_transformer
+from .utils import MLP, ContrastiveEmbed, sigmoid_focal_loss
+
+
+class GroundingDINO(nn.Module):
+ """This is the Cross-Attention Detector module that performs object detection"""
+
+ def __init__(
+ self,
+ backbone,
+ transformer,
+ num_queries,
+ aux_loss=False,
+ iter_update=False,
+ query_dim=2,
+ num_feature_levels=1,
+ nheads=8,
+ # two stage
+ two_stage_type="no", # ['no', 'standard']
+ dec_pred_bbox_embed_share=True,
+ two_stage_class_embed_share=True,
+ two_stage_bbox_embed_share=True,
+ num_patterns=0,
+ dn_number=100,
+ dn_box_noise_scale=0.4,
+ dn_label_noise_ratio=0.5,
+ dn_labelbook_size=100,
+ text_encoder_type="bert-base-uncased",
+ sub_sentence_present=True,
+ max_text_len=256,
+ ):
+ """Initializes the model.
+ Parameters:
+ backbone: torch module of the backbone to be used. See backbone.py
+ transformer: torch module of the transformer architecture. See transformer.py
+ num_queries: number of object queries, ie detection slot. This is the maximal number of objects
+ Conditional DETR can detect in a single image. For COCO, we recommend 100 queries.
+ aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
+ """
+ super().__init__()
+ self.num_queries = num_queries
+ self.transformer = transformer
+ self.hidden_dim = hidden_dim = transformer.d_model
+ self.num_feature_levels = num_feature_levels
+ self.nheads = nheads
+ self.max_text_len = 256
+ self.sub_sentence_present = sub_sentence_present
+
+ # setting query dim
+ self.query_dim = query_dim
+ assert query_dim == 4
+
+ # for dn training
+ self.num_patterns = num_patterns
+ self.dn_number = dn_number
+ self.dn_box_noise_scale = dn_box_noise_scale
+ self.dn_label_noise_ratio = dn_label_noise_ratio
+ self.dn_labelbook_size = dn_labelbook_size
+
+ # bert
+ self.tokenizer = get_tokenlizer.get_tokenlizer(text_encoder_type)
+ self.bert = get_tokenlizer.get_pretrained_language_model(text_encoder_type)
+ self.bert.pooler.dense.weight.requires_grad_(False)
+ self.bert.pooler.dense.bias.requires_grad_(False)
+ self.bert = BertModelWarper(bert_model=self.bert)
+
+ self.feat_map = nn.Linear(self.bert.config.hidden_size, self.hidden_dim, bias=True)
+ nn.init.constant_(self.feat_map.bias.data, 0)
+ nn.init.xavier_uniform_(self.feat_map.weight.data)
+ # freeze
+
+ # special tokens
+ self.specical_tokens = self.tokenizer.convert_tokens_to_ids(["[CLS]", "[SEP]", ".", "?"])
+
+ # prepare input projection layers
+ if num_feature_levels > 1:
+ num_backbone_outs = len(backbone.num_channels)
+ input_proj_list = []
+ for _ in range(num_backbone_outs):
+ in_channels = backbone.num_channels[_]
+ input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, hidden_dim, kernel_size=1),
+ nn.GroupNorm(32, hidden_dim),
+ )
+ )
+ for _ in range(num_feature_levels - num_backbone_outs):
+ input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1),
+ nn.GroupNorm(32, hidden_dim),
+ )
+ )
+ in_channels = hidden_dim
+ self.input_proj = nn.ModuleList(input_proj_list)
+ else:
+ assert two_stage_type == "no", "two_stage_type should be no if num_feature_levels=1 !!!"
+ self.input_proj = nn.ModuleList(
+ [
+ nn.Sequential(
+ nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1),
+ nn.GroupNorm(32, hidden_dim),
+ )
+ ]
+ )
+
+ self.backbone = backbone
+ self.aux_loss = aux_loss
+ self.box_pred_damping = box_pred_damping = None
+
+ self.iter_update = iter_update
+ assert iter_update, "Why not iter_update?"
+
+ # prepare pred layers
+ self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share
+ # prepare class & box embed
+ _class_embed = ContrastiveEmbed()
+
+ _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
+ nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0)
+ nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0)
+
+ if dec_pred_bbox_embed_share:
+ box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)]
+ else:
+ box_embed_layerlist = [
+ copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers)
+ ]
+ class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)]
+ self.bbox_embed = nn.ModuleList(box_embed_layerlist)
+ self.class_embed = nn.ModuleList(class_embed_layerlist)
+ self.transformer.decoder.bbox_embed = self.bbox_embed
+ self.transformer.decoder.class_embed = self.class_embed
+
+ # two stage
+ self.two_stage_type = two_stage_type
+ assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format(
+ two_stage_type
+ )
+ if two_stage_type != "no":
+ if two_stage_bbox_embed_share:
+ assert dec_pred_bbox_embed_share
+ self.transformer.enc_out_bbox_embed = _bbox_embed
+ else:
+ self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed)
+
+ if two_stage_class_embed_share:
+ assert dec_pred_bbox_embed_share
+ self.transformer.enc_out_class_embed = _class_embed
+ else:
+ self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed)
+
+ self.refpoint_embed = None
+
+ self._reset_parameters()
+
+ def _reset_parameters(self):
+ # init input_proj
+ for proj in self.input_proj:
+ nn.init.xavier_uniform_(proj[0].weight, gain=1)
+ nn.init.constant_(proj[0].bias, 0)
+
+ def set_image_tensor(self, samples: NestedTensor):
+ if isinstance(samples, (list, torch.Tensor)):
+ samples = nested_tensor_from_tensor_list(samples)
+ self.features, self.poss = self.backbone(samples)
+
+ def unset_image_tensor(self):
+ if hasattr(self, 'features'):
+ del self.features
+ if hasattr(self,'poss'):
+ del self.poss
+
+ def set_image_features(self, features , poss):
+ self.features = features
+ self.poss = poss
+
+ def init_ref_points(self, use_num_queries):
+ self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim)
+
+ def forward(self, samples: NestedTensor, targets: List = None, **kw):
+ """The forward expects a NestedTensor, which consists of:
+ - samples.tensor: batched images, of shape [batch_size x 3 x H x W]
+ - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
+
+ It returns a dict with the following elements:
+ - "pred_logits": the classification logits (including no-object) for all queries.
+ Shape= [batch_size x num_queries x num_classes]
+ - "pred_boxes": The normalized boxes coordinates for all queries, represented as
+ (center_x, center_y, width, height). These values are normalized in [0, 1],
+ relative to the size of each individual image (disregarding possible padding).
+ See PostProcess for information on how to retrieve the unnormalized bounding box.
+ - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
+ dictionnaries containing the two above keys for each decoder layer.
+ """
+ if targets is None:
+ captions = kw["captions"]
+ else:
+ captions = [t["caption"] for t in targets]
+
+ # encoder texts
+ tokenized = self.tokenizer(captions, padding="longest", return_tensors="pt").to(
+ samples.device
+ )
+ (
+ text_self_attention_masks,
+ position_ids,
+ cate_to_token_mask_list,
+ ) = generate_masks_with_special_tokens_and_transfer_map(
+ tokenized, self.specical_tokens, self.tokenizer
+ )
+
+ if text_self_attention_masks.shape[1] > self.max_text_len:
+ text_self_attention_masks = text_self_attention_masks[
+ :, : self.max_text_len, : self.max_text_len
+ ]
+ position_ids = position_ids[:, : self.max_text_len]
+ tokenized["input_ids"] = tokenized["input_ids"][:, : self.max_text_len]
+ tokenized["attention_mask"] = tokenized["attention_mask"][:, : self.max_text_len]
+ tokenized["token_type_ids"] = tokenized["token_type_ids"][:, : self.max_text_len]
+
+ # extract text embeddings
+ if self.sub_sentence_present:
+ tokenized_for_encoder = {k: v for k, v in tokenized.items() if k != "attention_mask"}
+ tokenized_for_encoder["attention_mask"] = text_self_attention_masks
+ tokenized_for_encoder["position_ids"] = position_ids
+ else:
+ # import ipdb; ipdb.set_trace()
+ tokenized_for_encoder = tokenized
+
+ bert_output = self.bert(**tokenized_for_encoder) # bs, 195, 768
+
+ encoded_text = self.feat_map(bert_output["last_hidden_state"]) # bs, 195, d_model
+ text_token_mask = tokenized.attention_mask.bool() # bs, 195
+ # text_token_mask: True for nomask, False for mask
+ # text_self_attention_masks: True for nomask, False for mask
+
+ if encoded_text.shape[1] > self.max_text_len:
+ encoded_text = encoded_text[:, : self.max_text_len, :]
+ text_token_mask = text_token_mask[:, : self.max_text_len]
+ position_ids = position_ids[:, : self.max_text_len]
+ text_self_attention_masks = text_self_attention_masks[
+ :, : self.max_text_len, : self.max_text_len
+ ]
+
+ text_dict = {
+ "encoded_text": encoded_text, # bs, 195, d_model
+ "text_token_mask": text_token_mask, # bs, 195
+ "position_ids": position_ids, # bs, 195
+ "text_self_attention_masks": text_self_attention_masks, # bs, 195,195
+ }
+
+ # import ipdb; ipdb.set_trace()
+ if isinstance(samples, (list, torch.Tensor)):
+ samples = nested_tensor_from_tensor_list(samples)
+ if not hasattr(self, 'features') or not hasattr(self, 'poss'):
+ self.set_image_tensor(samples)
+
+ srcs = []
+ masks = []
+ for l, feat in enumerate(self.features):
+ src, mask = feat.decompose()
+ srcs.append(self.input_proj[l](src))
+ masks.append(mask)
+ assert mask is not None
+ if self.num_feature_levels > len(srcs):
+ _len_srcs = len(srcs)
+ for l in range(_len_srcs, self.num_feature_levels):
+ if l == _len_srcs:
+ src = self.input_proj[l](self.features[-1].tensors)
+ else:
+ src = self.input_proj[l](srcs[-1])
+ m = samples.mask
+ mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]
+ pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype)
+ srcs.append(src)
+ masks.append(mask)
+ self.poss.append(pos_l)
+
+ input_query_bbox = input_query_label = attn_mask = dn_meta = None
+ hs, reference, hs_enc, ref_enc, init_box_proposal = self.transformer(
+ srcs, masks, input_query_bbox, self.poss, input_query_label, attn_mask, text_dict
+ )
+
+ # deformable-detr-like anchor update
+ outputs_coord_list = []
+ for dec_lid, (layer_ref_sig, layer_bbox_embed, layer_hs) in enumerate(
+ zip(reference[:-1], self.bbox_embed, hs)
+ ):
+ layer_delta_unsig = layer_bbox_embed(layer_hs)
+ layer_outputs_unsig = layer_delta_unsig + inverse_sigmoid(layer_ref_sig)
+ layer_outputs_unsig = layer_outputs_unsig.sigmoid()
+ outputs_coord_list.append(layer_outputs_unsig)
+ outputs_coord_list = torch.stack(outputs_coord_list)
+
+ # output
+ outputs_class = torch.stack(
+ [
+ layer_cls_embed(layer_hs, text_dict)
+ for layer_cls_embed, layer_hs in zip(self.class_embed, hs)
+ ]
+ )
+ out = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord_list[-1]}
+
+ # # for intermediate outputs
+ # if self.aux_loss:
+ # out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord_list)
+
+ # # for encoder output
+ # if hs_enc is not None:
+ # # prepare intermediate outputs
+ # interm_coord = ref_enc[-1]
+ # interm_class = self.transformer.enc_out_class_embed(hs_enc[-1], text_dict)
+ # out['interm_outputs'] = {'pred_logits': interm_class, 'pred_boxes': interm_coord}
+ # out['interm_outputs_for_matching_pre'] = {'pred_logits': interm_class, 'pred_boxes': init_box_proposal}
+ unset_image_tensor = kw.get('unset_image_tensor', True)
+ if unset_image_tensor:
+ self.unset_image_tensor() ## If necessary
+ return out
+
+ @torch.jit.unused
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ # this is a workaround to make torchscript happy, as torchscript
+ # doesn't support dictionary with non-homogeneous values, such
+ # as a dict having both a Tensor and a list.
+ return [
+ {"pred_logits": a, "pred_boxes": b}
+ for a, b in zip(outputs_class[:-1], outputs_coord[:-1])
+ ]
+
+
+@MODULE_BUILD_FUNCS.registe_with_name(module_name="groundingdino")
+def build_groundingdino(args):
+
+ backbone = build_backbone(args)
+ transformer = build_transformer(args)
+
+ dn_labelbook_size = args.dn_labelbook_size
+ dec_pred_bbox_embed_share = args.dec_pred_bbox_embed_share
+ sub_sentence_present = args.sub_sentence_present
+
+ model = GroundingDINO(
+ backbone,
+ transformer,
+ num_queries=args.num_queries,
+ aux_loss=True,
+ iter_update=True,
+ query_dim=4,
+ num_feature_levels=args.num_feature_levels,
+ nheads=args.nheads,
+ dec_pred_bbox_embed_share=dec_pred_bbox_embed_share,
+ two_stage_type=args.two_stage_type,
+ two_stage_bbox_embed_share=args.two_stage_bbox_embed_share,
+ two_stage_class_embed_share=args.two_stage_class_embed_share,
+ num_patterns=args.num_patterns,
+ dn_number=0,
+ dn_box_noise_scale=args.dn_box_noise_scale,
+ dn_label_noise_ratio=args.dn_label_noise_ratio,
+ dn_labelbook_size=dn_labelbook_size,
+ text_encoder_type=args.text_encoder_type,
+ sub_sentence_present=sub_sentence_present,
+ max_text_len=args.max_text_len,
+ )
+
+ return model
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/ms_deform_attn.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/ms_deform_attn.py
new file mode 100644
index 0000000000000000000000000000000000000000..489d501bef364020212306d81e9b85c8daa27491
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/ms_deform_attn.py
@@ -0,0 +1,413 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Deformable DETR
+# Copyright (c) 2020 SenseTime. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------------------------------
+# Modified from:
+# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/functions/ms_deform_attn_func.py
+# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py
+# https://github.com/open-mmlab/mmcv/blob/master/mmcv/ops/multi_scale_deform_attn.py
+# ------------------------------------------------------------------------------------------------
+
+import math
+import warnings
+from typing import Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.autograd import Function
+from torch.autograd.function import once_differentiable
+from torch.nn.init import constant_, xavier_uniform_
+
+try:
+ from groundingdino import _C
+except:
+ warnings.warn("Failed to load custom C++ ops. Running on CPU mode Only!")
+
+
+# helpers
+def _is_power_of_2(n):
+ if (not isinstance(n, int)) or (n < 0):
+ raise ValueError("invalid input for _is_power_of_2: {} (type: {})".format(n, type(n)))
+ return (n & (n - 1) == 0) and n != 0
+
+
+class MultiScaleDeformableAttnFunction(Function):
+ @staticmethod
+ def forward(
+ ctx,
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ im2col_step,
+ ):
+ ctx.im2col_step = im2col_step
+ output = _C.ms_deform_attn_forward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ ctx.im2col_step,
+ )
+ ctx.save_for_backward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ )
+ return output
+
+ @staticmethod
+ @once_differentiable
+ def backward(ctx, grad_output):
+ (
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ ) = ctx.saved_tensors
+ grad_value, grad_sampling_loc, grad_attn_weight = _C.ms_deform_attn_backward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ grad_output,
+ ctx.im2col_step,
+ )
+
+ return grad_value, None, None, grad_sampling_loc, grad_attn_weight, None
+
+
+def multi_scale_deformable_attn_pytorch(
+ value: torch.Tensor,
+ value_spatial_shapes: torch.Tensor,
+ sampling_locations: torch.Tensor,
+ attention_weights: torch.Tensor,
+) -> torch.Tensor:
+
+ bs, _, num_heads, embed_dims = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
+ value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level, (H_, W_) in enumerate(value_spatial_shapes):
+ # bs, H_*W_, num_heads, embed_dims ->
+ # bs, H_*W_, num_heads*embed_dims ->
+ # bs, num_heads*embed_dims, H_*W_ ->
+ # bs*num_heads, embed_dims, H_, W_
+ value_l_ = (
+ value_list[level].flatten(2).transpose(1, 2).reshape(bs * num_heads, embed_dims, H_, W_)
+ )
+ # bs, num_queries, num_heads, num_points, 2 ->
+ # bs, num_heads, num_queries, num_points, 2 ->
+ # bs*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :, level].transpose(1, 2).flatten(0, 1)
+ # bs*num_heads, embed_dims, num_queries, num_points
+ sampling_value_l_ = F.grid_sample(
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (bs, num_queries, num_heads, num_levels, num_points) ->
+ # (bs, num_heads, num_queries, num_levels, num_points) ->
+ # (bs, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ bs * num_heads, 1, num_queries, num_levels * num_points
+ )
+ output = (
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
+ .sum(-1)
+ .view(bs, num_heads * embed_dims, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+class MultiScaleDeformableAttention(nn.Module):
+ """Multi-Scale Deformable Attention Module used in Deformable-DETR
+
+ `Deformable DETR: Deformable Transformers for End-to-End Object Detection.
+ `_.
+
+ Args:
+ embed_dim (int): The embedding dimension of Attention. Default: 256.
+ num_heads (int): The number of attention heads. Default: 8.
+ num_levels (int): The number of feature map used in Attention. Default: 4.
+ num_points (int): The number of sampling points for each query
+ in each head. Default: 4.
+ img2col_steps (int): The step used in image_to_column. Defualt: 64.
+ dropout (float): Dropout layer used in output. Default: 0.1.
+ batch_first (bool): if ``True``, then the input and output tensor will be
+ provided as `(bs, n, embed_dim)`. Default: False. `(n, bs, embed_dim)`
+ """
+
+ def __init__(
+ self,
+ embed_dim: int = 256,
+ num_heads: int = 8,
+ num_levels: int = 4,
+ num_points: int = 4,
+ img2col_step: int = 64,
+ batch_first: bool = False,
+ ):
+ super().__init__()
+ if embed_dim % num_heads != 0:
+ raise ValueError(
+ "embed_dim must be divisible by num_heads, but got {} and {}".format(
+ embed_dim, num_heads
+ )
+ )
+ head_dim = embed_dim // num_heads
+
+ self.batch_first = batch_first
+
+ if not _is_power_of_2(head_dim):
+ warnings.warn(
+ """
+ You'd better set d_model in MSDeformAttn to make sure that
+ each dim of the attention head a power of 2, which is more efficient.
+ """
+ )
+
+ self.im2col_step = img2col_step
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.num_levels = num_levels
+ self.num_points = num_points
+ self.sampling_offsets = nn.Linear(embed_dim, num_heads * num_levels * num_points * 2)
+ self.attention_weights = nn.Linear(embed_dim, num_heads * num_levels * num_points)
+ self.value_proj = nn.Linear(embed_dim, embed_dim)
+ self.output_proj = nn.Linear(embed_dim, embed_dim)
+
+ self.init_weights()
+
+ def _reset_parameters(self):
+ return self.init_weights()
+
+ def init_weights(self):
+ """
+ Default initialization for Parameters of Module.
+ """
+ constant_(self.sampling_offsets.weight.data, 0.0)
+ thetas = torch.arange(self.num_heads, dtype=torch.float32) * (
+ 2.0 * math.pi / self.num_heads
+ )
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
+ .view(self.num_heads, 1, 1, 2)
+ .repeat(1, self.num_levels, self.num_points, 1)
+ )
+ for i in range(self.num_points):
+ grid_init[:, :, i, :] *= i + 1
+ with torch.no_grad():
+ self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))
+ constant_(self.attention_weights.weight.data, 0.0)
+ constant_(self.attention_weights.bias.data, 0.0)
+ xavier_uniform_(self.value_proj.weight.data)
+ constant_(self.value_proj.bias.data, 0.0)
+ xavier_uniform_(self.output_proj.weight.data)
+ constant_(self.output_proj.bias.data, 0.0)
+
+ def freeze_sampling_offsets(self):
+ print("Freeze sampling offsets")
+ self.sampling_offsets.weight.requires_grad = False
+ self.sampling_offsets.bias.requires_grad = False
+
+ def freeze_attention_weights(self):
+ print("Freeze attention weights")
+ self.attention_weights.weight.requires_grad = False
+ self.attention_weights.bias.requires_grad = False
+
+ def forward(
+ self,
+ query: torch.Tensor,
+ key: Optional[torch.Tensor] = None,
+ value: Optional[torch.Tensor] = None,
+ query_pos: Optional[torch.Tensor] = None,
+ key_padding_mask: Optional[torch.Tensor] = None,
+ reference_points: Optional[torch.Tensor] = None,
+ spatial_shapes: Optional[torch.Tensor] = None,
+ level_start_index: Optional[torch.Tensor] = None,
+ **kwargs
+ ) -> torch.Tensor:
+
+ """Forward Function of MultiScaleDeformableAttention
+
+ Args:
+ query (torch.Tensor): Query embeddings with shape
+ `(num_query, bs, embed_dim)`
+ key (torch.Tensor): Key embeddings with shape
+ `(num_key, bs, embed_dim)`
+ value (torch.Tensor): Value embeddings with shape
+ `(num_key, bs, embed_dim)`
+ query_pos (torch.Tensor): The position embedding for `query`. Default: None.
+ key_padding_mask (torch.Tensor): ByteTensor for `query`, with shape `(bs, num_key)`,
+ indicating which elements within `key` to be ignored in attention.
+ reference_points (torch.Tensor): The normalized reference points
+ with shape `(bs, num_query, num_levels, 2)`,
+ all elements is range in [0, 1], top-left (0, 0),
+ bottom-right (1, 1), including padding are.
+ or `(N, Length_{query}, num_levels, 4)`, add additional
+ two dimensions `(h, w)` to form reference boxes.
+ spatial_shapes (torch.Tensor): Spatial shape of features in different levels.
+ With shape `(num_levels, 2)`, last dimension represents `(h, w)`.
+ level_start_index (torch.Tensor): The start index of each level. A tensor with
+ shape `(num_levels, )` which can be represented as
+ `[0, h_0 * w_0, h_0 * w_0 + h_1 * w_1, ...]`.
+
+ Returns:
+ torch.Tensor: forward results with shape `(num_query, bs, embed_dim)`
+ """
+
+ if value is None:
+ value = query
+
+ if query_pos is not None:
+ query = query + query_pos
+
+ if not self.batch_first:
+ # change to (bs, num_query ,embed_dims)
+ query = query.permute(1, 0, 2)
+ value = value.permute(1, 0, 2)
+
+ bs, num_query, _ = query.shape
+ bs, num_value, _ = value.shape
+
+ assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
+
+ value = self.value_proj(value)
+ if key_padding_mask is not None:
+ value = value.masked_fill(key_padding_mask[..., None], float(0))
+ value = value.view(bs, num_value, self.num_heads, -1)
+ sampling_offsets = self.sampling_offsets(query).view(
+ bs, num_query, self.num_heads, self.num_levels, self.num_points, 2
+ )
+ attention_weights = self.attention_weights(query).view(
+ bs, num_query, self.num_heads, self.num_levels * self.num_points
+ )
+ attention_weights = attention_weights.softmax(-1)
+ attention_weights = attention_weights.view(
+ bs,
+ num_query,
+ self.num_heads,
+ self.num_levels,
+ self.num_points,
+ )
+
+ # bs, num_query, num_heads, num_levels, num_points, 2
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif reference_points.shape[-1] == 4:
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :2]
+ + sampling_offsets
+ / self.num_points
+ * reference_points[:, :, None, :, None, 2:]
+ * 0.5
+ )
+ else:
+ raise ValueError(
+ "Last dim of reference_points must be 2 or 4, but get {} instead.".format(
+ reference_points.shape[-1]
+ )
+ )
+
+ if torch.cuda.is_available() and value.is_cuda:
+ halffloat = False
+ if value.dtype == torch.float16:
+ halffloat = True
+ value = value.float()
+ sampling_locations = sampling_locations.float()
+ attention_weights = attention_weights.float()
+
+ output = MultiScaleDeformableAttnFunction.apply(
+ value,
+ spatial_shapes,
+ level_start_index,
+ sampling_locations,
+ attention_weights,
+ self.im2col_step,
+ )
+
+ if halffloat:
+ output = output.half()
+ else:
+ output = multi_scale_deformable_attn_pytorch(
+ value, spatial_shapes, sampling_locations, attention_weights
+ )
+
+ output = self.output_proj(output)
+
+ if not self.batch_first:
+ output = output.permute(1, 0, 2)
+
+ return output
+
+
+def create_dummy_class(klass, dependency, message=""):
+ """
+ When a dependency of a class is not available, create a dummy class which throws ImportError
+ when used.
+
+ Args:
+ klass (str): name of the class.
+ dependency (str): name of the dependency.
+ message: extra message to print
+ Returns:
+ class: a class object
+ """
+ err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, klass)
+ if message:
+ err = err + " " + message
+
+ class _DummyMetaClass(type):
+ # throw error on class attribute access
+ def __getattr__(_, __): # noqa: B902
+ raise ImportError(err)
+
+ class _Dummy(object, metaclass=_DummyMetaClass):
+ # throw error on constructor
+ def __init__(self, *args, **kwargs):
+ raise ImportError(err)
+
+ return _Dummy
+
+
+def create_dummy_func(func, dependency, message=""):
+ """
+ When a dependency of a function is not available, create a dummy function which throws
+ ImportError when used.
+
+ Args:
+ func (str): name of the function.
+ dependency (str or list[str]): name(s) of the dependency.
+ message: extra message to print
+ Returns:
+ function: a function object
+ """
+ err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, func)
+ if message:
+ err = err + " " + message
+
+ if isinstance(dependency, (list, tuple)):
+ dependency = ",".join(dependency)
+
+ def _dummy(*args, **kwargs):
+ raise ImportError(err)
+
+ return _dummy
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/transformer.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcb8742dbdde6e80fd38b11d064211f6935aae76
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/transformer.py
@@ -0,0 +1,959 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# DINO
+# Copyright (c) 2022 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR Transformer class.
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Modified from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+from typing import Optional
+
+import torch
+import torch.utils.checkpoint as checkpoint
+from torch import Tensor, nn
+
+from groundingdino.util.misc import inverse_sigmoid
+
+from .fuse_modules import BiAttentionBlock
+from .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttn
+from .transformer_vanilla import TransformerEncoderLayer
+from .utils import (
+ MLP,
+ _get_activation_fn,
+ _get_clones,
+ gen_encoder_output_proposals,
+ gen_sineembed_for_position,
+ get_sine_pos_embed,
+)
+
+
+class Transformer(nn.Module):
+ def __init__(
+ self,
+ d_model=256,
+ nhead=8,
+ num_queries=300,
+ num_encoder_layers=6,
+ num_unicoder_layers=0,
+ num_decoder_layers=6,
+ dim_feedforward=2048,
+ dropout=0.0,
+ activation="relu",
+ normalize_before=False,
+ return_intermediate_dec=False,
+ query_dim=4,
+ num_patterns=0,
+ # for deformable encoder
+ num_feature_levels=1,
+ enc_n_points=4,
+ dec_n_points=4,
+ # init query
+ learnable_tgt_init=False,
+ # two stage
+ two_stage_type="no", # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1']
+ embed_init_tgt=False,
+ # for text
+ use_text_enhancer=False,
+ use_fusion_layer=False,
+ use_checkpoint=False,
+ use_transformer_ckpt=False,
+ use_text_cross_attention=False,
+ text_dropout=0.1,
+ fusion_dropout=0.1,
+ fusion_droppath=0.0,
+ ):
+ super().__init__()
+ self.num_feature_levels = num_feature_levels
+ self.num_encoder_layers = num_encoder_layers
+ self.num_unicoder_layers = num_unicoder_layers
+ self.num_decoder_layers = num_decoder_layers
+ self.num_queries = num_queries
+ assert query_dim == 4
+
+ # choose encoder layer type
+ encoder_layer = DeformableTransformerEncoderLayer(
+ d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, enc_n_points
+ )
+
+ if use_text_enhancer:
+ text_enhance_layer = TransformerEncoderLayer(
+ d_model=d_model,
+ nhead=nhead // 2,
+ dim_feedforward=dim_feedforward // 2,
+ dropout=text_dropout,
+ )
+ else:
+ text_enhance_layer = None
+
+ if use_fusion_layer:
+ feature_fusion_layer = BiAttentionBlock(
+ v_dim=d_model,
+ l_dim=d_model,
+ embed_dim=dim_feedforward // 2,
+ num_heads=nhead // 2,
+ dropout=fusion_dropout,
+ drop_path=fusion_droppath,
+ )
+ else:
+ feature_fusion_layer = None
+
+ encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
+ assert encoder_norm is None
+ self.encoder = TransformerEncoder(
+ encoder_layer,
+ num_encoder_layers,
+ d_model=d_model,
+ num_queries=num_queries,
+ text_enhance_layer=text_enhance_layer,
+ feature_fusion_layer=feature_fusion_layer,
+ use_checkpoint=use_checkpoint,
+ use_transformer_ckpt=use_transformer_ckpt,
+ )
+
+ # choose decoder layer type
+ decoder_layer = DeformableTransformerDecoderLayer(
+ d_model,
+ dim_feedforward,
+ dropout,
+ activation,
+ num_feature_levels,
+ nhead,
+ dec_n_points,
+ use_text_cross_attention=use_text_cross_attention,
+ )
+
+ decoder_norm = nn.LayerNorm(d_model)
+ self.decoder = TransformerDecoder(
+ decoder_layer,
+ num_decoder_layers,
+ decoder_norm,
+ return_intermediate=return_intermediate_dec,
+ d_model=d_model,
+ query_dim=query_dim,
+ num_feature_levels=num_feature_levels,
+ )
+
+ self.d_model = d_model
+ self.nhead = nhead
+ self.dec_layers = num_decoder_layers
+ self.num_queries = num_queries # useful for single stage model only
+ self.num_patterns = num_patterns
+ if not isinstance(num_patterns, int):
+ Warning("num_patterns should be int but {}".format(type(num_patterns)))
+ self.num_patterns = 0
+
+ if num_feature_levels > 1:
+ if self.num_encoder_layers > 0:
+ self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
+ else:
+ self.level_embed = None
+
+ self.learnable_tgt_init = learnable_tgt_init
+ assert learnable_tgt_init, "why not learnable_tgt_init"
+ self.embed_init_tgt = embed_init_tgt
+ if (two_stage_type != "no" and embed_init_tgt) or (two_stage_type == "no"):
+ self.tgt_embed = nn.Embedding(self.num_queries, d_model)
+ nn.init.normal_(self.tgt_embed.weight.data)
+ else:
+ self.tgt_embed = None
+
+ # for two stage
+ self.two_stage_type = two_stage_type
+ assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format(
+ two_stage_type
+ )
+ if two_stage_type == "standard":
+ # anchor selection at the output of encoder
+ self.enc_output = nn.Linear(d_model, d_model)
+ self.enc_output_norm = nn.LayerNorm(d_model)
+ self.two_stage_wh_embedding = None
+
+ if two_stage_type == "no":
+ self.init_ref_points(num_queries) # init self.refpoint_embed
+
+ self.enc_out_class_embed = None
+ self.enc_out_bbox_embed = None
+
+ self._reset_parameters()
+
+ def _reset_parameters(self):
+ for p in self.parameters():
+ if p.dim() > 1:
+ nn.init.xavier_uniform_(p)
+ for m in self.modules():
+ if isinstance(m, MSDeformAttn):
+ m._reset_parameters()
+ if self.num_feature_levels > 1 and self.level_embed is not None:
+ nn.init.normal_(self.level_embed)
+
+ def get_valid_ratio(self, mask):
+ _, H, W = mask.shape
+ valid_H = torch.sum(~mask[:, :, 0], 1)
+ valid_W = torch.sum(~mask[:, 0, :], 1)
+ valid_ratio_h = valid_H.float() / H
+ valid_ratio_w = valid_W.float() / W
+ valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1)
+ return valid_ratio
+
+ def init_ref_points(self, use_num_queries):
+ self.refpoint_embed = nn.Embedding(use_num_queries, 4)
+
+ def forward(self, srcs, masks, refpoint_embed, pos_embeds, tgt, attn_mask=None, text_dict=None):
+ """
+ Input:
+ - srcs: List of multi features [bs, ci, hi, wi]
+ - masks: List of multi masks [bs, hi, wi]
+ - refpoint_embed: [bs, num_dn, 4]. None in infer
+ - pos_embeds: List of multi pos embeds [bs, ci, hi, wi]
+ - tgt: [bs, num_dn, d_model]. None in infer
+
+ """
+ # prepare input for encoder
+ src_flatten = []
+ mask_flatten = []
+ lvl_pos_embed_flatten = []
+ spatial_shapes = []
+ for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)):
+ bs, c, h, w = src.shape
+ spatial_shape = (h, w)
+ spatial_shapes.append(spatial_shape)
+
+ src = src.flatten(2).transpose(1, 2) # bs, hw, c
+ mask = mask.flatten(1) # bs, hw
+ pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c
+ if self.num_feature_levels > 1 and self.level_embed is not None:
+ lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1)
+ else:
+ lvl_pos_embed = pos_embed
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
+ src_flatten.append(src)
+ mask_flatten.append(mask)
+ src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c
+ mask_flatten = torch.cat(mask_flatten, 1) # bs, \sum{hxw}
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c
+ spatial_shapes = torch.as_tensor(
+ spatial_shapes, dtype=torch.long, device=src_flatten.device
+ )
+ level_start_index = torch.cat(
+ (spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1])
+ )
+ valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1)
+
+ # two stage
+ enc_topk_proposals = enc_refpoint_embed = None
+
+ #########################################################
+ # Begin Encoder
+ #########################################################
+ memory, memory_text = self.encoder(
+ src_flatten,
+ pos=lvl_pos_embed_flatten,
+ level_start_index=level_start_index,
+ spatial_shapes=spatial_shapes,
+ valid_ratios=valid_ratios,
+ key_padding_mask=mask_flatten,
+ memory_text=text_dict["encoded_text"],
+ text_attention_mask=~text_dict["text_token_mask"],
+ # we ~ the mask . False means use the token; True means pad the token
+ position_ids=text_dict["position_ids"],
+ text_self_attention_masks=text_dict["text_self_attention_masks"],
+ )
+ #########################################################
+ # End Encoder
+ # - memory: bs, \sum{hw}, c
+ # - mask_flatten: bs, \sum{hw}
+ # - lvl_pos_embed_flatten: bs, \sum{hw}, c
+ # - enc_intermediate_output: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c)
+ # - enc_intermediate_refpoints: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c)
+ #########################################################
+ text_dict["encoded_text"] = memory_text
+ # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1':
+ # if memory.isnan().any() | memory.isinf().any():
+ # import ipdb; ipdb.set_trace()
+
+ if self.two_stage_type == "standard":
+ output_memory, output_proposals = gen_encoder_output_proposals(
+ memory, mask_flatten, spatial_shapes
+ )
+ output_memory = self.enc_output_norm(self.enc_output(output_memory))
+
+ if text_dict is not None:
+ enc_outputs_class_unselected = self.enc_out_class_embed(output_memory, text_dict)
+ else:
+ enc_outputs_class_unselected = self.enc_out_class_embed(output_memory)
+
+ topk_logits = enc_outputs_class_unselected.max(-1)[0]
+ enc_outputs_coord_unselected = (
+ self.enc_out_bbox_embed(output_memory) + output_proposals
+ ) # (bs, \sum{hw}, 4) unsigmoid
+ topk = self.num_queries
+
+ topk_proposals = torch.topk(topk_logits, topk, dim=1)[1] # bs, nq
+
+ # gather boxes
+ refpoint_embed_undetach = torch.gather(
+ enc_outputs_coord_unselected, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)
+ ) # unsigmoid
+ refpoint_embed_ = refpoint_embed_undetach.detach()
+ init_box_proposal = torch.gather(
+ output_proposals, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)
+ ).sigmoid() # sigmoid
+
+ # gather tgt
+ tgt_undetach = torch.gather(
+ output_memory, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, self.d_model)
+ )
+ if self.embed_init_tgt:
+ tgt_ = (
+ self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1)
+ ) # nq, bs, d_model
+ else:
+ tgt_ = tgt_undetach.detach()
+
+ if refpoint_embed is not None:
+ refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1)
+ tgt = torch.cat([tgt, tgt_], dim=1)
+ else:
+ refpoint_embed, tgt = refpoint_embed_, tgt_
+
+ elif self.two_stage_type == "no":
+ tgt_ = (
+ self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1)
+ ) # nq, bs, d_model
+ refpoint_embed_ = (
+ self.refpoint_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1)
+ ) # nq, bs, 4
+
+ if refpoint_embed is not None:
+ refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1)
+ tgt = torch.cat([tgt, tgt_], dim=1)
+ else:
+ refpoint_embed, tgt = refpoint_embed_, tgt_
+
+ if self.num_patterns > 0:
+ tgt_embed = tgt.repeat(1, self.num_patterns, 1)
+ refpoint_embed = refpoint_embed.repeat(1, self.num_patterns, 1)
+ tgt_pat = self.patterns.weight[None, :, :].repeat_interleave(
+ self.num_queries, 1
+ ) # 1, n_q*n_pat, d_model
+ tgt = tgt_embed + tgt_pat
+
+ init_box_proposal = refpoint_embed_.sigmoid()
+
+ else:
+ raise NotImplementedError("unknown two_stage_type {}".format(self.two_stage_type))
+ #########################################################
+ # End preparing tgt
+ # - tgt: bs, NQ, d_model
+ # - refpoint_embed(unsigmoid): bs, NQ, d_model
+ #########################################################
+
+ #########################################################
+ # Begin Decoder
+ #########################################################
+ hs, references = self.decoder(
+ tgt=tgt.transpose(0, 1),
+ memory=memory.transpose(0, 1),
+ memory_key_padding_mask=mask_flatten,
+ pos=lvl_pos_embed_flatten.transpose(0, 1),
+ refpoints_unsigmoid=refpoint_embed.transpose(0, 1),
+ level_start_index=level_start_index,
+ spatial_shapes=spatial_shapes,
+ valid_ratios=valid_ratios,
+ tgt_mask=attn_mask,
+ memory_text=text_dict["encoded_text"],
+ text_attention_mask=~text_dict["text_token_mask"],
+ # we ~ the mask . False means use the token; True means pad the token
+ )
+ #########################################################
+ # End Decoder
+ # hs: n_dec, bs, nq, d_model
+ # references: n_dec+1, bs, nq, query_dim
+ #########################################################
+
+ #########################################################
+ # Begin postprocess
+ #########################################################
+ if self.two_stage_type == "standard":
+ hs_enc = tgt_undetach.unsqueeze(0)
+ ref_enc = refpoint_embed_undetach.sigmoid().unsqueeze(0)
+ else:
+ hs_enc = ref_enc = None
+ #########################################################
+ # End postprocess
+ # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or (n_enc, bs, nq, d_model) or None
+ # ref_enc: (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or (n_enc, bs, nq, d_model) or None
+ #########################################################
+
+ return hs, references, hs_enc, ref_enc, init_box_proposal
+ # hs: (n_dec, bs, nq, d_model)
+ # references: sigmoid coordinates. (n_dec+1, bs, bq, 4)
+ # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or None
+ # ref_enc: sigmoid coordinates. \
+ # (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or None
+
+
+class TransformerEncoder(nn.Module):
+ def __init__(
+ self,
+ encoder_layer,
+ num_layers,
+ d_model=256,
+ num_queries=300,
+ enc_layer_share=False,
+ text_enhance_layer=None,
+ feature_fusion_layer=None,
+ use_checkpoint=False,
+ use_transformer_ckpt=False,
+ ):
+ """_summary_
+
+ Args:
+ encoder_layer (_type_): _description_
+ num_layers (_type_): _description_
+ norm (_type_, optional): _description_. Defaults to None.
+ d_model (int, optional): _description_. Defaults to 256.
+ num_queries (int, optional): _description_. Defaults to 300.
+ enc_layer_share (bool, optional): _description_. Defaults to False.
+
+ """
+ super().__init__()
+ # prepare layers
+ self.layers = []
+ self.text_layers = []
+ self.fusion_layers = []
+ if num_layers > 0:
+ self.layers = _get_clones(encoder_layer, num_layers, layer_share=enc_layer_share)
+
+ if text_enhance_layer is not None:
+ self.text_layers = _get_clones(
+ text_enhance_layer, num_layers, layer_share=enc_layer_share
+ )
+ if feature_fusion_layer is not None:
+ self.fusion_layers = _get_clones(
+ feature_fusion_layer, num_layers, layer_share=enc_layer_share
+ )
+ else:
+ self.layers = []
+ del encoder_layer
+
+ if text_enhance_layer is not None:
+ self.text_layers = []
+ del text_enhance_layer
+ if feature_fusion_layer is not None:
+ self.fusion_layers = []
+ del feature_fusion_layer
+
+ self.query_scale = None
+ self.num_queries = num_queries
+ self.num_layers = num_layers
+ self.d_model = d_model
+
+ self.use_checkpoint = use_checkpoint
+ self.use_transformer_ckpt = use_transformer_ckpt
+
+ @staticmethod
+ def get_reference_points(spatial_shapes, valid_ratios, device):
+ reference_points_list = []
+ for lvl, (H_, W_) in enumerate(spatial_shapes):
+
+ ref_y, ref_x = torch.meshgrid(
+ torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device),
+ torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device),
+ )
+ ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_)
+ ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_)
+ ref = torch.stack((ref_x, ref_y), -1)
+ reference_points_list.append(ref)
+ reference_points = torch.cat(reference_points_list, 1)
+ reference_points = reference_points[:, :, None] * valid_ratios[:, None]
+ return reference_points
+
+ def forward(
+ self,
+ # for images
+ src: Tensor,
+ pos: Tensor,
+ spatial_shapes: Tensor,
+ level_start_index: Tensor,
+ valid_ratios: Tensor,
+ key_padding_mask: Tensor,
+ # for texts
+ memory_text: Tensor = None,
+ text_attention_mask: Tensor = None,
+ pos_text: Tensor = None,
+ text_self_attention_masks: Tensor = None,
+ position_ids: Tensor = None,
+ ):
+ """
+ Input:
+ - src: [bs, sum(hi*wi), 256]
+ - pos: pos embed for src. [bs, sum(hi*wi), 256]
+ - spatial_shapes: h,w of each level [num_level, 2]
+ - level_start_index: [num_level] start point of level in sum(hi*wi).
+ - valid_ratios: [bs, num_level, 2]
+ - key_padding_mask: [bs, sum(hi*wi)]
+
+ - memory_text: bs, n_text, 256
+ - text_attention_mask: bs, n_text
+ False for no padding; True for padding
+ - pos_text: bs, n_text, 256
+
+ - position_ids: bs, n_text
+ Intermedia:
+ - reference_points: [bs, sum(hi*wi), num_level, 2]
+ Outpus:
+ - output: [bs, sum(hi*wi), 256]
+ """
+
+ output = src
+
+ # preparation and reshape
+ if self.num_layers > 0:
+ reference_points = self.get_reference_points(
+ spatial_shapes, valid_ratios, device=src.device
+ )
+
+ if self.text_layers:
+ # generate pos_text
+ bs, n_text, text_dim = memory_text.shape
+ if pos_text is None and position_ids is None:
+ pos_text = (
+ torch.arange(n_text, device=memory_text.device)
+ .float()
+ .unsqueeze(0)
+ .unsqueeze(-1)
+ .repeat(bs, 1, 1)
+ )
+ pos_text = get_sine_pos_embed(pos_text, num_pos_feats=256, exchange_xy=False)
+ if position_ids is not None:
+ pos_text = get_sine_pos_embed(
+ position_ids[..., None], num_pos_feats=256, exchange_xy=False
+ )
+
+ # main process
+ for layer_id, layer in enumerate(self.layers):
+ # if output.isnan().any() or memory_text.isnan().any():
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ if self.fusion_layers:
+ if self.use_checkpoint:
+ output, memory_text = checkpoint.checkpoint(
+ self.fusion_layers[layer_id],
+ output,
+ memory_text,
+ key_padding_mask,
+ text_attention_mask,
+ )
+ else:
+ output, memory_text = self.fusion_layers[layer_id](
+ v=output,
+ l=memory_text,
+ attention_mask_v=key_padding_mask,
+ attention_mask_l=text_attention_mask,
+ )
+
+ if self.text_layers:
+ memory_text = self.text_layers[layer_id](
+ src=memory_text.transpose(0, 1),
+ src_mask=~text_self_attention_masks, # note we use ~ for mask here
+ src_key_padding_mask=text_attention_mask,
+ pos=(pos_text.transpose(0, 1) if pos_text is not None else None),
+ ).transpose(0, 1)
+
+ # main process
+ if self.use_transformer_ckpt:
+ output = checkpoint.checkpoint(
+ layer,
+ output,
+ pos,
+ reference_points,
+ spatial_shapes,
+ level_start_index,
+ key_padding_mask,
+ )
+ else:
+ output = layer(
+ src=output,
+ pos=pos,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ key_padding_mask=key_padding_mask,
+ )
+
+ return output, memory_text
+
+
+class TransformerDecoder(nn.Module):
+ def __init__(
+ self,
+ decoder_layer,
+ num_layers,
+ norm=None,
+ return_intermediate=False,
+ d_model=256,
+ query_dim=4,
+ num_feature_levels=1,
+ ):
+ super().__init__()
+ if num_layers > 0:
+ self.layers = _get_clones(decoder_layer, num_layers)
+ else:
+ self.layers = []
+ self.num_layers = num_layers
+ self.norm = norm
+ self.return_intermediate = return_intermediate
+ assert return_intermediate, "support return_intermediate only"
+ self.query_dim = query_dim
+ assert query_dim in [2, 4], "query_dim should be 2/4 but {}".format(query_dim)
+ self.num_feature_levels = num_feature_levels
+
+ self.ref_point_head = MLP(query_dim // 2 * d_model, d_model, d_model, 2)
+ self.query_pos_sine_scale = None
+
+ self.query_scale = None
+ self.bbox_embed = None
+ self.class_embed = None
+
+ self.d_model = d_model
+
+ self.ref_anchor_head = None
+
+ def forward(
+ self,
+ tgt,
+ memory,
+ tgt_mask: Optional[Tensor] = None,
+ memory_mask: Optional[Tensor] = None,
+ tgt_key_padding_mask: Optional[Tensor] = None,
+ memory_key_padding_mask: Optional[Tensor] = None,
+ pos: Optional[Tensor] = None,
+ refpoints_unsigmoid: Optional[Tensor] = None, # num_queries, bs, 2
+ # for memory
+ level_start_index: Optional[Tensor] = None, # num_levels
+ spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2
+ valid_ratios: Optional[Tensor] = None,
+ # for text
+ memory_text: Optional[Tensor] = None,
+ text_attention_mask: Optional[Tensor] = None,
+ ):
+ """
+ Input:
+ - tgt: nq, bs, d_model
+ - memory: hw, bs, d_model
+ - pos: hw, bs, d_model
+ - refpoints_unsigmoid: nq, bs, 2/4
+ - valid_ratios/spatial_shapes: bs, nlevel, 2
+ """
+ output = tgt
+
+ intermediate = []
+ reference_points = refpoints_unsigmoid.sigmoid()
+ ref_points = [reference_points]
+
+ for layer_id, layer in enumerate(self.layers):
+
+ if reference_points.shape[-1] == 4:
+ reference_points_input = (
+ reference_points[:, :, None]
+ * torch.cat([valid_ratios, valid_ratios], -1)[None, :]
+ ) # nq, bs, nlevel, 4
+ else:
+ assert reference_points.shape[-1] == 2
+ reference_points_input = reference_points[:, :, None] * valid_ratios[None, :]
+ query_sine_embed = gen_sineembed_for_position(
+ reference_points_input[:, :, 0, :]
+ ) # nq, bs, 256*2
+
+ # conditional query
+ raw_query_pos = self.ref_point_head(query_sine_embed) # nq, bs, 256
+ pos_scale = self.query_scale(output) if self.query_scale is not None else 1
+ query_pos = pos_scale * raw_query_pos
+ # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1':
+ # if query_pos.isnan().any() | query_pos.isinf().any():
+ # import ipdb; ipdb.set_trace()
+
+ # main process
+ output = layer(
+ tgt=output,
+ tgt_query_pos=query_pos,
+ tgt_query_sine_embed=query_sine_embed,
+ tgt_key_padding_mask=tgt_key_padding_mask,
+ tgt_reference_points=reference_points_input,
+ memory_text=memory_text,
+ text_attention_mask=text_attention_mask,
+ memory=memory,
+ memory_key_padding_mask=memory_key_padding_mask,
+ memory_level_start_index=level_start_index,
+ memory_spatial_shapes=spatial_shapes,
+ memory_pos=pos,
+ self_attn_mask=tgt_mask,
+ cross_attn_mask=memory_mask,
+ )
+ if output.isnan().any() | output.isinf().any():
+ print(f"output layer_id {layer_id} is nan")
+ try:
+ num_nan = output.isnan().sum().item()
+ num_inf = output.isinf().sum().item()
+ print(f"num_nan {num_nan}, num_inf {num_inf}")
+ except Exception as e:
+ print(e)
+ # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1':
+ # import ipdb; ipdb.set_trace()
+
+ # iter update
+ if self.bbox_embed is not None:
+ # box_holder = self.bbox_embed(output)
+ # box_holder[..., :self.query_dim] += inverse_sigmoid(reference_points)
+ # new_reference_points = box_holder[..., :self.query_dim].sigmoid()
+
+ reference_before_sigmoid = inverse_sigmoid(reference_points)
+ delta_unsig = self.bbox_embed[layer_id](output)
+ outputs_unsig = delta_unsig + reference_before_sigmoid
+ new_reference_points = outputs_unsig.sigmoid()
+
+ reference_points = new_reference_points.detach()
+ # if layer_id != self.num_layers - 1:
+ ref_points.append(new_reference_points)
+
+ intermediate.append(self.norm(output))
+
+ return [
+ [itm_out.transpose(0, 1) for itm_out in intermediate],
+ [itm_refpoint.transpose(0, 1) for itm_refpoint in ref_points],
+ ]
+
+
+class DeformableTransformerEncoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model=256,
+ d_ffn=1024,
+ dropout=0.1,
+ activation="relu",
+ n_levels=4,
+ n_heads=8,
+ n_points=4,
+ ):
+ super().__init__()
+
+ # self attention
+ self.self_attn = MSDeformAttn(
+ embed_dim=d_model,
+ num_levels=n_levels,
+ num_heads=n_heads,
+ num_points=n_points,
+ batch_first=True,
+ )
+ self.dropout1 = nn.Dropout(dropout)
+ self.norm1 = nn.LayerNorm(d_model)
+
+ # ffn
+ self.linear1 = nn.Linear(d_model, d_ffn)
+ self.activation = _get_activation_fn(activation, d_model=d_ffn)
+ self.dropout2 = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(d_ffn, d_model)
+ self.dropout3 = nn.Dropout(dropout)
+ self.norm2 = nn.LayerNorm(d_model)
+
+ @staticmethod
+ def with_pos_embed(tensor, pos):
+ return tensor if pos is None else tensor + pos
+
+ def forward_ffn(self, src):
+ src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
+ src = src + self.dropout3(src2)
+ src = self.norm2(src)
+ return src
+
+ def forward(
+ self, src, pos, reference_points, spatial_shapes, level_start_index, key_padding_mask=None
+ ):
+ # self attention
+ # import ipdb; ipdb.set_trace()
+ src2 = self.self_attn(
+ query=self.with_pos_embed(src, pos),
+ reference_points=reference_points,
+ value=src,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ key_padding_mask=key_padding_mask,
+ )
+ src = src + self.dropout1(src2)
+ src = self.norm1(src)
+
+ # ffn
+ src = self.forward_ffn(src)
+
+ return src
+
+
+class DeformableTransformerDecoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model=256,
+ d_ffn=1024,
+ dropout=0.1,
+ activation="relu",
+ n_levels=4,
+ n_heads=8,
+ n_points=4,
+ use_text_feat_guide=False,
+ use_text_cross_attention=False,
+ ):
+ super().__init__()
+
+ # cross attention
+ self.cross_attn = MSDeformAttn(
+ embed_dim=d_model,
+ num_levels=n_levels,
+ num_heads=n_heads,
+ num_points=n_points,
+ batch_first=True,
+ )
+ self.dropout1 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.norm1 = nn.LayerNorm(d_model)
+
+ # cross attention text
+ if use_text_cross_attention:
+ self.ca_text = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
+ self.catext_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.catext_norm = nn.LayerNorm(d_model)
+
+ # self attention
+ self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
+ self.dropout2 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.norm2 = nn.LayerNorm(d_model)
+
+ # ffn
+ self.linear1 = nn.Linear(d_model, d_ffn)
+ self.activation = _get_activation_fn(activation, d_model=d_ffn, batch_dim=1)
+ self.dropout3 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.linear2 = nn.Linear(d_ffn, d_model)
+ self.dropout4 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.norm3 = nn.LayerNorm(d_model)
+
+ self.key_aware_proj = None
+ self.use_text_feat_guide = use_text_feat_guide
+ assert not use_text_feat_guide
+ self.use_text_cross_attention = use_text_cross_attention
+
+ def rm_self_attn_modules(self):
+ self.self_attn = None
+ self.dropout2 = None
+ self.norm2 = None
+
+ @staticmethod
+ def with_pos_embed(tensor, pos):
+ return tensor if pos is None else tensor + pos
+
+ def forward_ffn(self, tgt):
+ with torch.cuda.amp.autocast(enabled=False):
+ tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt))))
+ tgt = tgt + self.dropout4(tgt2)
+ tgt = self.norm3(tgt)
+ return tgt
+
+ def forward(
+ self,
+ # for tgt
+ tgt: Optional[Tensor], # nq, bs, d_model
+ tgt_query_pos: Optional[Tensor] = None, # pos for query. MLP(Sine(pos))
+ tgt_query_sine_embed: Optional[Tensor] = None, # pos for query. Sine(pos)
+ tgt_key_padding_mask: Optional[Tensor] = None,
+ tgt_reference_points: Optional[Tensor] = None, # nq, bs, 4
+ memory_text: Optional[Tensor] = None, # bs, num_token, d_model
+ text_attention_mask: Optional[Tensor] = None, # bs, num_token
+ # for memory
+ memory: Optional[Tensor] = None, # hw, bs, d_model
+ memory_key_padding_mask: Optional[Tensor] = None,
+ memory_level_start_index: Optional[Tensor] = None, # num_levels
+ memory_spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2
+ memory_pos: Optional[Tensor] = None, # pos for memory
+ # sa
+ self_attn_mask: Optional[Tensor] = None, # mask used for self-attention
+ cross_attn_mask: Optional[Tensor] = None, # mask used for cross-attention
+ ):
+ """
+ Input:
+ - tgt/tgt_query_pos: nq, bs, d_model
+ -
+ """
+ assert cross_attn_mask is None
+
+ # self attention
+ if self.self_attn is not None:
+ # import ipdb; ipdb.set_trace()
+ q = k = self.with_pos_embed(tgt, tgt_query_pos)
+ tgt2 = self.self_attn(q, k, tgt, attn_mask=self_attn_mask)[0]
+ tgt = tgt + self.dropout2(tgt2)
+ tgt = self.norm2(tgt)
+
+ if self.use_text_cross_attention:
+ tgt2 = self.ca_text(
+ self.with_pos_embed(tgt, tgt_query_pos),
+ memory_text.transpose(0, 1),
+ memory_text.transpose(0, 1),
+ key_padding_mask=text_attention_mask,
+ )[0]
+ tgt = tgt + self.catext_dropout(tgt2)
+ tgt = self.catext_norm(tgt)
+
+ tgt2 = self.cross_attn(
+ query=self.with_pos_embed(tgt, tgt_query_pos).transpose(0, 1),
+ reference_points=tgt_reference_points.transpose(0, 1).contiguous(),
+ value=memory.transpose(0, 1),
+ spatial_shapes=memory_spatial_shapes,
+ level_start_index=memory_level_start_index,
+ key_padding_mask=memory_key_padding_mask,
+ ).transpose(0, 1)
+ tgt = tgt + self.dropout1(tgt2)
+ tgt = self.norm1(tgt)
+
+ # ffn
+ tgt = self.forward_ffn(tgt)
+
+ return tgt
+
+
+def build_transformer(args):
+ return Transformer(
+ d_model=args.hidden_dim,
+ dropout=args.dropout,
+ nhead=args.nheads,
+ num_queries=args.num_queries,
+ dim_feedforward=args.dim_feedforward,
+ num_encoder_layers=args.enc_layers,
+ num_decoder_layers=args.dec_layers,
+ normalize_before=args.pre_norm,
+ return_intermediate_dec=True,
+ query_dim=args.query_dim,
+ activation=args.transformer_activation,
+ num_patterns=args.num_patterns,
+ num_feature_levels=args.num_feature_levels,
+ enc_n_points=args.enc_n_points,
+ dec_n_points=args.dec_n_points,
+ learnable_tgt_init=True,
+ # two stage
+ two_stage_type=args.two_stage_type, # ['no', 'standard', 'early']
+ embed_init_tgt=args.embed_init_tgt,
+ use_text_enhancer=args.use_text_enhancer,
+ use_fusion_layer=args.use_fusion_layer,
+ use_checkpoint=args.use_checkpoint,
+ use_transformer_ckpt=args.use_transformer_ckpt,
+ use_text_cross_attention=args.use_text_cross_attention,
+ text_dropout=args.text_dropout,
+ fusion_dropout=args.fusion_dropout,
+ fusion_droppath=args.fusion_droppath,
+ )
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/transformer_vanilla.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/transformer_vanilla.py
new file mode 100644
index 0000000000000000000000000000000000000000..10c0920c1a217af5bb3e1b13077568035ab3b7b5
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/transformer_vanilla.py
@@ -0,0 +1,123 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+DETR Transformer class.
+
+Copy-paste from torch.nn.Transformer with modifications:
+ * positional encodings are passed in MHattention
+ * extra LN at the end of encoder is removed
+ * decoder returns a stack of activations from all decoding layers
+"""
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+from .utils import (
+ MLP,
+ _get_activation_fn,
+ _get_clones,
+ gen_encoder_output_proposals,
+ gen_sineembed_for_position,
+ sigmoid_focal_loss,
+)
+
+
+class TextTransformer(nn.Module):
+ def __init__(self, num_layers, d_model=256, nheads=8, dim_feedforward=2048, dropout=0.1):
+ super().__init__()
+ self.num_layers = num_layers
+ self.d_model = d_model
+ self.nheads = nheads
+ self.dim_feedforward = dim_feedforward
+ self.norm = None
+
+ single_encoder_layer = TransformerEncoderLayer(
+ d_model=d_model, nhead=nheads, dim_feedforward=dim_feedforward, dropout=dropout
+ )
+ self.layers = _get_clones(single_encoder_layer, num_layers)
+
+ def forward(self, memory_text: torch.Tensor, text_attention_mask: torch.Tensor):
+ """
+
+ Args:
+ text_attention_mask: bs, num_token
+ memory_text: bs, num_token, d_model
+
+ Raises:
+ RuntimeError: _description_
+
+ Returns:
+ output: bs, num_token, d_model
+ """
+
+ output = memory_text.transpose(0, 1)
+
+ for layer in self.layers:
+ output = layer(output, src_key_padding_mask=text_attention_mask)
+
+ if self.norm is not None:
+ output = self.norm(output)
+
+ return output.transpose(0, 1)
+
+
+class TransformerEncoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model,
+ nhead,
+ dim_feedforward=2048,
+ dropout=0.1,
+ activation="relu",
+ normalize_before=False,
+ ):
+ super().__init__()
+ self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
+ # Implementation of Feedforward model
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
+
+ self.norm1 = nn.LayerNorm(d_model)
+ self.norm2 = nn.LayerNorm(d_model)
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(dropout)
+
+ self.activation = _get_activation_fn(activation)
+ self.normalize_before = normalize_before
+ self.nhead = nhead
+
+ def with_pos_embed(self, tensor, pos: Optional[Tensor]):
+ return tensor if pos is None else tensor + pos
+
+ def forward(
+ self,
+ src,
+ src_mask: Optional[Tensor] = None,
+ src_key_padding_mask: Optional[Tensor] = None,
+ pos: Optional[Tensor] = None,
+ ):
+ # repeat attn mask
+ if src_mask.dim() == 3 and src_mask.shape[0] == src.shape[1]:
+ # bs, num_q, num_k
+ src_mask = src_mask.repeat(self.nhead, 1, 1)
+
+ q = k = self.with_pos_embed(src, pos)
+
+ src2 = self.self_attn(q, k, value=src, attn_mask=src_mask)[0]
+
+ # src2 = self.self_attn(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]
+ src = src + self.dropout1(src2)
+ src = self.norm1(src)
+ src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
+ src = src + self.dropout2(src2)
+ src = self.norm2(src)
+ return src
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/utils.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bd18f70225e12b2e27fdb4eabcde91d959f8e31
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/GroundingDINO/utils.py
@@ -0,0 +1,268 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+
+import copy
+import math
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+
+def _get_clones(module, N, layer_share=False):
+ # import ipdb; ipdb.set_trace()
+ if layer_share:
+ return nn.ModuleList([module for i in range(N)])
+ else:
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
+
+
+def get_sine_pos_embed(
+ pos_tensor: torch.Tensor,
+ num_pos_feats: int = 128,
+ temperature: int = 10000,
+ exchange_xy: bool = True,
+):
+ """generate sine position embedding from a position tensor
+ Args:
+ pos_tensor (torch.Tensor): shape: [..., n].
+ num_pos_feats (int): projected shape for each float in the tensor.
+ temperature (int): temperature in the sine/cosine function.
+ exchange_xy (bool, optional): exchange pos x and pos y. \
+ For example, input tensor is [x,y], the results will be [pos(y), pos(x)]. Defaults to True.
+ Returns:
+ pos_embed (torch.Tensor): shape: [..., n*num_pos_feats].
+ """
+ scale = 2 * math.pi
+ dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos_tensor.device)
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_pos_feats)
+
+ def sine_func(x: torch.Tensor):
+ sin_x = x * scale / dim_t
+ sin_x = torch.stack((sin_x[..., 0::2].sin(), sin_x[..., 1::2].cos()), dim=3).flatten(2)
+ return sin_x
+
+ pos_res = [sine_func(x) for x in pos_tensor.split([1] * pos_tensor.shape[-1], dim=-1)]
+ if exchange_xy:
+ pos_res[0], pos_res[1] = pos_res[1], pos_res[0]
+ pos_res = torch.cat(pos_res, dim=-1)
+ return pos_res
+
+
+def gen_encoder_output_proposals(
+ memory: Tensor, memory_padding_mask: Tensor, spatial_shapes: Tensor, learnedwh=None
+):
+ """
+ Input:
+ - memory: bs, \sum{hw}, d_model
+ - memory_padding_mask: bs, \sum{hw}
+ - spatial_shapes: nlevel, 2
+ - learnedwh: 2
+ Output:
+ - output_memory: bs, \sum{hw}, d_model
+ - output_proposals: bs, \sum{hw}, 4
+ """
+ N_, S_, C_ = memory.shape
+ proposals = []
+ _cur = 0
+ for lvl, (H_, W_) in enumerate(spatial_shapes):
+ mask_flatten_ = memory_padding_mask[:, _cur : (_cur + H_ * W_)].view(N_, H_, W_, 1)
+ valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1)
+ valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1)
+
+ # import ipdb; ipdb.set_trace()
+
+ grid_y, grid_x = torch.meshgrid(
+ torch.linspace(0, H_ - 1, H_, dtype=torch.float32, device=memory.device),
+ torch.linspace(0, W_ - 1, W_, dtype=torch.float32, device=memory.device),
+ )
+ grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1) # H_, W_, 2
+
+ scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N_, 1, 1, 2)
+ grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale
+
+ if learnedwh is not None:
+ # import ipdb; ipdb.set_trace()
+ wh = torch.ones_like(grid) * learnedwh.sigmoid() * (2.0**lvl)
+ else:
+ wh = torch.ones_like(grid) * 0.05 * (2.0**lvl)
+
+ # scale = torch.cat([W_[None].unsqueeze(-1), H_[None].unsqueeze(-1)], 1).view(1, 1, 1, 2).repeat(N_, 1, 1, 1)
+ # grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale
+ # wh = torch.ones_like(grid) / scale
+ proposal = torch.cat((grid, wh), -1).view(N_, -1, 4)
+ proposals.append(proposal)
+ _cur += H_ * W_
+ # import ipdb; ipdb.set_trace()
+ output_proposals = torch.cat(proposals, 1)
+ output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(
+ -1, keepdim=True
+ )
+ output_proposals = torch.log(output_proposals / (1 - output_proposals)) # unsigmoid
+ output_proposals = output_proposals.masked_fill(memory_padding_mask.unsqueeze(-1), float("inf"))
+ output_proposals = output_proposals.masked_fill(~output_proposals_valid, float("inf"))
+
+ output_memory = memory
+ output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0))
+ output_memory = output_memory.masked_fill(~output_proposals_valid, float(0))
+
+ # output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float('inf'))
+ # output_memory = output_memory.masked_fill(~output_proposals_valid, float('inf'))
+
+ return output_memory, output_proposals
+
+
+class RandomBoxPerturber:
+ def __init__(
+ self, x_noise_scale=0.2, y_noise_scale=0.2, w_noise_scale=0.2, h_noise_scale=0.2
+ ) -> None:
+ self.noise_scale = torch.Tensor(
+ [x_noise_scale, y_noise_scale, w_noise_scale, h_noise_scale]
+ )
+
+ def __call__(self, refanchors: Tensor) -> Tensor:
+ nq, bs, query_dim = refanchors.shape
+ device = refanchors.device
+
+ noise_raw = torch.rand_like(refanchors)
+ noise_scale = self.noise_scale.to(device)[:query_dim]
+
+ new_refanchors = refanchors * (1 + (noise_raw - 0.5) * noise_scale)
+ return new_refanchors.clamp_(0, 1)
+
+
+def sigmoid_focal_loss(
+ inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2, no_reduction=False
+):
+ """
+ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
+ Args:
+ inputs: A float tensor of arbitrary shape.
+ The predictions for each example.
+ targets: A float tensor with the same shape as inputs. Stores the binary
+ classification label for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+ alpha: (optional) Weighting factor in range (0,1) to balance
+ positive vs negative examples. Default = -1 (no weighting).
+ gamma: Exponent of the modulating factor (1 - p_t) to
+ balance easy vs hard examples.
+ Returns:
+ Loss tensor
+ """
+ prob = inputs.sigmoid()
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
+ p_t = prob * targets + (1 - prob) * (1 - targets)
+ loss = ce_loss * ((1 - p_t) ** gamma)
+
+ if alpha >= 0:
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
+ loss = alpha_t * loss
+
+ if no_reduction:
+ return loss
+
+ return loss.mean(1).sum() / num_boxes
+
+
+class MLP(nn.Module):
+ """Very simple multi-layer perceptron (also called FFN)"""
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
+ )
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+def _get_activation_fn(activation, d_model=256, batch_dim=0):
+ """Return an activation function given a string"""
+ if activation == "relu":
+ return F.relu
+ if activation == "gelu":
+ return F.gelu
+ if activation == "glu":
+ return F.glu
+ if activation == "prelu":
+ return nn.PReLU()
+ if activation == "selu":
+ return F.selu
+
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
+
+
+def gen_sineembed_for_position(pos_tensor):
+ # n_query, bs, _ = pos_tensor.size()
+ # sineembed_tensor = torch.zeros(n_query, bs, 256)
+ scale = 2 * math.pi
+ dim_t = torch.arange(128, dtype=torch.float32, device=pos_tensor.device)
+ dim_t = 10000 ** (2 * (torch.div(dim_t, 2, rounding_mode='floor')) / 128)
+ x_embed = pos_tensor[:, :, 0] * scale
+ y_embed = pos_tensor[:, :, 1] * scale
+ pos_x = x_embed[:, :, None] / dim_t
+ pos_y = y_embed[:, :, None] / dim_t
+ pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
+ pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
+ if pos_tensor.size(-1) == 2:
+ pos = torch.cat((pos_y, pos_x), dim=2)
+ elif pos_tensor.size(-1) == 4:
+ w_embed = pos_tensor[:, :, 2] * scale
+ pos_w = w_embed[:, :, None] / dim_t
+ pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2)
+
+ h_embed = pos_tensor[:, :, 3] * scale
+ pos_h = h_embed[:, :, None] / dim_t
+ pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2)
+
+ pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2)
+ else:
+ raise ValueError("Unknown pos_tensor shape(-1):{}".format(pos_tensor.size(-1)))
+ return pos
+
+
+class ContrastiveEmbed(nn.Module):
+ def __init__(self, max_text_len=256):
+ """
+ Args:
+ max_text_len: max length of text.
+ """
+ super().__init__()
+ self.max_text_len = max_text_len
+
+ def forward(self, x, text_dict):
+ """_summary_
+
+ Args:
+ x (_type_): _description_
+ text_dict (_type_): _description_
+ {
+ 'encoded_text': encoded_text, # bs, 195, d_model
+ 'text_token_mask': text_token_mask, # bs, 195
+ # True for used tokens. False for padding tokens
+ }
+ Returns:
+ _type_: _description_
+ """
+ assert isinstance(text_dict, dict)
+
+ y = text_dict["encoded_text"]
+ text_token_mask = text_dict["text_token_mask"]
+
+ res = x @ y.transpose(-1, -2)
+ res.masked_fill_(~text_token_mask[:, None, :], float("-inf"))
+
+ # padding to max_text_len
+ new_res = torch.full((*res.shape[:-1], self.max_text_len), float("-inf"), device=res.device)
+ new_res[..., : res.shape[-1]] = res
+
+ return new_res
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3413961d1d184b99835eb1e919b052d70298bc6
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/__init__.py
@@ -0,0 +1,18 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+from .GroundingDINO import build_groundingdino
+
+
+def build_model(args):
+ # we use register to maintain models from catdet6 on.
+ from .registry import MODULE_BUILD_FUNCS
+
+ assert args.modelname in MODULE_BUILD_FUNCS._module_dict
+ build_func = MODULE_BUILD_FUNCS.get(args.modelname)
+ model = build_func(args)
+ return model
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/registry.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d22a59eec79a2a19b83fa1779f2adaf5753aec6
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/models/registry.py
@@ -0,0 +1,66 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# -*- coding: utf-8 -*-
+# @Author: Yihao Chen
+# @Date: 2021-08-16 16:03:17
+# @Last Modified by: Shilong Liu
+# @Last Modified time: 2022-01-23 15:26
+# modified from mmcv
+
+import inspect
+from functools import partial
+
+
+class Registry(object):
+ def __init__(self, name):
+ self._name = name
+ self._module_dict = dict()
+
+ def __repr__(self):
+ format_str = self.__class__.__name__ + "(name={}, items={})".format(
+ self._name, list(self._module_dict.keys())
+ )
+ return format_str
+
+ def __len__(self):
+ return len(self._module_dict)
+
+ @property
+ def name(self):
+ return self._name
+
+ @property
+ def module_dict(self):
+ return self._module_dict
+
+ def get(self, key):
+ return self._module_dict.get(key, None)
+
+ def registe_with_name(self, module_name=None, force=False):
+ return partial(self.register, module_name=module_name, force=force)
+
+ def register(self, module_build_function, module_name=None, force=False):
+ """Register a module build function.
+ Args:
+ module (:obj:`nn.Module`): Module to be registered.
+ """
+ if not inspect.isfunction(module_build_function):
+ raise TypeError(
+ "module_build_function must be a function, but got {}".format(
+ type(module_build_function)
+ )
+ )
+ if module_name is None:
+ module_name = module_build_function.__name__
+ if not force and module_name in self._module_dict:
+ raise KeyError("{} is already registered in {}".format(module_name, self.name))
+ self._module_dict[module_name] = module_build_function
+
+ return module_build_function
+
+
+MODULE_BUILD_FUNCS = Registry("model build functions")
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..168f9979a4623806934b0ff1102ac166704e7dec
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/__init__.py
@@ -0,0 +1 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/box_ops.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/box_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..781068d294e576954edb4bd07b6e0f30e4e1bcd9
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/box_ops.py
@@ -0,0 +1,140 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+Utilities for bounding box manipulation and GIoU.
+"""
+import torch
+from torchvision.ops.boxes import box_area
+
+
+def box_cxcywh_to_xyxy(x):
+ x_c, y_c, w, h = x.unbind(-1)
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
+ return torch.stack(b, dim=-1)
+
+
+def box_xyxy_to_cxcywh(x):
+ x0, y0, x1, y1 = x.unbind(-1)
+ b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
+ return torch.stack(b, dim=-1)
+
+
+# modified from torchvision to also return the union
+def box_iou(boxes1, boxes2):
+ area1 = box_area(boxes1)
+ area2 = box_area(boxes2)
+
+ # import ipdb; ipdb.set_trace()
+ lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
+ rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
+
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
+ inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
+
+ union = area1[:, None] + area2 - inter
+
+ iou = inter / (union + 1e-6)
+ return iou, union
+
+
+def generalized_box_iou(boxes1, boxes2):
+ """
+ Generalized IoU from https://giou.stanford.edu/
+
+ The boxes should be in [x0, y0, x1, y1] format
+
+ Returns a [N, M] pairwise matrix, where N = len(boxes1)
+ and M = len(boxes2)
+ """
+ # degenerate boxes gives inf / nan results
+ # so do an early check
+ assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
+ assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
+ # except:
+ # import ipdb; ipdb.set_trace()
+ iou, union = box_iou(boxes1, boxes2)
+
+ lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])
+ rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
+
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
+ area = wh[:, :, 0] * wh[:, :, 1]
+
+ return iou - (area - union) / (area + 1e-6)
+
+
+# modified from torchvision to also return the union
+def box_iou_pairwise(boxes1, boxes2):
+ area1 = box_area(boxes1)
+ area2 = box_area(boxes2)
+
+ lt = torch.max(boxes1[:, :2], boxes2[:, :2]) # [N,2]
+ rb = torch.min(boxes1[:, 2:], boxes2[:, 2:]) # [N,2]
+
+ wh = (rb - lt).clamp(min=0) # [N,2]
+ inter = wh[:, 0] * wh[:, 1] # [N]
+
+ union = area1 + area2 - inter
+
+ iou = inter / union
+ return iou, union
+
+
+def generalized_box_iou_pairwise(boxes1, boxes2):
+ """
+ Generalized IoU from https://giou.stanford.edu/
+
+ Input:
+ - boxes1, boxes2: N,4
+ Output:
+ - giou: N, 4
+ """
+ # degenerate boxes gives inf / nan results
+ # so do an early check
+ assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
+ assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
+ assert boxes1.shape == boxes2.shape
+ iou, union = box_iou_pairwise(boxes1, boxes2) # N, 4
+
+ lt = torch.min(boxes1[:, :2], boxes2[:, :2])
+ rb = torch.max(boxes1[:, 2:], boxes2[:, 2:])
+
+ wh = (rb - lt).clamp(min=0) # [N,2]
+ area = wh[:, 0] * wh[:, 1]
+
+ return iou - (area - union) / area
+
+
+def masks_to_boxes(masks):
+ """Compute the bounding boxes around the provided masks
+
+ The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
+
+ Returns a [N, 4] tensors, with the boxes in xyxy format
+ """
+ if masks.numel() == 0:
+ return torch.zeros((0, 4), device=masks.device)
+
+ h, w = masks.shape[-2:]
+
+ y = torch.arange(0, h, dtype=torch.float)
+ x = torch.arange(0, w, dtype=torch.float)
+ y, x = torch.meshgrid(y, x)
+
+ x_mask = masks * x.unsqueeze(0)
+ x_max = x_mask.flatten(1).max(-1)[0]
+ x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
+
+ y_mask = masks * y.unsqueeze(0)
+ y_max = y_mask.flatten(1).max(-1)[0]
+ y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
+
+ return torch.stack([x_min, y_min, x_max, y_max], 1)
+
+
+if __name__ == "__main__":
+ x = torch.rand(5, 4)
+ y = torch.rand(3, 4)
+ iou, union = box_iou(x, y)
+ import ipdb
+
+ ipdb.set_trace()
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/get_tokenlizer.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/get_tokenlizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd2d972b4278e04a1ebef7d5e77aecd4eaf4205b
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/get_tokenlizer.py
@@ -0,0 +1,29 @@
+from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
+import os
+
+def get_tokenlizer(text_encoder_type):
+ if not isinstance(text_encoder_type, str):
+ # print("text_encoder_type is not a str")
+ if hasattr(text_encoder_type, "text_encoder_type"):
+ text_encoder_type = text_encoder_type.text_encoder_type
+ elif text_encoder_type.get("text_encoder_type", False):
+ text_encoder_type = text_encoder_type.get("text_encoder_type")
+ elif os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type):
+ pass
+ else:
+ raise ValueError(
+ "Unknown type of text_encoder_type: {}".format(type(text_encoder_type))
+ )
+ print("final text_encoder_type: {}".format(text_encoder_type))
+
+ tokenizer = AutoTokenizer.from_pretrained(text_encoder_type)
+ return tokenizer
+
+
+def get_pretrained_language_model(text_encoder_type):
+ if text_encoder_type == "bert-base-uncased" or (os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type)):
+ return BertModel.from_pretrained(text_encoder_type)
+ if text_encoder_type == "roberta-base":
+ return RobertaModel.from_pretrained(text_encoder_type)
+
+ raise ValueError("Unknown text_encoder_type {}".format(text_encoder_type))
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/inference.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..84a962e9334fcdda8cd94279b476eb27e00eb004
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/inference.py
@@ -0,0 +1,273 @@
+from typing import Tuple, List
+
+import cv2
+import numpy as np
+import supervision as sv
+import torch
+from PIL import Image
+from torchvision.ops import box_convert
+import bisect
+
+import groundingdino.datasets.transforms as T
+from groundingdino.models import build_model
+from groundingdino.util.misc import clean_state_dict
+from groundingdino.util.slconfig import SLConfig
+from groundingdino.util.utils import get_phrases_from_posmap
+
+# ----------------------------------------------------------------------------------------------------------------------
+# OLD API
+# ----------------------------------------------------------------------------------------------------------------------
+
+
+def preprocess_caption(caption: str) -> str:
+ result = caption.lower().strip()
+ if result.endswith("."):
+ return result
+ return result + "."
+
+
+def load_model(model_config_path: str, model_checkpoint_path: str, device: str = "cuda"):
+ args = SLConfig.fromfile(model_config_path)
+ args.device = device
+ model = build_model(args)
+ checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
+ model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
+ model.eval()
+ return model
+
+
+def load_image(image_path: str) -> Tuple[np.array, torch.Tensor]:
+ transform = T.Compose(
+ [
+ T.RandomResize([800], max_size=1333),
+ T.ToTensor(),
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
+ ]
+ )
+ image_source = Image.open(image_path).convert("RGB")
+ image = np.asarray(image_source)
+ image_transformed, _ = transform(image_source, None)
+ return image, image_transformed
+
+
+def predict(
+ model,
+ image: torch.Tensor,
+ caption: str,
+ box_threshold: float,
+ text_threshold: float,
+ device: str = "cuda",
+ remove_combined: bool = False
+) -> Tuple[torch.Tensor, torch.Tensor, List[str]]:
+ caption = preprocess_caption(caption=caption)
+
+ model = model.to(device)
+ image = image.to(device)
+
+ with torch.no_grad():
+ outputs = model(image[None], captions=[caption])
+
+ prediction_logits = outputs["pred_logits"].cpu().sigmoid()[0] # prediction_logits.shape = (nq, 256)
+ prediction_boxes = outputs["pred_boxes"].cpu()[0] # prediction_boxes.shape = (nq, 4)
+
+ mask = prediction_logits.max(dim=1)[0] > box_threshold
+ logits = prediction_logits[mask] # logits.shape = (n, 256)
+ boxes = prediction_boxes[mask] # boxes.shape = (n, 4)
+
+ tokenizer = model.tokenizer
+ tokenized = tokenizer(caption)
+
+ if remove_combined:
+ sep_idx = [i for i in range(len(tokenized['input_ids'])) if tokenized['input_ids'][i] in [101, 102, 1012]]
+
+ phrases = []
+ for logit in logits:
+ max_idx = logit.argmax()
+ insert_idx = bisect.bisect_left(sep_idx, max_idx)
+ right_idx = sep_idx[insert_idx]
+ left_idx = sep_idx[insert_idx - 1]
+ phrases.append(get_phrases_from_posmap(logit > text_threshold, tokenized, tokenizer, left_idx, right_idx).replace('.', ''))
+ else:
+ phrases = [
+ get_phrases_from_posmap(logit > text_threshold, tokenized, tokenizer).replace('.', '')
+ for logit
+ in logits
+ ]
+
+ return boxes, logits.max(dim=1)[0], phrases
+
+
+def annotate(image_source: np.ndarray, boxes: torch.Tensor, logits: torch.Tensor, phrases: List[str]) -> np.ndarray:
+ """
+ This function annotates an image with bounding boxes and labels.
+
+ Parameters:
+ image_source (np.ndarray): The source image to be annotated.
+ boxes (torch.Tensor): A tensor containing bounding box coordinates.
+ logits (torch.Tensor): A tensor containing confidence scores for each bounding box.
+ phrases (List[str]): A list of labels for each bounding box.
+
+ Returns:
+ np.ndarray: The annotated image.
+ """
+ h, w, _ = image_source.shape
+ boxes = boxes * torch.Tensor([w, h, w, h])
+ xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy()
+ detections = sv.Detections(xyxy=xyxy)
+
+ labels = [
+ f"{phrase} {logit:.2f}"
+ for phrase, logit
+ in zip(phrases, logits)
+ ]
+
+ bbox_annotator = sv.BoxAnnotator(color_lookup=sv.ColorLookup.INDEX)
+ label_annotator = sv.LabelAnnotator(color_lookup=sv.ColorLookup.INDEX)
+ annotated_frame = cv2.cvtColor(image_source, cv2.COLOR_RGB2BGR)
+ annotated_frame = bbox_annotator.annotate(scene=annotated_frame, detections=detections)
+ annotated_frame = label_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels)
+ return annotated_frame
+
+
+# ----------------------------------------------------------------------------------------------------------------------
+# NEW API
+# ----------------------------------------------------------------------------------------------------------------------
+
+
+class Model:
+
+ def __init__(
+ self,
+ model_config_path: str,
+ model_checkpoint_path: str,
+ device: str = "cuda"
+ ):
+ self.model = load_model(
+ model_config_path=model_config_path,
+ model_checkpoint_path=model_checkpoint_path,
+ device=device
+ ).to(device)
+ self.device = device
+
+ def predict_with_caption(
+ self,
+ image: np.ndarray,
+ caption: str,
+ box_threshold: float = 0.35,
+ text_threshold: float = 0.25
+ ) -> Tuple[sv.Detections, List[str]]:
+ """
+ import cv2
+
+ image = cv2.imread(IMAGE_PATH)
+
+ model = Model(model_config_path=CONFIG_PATH, model_checkpoint_path=WEIGHTS_PATH)
+ detections, labels = model.predict_with_caption(
+ image=image,
+ caption=caption,
+ box_threshold=BOX_THRESHOLD,
+ text_threshold=TEXT_THRESHOLD
+ )
+
+ import supervision as sv
+
+ box_annotator = sv.BoxAnnotator()
+ annotated_image = box_annotator.annotate(scene=image, detections=detections, labels=labels)
+ """
+ processed_image = Model.preprocess_image(image_bgr=image).to(self.device)
+ boxes, logits, phrases = predict(
+ model=self.model,
+ image=processed_image,
+ caption=caption,
+ box_threshold=box_threshold,
+ text_threshold=text_threshold,
+ device=self.device)
+ source_h, source_w, _ = image.shape
+ detections = Model.post_process_result(
+ source_h=source_h,
+ source_w=source_w,
+ boxes=boxes,
+ logits=logits)
+ return detections, phrases
+
+ def predict_with_classes(
+ self,
+ image: np.ndarray,
+ classes: List[str],
+ box_threshold: float,
+ text_threshold: float
+ ) -> sv.Detections:
+ """
+ import cv2
+
+ image = cv2.imread(IMAGE_PATH)
+
+ model = Model(model_config_path=CONFIG_PATH, model_checkpoint_path=WEIGHTS_PATH)
+ detections = model.predict_with_classes(
+ image=image,
+ classes=CLASSES,
+ box_threshold=BOX_THRESHOLD,
+ text_threshold=TEXT_THRESHOLD
+ )
+
+
+ import supervision as sv
+
+ box_annotator = sv.BoxAnnotator()
+ annotated_image = box_annotator.annotate(scene=image, detections=detections)
+ """
+ caption = ". ".join(classes)
+ processed_image = Model.preprocess_image(image_bgr=image).to(self.device)
+ boxes, logits, phrases = predict(
+ model=self.model,
+ image=processed_image,
+ caption=caption,
+ box_threshold=box_threshold,
+ text_threshold=text_threshold,
+ device=self.device)
+ source_h, source_w, _ = image.shape
+ detections = Model.post_process_result(
+ source_h=source_h,
+ source_w=source_w,
+ boxes=boxes,
+ logits=logits)
+ class_id = Model.phrases2classes(phrases=phrases, classes=classes)
+ detections.class_id = class_id
+ return detections
+
+ @staticmethod
+ def preprocess_image(image_bgr: np.ndarray) -> torch.Tensor:
+ transform = T.Compose(
+ [
+ T.RandomResize([800], max_size=1333),
+ T.ToTensor(),
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
+ ]
+ )
+ image_pillow = Image.fromarray(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB))
+ image_transformed, _ = transform(image_pillow, None)
+ return image_transformed
+
+ @staticmethod
+ def post_process_result(
+ source_h: int,
+ source_w: int,
+ boxes: torch.Tensor,
+ logits: torch.Tensor
+ ) -> sv.Detections:
+ boxes = boxes * torch.Tensor([source_w, source_h, source_w, source_h])
+ xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy()
+ confidence = logits.numpy()
+ return sv.Detections(xyxy=xyxy, confidence=confidence)
+
+ @staticmethod
+ def phrases2classes(phrases: List[str], classes: List[str]) -> np.ndarray:
+ class_ids = []
+ for phrase in phrases:
+ for class_ in classes:
+ if class_ in phrase:
+ class_ids.append(classes.index(class_))
+ break
+ else:
+ class_ids.append(None)
+ return np.array(class_ids)
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/logger.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..18145f54c927abd59b95f3fa6e6da8002bc2ce97
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/logger.py
@@ -0,0 +1,93 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+import functools
+import logging
+import os
+import sys
+
+from termcolor import colored
+
+
+class _ColorfulFormatter(logging.Formatter):
+ def __init__(self, *args, **kwargs):
+ self._root_name = kwargs.pop("root_name") + "."
+ self._abbrev_name = kwargs.pop("abbrev_name", "")
+ if len(self._abbrev_name):
+ self._abbrev_name = self._abbrev_name + "."
+ super(_ColorfulFormatter, self).__init__(*args, **kwargs)
+
+ def formatMessage(self, record):
+ record.name = record.name.replace(self._root_name, self._abbrev_name)
+ log = super(_ColorfulFormatter, self).formatMessage(record)
+ if record.levelno == logging.WARNING:
+ prefix = colored("WARNING", "red", attrs=["blink"])
+ elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
+ prefix = colored("ERROR", "red", attrs=["blink", "underline"])
+ else:
+ return log
+ return prefix + " " + log
+
+
+# so that calling setup_logger multiple times won't add many handlers
+@functools.lru_cache()
+def setup_logger(output=None, distributed_rank=0, *, color=True, name="imagenet", abbrev_name=None):
+ """
+ Initialize the detectron2 logger and set its verbosity level to "INFO".
+
+ Args:
+ output (str): a file name or a directory to save log. If None, will not save log file.
+ If ends with ".txt" or ".log", assumed to be a file name.
+ Otherwise, logs will be saved to `output/log.txt`.
+ name (str): the root module name of this logger
+
+ Returns:
+ logging.Logger: a logger
+ """
+ logger = logging.getLogger(name)
+ logger.setLevel(logging.DEBUG)
+ logger.propagate = False
+
+ if abbrev_name is None:
+ abbrev_name = name
+
+ plain_formatter = logging.Formatter(
+ "[%(asctime)s.%(msecs)03d]: %(message)s", datefmt="%m/%d %H:%M:%S"
+ )
+ # stdout logging: master only
+ if distributed_rank == 0:
+ ch = logging.StreamHandler(stream=sys.stdout)
+ ch.setLevel(logging.DEBUG)
+ if color:
+ formatter = _ColorfulFormatter(
+ colored("[%(asctime)s.%(msecs)03d]: ", "green") + "%(message)s",
+ datefmt="%m/%d %H:%M:%S",
+ root_name=name,
+ abbrev_name=str(abbrev_name),
+ )
+ else:
+ formatter = plain_formatter
+ ch.setFormatter(formatter)
+ logger.addHandler(ch)
+
+ # file logging: all workers
+ if output is not None:
+ if output.endswith(".txt") or output.endswith(".log"):
+ filename = output
+ else:
+ filename = os.path.join(output, "log.txt")
+ if distributed_rank > 0:
+ filename = filename + f".rank{distributed_rank}"
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
+
+ fh = logging.StreamHandler(_cached_log_stream(filename))
+ fh.setLevel(logging.DEBUG)
+ fh.setFormatter(plain_formatter)
+ logger.addHandler(fh)
+
+ return logger
+
+
+# cache the opened file object, so that different calls to `setup_logger`
+# with the same file name can safely write to the same file.
+@functools.lru_cache(maxsize=None)
+def _cached_log_stream(filename):
+ return open(filename, "a")
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/misc.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..d64b84ef24bea0c98e76824feb1903f6bfebe7a5
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/misc.py
@@ -0,0 +1,717 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+Misc functions, including distributed helpers.
+
+Mostly copy-paste from torchvision references.
+"""
+import colorsys
+import datetime
+import functools
+import io
+import json
+import os
+import pickle
+import subprocess
+import time
+from collections import OrderedDict, defaultdict, deque
+from typing import List, Optional
+
+import numpy as np
+import torch
+import torch.distributed as dist
+
+# needed due to empty tensor bug in pytorch and torchvision 0.5
+import torchvision
+from torch import Tensor
+
+__torchvision_need_compat_flag = float(torchvision.__version__.split(".")[1]) < 7
+if __torchvision_need_compat_flag:
+ from torchvision.ops import _new_empty_tensor
+ from torchvision.ops.misc import _output_size
+
+
+class SmoothedValue(object):
+ """Track a series of values and provide access to smoothed values over a
+ window or the global series average.
+ """
+
+ def __init__(self, window_size=20, fmt=None):
+ if fmt is None:
+ fmt = "{median:.4f} ({global_avg:.4f})"
+ self.deque = deque(maxlen=window_size)
+ self.total = 0.0
+ self.count = 0
+ self.fmt = fmt
+
+ def update(self, value, n=1):
+ self.deque.append(value)
+ self.count += n
+ self.total += value * n
+
+ def synchronize_between_processes(self):
+ """
+ Warning: does not synchronize the deque!
+ """
+ if not is_dist_avail_and_initialized():
+ return
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
+ dist.barrier()
+ dist.all_reduce(t)
+ t = t.tolist()
+ self.count = int(t[0])
+ self.total = t[1]
+
+ @property
+ def median(self):
+ d = torch.tensor(list(self.deque))
+ if d.shape[0] == 0:
+ return 0
+ return d.median().item()
+
+ @property
+ def avg(self):
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
+ return d.mean().item()
+
+ @property
+ def global_avg(self):
+ if os.environ.get("SHILONG_AMP", None) == "1":
+ eps = 1e-4
+ else:
+ eps = 1e-6
+ return self.total / (self.count + eps)
+
+ @property
+ def max(self):
+ return max(self.deque)
+
+ @property
+ def value(self):
+ return self.deque[-1]
+
+ def __str__(self):
+ return self.fmt.format(
+ median=self.median,
+ avg=self.avg,
+ global_avg=self.global_avg,
+ max=self.max,
+ value=self.value,
+ )
+
+
+@functools.lru_cache()
+def _get_global_gloo_group():
+ """
+ Return a process group based on gloo backend, containing all the ranks
+ The result is cached.
+ """
+
+ if dist.get_backend() == "nccl":
+ return dist.new_group(backend="gloo")
+
+ return dist.group.WORLD
+
+
+def all_gather_cpu(data):
+ """
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
+ Args:
+ data: any picklable object
+ Returns:
+ list[data]: list of data gathered from each rank
+ """
+
+ world_size = get_world_size()
+ if world_size == 1:
+ return [data]
+
+ cpu_group = _get_global_gloo_group()
+
+ buffer = io.BytesIO()
+ torch.save(data, buffer)
+ data_view = buffer.getbuffer()
+ device = "cuda" if cpu_group is None else "cpu"
+ tensor = torch.ByteTensor(data_view).to(device)
+
+ # obtain Tensor size of each rank
+ local_size = torch.tensor([tensor.numel()], device=device, dtype=torch.long)
+ size_list = [torch.tensor([0], device=device, dtype=torch.long) for _ in range(world_size)]
+ if cpu_group is None:
+ dist.all_gather(size_list, local_size)
+ else:
+ print("gathering on cpu")
+ dist.all_gather(size_list, local_size, group=cpu_group)
+ size_list = [int(size.item()) for size in size_list]
+ max_size = max(size_list)
+ assert isinstance(local_size.item(), int)
+ local_size = int(local_size.item())
+
+ # receiving Tensor from all ranks
+ # we pad the tensor because torch all_gather does not support
+ # gathering tensors of different shapes
+ tensor_list = []
+ for _ in size_list:
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=device))
+ if local_size != max_size:
+ padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device=device)
+ tensor = torch.cat((tensor, padding), dim=0)
+ if cpu_group is None:
+ dist.all_gather(tensor_list, tensor)
+ else:
+ dist.all_gather(tensor_list, tensor, group=cpu_group)
+
+ data_list = []
+ for size, tensor in zip(size_list, tensor_list):
+ tensor = torch.split(tensor, [size, max_size - size], dim=0)[0]
+ buffer = io.BytesIO(tensor.cpu().numpy())
+ obj = torch.load(buffer)
+ data_list.append(obj)
+
+ return data_list
+
+
+def all_gather(data):
+ """
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
+ Args:
+ data: any picklable object
+ Returns:
+ list[data]: list of data gathered from each rank
+ """
+
+ if os.getenv("CPU_REDUCE") == "1":
+ return all_gather_cpu(data)
+
+ world_size = get_world_size()
+ if world_size == 1:
+ return [data]
+
+ # serialized to a Tensor
+ buffer = pickle.dumps(data)
+ storage = torch.ByteStorage.from_buffer(buffer)
+ tensor = torch.ByteTensor(storage).to("cuda")
+
+ # obtain Tensor size of each rank
+ local_size = torch.tensor([tensor.numel()], device="cuda")
+ size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)]
+ dist.all_gather(size_list, local_size)
+ size_list = [int(size.item()) for size in size_list]
+ max_size = max(size_list)
+
+ # receiving Tensor from all ranks
+ # we pad the tensor because torch all_gather does not support
+ # gathering tensors of different shapes
+ tensor_list = []
+ for _ in size_list:
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda"))
+ if local_size != max_size:
+ padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda")
+ tensor = torch.cat((tensor, padding), dim=0)
+ dist.all_gather(tensor_list, tensor)
+
+ data_list = []
+ for size, tensor in zip(size_list, tensor_list):
+ buffer = tensor.cpu().numpy().tobytes()[:size]
+ data_list.append(pickle.loads(buffer))
+
+ return data_list
+
+
+def reduce_dict(input_dict, average=True):
+ """
+ Args:
+ input_dict (dict): all the values will be reduced
+ average (bool): whether to do average or sum
+ Reduce the values in the dictionary from all processes so that all processes
+ have the averaged results. Returns a dict with the same fields as
+ input_dict, after reduction.
+ """
+ world_size = get_world_size()
+ if world_size < 2:
+ return input_dict
+ with torch.no_grad():
+ names = []
+ values = []
+ # sort the keys so that they are consistent across processes
+ for k in sorted(input_dict.keys()):
+ names.append(k)
+ values.append(input_dict[k])
+ values = torch.stack(values, dim=0)
+ dist.all_reduce(values)
+ if average:
+ values /= world_size
+ reduced_dict = {k: v for k, v in zip(names, values)}
+ return reduced_dict
+
+
+class MetricLogger(object):
+ def __init__(self, delimiter="\t"):
+ self.meters = defaultdict(SmoothedValue)
+ self.delimiter = delimiter
+
+ def update(self, **kwargs):
+ for k, v in kwargs.items():
+ if isinstance(v, torch.Tensor):
+ v = v.item()
+ assert isinstance(v, (float, int))
+ self.meters[k].update(v)
+
+ def __getattr__(self, attr):
+ if attr in self.meters:
+ return self.meters[attr]
+ if attr in self.__dict__:
+ return self.__dict__[attr]
+ raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr))
+
+ def __str__(self):
+ loss_str = []
+ for name, meter in self.meters.items():
+ # print(name, str(meter))
+ # import ipdb;ipdb.set_trace()
+ if meter.count > 0:
+ loss_str.append("{}: {}".format(name, str(meter)))
+ return self.delimiter.join(loss_str)
+
+ def synchronize_between_processes(self):
+ for meter in self.meters.values():
+ meter.synchronize_between_processes()
+
+ def add_meter(self, name, meter):
+ self.meters[name] = meter
+
+ def log_every(self, iterable, print_freq, header=None, logger=None):
+ if logger is None:
+ print_func = print
+ else:
+ print_func = logger.info
+
+ i = 0
+ if not header:
+ header = ""
+ start_time = time.time()
+ end = time.time()
+ iter_time = SmoothedValue(fmt="{avg:.4f}")
+ data_time = SmoothedValue(fmt="{avg:.4f}")
+ space_fmt = ":" + str(len(str(len(iterable)))) + "d"
+ if torch.cuda.is_available():
+ log_msg = self.delimiter.join(
+ [
+ header,
+ "[{0" + space_fmt + "}/{1}]",
+ "eta: {eta}",
+ "{meters}",
+ "time: {time}",
+ "data: {data}",
+ "max mem: {memory:.0f}",
+ ]
+ )
+ else:
+ log_msg = self.delimiter.join(
+ [
+ header,
+ "[{0" + space_fmt + "}/{1}]",
+ "eta: {eta}",
+ "{meters}",
+ "time: {time}",
+ "data: {data}",
+ ]
+ )
+ MB = 1024.0 * 1024.0
+ for obj in iterable:
+ data_time.update(time.time() - end)
+ yield obj
+ # import ipdb; ipdb.set_trace()
+ iter_time.update(time.time() - end)
+ if i % print_freq == 0 or i == len(iterable) - 1:
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
+ if torch.cuda.is_available():
+ print_func(
+ log_msg.format(
+ i,
+ len(iterable),
+ eta=eta_string,
+ meters=str(self),
+ time=str(iter_time),
+ data=str(data_time),
+ memory=torch.cuda.max_memory_allocated() / MB,
+ )
+ )
+ else:
+ print_func(
+ log_msg.format(
+ i,
+ len(iterable),
+ eta=eta_string,
+ meters=str(self),
+ time=str(iter_time),
+ data=str(data_time),
+ )
+ )
+ i += 1
+ end = time.time()
+ total_time = time.time() - start_time
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
+ print_func(
+ "{} Total time: {} ({:.4f} s / it)".format(
+ header, total_time_str, total_time / len(iterable)
+ )
+ )
+
+
+def get_sha():
+ cwd = os.path.dirname(os.path.abspath(__file__))
+
+ def _run(command):
+ return subprocess.check_output(command, cwd=cwd).decode("ascii").strip()
+
+ sha = "N/A"
+ diff = "clean"
+ branch = "N/A"
+ try:
+ sha = _run(["git", "rev-parse", "HEAD"])
+ subprocess.check_output(["git", "diff"], cwd=cwd)
+ diff = _run(["git", "diff-index", "HEAD"])
+ diff = "has uncommited changes" if diff else "clean"
+ branch = _run(["git", "rev-parse", "--abbrev-ref", "HEAD"])
+ except Exception:
+ pass
+ message = f"sha: {sha}, status: {diff}, branch: {branch}"
+ return message
+
+
+def collate_fn(batch):
+ # import ipdb; ipdb.set_trace()
+ batch = list(zip(*batch))
+ batch[0] = nested_tensor_from_tensor_list(batch[0])
+ return tuple(batch)
+
+
+def _max_by_axis(the_list):
+ # type: (List[List[int]]) -> List[int]
+ maxes = the_list[0]
+ for sublist in the_list[1:]:
+ for index, item in enumerate(sublist):
+ maxes[index] = max(maxes[index], item)
+ return maxes
+
+
+class NestedTensor(object):
+ def __init__(self, tensors, mask: Optional[Tensor]):
+ self.tensors = tensors
+ self.mask = mask
+ if mask == "auto":
+ self.mask = torch.zeros_like(tensors).to(tensors.device)
+ if self.mask.dim() == 3:
+ self.mask = self.mask.sum(0).to(bool)
+ elif self.mask.dim() == 4:
+ self.mask = self.mask.sum(1).to(bool)
+ else:
+ raise ValueError(
+ "tensors dim must be 3 or 4 but {}({})".format(
+ self.tensors.dim(), self.tensors.shape
+ )
+ )
+
+ def imgsize(self):
+ res = []
+ for i in range(self.tensors.shape[0]):
+ mask = self.mask[i]
+ maxH = (~mask).sum(0).max()
+ maxW = (~mask).sum(1).max()
+ res.append(torch.Tensor([maxH, maxW]))
+ return res
+
+ def to(self, device):
+ # type: (Device) -> NestedTensor # noqa
+ cast_tensor = self.tensors.to(device)
+ mask = self.mask
+ if mask is not None:
+ assert mask is not None
+ cast_mask = mask.to(device)
+ else:
+ cast_mask = None
+ return NestedTensor(cast_tensor, cast_mask)
+
+ def to_img_list_single(self, tensor, mask):
+ assert tensor.dim() == 3, "dim of tensor should be 3 but {}".format(tensor.dim())
+ maxH = (~mask).sum(0).max()
+ maxW = (~mask).sum(1).max()
+ img = tensor[:, :maxH, :maxW]
+ return img
+
+ def to_img_list(self):
+ """remove the padding and convert to img list
+
+ Returns:
+ [type]: [description]
+ """
+ if self.tensors.dim() == 3:
+ return self.to_img_list_single(self.tensors, self.mask)
+ else:
+ res = []
+ for i in range(self.tensors.shape[0]):
+ tensor_i = self.tensors[i]
+ mask_i = self.mask[i]
+ res.append(self.to_img_list_single(tensor_i, mask_i))
+ return res
+
+ @property
+ def device(self):
+ return self.tensors.device
+
+ def decompose(self):
+ return self.tensors, self.mask
+
+ def __repr__(self):
+ return str(self.tensors)
+
+ @property
+ def shape(self):
+ return {"tensors.shape": self.tensors.shape, "mask.shape": self.mask.shape}
+
+
+def nested_tensor_from_tensor_list(tensor_list: List[Tensor]):
+ # TODO make this more general
+ if tensor_list[0].ndim == 3:
+ if torchvision._is_tracing():
+ # nested_tensor_from_tensor_list() does not export well to ONNX
+ # call _onnx_nested_tensor_from_tensor_list() instead
+ return _onnx_nested_tensor_from_tensor_list(tensor_list)
+
+ # TODO make it support different-sized images
+ max_size = _max_by_axis([list(img.shape) for img in tensor_list])
+ # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list]))
+ batch_shape = [len(tensor_list)] + max_size
+ b, c, h, w = batch_shape
+ dtype = tensor_list[0].dtype
+ device = tensor_list[0].device
+ tensor = torch.zeros(batch_shape, dtype=dtype, device=device)
+ mask = torch.ones((b, h, w), dtype=torch.bool, device=device)
+ for img, pad_img, m in zip(tensor_list, tensor, mask):
+ pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
+ m[: img.shape[1], : img.shape[2]] = False
+ else:
+ raise ValueError("not supported")
+ return NestedTensor(tensor, mask)
+
+
+# _onnx_nested_tensor_from_tensor_list() is an implementation of
+# nested_tensor_from_tensor_list() that is supported by ONNX tracing.
+@torch.jit.unused
+def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor:
+ max_size = []
+ for i in range(tensor_list[0].dim()):
+ max_size_i = torch.max(
+ torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)
+ ).to(torch.int64)
+ max_size.append(max_size_i)
+ max_size = tuple(max_size)
+
+ # work around for
+ # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
+ # m[: img.shape[1], :img.shape[2]] = False
+ # which is not yet supported in onnx
+ padded_imgs = []
+ padded_masks = []
+ for img in tensor_list:
+ padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))]
+ padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0]))
+ padded_imgs.append(padded_img)
+
+ m = torch.zeros_like(img[0], dtype=torch.int, device=img.device)
+ padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1)
+ padded_masks.append(padded_mask.to(torch.bool))
+
+ tensor = torch.stack(padded_imgs)
+ mask = torch.stack(padded_masks)
+
+ return NestedTensor(tensor, mask=mask)
+
+
+def setup_for_distributed(is_master):
+ """
+ This function disables printing when not in master process
+ """
+ import builtins as __builtin__
+
+ builtin_print = __builtin__.print
+
+ def print(*args, **kwargs):
+ force = kwargs.pop("force", False)
+ if is_master or force:
+ builtin_print(*args, **kwargs)
+
+ __builtin__.print = print
+
+
+def is_dist_avail_and_initialized():
+ if not dist.is_available():
+ return False
+ if not dist.is_initialized():
+ return False
+ return True
+
+
+def get_world_size():
+ if not is_dist_avail_and_initialized():
+ return 1
+ return dist.get_world_size()
+
+
+def get_rank():
+ if not is_dist_avail_and_initialized():
+ return 0
+ return dist.get_rank()
+
+
+def is_main_process():
+ return get_rank() == 0
+
+
+def save_on_master(*args, **kwargs):
+ if is_main_process():
+ torch.save(*args, **kwargs)
+
+
+def init_distributed_mode(args):
+ if "WORLD_SIZE" in os.environ and os.environ["WORLD_SIZE"] != "": # 'RANK' in os.environ and
+ args.rank = int(os.environ["RANK"])
+ args.world_size = int(os.environ["WORLD_SIZE"])
+ args.gpu = args.local_rank = int(os.environ["LOCAL_RANK"])
+
+ # launch by torch.distributed.launch
+ # Single node
+ # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ...
+ # Multi nodes
+ # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ...
+ # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ...
+ # args.rank = int(os.environ.get('OMPI_COMM_WORLD_RANK'))
+ # local_world_size = int(os.environ['GPU_PER_NODE_COUNT'])
+ # args.world_size = args.world_size * local_world_size
+ # args.gpu = args.local_rank = int(os.environ['LOCAL_RANK'])
+ # args.rank = args.rank * local_world_size + args.local_rank
+ print(
+ "world size: {}, rank: {}, local rank: {}".format(
+ args.world_size, args.rank, args.local_rank
+ )
+ )
+ print(json.dumps(dict(os.environ), indent=2))
+ elif "SLURM_PROCID" in os.environ:
+ args.rank = int(os.environ["SLURM_PROCID"])
+ args.gpu = args.local_rank = int(os.environ["SLURM_LOCALID"])
+ args.world_size = int(os.environ["SLURM_NPROCS"])
+
+ print(
+ "world size: {}, world rank: {}, local rank: {}, device_count: {}".format(
+ args.world_size, args.rank, args.local_rank, torch.cuda.device_count()
+ )
+ )
+ else:
+ print("Not using distributed mode")
+ args.distributed = False
+ args.world_size = 1
+ args.rank = 0
+ args.local_rank = 0
+ return
+
+ print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank))
+ args.distributed = True
+ torch.cuda.set_device(args.local_rank)
+ args.dist_backend = "nccl"
+ print("| distributed init (rank {}): {}".format(args.rank, args.dist_url), flush=True)
+
+ torch.distributed.init_process_group(
+ backend=args.dist_backend,
+ world_size=args.world_size,
+ rank=args.rank,
+ init_method=args.dist_url,
+ )
+
+ print("Before torch.distributed.barrier()")
+ torch.distributed.barrier()
+ print("End torch.distributed.barrier()")
+ setup_for_distributed(args.rank == 0)
+
+
+@torch.no_grad()
+def accuracy(output, target, topk=(1,)):
+ """Computes the precision@k for the specified values of k"""
+ if target.numel() == 0:
+ return [torch.zeros([], device=output.device)]
+ maxk = max(topk)
+ batch_size = target.size(0)
+
+ _, pred = output.topk(maxk, 1, True, True)
+ pred = pred.t()
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
+
+ res = []
+ for k in topk:
+ correct_k = correct[:k].view(-1).float().sum(0)
+ res.append(correct_k.mul_(100.0 / batch_size))
+ return res
+
+
+@torch.no_grad()
+def accuracy_onehot(pred, gt):
+ """_summary_
+
+ Args:
+ pred (_type_): n, c
+ gt (_type_): n, c
+ """
+ tp = ((pred - gt).abs().sum(-1) < 1e-4).float().sum()
+ acc = tp / gt.shape[0] * 100
+ return acc
+
+
+def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
+ # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor
+ """
+ Equivalent to nn.functional.interpolate, but with support for empty batch sizes.
+ This will eventually be supported natively by PyTorch, and this
+ class can go away.
+ """
+ if __torchvision_need_compat_flag < 0.7:
+ if input.numel() > 0:
+ return torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners)
+
+ output_shape = _output_size(2, input, size, scale_factor)
+ output_shape = list(input.shape[:-2]) + list(output_shape)
+ return _new_empty_tensor(input, output_shape)
+ else:
+ return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners)
+
+
+class color_sys:
+ def __init__(self, num_colors) -> None:
+ self.num_colors = num_colors
+ colors = []
+ for i in np.arange(0.0, 360.0, 360.0 / num_colors):
+ hue = i / 360.0
+ lightness = (50 + np.random.rand() * 10) / 100.0
+ saturation = (90 + np.random.rand() * 10) / 100.0
+ colors.append(
+ tuple([int(j * 255) for j in colorsys.hls_to_rgb(hue, lightness, saturation)])
+ )
+ self.colors = colors
+
+ def __call__(self, idx):
+ return self.colors[idx]
+
+
+def inverse_sigmoid(x, eps=1e-3):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+def clean_state_dict(state_dict):
+ new_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k[:7] == "module.":
+ k = k[7:] # remove `module.`
+ new_state_dict[k] = v
+ return new_state_dict
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/slconfig.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/slconfig.py
new file mode 100644
index 0000000000000000000000000000000000000000..672e72ed0b68a54c13ade66c9f146d2d542e97c6
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/slconfig.py
@@ -0,0 +1,427 @@
+# ==========================================================
+# Modified from mmcv
+# ==========================================================
+import ast
+import os
+import os.path as osp
+import shutil
+import sys
+import tempfile
+from argparse import Action
+from importlib import import_module
+
+from addict import Dict
+from yapf.yapflib.yapf_api import FormatCode
+
+BASE_KEY = "_base_"
+DELETE_KEY = "_delete_"
+RESERVED_KEYS = ["filename", "text", "pretty_text", "get", "dump", "merge_from_dict"]
+
+
+def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
+ if not osp.isfile(filename):
+ raise FileNotFoundError(msg_tmpl.format(filename))
+
+
+class ConfigDict(Dict):
+ def __missing__(self, name):
+ raise KeyError(name)
+
+ def __getattr__(self, name):
+ try:
+ value = super(ConfigDict, self).__getattr__(name)
+ except KeyError:
+ ex = AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'")
+ except Exception as e:
+ ex = e
+ else:
+ return value
+ raise ex
+
+
+class SLConfig(object):
+ """
+ config files.
+ only support .py file as config now.
+
+ ref: mmcv.utils.config
+
+ Example:
+ >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ >>> cfg.a
+ 1
+ >>> cfg.b
+ {'b1': [0, 1]}
+ >>> cfg.b.b1
+ [0, 1]
+ >>> cfg = Config.fromfile('tests/data/config/a.py')
+ >>> cfg.filename
+ "/home/kchen/projects/mmcv/tests/data/config/a.py"
+ >>> cfg.item4
+ 'test'
+ >>> cfg
+ "Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: "
+ "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}"
+ """
+
+ @staticmethod
+ def _validate_py_syntax(filename):
+ with open(filename) as f:
+ content = f.read()
+ try:
+ ast.parse(content)
+ except SyntaxError:
+ raise SyntaxError("There are syntax errors in config " f"file {filename}")
+
+ @staticmethod
+ def _file2dict(filename):
+ filename = osp.abspath(osp.expanduser(filename))
+ check_file_exist(filename)
+ if filename.lower().endswith(".py"):
+ with tempfile.TemporaryDirectory() as temp_config_dir:
+ temp_config_file = tempfile.NamedTemporaryFile(dir=temp_config_dir, suffix=".py")
+ temp_config_name = osp.basename(temp_config_file.name)
+ if os.name == 'nt':
+ temp_config_file.close()
+ shutil.copyfile(filename, osp.join(temp_config_dir, temp_config_name))
+ temp_module_name = osp.splitext(temp_config_name)[0]
+ sys.path.insert(0, temp_config_dir)
+ SLConfig._validate_py_syntax(filename)
+ mod = import_module(temp_module_name)
+ sys.path.pop(0)
+ cfg_dict = {
+ name: value for name, value in mod.__dict__.items() if not name.startswith("__")
+ }
+ # delete imported module
+ del sys.modules[temp_module_name]
+ # close temp file
+ temp_config_file.close()
+ elif filename.lower().endswith((".yml", ".yaml", ".json")):
+ from .slio import slload
+
+ cfg_dict = slload(filename)
+ else:
+ raise IOError("Only py/yml/yaml/json type are supported now!")
+
+ cfg_text = filename + "\n"
+ with open(filename, "r") as f:
+ cfg_text += f.read()
+
+ # parse the base file
+ if BASE_KEY in cfg_dict:
+ cfg_dir = osp.dirname(filename)
+ base_filename = cfg_dict.pop(BASE_KEY)
+ base_filename = base_filename if isinstance(base_filename, list) else [base_filename]
+
+ cfg_dict_list = list()
+ cfg_text_list = list()
+ for f in base_filename:
+ _cfg_dict, _cfg_text = SLConfig._file2dict(osp.join(cfg_dir, f))
+ cfg_dict_list.append(_cfg_dict)
+ cfg_text_list.append(_cfg_text)
+
+ base_cfg_dict = dict()
+ for c in cfg_dict_list:
+ if len(base_cfg_dict.keys() & c.keys()) > 0:
+ raise KeyError("Duplicate key is not allowed among bases")
+ # TODO Allow the duplicate key while warnning user
+ base_cfg_dict.update(c)
+
+ base_cfg_dict = SLConfig._merge_a_into_b(cfg_dict, base_cfg_dict)
+ cfg_dict = base_cfg_dict
+
+ # merge cfg_text
+ cfg_text_list.append(cfg_text)
+ cfg_text = "\n".join(cfg_text_list)
+
+ return cfg_dict, cfg_text
+
+ @staticmethod
+ def _merge_a_into_b(a, b):
+ """merge dict `a` into dict `b` (non-inplace).
+ values in `a` will overwrite `b`.
+ copy first to avoid inplace modification
+
+ Args:
+ a ([type]): [description]
+ b ([type]): [description]
+
+ Returns:
+ [dict]: [description]
+ """
+ # import ipdb; ipdb.set_trace()
+ if not isinstance(a, dict):
+ return a
+
+ b = b.copy()
+ for k, v in a.items():
+ if isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False):
+
+ if not isinstance(b[k], dict) and not isinstance(b[k], list):
+ # if :
+ # import ipdb; ipdb.set_trace()
+ raise TypeError(
+ f"{k}={v} in child config cannot inherit from base "
+ f"because {k} is a dict in the child config but is of "
+ f"type {type(b[k])} in base config. You may set "
+ f"`{DELETE_KEY}=True` to ignore the base config"
+ )
+ b[k] = SLConfig._merge_a_into_b(v, b[k])
+ elif isinstance(b, list):
+ try:
+ _ = int(k)
+ except:
+ raise TypeError(
+ f"b is a list, " f"index {k} should be an int when input but {type(k)}"
+ )
+ b[int(k)] = SLConfig._merge_a_into_b(v, b[int(k)])
+ else:
+ b[k] = v
+
+ return b
+
+ @staticmethod
+ def fromfile(filename):
+ cfg_dict, cfg_text = SLConfig._file2dict(filename)
+ return SLConfig(cfg_dict, cfg_text=cfg_text, filename=filename)
+
+ def __init__(self, cfg_dict=None, cfg_text=None, filename=None):
+ if cfg_dict is None:
+ cfg_dict = dict()
+ elif not isinstance(cfg_dict, dict):
+ raise TypeError("cfg_dict must be a dict, but " f"got {type(cfg_dict)}")
+ for key in cfg_dict:
+ if key in RESERVED_KEYS:
+ raise KeyError(f"{key} is reserved for config file")
+
+ super(SLConfig, self).__setattr__("_cfg_dict", ConfigDict(cfg_dict))
+ super(SLConfig, self).__setattr__("_filename", filename)
+ if cfg_text:
+ text = cfg_text
+ elif filename:
+ with open(filename, "r") as f:
+ text = f.read()
+ else:
+ text = ""
+ super(SLConfig, self).__setattr__("_text", text)
+
+ @property
+ def filename(self):
+ return self._filename
+
+ @property
+ def text(self):
+ return self._text
+
+ @property
+ def pretty_text(self):
+
+ indent = 4
+
+ def _indent(s_, num_spaces):
+ s = s_.split("\n")
+ if len(s) == 1:
+ return s_
+ first = s.pop(0)
+ s = [(num_spaces * " ") + line for line in s]
+ s = "\n".join(s)
+ s = first + "\n" + s
+ return s
+
+ def _format_basic_types(k, v, use_mapping=False):
+ if isinstance(v, str):
+ v_str = f"'{v}'"
+ else:
+ v_str = str(v)
+
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f"{k_str}: {v_str}"
+ else:
+ attr_str = f"{str(k)}={v_str}"
+ attr_str = _indent(attr_str, indent)
+
+ return attr_str
+
+ def _format_list(k, v, use_mapping=False):
+ # check if all items in the list are dict
+ if all(isinstance(_, dict) for _ in v):
+ v_str = "[\n"
+ v_str += "\n".join(
+ f"dict({_indent(_format_dict(v_), indent)})," for v_ in v
+ ).rstrip(",")
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f"{k_str}: {v_str}"
+ else:
+ attr_str = f"{str(k)}={v_str}"
+ attr_str = _indent(attr_str, indent) + "]"
+ else:
+ attr_str = _format_basic_types(k, v, use_mapping)
+ return attr_str
+
+ def _contain_invalid_identifier(dict_str):
+ contain_invalid_identifier = False
+ for key_name in dict_str:
+ contain_invalid_identifier |= not str(key_name).isidentifier()
+ return contain_invalid_identifier
+
+ def _format_dict(input_dict, outest_level=False):
+ r = ""
+ s = []
+
+ use_mapping = _contain_invalid_identifier(input_dict)
+ if use_mapping:
+ r += "{"
+ for idx, (k, v) in enumerate(input_dict.items()):
+ is_last = idx >= len(input_dict) - 1
+ end = "" if outest_level or is_last else ","
+ if isinstance(v, dict):
+ v_str = "\n" + _format_dict(v)
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f"{k_str}: dict({v_str}"
+ else:
+ attr_str = f"{str(k)}=dict({v_str}"
+ attr_str = _indent(attr_str, indent) + ")" + end
+ elif isinstance(v, list):
+ attr_str = _format_list(k, v, use_mapping) + end
+ else:
+ attr_str = _format_basic_types(k, v, use_mapping) + end
+
+ s.append(attr_str)
+ r += "\n".join(s)
+ if use_mapping:
+ r += "}"
+ return r
+
+ cfg_dict = self._cfg_dict.to_dict()
+ text = _format_dict(cfg_dict, outest_level=True)
+ # copied from setup.cfg
+ yapf_style = dict(
+ based_on_style="pep8",
+ blank_line_before_nested_class_or_def=True,
+ split_before_expression_after_opening_paren=True,
+ )
+ text, _ = FormatCode(text, style_config=yapf_style, verify=True)
+
+ return text
+
+ def __repr__(self):
+ return f"Config (path: {self.filename}): {self._cfg_dict.__repr__()}"
+
+ def __len__(self):
+ return len(self._cfg_dict)
+
+ def __getattr__(self, name):
+ # # debug
+ # print('+'*15)
+ # print('name=%s' % name)
+ # print("addr:", id(self))
+ # # print('type(self):', type(self))
+ # print(self.__dict__)
+ # print('+'*15)
+ # if self.__dict__ == {}:
+ # raise ValueError
+
+ return getattr(self._cfg_dict, name)
+
+ def __getitem__(self, name):
+ return self._cfg_dict.__getitem__(name)
+
+ def __setattr__(self, name, value):
+ if isinstance(value, dict):
+ value = ConfigDict(value)
+ self._cfg_dict.__setattr__(name, value)
+
+ def __setitem__(self, name, value):
+ if isinstance(value, dict):
+ value = ConfigDict(value)
+ self._cfg_dict.__setitem__(name, value)
+
+ def __iter__(self):
+ return iter(self._cfg_dict)
+
+ def dump(self, file=None):
+ # import ipdb; ipdb.set_trace()
+ if file is None:
+ return self.pretty_text
+ else:
+ with open(file, "w") as f:
+ f.write(self.pretty_text)
+
+ def merge_from_dict(self, options):
+ """Merge list into cfg_dict
+
+ Merge the dict parsed by MultipleKVAction into this cfg.
+
+ Examples:
+ >>> options = {'model.backbone.depth': 50,
+ ... 'model.backbone.with_cp':True}
+ >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet'))))
+ >>> cfg.merge_from_dict(options)
+ >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
+ >>> assert cfg_dict == dict(
+ ... model=dict(backbone=dict(depth=50, with_cp=True)))
+
+ Args:
+ options (dict): dict of configs to merge from.
+ """
+ option_cfg_dict = {}
+ for full_key, v in options.items():
+ d = option_cfg_dict
+ key_list = full_key.split(".")
+ for subkey in key_list[:-1]:
+ d.setdefault(subkey, ConfigDict())
+ d = d[subkey]
+ subkey = key_list[-1]
+ d[subkey] = v
+
+ cfg_dict = super(SLConfig, self).__getattribute__("_cfg_dict")
+ super(SLConfig, self).__setattr__(
+ "_cfg_dict", SLConfig._merge_a_into_b(option_cfg_dict, cfg_dict)
+ )
+
+ # for multiprocess
+ def __setstate__(self, state):
+ self.__init__(state)
+
+ def copy(self):
+ return SLConfig(self._cfg_dict.copy())
+
+ def deepcopy(self):
+ return SLConfig(self._cfg_dict.deepcopy())
+
+
+class DictAction(Action):
+ """
+ argparse action to split an argument into KEY=VALUE form
+ on the first = and append to a dictionary. List options should
+ be passed as comma separated values, i.e KEY=V1,V2,V3
+ """
+
+ @staticmethod
+ def _parse_int_float_bool(val):
+ try:
+ return int(val)
+ except ValueError:
+ pass
+ try:
+ return float(val)
+ except ValueError:
+ pass
+ if val.lower() in ["true", "false"]:
+ return True if val.lower() == "true" else False
+ if val.lower() in ["none", "null"]:
+ return None
+ return val
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ options = {}
+ for kv in values:
+ key, val = kv.split("=", maxsplit=1)
+ val = [self._parse_int_float_bool(v) for v in val.split(",")]
+ if len(val) == 1:
+ val = val[0]
+ options[key] = val
+ setattr(namespace, self.dest, options)
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/slio.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/slio.py
new file mode 100644
index 0000000000000000000000000000000000000000..72c1f0f7b82cdc931d381feef64fe15815ba657e
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/slio.py
@@ -0,0 +1,177 @@
+# ==========================================================
+# Modified from mmcv
+# ==========================================================
+
+import json
+import pickle
+from abc import ABCMeta, abstractmethod
+from pathlib import Path
+
+import yaml
+
+try:
+ from yaml import CLoader as Loader, CDumper as Dumper
+except ImportError:
+ from yaml import Loader, Dumper
+
+
+# ===========================
+# Rigister handler
+# ===========================
+
+
+class BaseFileHandler(metaclass=ABCMeta):
+ @abstractmethod
+ def load_from_fileobj(self, file, **kwargs):
+ pass
+
+ @abstractmethod
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ pass
+
+ @abstractmethod
+ def dump_to_str(self, obj, **kwargs):
+ pass
+
+ def load_from_path(self, filepath, mode="r", **kwargs):
+ with open(filepath, mode) as f:
+ return self.load_from_fileobj(f, **kwargs)
+
+ def dump_to_path(self, obj, filepath, mode="w", **kwargs):
+ with open(filepath, mode) as f:
+ self.dump_to_fileobj(obj, f, **kwargs)
+
+
+class JsonHandler(BaseFileHandler):
+ def load_from_fileobj(self, file):
+ return json.load(file)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ json.dump(obj, file, **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ return json.dumps(obj, **kwargs)
+
+
+class PickleHandler(BaseFileHandler):
+ def load_from_fileobj(self, file, **kwargs):
+ return pickle.load(file, **kwargs)
+
+ def load_from_path(self, filepath, **kwargs):
+ return super(PickleHandler, self).load_from_path(filepath, mode="rb", **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault("protocol", 2)
+ return pickle.dumps(obj, **kwargs)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault("protocol", 2)
+ pickle.dump(obj, file, **kwargs)
+
+ def dump_to_path(self, obj, filepath, **kwargs):
+ super(PickleHandler, self).dump_to_path(obj, filepath, mode="wb", **kwargs)
+
+
+class YamlHandler(BaseFileHandler):
+ def load_from_fileobj(self, file, **kwargs):
+ kwargs.setdefault("Loader", Loader)
+ return yaml.load(file, **kwargs)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault("Dumper", Dumper)
+ yaml.dump(obj, file, **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault("Dumper", Dumper)
+ return yaml.dump(obj, **kwargs)
+
+
+file_handlers = {
+ "json": JsonHandler(),
+ "yaml": YamlHandler(),
+ "yml": YamlHandler(),
+ "pickle": PickleHandler(),
+ "pkl": PickleHandler(),
+}
+
+# ===========================
+# load and dump
+# ===========================
+
+
+def is_str(x):
+ """Whether the input is an string instance.
+
+ Note: This method is deprecated since python 2 is no longer supported.
+ """
+ return isinstance(x, str)
+
+
+def slload(file, file_format=None, **kwargs):
+ """Load data from json/yaml/pickle files.
+
+ This method provides a unified api for loading data from serialized files.
+
+ Args:
+ file (str or :obj:`Path` or file-like object): Filename or a file-like
+ object.
+ file_format (str, optional): If not specified, the file format will be
+ inferred from the file extension, otherwise use the specified one.
+ Currently supported formats include "json", "yaml/yml" and
+ "pickle/pkl".
+
+ Returns:
+ The content from the file.
+ """
+ if isinstance(file, Path):
+ file = str(file)
+ if file_format is None and is_str(file):
+ file_format = file.split(".")[-1]
+ if file_format not in file_handlers:
+ raise TypeError(f"Unsupported format: {file_format}")
+
+ handler = file_handlers[file_format]
+ if is_str(file):
+ obj = handler.load_from_path(file, **kwargs)
+ elif hasattr(file, "read"):
+ obj = handler.load_from_fileobj(file, **kwargs)
+ else:
+ raise TypeError('"file" must be a filepath str or a file-object')
+ return obj
+
+
+def sldump(obj, file=None, file_format=None, **kwargs):
+ """Dump data to json/yaml/pickle strings or files.
+
+ This method provides a unified api for dumping data as strings or to files,
+ and also supports custom arguments for each file format.
+
+ Args:
+ obj (any): The python object to be dumped.
+ file (str or :obj:`Path` or file-like object, optional): If not
+ specified, then the object is dump to a str, otherwise to a file
+ specified by the filename or file-like object.
+ file_format (str, optional): Same as :func:`load`.
+
+ Returns:
+ bool: True for success, False otherwise.
+ """
+ if isinstance(file, Path):
+ file = str(file)
+ if file_format is None:
+ if is_str(file):
+ file_format = file.split(".")[-1]
+ elif file is None:
+ raise ValueError("file_format must be specified since file is None")
+ if file_format not in file_handlers:
+ raise TypeError(f"Unsupported format: {file_format}")
+
+ handler = file_handlers[file_format]
+ if file is None:
+ return handler.dump_to_str(obj, **kwargs)
+ elif is_str(file):
+ handler.dump_to_path(obj, file, **kwargs)
+ elif hasattr(file, "write"):
+ handler.dump_to_fileobj(obj, file, **kwargs)
+ else:
+ raise TypeError('"file" must be a filename str or a file-object')
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/time_counter.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/time_counter.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aedb2e4d61bfbe7571dca9d50053f0fedaa1359
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/time_counter.py
@@ -0,0 +1,62 @@
+import json
+import time
+
+
+class TimeCounter:
+ def __init__(self) -> None:
+ pass
+
+ def clear(self):
+ self.timedict = {}
+ self.basetime = time.perf_counter()
+
+ def timeit(self, name):
+ nowtime = time.perf_counter() - self.basetime
+ self.timedict[name] = nowtime
+ self.basetime = time.perf_counter()
+
+
+class TimeHolder:
+ def __init__(self) -> None:
+ self.timedict = {}
+
+ def update(self, _timedict: dict):
+ for k, v in _timedict.items():
+ if k not in self.timedict:
+ self.timedict[k] = AverageMeter(name=k, val_only=True)
+ self.timedict[k].update(val=v)
+
+ def final_res(self):
+ return {k: v.avg for k, v in self.timedict.items()}
+
+ def __str__(self):
+ return json.dumps(self.final_res(), indent=2)
+
+
+class AverageMeter(object):
+ """Computes and stores the average and current value"""
+
+ def __init__(self, name, fmt=":f", val_only=False):
+ self.name = name
+ self.fmt = fmt
+ self.val_only = val_only
+ self.reset()
+
+ def reset(self):
+ self.val = 0
+ self.avg = 0
+ self.sum = 0
+ self.count = 0
+
+ def update(self, val, n=1):
+ self.val = val
+ self.sum += val * n
+ self.count += n
+ self.avg = self.sum / self.count
+
+ def __str__(self):
+ if self.val_only:
+ fmtstr = "{name} {val" + self.fmt + "}"
+ else:
+ fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})"
+ return fmtstr.format(**self.__dict__)
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/utils.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cf83ae03a7865bc48493be16e8b1b2d53a1b09f
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/utils.py
@@ -0,0 +1,610 @@
+import argparse
+import json
+import warnings
+from collections import OrderedDict
+from copy import deepcopy
+from typing import Any, Dict, List
+
+import numpy as np
+import torch
+from transformers import AutoTokenizer
+
+from groundingdino.util.slconfig import SLConfig
+
+
+def slprint(x, name="x"):
+ if isinstance(x, (torch.Tensor, np.ndarray)):
+ print(f"{name}.shape:", x.shape)
+ elif isinstance(x, (tuple, list)):
+ print("type x:", type(x))
+ for i in range(min(10, len(x))):
+ slprint(x[i], f"{name}[{i}]")
+ elif isinstance(x, dict):
+ for k, v in x.items():
+ slprint(v, f"{name}[{k}]")
+ else:
+ print(f"{name}.type:", type(x))
+
+
+def clean_state_dict(state_dict):
+ new_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k[:7] == "module.":
+ k = k[7:] # remove `module.`
+ new_state_dict[k] = v
+ return new_state_dict
+
+
+def renorm(
+ img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
+) -> torch.FloatTensor:
+ # img: tensor(3,H,W) or tensor(B,3,H,W)
+ # return: same as img
+ assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim()
+ if img.dim() == 3:
+ assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % (
+ img.size(0),
+ str(img.size()),
+ )
+ img_perm = img.permute(1, 2, 0)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(2, 0, 1)
+ else: # img.dim() == 4
+ assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % (
+ img.size(1),
+ str(img.size()),
+ )
+ img_perm = img.permute(0, 2, 3, 1)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(0, 3, 1, 2)
+
+
+class CocoClassMapper:
+ def __init__(self) -> None:
+ self.category_map_str = {
+ "1": 1,
+ "2": 2,
+ "3": 3,
+ "4": 4,
+ "5": 5,
+ "6": 6,
+ "7": 7,
+ "8": 8,
+ "9": 9,
+ "10": 10,
+ "11": 11,
+ "13": 12,
+ "14": 13,
+ "15": 14,
+ "16": 15,
+ "17": 16,
+ "18": 17,
+ "19": 18,
+ "20": 19,
+ "21": 20,
+ "22": 21,
+ "23": 22,
+ "24": 23,
+ "25": 24,
+ "27": 25,
+ "28": 26,
+ "31": 27,
+ "32": 28,
+ "33": 29,
+ "34": 30,
+ "35": 31,
+ "36": 32,
+ "37": 33,
+ "38": 34,
+ "39": 35,
+ "40": 36,
+ "41": 37,
+ "42": 38,
+ "43": 39,
+ "44": 40,
+ "46": 41,
+ "47": 42,
+ "48": 43,
+ "49": 44,
+ "50": 45,
+ "51": 46,
+ "52": 47,
+ "53": 48,
+ "54": 49,
+ "55": 50,
+ "56": 51,
+ "57": 52,
+ "58": 53,
+ "59": 54,
+ "60": 55,
+ "61": 56,
+ "62": 57,
+ "63": 58,
+ "64": 59,
+ "65": 60,
+ "67": 61,
+ "70": 62,
+ "72": 63,
+ "73": 64,
+ "74": 65,
+ "75": 66,
+ "76": 67,
+ "77": 68,
+ "78": 69,
+ "79": 70,
+ "80": 71,
+ "81": 72,
+ "82": 73,
+ "84": 74,
+ "85": 75,
+ "86": 76,
+ "87": 77,
+ "88": 78,
+ "89": 79,
+ "90": 80,
+ }
+ self.origin2compact_mapper = {int(k): v - 1 for k, v in self.category_map_str.items()}
+ self.compact2origin_mapper = {int(v - 1): int(k) for k, v in self.category_map_str.items()}
+
+ def origin2compact(self, idx):
+ return self.origin2compact_mapper[int(idx)]
+
+ def compact2origin(self, idx):
+ return self.compact2origin_mapper[int(idx)]
+
+
+def to_device(item, device):
+ if isinstance(item, torch.Tensor):
+ return item.to(device)
+ elif isinstance(item, list):
+ return [to_device(i, device) for i in item]
+ elif isinstance(item, dict):
+ return {k: to_device(v, device) for k, v in item.items()}
+ else:
+ raise NotImplementedError(
+ "Call Shilong if you use other containers! type: {}".format(type(item))
+ )
+
+
+#
+def get_gaussian_mean(x, axis, other_axis, softmax=True):
+ """
+
+ Args:
+ x (float): Input images(BxCxHxW)
+ axis (int): The index for weighted mean
+ other_axis (int): The other index
+
+ Returns: weighted index for axis, BxC
+
+ """
+ mat2line = torch.sum(x, axis=other_axis)
+ # mat2line = mat2line / mat2line.mean() * 10
+ if softmax:
+ u = torch.softmax(mat2line, axis=2)
+ else:
+ u = mat2line / (mat2line.sum(2, keepdim=True) + 1e-6)
+ size = x.shape[axis]
+ ind = torch.linspace(0, 1, size).to(x.device)
+ batch = x.shape[0]
+ channel = x.shape[1]
+ index = ind.repeat([batch, channel, 1])
+ mean_position = torch.sum(index * u, dim=2)
+ return mean_position
+
+
+def get_expected_points_from_map(hm, softmax=True):
+ """get_gaussian_map_from_points
+ B,C,H,W -> B,N,2 float(0, 1) float(0, 1)
+ softargmax function
+
+ Args:
+ hm (float): Input images(BxCxHxW)
+
+ Returns:
+ weighted index for axis, BxCx2. float between 0 and 1.
+
+ """
+ # hm = 10*hm
+ B, C, H, W = hm.shape
+ y_mean = get_gaussian_mean(hm, 2, 3, softmax=softmax) # B,C
+ x_mean = get_gaussian_mean(hm, 3, 2, softmax=softmax) # B,C
+ # return torch.cat((x_mean.unsqueeze(-1), y_mean.unsqueeze(-1)), 2)
+ return torch.stack([x_mean, y_mean], dim=2)
+
+
+# Positional encoding (section 5.1)
+# borrow from nerf
+class Embedder:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+ self.create_embedding_fn()
+
+ def create_embedding_fn(self):
+ embed_fns = []
+ d = self.kwargs["input_dims"]
+ out_dim = 0
+ if self.kwargs["include_input"]:
+ embed_fns.append(lambda x: x)
+ out_dim += d
+
+ max_freq = self.kwargs["max_freq_log2"]
+ N_freqs = self.kwargs["num_freqs"]
+
+ if self.kwargs["log_sampling"]:
+ freq_bands = 2.0 ** torch.linspace(0.0, max_freq, steps=N_freqs)
+ else:
+ freq_bands = torch.linspace(2.0**0.0, 2.0**max_freq, steps=N_freqs)
+
+ for freq in freq_bands:
+ for p_fn in self.kwargs["periodic_fns"]:
+ embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq))
+ out_dim += d
+
+ self.embed_fns = embed_fns
+ self.out_dim = out_dim
+
+ def embed(self, inputs):
+ return torch.cat([fn(inputs) for fn in self.embed_fns], -1)
+
+
+def get_embedder(multires, i=0):
+ import torch.nn as nn
+
+ if i == -1:
+ return nn.Identity(), 3
+
+ embed_kwargs = {
+ "include_input": True,
+ "input_dims": 3,
+ "max_freq_log2": multires - 1,
+ "num_freqs": multires,
+ "log_sampling": True,
+ "periodic_fns": [torch.sin, torch.cos],
+ }
+
+ embedder_obj = Embedder(**embed_kwargs)
+ embed = lambda x, eo=embedder_obj: eo.embed(x)
+ return embed, embedder_obj.out_dim
+
+
+class APOPMeter:
+ def __init__(self) -> None:
+ self.tp = 0
+ self.fp = 0
+ self.tn = 0
+ self.fn = 0
+
+ def update(self, pred, gt):
+ """
+ Input:
+ pred, gt: Tensor()
+ """
+ assert pred.shape == gt.shape
+ self.tp += torch.logical_and(pred == 1, gt == 1).sum().item()
+ self.fp += torch.logical_and(pred == 1, gt == 0).sum().item()
+ self.tn += torch.logical_and(pred == 0, gt == 0).sum().item()
+ self.tn += torch.logical_and(pred == 1, gt == 0).sum().item()
+
+ def update_cm(self, tp, fp, tn, fn):
+ self.tp += tp
+ self.fp += fp
+ self.tn += tn
+ self.tn += fn
+
+
+def inverse_sigmoid(x, eps=1e-5):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+def get_raw_dict(args):
+ """
+ return the dicf contained in args.
+
+ e.g:
+ >>> with open(path, 'w') as f:
+ json.dump(get_raw_dict(args), f, indent=2)
+ """
+ if isinstance(args, argparse.Namespace):
+ return vars(args)
+ elif isinstance(args, dict):
+ return args
+ elif isinstance(args, SLConfig):
+ return args._cfg_dict
+ else:
+ raise NotImplementedError("Unknown type {}".format(type(args)))
+
+
+def stat_tensors(tensor):
+ assert tensor.dim() == 1
+ tensor_sm = tensor.softmax(0)
+ entropy = (tensor_sm * torch.log(tensor_sm + 1e-9)).sum()
+
+ return {
+ "max": tensor.max(),
+ "min": tensor.min(),
+ "mean": tensor.mean(),
+ "var": tensor.var(),
+ "std": tensor.var() ** 0.5,
+ "entropy": entropy,
+ }
+
+
+class NiceRepr:
+ """Inherit from this class and define ``__nice__`` to "nicely" print your
+ objects.
+
+ Defines ``__str__`` and ``__repr__`` in terms of ``__nice__`` function
+ Classes that inherit from :class:`NiceRepr` should redefine ``__nice__``.
+ If the inheriting class has a ``__len__``, method then the default
+ ``__nice__`` method will return its length.
+
+ Example:
+ >>> class Foo(NiceRepr):
+ ... def __nice__(self):
+ ... return 'info'
+ >>> foo = Foo()
+ >>> assert str(foo) == ''
+ >>> assert repr(foo).startswith('>> class Bar(NiceRepr):
+ ... pass
+ >>> bar = Bar()
+ >>> import pytest
+ >>> with pytest.warns(None) as record:
+ >>> assert 'object at' in str(bar)
+ >>> assert 'object at' in repr(bar)
+
+ Example:
+ >>> class Baz(NiceRepr):
+ ... def __len__(self):
+ ... return 5
+ >>> baz = Baz()
+ >>> assert str(baz) == ''
+ """
+
+ def __nice__(self):
+ """str: a "nice" summary string describing this module"""
+ if hasattr(self, "__len__"):
+ # It is a common pattern for objects to use __len__ in __nice__
+ # As a convenience we define a default __nice__ for these objects
+ return str(len(self))
+ else:
+ # In all other cases force the subclass to overload __nice__
+ raise NotImplementedError(f"Define the __nice__ method for {self.__class__!r}")
+
+ def __repr__(self):
+ """str: the string of the module"""
+ try:
+ nice = self.__nice__()
+ classname = self.__class__.__name__
+ return f"<{classname}({nice}) at {hex(id(self))}>"
+ except NotImplementedError as ex:
+ warnings.warn(str(ex), category=RuntimeWarning)
+ return object.__repr__(self)
+
+ def __str__(self):
+ """str: the string of the module"""
+ try:
+ classname = self.__class__.__name__
+ nice = self.__nice__()
+ return f"<{classname}({nice})>"
+ except NotImplementedError as ex:
+ warnings.warn(str(ex), category=RuntimeWarning)
+ return object.__repr__(self)
+
+
+def ensure_rng(rng=None):
+ """Coerces input into a random number generator.
+
+ If the input is None, then a global random state is returned.
+
+ If the input is a numeric value, then that is used as a seed to construct a
+ random state. Otherwise the input is returned as-is.
+
+ Adapted from [1]_.
+
+ Args:
+ rng (int | numpy.random.RandomState | None):
+ if None, then defaults to the global rng. Otherwise this can be an
+ integer or a RandomState class
+ Returns:
+ (numpy.random.RandomState) : rng -
+ a numpy random number generator
+
+ References:
+ .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501
+ """
+
+ if rng is None:
+ rng = np.random.mtrand._rand
+ elif isinstance(rng, int):
+ rng = np.random.RandomState(rng)
+ else:
+ rng = rng
+ return rng
+
+
+def random_boxes(num=1, scale=1, rng=None):
+ """Simple version of ``kwimage.Boxes.random``
+
+ Returns:
+ Tensor: shape (n, 4) in x1, y1, x2, y2 format.
+
+ References:
+ https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390
+
+ Example:
+ >>> num = 3
+ >>> scale = 512
+ >>> rng = 0
+ >>> boxes = random_boxes(num, scale, rng)
+ >>> print(boxes)
+ tensor([[280.9925, 278.9802, 308.6148, 366.1769],
+ [216.9113, 330.6978, 224.0446, 456.5878],
+ [405.3632, 196.3221, 493.3953, 270.7942]])
+ """
+ rng = ensure_rng(rng)
+
+ tlbr = rng.rand(num, 4).astype(np.float32)
+
+ tl_x = np.minimum(tlbr[:, 0], tlbr[:, 2])
+ tl_y = np.minimum(tlbr[:, 1], tlbr[:, 3])
+ br_x = np.maximum(tlbr[:, 0], tlbr[:, 2])
+ br_y = np.maximum(tlbr[:, 1], tlbr[:, 3])
+
+ tlbr[:, 0] = tl_x * scale
+ tlbr[:, 1] = tl_y * scale
+ tlbr[:, 2] = br_x * scale
+ tlbr[:, 3] = br_y * scale
+
+ boxes = torch.from_numpy(tlbr)
+ return boxes
+
+
+class ModelEma(torch.nn.Module):
+ def __init__(self, model, decay=0.9997, device=None):
+ super(ModelEma, self).__init__()
+ # make a copy of the model for accumulating moving average of weights
+ self.module = deepcopy(model)
+ self.module.eval()
+
+ # import ipdb; ipdb.set_trace()
+
+ self.decay = decay
+ self.device = device # perform ema on different device from model if set
+ if self.device is not None:
+ self.module.to(device=device)
+
+ def _update(self, model, update_fn):
+ with torch.no_grad():
+ for ema_v, model_v in zip(
+ self.module.state_dict().values(), model.state_dict().values()
+ ):
+ if self.device is not None:
+ model_v = model_v.to(device=self.device)
+ ema_v.copy_(update_fn(ema_v, model_v))
+
+ def update(self, model):
+ self._update(model, update_fn=lambda e, m: self.decay * e + (1.0 - self.decay) * m)
+
+ def set(self, model):
+ self._update(model, update_fn=lambda e, m: m)
+
+
+class BestMetricSingle:
+ def __init__(self, init_res=0.0, better="large") -> None:
+ self.init_res = init_res
+ self.best_res = init_res
+ self.best_ep = -1
+
+ self.better = better
+ assert better in ["large", "small"]
+
+ def isbetter(self, new_res, old_res):
+ if self.better == "large":
+ return new_res > old_res
+ if self.better == "small":
+ return new_res < old_res
+
+ def update(self, new_res, ep):
+ if self.isbetter(new_res, self.best_res):
+ self.best_res = new_res
+ self.best_ep = ep
+ return True
+ return False
+
+ def __str__(self) -> str:
+ return "best_res: {}\t best_ep: {}".format(self.best_res, self.best_ep)
+
+ def __repr__(self) -> str:
+ return self.__str__()
+
+ def summary(self) -> dict:
+ return {
+ "best_res": self.best_res,
+ "best_ep": self.best_ep,
+ }
+
+
+class BestMetricHolder:
+ def __init__(self, init_res=0.0, better="large", use_ema=False) -> None:
+ self.best_all = BestMetricSingle(init_res, better)
+ self.use_ema = use_ema
+ if use_ema:
+ self.best_ema = BestMetricSingle(init_res, better)
+ self.best_regular = BestMetricSingle(init_res, better)
+
+ def update(self, new_res, epoch, is_ema=False):
+ """
+ return if the results is the best.
+ """
+ if not self.use_ema:
+ return self.best_all.update(new_res, epoch)
+ else:
+ if is_ema:
+ self.best_ema.update(new_res, epoch)
+ return self.best_all.update(new_res, epoch)
+ else:
+ self.best_regular.update(new_res, epoch)
+ return self.best_all.update(new_res, epoch)
+
+ def summary(self):
+ if not self.use_ema:
+ return self.best_all.summary()
+
+ res = {}
+ res.update({f"all_{k}": v for k, v in self.best_all.summary().items()})
+ res.update({f"regular_{k}": v for k, v in self.best_regular.summary().items()})
+ res.update({f"ema_{k}": v for k, v in self.best_ema.summary().items()})
+ return res
+
+ def __repr__(self) -> str:
+ return json.dumps(self.summary(), indent=2)
+
+ def __str__(self) -> str:
+ return self.__repr__()
+
+
+def targets_to(targets: List[Dict[str, Any]], device):
+ """Moves the target dicts to the given device."""
+ excluded_keys = [
+ "questionId",
+ "tokens_positive",
+ "strings_positive",
+ "tokens",
+ "dataset_name",
+ "sentence_id",
+ "original_img_id",
+ "nb_eval",
+ "task_id",
+ "original_id",
+ "token_span",
+ "caption",
+ "dataset_type",
+ ]
+ return [
+ {k: v.to(device) if k not in excluded_keys else v for k, v in t.items()} for t in targets
+ ]
+
+
+def get_phrases_from_posmap(
+ posmap: torch.BoolTensor, tokenized: Dict, tokenizer: AutoTokenizer, left_idx: int = 0, right_idx: int = 255
+):
+ assert isinstance(posmap, torch.Tensor), "posmap must be torch.Tensor"
+ if posmap.dim() == 1:
+ posmap[0: left_idx + 1] = False
+ posmap[right_idx:] = False
+ non_zero_idx = posmap.nonzero(as_tuple=True)[0].tolist()
+ token_ids = [tokenized["input_ids"][i] for i in non_zero_idx]
+ return tokenizer.decode(token_ids)
+ else:
+ raise NotImplementedError("posmap must be 1-dim")
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/visualizer.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a1b7b101e9b73f75f9136bc67f2063c7c1cf1c1
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/visualizer.py
@@ -0,0 +1,318 @@
+# -*- coding: utf-8 -*-
+"""
+@File : visualizer.py
+@Time : 2022/04/05 11:39:33
+@Author : Shilong Liu
+@Contact : slongliu86@gmail.com
+"""
+
+import datetime
+import os
+
+import cv2
+import matplotlib.pyplot as plt
+import numpy as np
+import torch
+from matplotlib import transforms
+from matplotlib.collections import PatchCollection
+from matplotlib.patches import Polygon
+from pycocotools import mask as maskUtils
+
+
+def renorm(
+ img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
+) -> torch.FloatTensor:
+ # img: tensor(3,H,W) or tensor(B,3,H,W)
+ # return: same as img
+ assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim()
+ if img.dim() == 3:
+ assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % (
+ img.size(0),
+ str(img.size()),
+ )
+ img_perm = img.permute(1, 2, 0)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(2, 0, 1)
+ else: # img.dim() == 4
+ assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % (
+ img.size(1),
+ str(img.size()),
+ )
+ img_perm = img.permute(0, 2, 3, 1)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(0, 3, 1, 2)
+
+
+class ColorMap:
+ def __init__(self, basergb=[255, 255, 0]):
+ self.basergb = np.array(basergb)
+
+ def __call__(self, attnmap):
+ # attnmap: h, w. np.uint8.
+ # return: h, w, 4. np.uint8.
+ assert attnmap.dtype == np.uint8
+ h, w = attnmap.shape
+ res = self.basergb.copy()
+ res = res[None][None].repeat(h, 0).repeat(w, 1) # h, w, 3
+ attn1 = attnmap.copy()[..., None] # h, w, 1
+ res = np.concatenate((res, attn1), axis=-1).astype(np.uint8)
+ return res
+
+
+def rainbow_text(x, y, ls, lc, **kw):
+ """
+ Take a list of strings ``ls`` and colors ``lc`` and place them next to each
+ other, with text ls[i] being shown in color lc[i].
+
+ This example shows how to do both vertical and horizontal text, and will
+ pass all keyword arguments to plt.text, so you can set the font size,
+ family, etc.
+ """
+ t = plt.gca().transData
+ fig = plt.gcf()
+ plt.show()
+
+ # horizontal version
+ for s, c in zip(ls, lc):
+ text = plt.text(x, y, " " + s + " ", color=c, transform=t, **kw)
+ text.draw(fig.canvas.get_renderer())
+ ex = text.get_window_extent()
+ t = transforms.offset_copy(text._transform, x=ex.width, units="dots")
+
+ # #vertical version
+ # for s,c in zip(ls,lc):
+ # text = plt.text(x,y," "+s+" ",color=c, transform=t,
+ # rotation=90,va='bottom',ha='center',**kw)
+ # text.draw(fig.canvas.get_renderer())
+ # ex = text.get_window_extent()
+ # t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
+
+
+class COCOVisualizer:
+ def __init__(self, coco=None, tokenlizer=None) -> None:
+ self.coco = coco
+
+ def visualize(self, img, tgt, caption=None, dpi=180, savedir="vis"):
+ """
+ img: tensor(3, H, W)
+ tgt: make sure they are all on cpu.
+ must have items: 'image_id', 'boxes', 'size'
+ """
+ plt.figure(dpi=dpi)
+ plt.rcParams["font.size"] = "5"
+ ax = plt.gca()
+ img = renorm(img).permute(1, 2, 0)
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ ax.imshow(img)
+
+ self.addtgt(tgt)
+
+ if tgt is None:
+ image_id = 0
+ elif "image_id" not in tgt:
+ image_id = 0
+ else:
+ image_id = tgt["image_id"]
+
+ if caption is None:
+ savename = "{}/{}-{}.png".format(
+ savedir, int(image_id), str(datetime.datetime.now()).replace(" ", "-")
+ )
+ else:
+ savename = "{}/{}-{}-{}.png".format(
+ savedir, caption, int(image_id), str(datetime.datetime.now()).replace(" ", "-")
+ )
+ print("savename: {}".format(savename))
+ os.makedirs(os.path.dirname(savename), exist_ok=True)
+ plt.savefig(savename)
+ plt.close()
+
+ def addtgt(self, tgt):
+ """ """
+ if tgt is None or not "boxes" in tgt:
+ ax = plt.gca()
+
+ if "caption" in tgt:
+ ax.set_title(tgt["caption"], wrap=True)
+
+ ax.set_axis_off()
+ return
+
+ ax = plt.gca()
+ H, W = tgt["size"]
+ numbox = tgt["boxes"].shape[0]
+
+ color = []
+ polygons = []
+ boxes = []
+ for box in tgt["boxes"].cpu():
+ unnormbbox = box * torch.Tensor([W, H, W, H])
+ unnormbbox[:2] -= unnormbbox[2:] / 2
+ [bbox_x, bbox_y, bbox_w, bbox_h] = unnormbbox.tolist()
+ boxes.append([bbox_x, bbox_y, bbox_w, bbox_h])
+ poly = [
+ [bbox_x, bbox_y],
+ [bbox_x, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y],
+ ]
+ np_poly = np.array(poly).reshape((4, 2))
+ polygons.append(Polygon(np_poly))
+ c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0]
+ color.append(c)
+
+ p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.1)
+ ax.add_collection(p)
+ p = PatchCollection(polygons, facecolor="none", edgecolors=color, linewidths=2)
+ ax.add_collection(p)
+
+ if "strings_positive" in tgt and len(tgt["strings_positive"]) > 0:
+ assert (
+ len(tgt["strings_positive"]) == numbox
+ ), f"{len(tgt['strings_positive'])} = {numbox}, "
+ for idx, strlist in enumerate(tgt["strings_positive"]):
+ cate_id = int(tgt["labels"][idx])
+ _string = str(cate_id) + ":" + " ".join(strlist)
+ bbox_x, bbox_y, bbox_w, bbox_h = boxes[idx]
+ # ax.text(bbox_x, bbox_y, _string, color='black', bbox={'facecolor': 'yellow', 'alpha': 1.0, 'pad': 1})
+ ax.text(
+ bbox_x,
+ bbox_y,
+ _string,
+ color="black",
+ bbox={"facecolor": color[idx], "alpha": 0.6, "pad": 1},
+ )
+
+ if "box_label" in tgt:
+ assert len(tgt["box_label"]) == numbox, f"{len(tgt['box_label'])} = {numbox}, "
+ for idx, bl in enumerate(tgt["box_label"]):
+ _string = str(bl)
+ bbox_x, bbox_y, bbox_w, bbox_h = boxes[idx]
+ # ax.text(bbox_x, bbox_y, _string, color='black', bbox={'facecolor': 'yellow', 'alpha': 1.0, 'pad': 1})
+ ax.text(
+ bbox_x,
+ bbox_y,
+ _string,
+ color="black",
+ bbox={"facecolor": color[idx], "alpha": 0.6, "pad": 1},
+ )
+
+ if "caption" in tgt:
+ ax.set_title(tgt["caption"], wrap=True)
+ # plt.figure()
+ # rainbow_text(0.0,0.0,"all unicorns poop rainbows ! ! !".split(),
+ # ['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'])
+
+ if "attn" in tgt:
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ if isinstance(tgt["attn"], tuple):
+ tgt["attn"] = [tgt["attn"]]
+ for item in tgt["attn"]:
+ attn_map, basergb = item
+ attn_map = (attn_map - attn_map.min()) / (attn_map.max() - attn_map.min() + 1e-3)
+ attn_map = (attn_map * 255).astype(np.uint8)
+ cm = ColorMap(basergb)
+ heatmap = cm(attn_map)
+ ax.imshow(heatmap)
+ ax.set_axis_off()
+
+ def showAnns(self, anns, draw_bbox=False):
+ """
+ Display the specified annotations.
+ :param anns (array of object): annotations to display
+ :return: None
+ """
+ if len(anns) == 0:
+ return 0
+ if "segmentation" in anns[0] or "keypoints" in anns[0]:
+ datasetType = "instances"
+ elif "caption" in anns[0]:
+ datasetType = "captions"
+ else:
+ raise Exception("datasetType not supported")
+ if datasetType == "instances":
+ ax = plt.gca()
+ ax.set_autoscale_on(False)
+ polygons = []
+ color = []
+ for ann in anns:
+ c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0]
+ if "segmentation" in ann:
+ if type(ann["segmentation"]) == list:
+ # polygon
+ for seg in ann["segmentation"]:
+ poly = np.array(seg).reshape((int(len(seg) / 2), 2))
+ polygons.append(Polygon(poly))
+ color.append(c)
+ else:
+ # mask
+ t = self.imgs[ann["image_id"]]
+ if type(ann["segmentation"]["counts"]) == list:
+ rle = maskUtils.frPyObjects(
+ [ann["segmentation"]], t["height"], t["width"]
+ )
+ else:
+ rle = [ann["segmentation"]]
+ m = maskUtils.decode(rle)
+ img = np.ones((m.shape[0], m.shape[1], 3))
+ if ann["iscrowd"] == 1:
+ color_mask = np.array([2.0, 166.0, 101.0]) / 255
+ if ann["iscrowd"] == 0:
+ color_mask = np.random.random((1, 3)).tolist()[0]
+ for i in range(3):
+ img[:, :, i] = color_mask[i]
+ ax.imshow(np.dstack((img, m * 0.5)))
+ if "keypoints" in ann and type(ann["keypoints"]) == list:
+ # turn skeleton into zero-based index
+ sks = np.array(self.loadCats(ann["category_id"])[0]["skeleton"]) - 1
+ kp = np.array(ann["keypoints"])
+ x = kp[0::3]
+ y = kp[1::3]
+ v = kp[2::3]
+ for sk in sks:
+ if np.all(v[sk] > 0):
+ plt.plot(x[sk], y[sk], linewidth=3, color=c)
+ plt.plot(
+ x[v > 0],
+ y[v > 0],
+ "o",
+ markersize=8,
+ markerfacecolor=c,
+ markeredgecolor="k",
+ markeredgewidth=2,
+ )
+ plt.plot(
+ x[v > 1],
+ y[v > 1],
+ "o",
+ markersize=8,
+ markerfacecolor=c,
+ markeredgecolor=c,
+ markeredgewidth=2,
+ )
+
+ if draw_bbox:
+ [bbox_x, bbox_y, bbox_w, bbox_h] = ann["bbox"]
+ poly = [
+ [bbox_x, bbox_y],
+ [bbox_x, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y],
+ ]
+ np_poly = np.array(poly).reshape((4, 2))
+ polygons.append(Polygon(np_poly))
+ color.append(c)
+
+ # p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
+ # ax.add_collection(p)
+ p = PatchCollection(polygons, facecolor="none", edgecolors=color, linewidths=2)
+ ax.add_collection(p)
+ elif datasetType == "captions":
+ for ann in anns:
+ print(ann["caption"])
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/vl_utils.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/vl_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c91bb02f584398f08a28e6b7719e2b99f6e28616
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/util/vl_utils.py
@@ -0,0 +1,100 @@
+import os
+import random
+from typing import List
+
+import torch
+
+
+def create_positive_map_from_span(tokenized, token_span, max_text_len=256):
+ """construct a map such that positive_map[i,j] = True iff box i is associated to token j
+ Input:
+ - tokenized:
+ - input_ids: Tensor[1, ntokens]
+ - attention_mask: Tensor[1, ntokens]
+ - token_span: list with length num_boxes.
+ - each item: [start_idx, end_idx]
+ """
+ positive_map = torch.zeros((len(token_span), max_text_len), dtype=torch.float)
+ for j, tok_list in enumerate(token_span):
+ for (beg, end) in tok_list:
+ beg_pos = tokenized.char_to_token(beg)
+ end_pos = tokenized.char_to_token(end - 1)
+ if beg_pos is None:
+ try:
+ beg_pos = tokenized.char_to_token(beg + 1)
+ if beg_pos is None:
+ beg_pos = tokenized.char_to_token(beg + 2)
+ except:
+ beg_pos = None
+ if end_pos is None:
+ try:
+ end_pos = tokenized.char_to_token(end - 2)
+ if end_pos is None:
+ end_pos = tokenized.char_to_token(end - 3)
+ except:
+ end_pos = None
+ if beg_pos is None or end_pos is None:
+ continue
+
+ assert beg_pos is not None and end_pos is not None
+ if os.environ.get("SHILONG_DEBUG_ONLY_ONE_POS", None) == "TRUE":
+ positive_map[j, beg_pos] = 1
+ break
+ else:
+ positive_map[j, beg_pos : end_pos + 1].fill_(1)
+
+ return positive_map / (positive_map.sum(-1)[:, None] + 1e-6)
+
+
+def build_captions_and_token_span(cat_list, force_lowercase):
+ """
+ Return:
+ captions: str
+ cat2tokenspan: dict
+ {
+ 'dog': [[0, 2]],
+ ...
+ }
+ """
+
+ cat2tokenspan = {}
+ captions = ""
+ for catname in cat_list:
+ class_name = catname
+ if force_lowercase:
+ class_name = class_name.lower()
+ if "/" in class_name:
+ class_name_list: List = class_name.strip().split("/")
+ class_name_list.append(class_name)
+ class_name: str = random.choice(class_name_list)
+
+ tokens_positive_i = []
+ subnamelist = [i.strip() for i in class_name.strip().split(" ")]
+ for subname in subnamelist:
+ if len(subname) == 0:
+ continue
+ if len(captions) > 0:
+ captions = captions + " "
+ strat_idx = len(captions)
+ end_idx = strat_idx + len(subname)
+ tokens_positive_i.append([strat_idx, end_idx])
+ captions = captions + subname
+
+ if len(tokens_positive_i) > 0:
+ captions = captions + " ."
+ cat2tokenspan[class_name] = tokens_positive_i
+
+ return captions, cat2tokenspan
+
+
+def build_id2posspan_and_caption(category_dict: dict):
+ """Build id2pos_span and caption from category_dict
+
+ Args:
+ category_dict (dict): category_dict
+ """
+ cat_list = [item["name"].lower() for item in category_dict]
+ id2catname = {item["id"]: item["name"].lower() for item in category_dict}
+ caption, cat2posspan = build_captions_and_token_span(cat_list, force_lowercase=True)
+ id2posspan = {catid: cat2posspan[catname] for catid, catname in id2catname.items()}
+ return id2posspan, caption
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/version.py b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..b794fd409a5e3b3b65ad76a43d6a01a318877640
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/groundingdino/version.py
@@ -0,0 +1 @@
+__version__ = '0.1.0'
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/qwen_vl_utils/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/qwen_vl_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..daa8708442e93d5ec3a02e863ad7ae833952d199
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/qwen_vl_utils/__init__.py
@@ -0,0 +1,7 @@
+from .vision_process import (
+ extract_vision_info,
+ fetch_image,
+ fetch_video,
+ process_vision_info,
+ smart_resize,
+)
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/qwen_vl_utils/vision_process.py b/benchmarks/edit/code/IVEBench/metrics/compliance/qwen_vl_utils/vision_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb456f8685ab82bc5f29d9e79e95afa6ff9909bf
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/qwen_vl_utils/vision_process.py
@@ -0,0 +1,377 @@
+from __future__ import annotations
+
+import base64
+import logging
+import math
+import os
+import sys
+import time
+import warnings
+from functools import lru_cache
+from io import BytesIO
+
+import requests
+import torch
+import torchvision
+from packaging import version
+from PIL import Image
+from torchvision import io, transforms
+from torchvision.transforms import InterpolationMode
+from typing import Optional
+
+
+logger = logging.getLogger(__name__)
+
+IMAGE_FACTOR = 28
+MIN_PIXELS = 4 * 28 * 28
+MAX_PIXELS = 16384 * 28 * 28
+MAX_RATIO = 200
+
+VIDEO_MIN_PIXELS = 128 * 28 * 28
+VIDEO_MAX_PIXELS = 768 * 28 * 28
+FRAME_FACTOR = 2
+FPS = 2.0
+FPS_MIN_FRAMES = 4
+FPS_MAX_FRAMES = 768
+
+# Set the maximum number of video token inputs.
+# Here, 128K represents the maximum number of input tokens for the VLLM model.
+# Remember to adjust it according to your own configuration.
+VIDEO_TOTAL_PIXELS = int(float(os.environ.get('VIDEO_MAX_PIXELS', 128000 * 28 * 28 * 0.9)))
+logger.info(f"set VIDEO_TOTAL_PIXELS: {VIDEO_TOTAL_PIXELS}")
+
+
+def round_by_factor(number: int, factor: int) -> int:
+ """Returns the closest integer to 'number' that is divisible by 'factor'."""
+ return round(number / factor) * factor
+
+
+def ceil_by_factor(number: int, factor: int) -> int:
+ """Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""
+ return math.ceil(number / factor) * factor
+
+
+def floor_by_factor(number: int, factor: int) -> int:
+ """Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""
+ return math.floor(number / factor) * factor
+
+
+def smart_resize(
+ height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS
+) -> tuple[int, int]:
+ """
+ Rescales the image so that the following conditions are met:
+
+ 1. Both dimensions (height and width) are divisible by 'factor'.
+
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
+
+ 3. The aspect ratio of the image is maintained as closely as possible.
+ """
+ if max(height, width) / min(height, width) > MAX_RATIO:
+ raise ValueError(
+ f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}"
+ )
+ h_bar = max(factor, round_by_factor(height, factor))
+ w_bar = max(factor, round_by_factor(width, factor))
+ if h_bar * w_bar > max_pixels:
+ beta = math.sqrt((height * width) / max_pixels)
+ h_bar = floor_by_factor(height / beta, factor)
+ w_bar = floor_by_factor(width / beta, factor)
+ elif h_bar * w_bar < min_pixels:
+ beta = math.sqrt(min_pixels / (height * width))
+ h_bar = ceil_by_factor(height * beta, factor)
+ w_bar = ceil_by_factor(width * beta, factor)
+ return h_bar, w_bar
+
+
+def to_rgb(pil_image: Image.Image) -> Image.Image:
+ if pil_image.mode == 'RGBA':
+ white_background = Image.new("RGB", pil_image.size, (255, 255, 255))
+ white_background.paste(pil_image, mask=pil_image.split()[3]) # Use alpha channel as mask
+ return white_background
+ else:
+ return pil_image.convert("RGB")
+
+
+def fetch_image(ele: dict[str, str | Image.Image], size_factor: int = IMAGE_FACTOR) -> Image.Image:
+ if "image" in ele:
+ image = ele["image"]
+ else:
+ image = ele["image_url"]
+ image_obj = None
+ if isinstance(image, Image.Image):
+ image_obj = image
+ elif image.startswith("http://") or image.startswith("https://"):
+ response = requests.get(image, stream=True)
+ image_obj = Image.open(BytesIO(response.content))
+ elif image.startswith("file://"):
+ image_obj = Image.open(image[7:])
+ elif image.startswith("data:image"):
+ if "base64," in image:
+ _, base64_data = image.split("base64,", 1)
+ data = base64.b64decode(base64_data)
+ image_obj = Image.open(BytesIO(data))
+ else:
+ image_obj = Image.open(image)
+ if image_obj is None:
+ raise ValueError(f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}")
+ image = to_rgb(image_obj)
+ ## resize
+ if "resized_height" in ele and "resized_width" in ele:
+ resized_height, resized_width = smart_resize(
+ ele["resized_height"],
+ ele["resized_width"],
+ factor=size_factor,
+ )
+ else:
+ width, height = image.size
+ min_pixels = ele.get("min_pixels", MIN_PIXELS)
+ max_pixels = ele.get("max_pixels", MAX_PIXELS)
+ resized_height, resized_width = smart_resize(
+ height,
+ width,
+ factor=size_factor,
+ min_pixels=min_pixels,
+ max_pixels=max_pixels,
+ )
+ image = image.resize((resized_width, resized_height))
+
+ return image
+
+
+def smart_nframes(
+ ele: dict,
+ total_frames: int,
+ video_fps: int | float,
+) -> int:
+ """calculate the number of frames for video used for model inputs.
+
+ Args:
+ ele (dict): a dict contains the configuration of video.
+ support either `fps` or `nframes`:
+ - nframes: the number of frames to extract for model inputs.
+ - fps: the fps to extract frames for model inputs.
+ - min_frames: the minimum number of frames of the video, only used when fps is provided.
+ - max_frames: the maximum number of frames of the video, only used when fps is provided.
+ total_frames (int): the original total number of frames of the video.
+ video_fps (int | float): the original fps of the video.
+
+ Raises:
+ ValueError: nframes should in interval [FRAME_FACTOR, total_frames].
+
+ Returns:
+ int: the number of frames for video used for model inputs.
+ """
+ assert not ("fps" in ele and "nframes" in ele), "Only accept either `fps` or `nframes`"
+ if "nframes" in ele:
+ nframes = round_by_factor(ele["nframes"], FRAME_FACTOR)
+ else:
+ fps = ele.get("fps", FPS)
+ min_frames = ceil_by_factor(ele.get("min_frames", FPS_MIN_FRAMES), FRAME_FACTOR)
+ max_frames = floor_by_factor(ele.get("max_frames", min(FPS_MAX_FRAMES, total_frames)), FRAME_FACTOR)
+ nframes = total_frames / video_fps * fps
+ if nframes > total_frames:
+ logger.warning(f"smart_nframes: nframes[{nframes}] > total_frames[{total_frames}]")
+ nframes = min(min(max(nframes, min_frames), max_frames), total_frames)
+ nframes = floor_by_factor(nframes, FRAME_FACTOR)
+ if not (FRAME_FACTOR <= nframes and nframes <= total_frames):
+ raise ValueError(f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}.")
+ return nframes
+
+
+def _read_video_torchvision(
+ ele: dict,
+) -> (torch.Tensor, float):
+ """read video using torchvision.io.read_video
+
+ Args:
+ ele (dict): a dict contains the configuration of video.
+ support keys:
+ - video: the path of video. support "file://", "http://", "https://" and local path.
+ - video_start: the start time of video.
+ - video_end: the end time of video.
+ Returns:
+ torch.Tensor: the video tensor with shape (T, C, H, W).
+ """
+ video_path = ele["video"]
+ if version.parse(torchvision.__version__) < version.parse("0.19.0"):
+ if "http://" in video_path or "https://" in video_path:
+ warnings.warn("torchvision < 0.19.0 does not support http/https video path, please upgrade to 0.19.0.")
+ if "file://" in video_path:
+ video_path = video_path[7:]
+ st = time.time()
+ video, audio, info = io.read_video(
+ video_path,
+ start_pts=ele.get("video_start", 0.0),
+ end_pts=ele.get("video_end", None),
+ pts_unit="sec",
+ output_format="TCHW",
+ )
+ total_frames, video_fps = video.size(0), info["video_fps"]
+ logger.info(f"torchvision: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
+ nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
+ idx = torch.linspace(0, total_frames - 1, nframes).round().long()
+ sample_fps = nframes / max(total_frames, 1e-6) * video_fps
+ video = video[idx]
+ return video, sample_fps
+
+
+def is_decord_available() -> bool:
+ import importlib.util
+
+ return importlib.util.find_spec("decord") is not None
+
+
+def _read_video_decord(
+ ele: dict,
+) -> (torch.Tensor, float):
+ """read video using decord.VideoReader
+
+ Args:
+ ele (dict): a dict contains the configuration of video.
+ support keys:
+ - video: the path of video. support "file://", "http://", "https://" and local path.
+ - video_start: the start time of video.
+ - video_end: the end time of video.
+ Returns:
+ torch.Tensor: the video tensor with shape (T, C, H, W).
+ """
+ import decord
+ video_path = ele["video"]
+ st = time.time()
+ vr = decord.VideoReader(video_path)
+ # TODO: support start_pts and end_pts
+ if 'video_start' in ele or 'video_end' in ele:
+ raise NotImplementedError("not support start_pts and end_pts in decord for now.")
+ total_frames, video_fps = len(vr), vr.get_avg_fps()
+ logger.info(f"decord: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
+ nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
+ idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
+ video = vr.get_batch(idx).asnumpy()
+ video = torch.tensor(video).permute(0, 3, 1, 2) # Convert to TCHW format
+ sample_fps = nframes / max(total_frames, 1e-6) * video_fps
+ return video, sample_fps
+
+
+VIDEO_READER_BACKENDS = {
+ "decord": _read_video_decord,
+ "torchvision": _read_video_torchvision,
+}
+
+FORCE_QWENVL_VIDEO_READER = os.getenv("FORCE_QWENVL_VIDEO_READER", None)
+
+
+@lru_cache(maxsize=1)
+def get_video_reader_backend() -> str:
+ if FORCE_QWENVL_VIDEO_READER is not None:
+ video_reader_backend = FORCE_QWENVL_VIDEO_READER
+ elif is_decord_available():
+ video_reader_backend = "decord"
+ else:
+ video_reader_backend = "torchvision"
+ print(f"qwen-vl-utils using {video_reader_backend} to read video.", file=sys.stderr)
+ return video_reader_backend
+
+
+def fetch_video(ele: dict, image_factor: int = IMAGE_FACTOR, return_video_sample_fps: bool = False) -> torch.Tensor | list[Image.Image]:
+ if isinstance(ele["video"], str):
+ video_reader_backend = get_video_reader_backend()
+ try:
+ video, sample_fps = VIDEO_READER_BACKENDS[video_reader_backend](ele)
+ except Exception as e:
+ logger.warning(f"video_reader_backend {video_reader_backend} error, use torchvision as default, msg: {e}")
+ video, sample_fps = VIDEO_READER_BACKENDS["torchvision"](ele)
+
+ nframes, _, height, width = video.shape
+ min_pixels = ele.get("min_pixels", VIDEO_MIN_PIXELS)
+ total_pixels = ele.get("total_pixels", VIDEO_TOTAL_PIXELS)
+ max_pixels = max(min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05))
+ max_pixels_supposed = ele.get("max_pixels", max_pixels)
+ if max_pixels_supposed > max_pixels:
+ logger.warning(f"The given max_pixels[{max_pixels_supposed}] exceeds limit[{max_pixels}].")
+ max_pixels = min(max_pixels_supposed, max_pixels)
+ if "resized_height" in ele and "resized_width" in ele:
+ resized_height, resized_width = smart_resize(
+ ele["resized_height"],
+ ele["resized_width"],
+ factor=image_factor,
+ )
+ else:
+ resized_height, resized_width = smart_resize(
+ height,
+ width,
+ factor=image_factor,
+ min_pixels=min_pixels,
+ max_pixels=max_pixels,
+ )
+ video = transforms.functional.resize(
+ video,
+ [resized_height, resized_width],
+ interpolation=InterpolationMode.BICUBIC,
+ antialias=True,
+ ).float()
+ if return_video_sample_fps:
+ return video, sample_fps
+ return video
+ else:
+ assert isinstance(ele["video"], (list, tuple))
+ process_info = ele.copy()
+ process_info.pop("type", None)
+ process_info.pop("video", None)
+ images = [
+ fetch_image({"image": video_element, **process_info}, size_factor=image_factor)
+ for video_element in ele["video"]
+ ]
+ nframes = ceil_by_factor(len(images), FRAME_FACTOR)
+ if len(images) < nframes:
+ images.extend([images[-1]] * (nframes - len(images)))
+ if return_video_sample_fps:
+ return images, process_info.pop("fps", 2.0)
+ return images
+
+
+def extract_vision_info(conversations: list[dict] | list[list[dict]]) -> list[dict]:
+ vision_infos = []
+ if isinstance(conversations[0], dict):
+ conversations = [conversations]
+ for conversation in conversations:
+ for message in conversation:
+ if isinstance(message["content"], list):
+ for ele in message["content"]:
+ if (
+ "image" in ele
+ or "image_url" in ele
+ or "video" in ele
+ or ele["type"] in ("image", "image_url", "video")
+ ):
+ vision_infos.append(ele)
+ return vision_infos
+
+
+def process_vision_info(
+ conversations: list[dict] | list[list[dict]],
+ return_video_kwargs: bool = False,
+) -> tuple[list[Image.Image] | None, list[torch.Tensor | list[Image.Image]] | None, Optional[dict]]:
+
+ vision_infos = extract_vision_info(conversations)
+ ## Read images or videos
+ image_inputs = []
+ video_inputs = []
+ video_sample_fps_list = []
+ for vision_info in vision_infos:
+ if "image" in vision_info or "image_url" in vision_info:
+ image_inputs.append(fetch_image(vision_info))
+ elif "video" in vision_info:
+ video_input, video_sample_fps = fetch_video(vision_info, return_video_sample_fps=True)
+ video_sample_fps_list.append(video_sample_fps)
+ video_inputs.append(video_input)
+ else:
+ raise ValueError("image, image_url or video should in content.")
+ if len(image_inputs) == 0:
+ image_inputs = None
+ if len(video_inputs) == 0:
+ video_inputs = None
+ if return_video_kwargs:
+ return image_inputs, video_inputs, {'fps': video_sample_fps_list}
+ return image_inputs, video_inputs
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/modeling.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/modeling.py
new file mode 100644
index 0000000000000000000000000000000000000000..74ac9524f6ed306b8c50af039b8521ede9b82b60
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/modeling.py
@@ -0,0 +1,18 @@
+import os
+from typing import List
+
+import cv2
+import numpy as np
+import torch
+import torch.nn as nn
+from PIL import Image
+
+from .text_encoder import text_encoder
+from .vision_encoder import get_vision_encoder
+
+
+class VideoCLIP_XL(nn.Module):
+ def __init__(self):
+ super(VideoCLIP_XL, self).__init__()
+ self.text_model = text_encoder.load().float()
+ self.vision_model = get_vision_encoder().float()
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..381ad5a0cfd0197c41148165483c57042628b5ca
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/__init__.py
@@ -0,0 +1 @@
+from .text_encoder import *
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/bpe_simple_vocab_16e6.txt.gz b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/bpe_simple_vocab_16e6.txt.gz
new file mode 100644
index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/bpe_simple_vocab_16e6.txt.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
+size 1356917
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/model_text_encoder.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/model_text_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1215679814e6de5fb5cd05db4daf270a9449b3a
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/model_text_encoder.py
@@ -0,0 +1,395 @@
+from collections import OrderedDict
+from typing import Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+
+class Bottleneck(nn.Module):
+ expansion = 4
+
+ def __init__(self, inplanes, planes, stride=1):
+ super().__init__()
+
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
+ self.bn1 = nn.BatchNorm2d(planes)
+ self.relu1 = nn.ReLU(inplace=True)
+
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
+ self.bn2 = nn.BatchNorm2d(planes)
+ self.relu2 = nn.ReLU(inplace=True)
+
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
+
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
+ self.relu3 = nn.ReLU(inplace=True)
+
+ self.downsample = None
+ self.stride = stride
+
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
+ self.downsample = nn.Sequential(OrderedDict([
+ ("-1", nn.AvgPool2d(stride)),
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
+ ("1", nn.BatchNorm2d(planes * self.expansion))
+ ]))
+
+ def forward(self, x: torch.Tensor):
+ identity = x
+
+ out = self.relu1(self.bn1(self.conv1(x)))
+ out = self.relu2(self.bn2(self.conv2(out)))
+ out = self.avgpool(out)
+ out = self.bn3(self.conv3(out))
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+ out = self.relu3(out)
+ return out
+
+
+class AttentionPool2d(nn.Module):
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
+ super().__init__()
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
+ self.num_heads = num_heads
+
+ def forward(self, x):
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
+ x, _ = F.multi_head_attention_forward(
+ query=x[:1], key=x, value=x,
+ embed_dim_to_check=x.shape[-1],
+ num_heads=self.num_heads,
+ q_proj_weight=self.q_proj.weight,
+ k_proj_weight=self.k_proj.weight,
+ v_proj_weight=self.v_proj.weight,
+ in_proj_weight=None,
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
+ bias_k=None,
+ bias_v=None,
+ add_zero_attn=False,
+ dropout_p=0,
+ out_proj_weight=self.c_proj.weight,
+ out_proj_bias=self.c_proj.bias,
+ use_separate_proj_weight=True,
+ training=self.training,
+ need_weights=False
+ )
+ return x.squeeze(0)
+
+
+class ModifiedResNet(nn.Module):
+ """
+ A ResNet class that is similar to torchvision's but contains the following changes:
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
+ - The final pooling layer is a QKV attention instead of an average pool
+ """
+
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
+ super().__init__()
+ self.output_dim = output_dim
+ self.input_resolution = input_resolution
+
+ # the 3-layer stem
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
+ self.bn1 = nn.BatchNorm2d(width // 2)
+ self.relu1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
+ self.bn2 = nn.BatchNorm2d(width // 2)
+ self.relu2 = nn.ReLU(inplace=True)
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
+ self.bn3 = nn.BatchNorm2d(width)
+ self.relu3 = nn.ReLU(inplace=True)
+ self.avgpool = nn.AvgPool2d(2)
+
+ # residual layers
+ self._inplanes = width # this is a *mutable* variable used during construction
+ self.layer1 = self._make_layer(width, layers[0])
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
+
+ embed_dim = width * 32 # the ResNet feature dimension
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
+
+ def _make_layer(self, planes, blocks, stride=1):
+ layers = [Bottleneck(self._inplanes, planes, stride)]
+
+ self._inplanes = planes * Bottleneck.expansion
+ for _ in range(1, blocks):
+ layers.append(Bottleneck(self._inplanes, planes))
+
+ return nn.Sequential(*layers)
+
+ def forward(self, x):
+ def stem(x):
+ x = self.relu1(self.bn1(self.conv1(x)))
+ x = self.relu2(self.bn2(self.conv2(x)))
+ x = self.relu3(self.bn3(self.conv3(x)))
+ x = self.avgpool(x)
+ return x
+
+ x = x.type(self.conv1.weight.dtype)
+ x = stem(x)
+ x = self.layer1(x)
+ x = self.layer2(x)
+ x = self.layer3(x)
+ x = self.layer4(x)
+ x = self.attnpool(x)
+
+ return x
+
+
+class LayerNorm(nn.LayerNorm):
+ """Subclass torch's LayerNorm to handle fp16."""
+
+ def forward(self, x: torch.Tensor):
+ orig_type = x.dtype
+ ret = super().forward(x.type(torch.float32))
+ return ret.type(orig_type)
+
+
+class QuickGELU(nn.Module):
+ def forward(self, x: torch.Tensor):
+ return x * torch.sigmoid(1.702 * x)
+
+
+class ResidualAttentionBlock(nn.Module):
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
+ super().__init__()
+
+ self.attn = nn.MultiheadAttention(d_model, n_head)
+ self.ln_1 = LayerNorm(d_model)
+ self.mlp = nn.Sequential(OrderedDict([
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
+ ("gelu", QuickGELU()),
+ ("c_proj", nn.Linear(d_model * 4, d_model))
+ ]))
+ self.ln_2 = LayerNorm(d_model)
+ self.attn_mask = attn_mask
+
+ def attention(self, x: torch.Tensor):
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
+
+ def forward(self, x: torch.Tensor):
+ x = x + self.attention(self.ln_1(x))
+ x = x + self.mlp(self.ln_2(x))
+ return x
+
+
+class Transformer(nn.Module):
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
+ super().__init__()
+ self.width = width
+ self.layers = layers
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
+
+ def forward(self, x: torch.Tensor):
+ return self.resblocks(x)
+
+
+class VisionTransformer(nn.Module):
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
+ super().__init__()
+ self.input_resolution = input_resolution
+ self.output_dim = output_dim
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
+
+ scale = width ** -0.5
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
+ self.ln_pre = LayerNorm(width)
+
+ self.transformer = Transformer(width, layers, heads)
+
+ self.ln_post = LayerNorm(width)
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
+
+ def forward(self, x: torch.Tensor):
+ x = self.conv1(x) # shape = [*, width, grid, grid]
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
+ x = x + self.positional_embedding.to(x.dtype)
+ x = self.ln_pre(x)
+
+ x = x.permute(1, 0, 2) # NLD -> LND
+ x = self.transformer(x)
+ x = x.permute(1, 0, 2) # LND -> NLD
+
+ x = self.ln_post(x[:, 0, :])
+
+ if self.proj is not None:
+ x = x @ self.proj
+
+ return x
+
+
+class CLIP(nn.Module):
+ def __init__(self,
+ embed_dim: int,
+ # vision
+ image_resolution: int,
+ vision_layers: Union[Tuple[int, int, int, int], int],
+ vision_width: int,
+ vision_patch_size: int,
+ # text
+ context_length: int,
+ vocab_size: int,
+ transformer_width: int,
+ transformer_heads: int,
+ transformer_layers: int,
+ load_from_clip: bool
+ ):
+ super().__init__()
+
+ self.context_length = 248
+
+ self.transformer = Transformer(
+ width=transformer_width,
+ layers=transformer_layers,
+ heads=transformer_heads,
+ attn_mask=self.build_attention_mask()
+ )
+
+ self.vocab_size = vocab_size
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
+
+ if load_from_clip == False:
+ self.positional_embedding = nn.Parameter(torch.empty(248, transformer_width))
+ self.positional_embedding_res = nn.Parameter(torch.empty(248, transformer_width))
+
+ else:
+ self.positional_embedding = nn.Parameter(torch.empty(77, transformer_width))
+
+ self.ln_final = LayerNorm(transformer_width)
+
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
+
+ self.initialize_parameters()
+ self.mask1 = torch.zeros([248, 1])
+ self.mask1[:20, :] = 1
+ self.mask2 = torch.zeros([248, 1])
+ self.mask2[20:, :] = 1
+
+
+ def initialize_parameters(self):
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
+ nn.init.normal_(self.positional_embedding, std=0.01)
+
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
+ attn_std = self.transformer.width ** -0.5
+ fc_std = (2 * self.transformer.width) ** -0.5
+ for block in self.transformer.resblocks:
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
+
+ if self.text_projection is not None:
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
+
+ def build_attention_mask(self):
+ # lazily create causal attention mask, with full attention between the vision tokens
+ # pytorch uses additive attention mask; fill with -inf
+ mask = torch.empty(self.context_length, self.context_length)
+ mask.fill_(float("-inf"))
+ mask.triu_(1) # zero out the lower diagonal
+ return mask
+
+ @property
+ def dtype(self):
+ return self.token_embedding.weight.dtype
+
+ def encode_text(self, text):
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
+
+ x = x + (self.positional_embedding.to(x.device) * self.mask1.to(x.device)).type(self.dtype).to(x.device) + (self.positional_embedding_res.to(x.device) * self.mask2.to(x.device)).type(self.dtype).to(x.device)
+
+ x = x.permute(1, 0, 2) # NLD -> LND
+ x = self.transformer(x)
+ x = x.permute(1, 0, 2) # LND -> NLD
+ x = self.ln_final(x).type(self.dtype)
+
+ # x.shape = [batch_size, n_ctx, transformer.width]
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
+
+ return x
+
+ def encode_text_full(self, text):
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
+
+ x = x + (self.positional_embedding.to(x.device) * self.mask1.to(x.device)).type(self.dtype).to(x.device) + (self.positional_embedding_res.to(x.device) * self.mask2.to(x.device)).type(self.dtype).to(x.device)
+
+ x = x.permute(1, 0, 2) # NLD -> LND
+ x = self.transformer(x)
+ x = x.permute(1, 0, 2) # LND -> NLD
+ x = self.ln_final(x).type(self.dtype)
+
+ return x
+
+
+def convert_weights(model: nn.Module):
+ """Convert applicable model parameters to fp16"""
+
+ def _convert_weights_to_fp16(l):
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
+ l.weight.data = l.weight.data.half()
+ if l.bias is not None:
+ l.bias.data = l.bias.data.half()
+
+ if isinstance(l, nn.MultiheadAttention):
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
+ tensor = getattr(l, attr)
+ if tensor is not None:
+ tensor.data = tensor.data.half()
+
+ for name in ["text_projection", "proj"]:
+ if hasattr(l, name):
+ attr = getattr(l, name)
+ if attr is not None:
+ attr.data = attr.data.half()
+
+ model.apply(_convert_weights_to_fp16)
+
+
+def build_model(load_from_clip: bool):
+
+ vision_width = 1024
+ vision_layers = 24
+ vision_patch_size = 14
+ grid_size = 16
+ image_resolution = 224
+
+ embed_dim = 768
+ context_length = 248
+ vocab_size = 49408
+ transformer_width = 768
+ transformer_heads = 12
+ transformer_layers = 12
+
+ model = CLIP(
+ embed_dim,
+ image_resolution, vision_layers, vision_width, vision_patch_size,
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, load_from_clip
+ )
+
+ convert_weights(model)
+ return model.eval()
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/simple_tokenizer.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/simple_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a66286b7d5019c6e221932a813768038f839c91
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/simple_tokenizer.py
@@ -0,0 +1,132 @@
+import gzip
+import html
+import os
+from functools import lru_cache
+
+import ftfy
+import regex as re
+
+
+@lru_cache()
+def default_bpe():
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
+
+
+@lru_cache()
+def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
+ The reversible bpe codes work on unicode strings.
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
+ """
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
+ cs = bs[:]
+ n = 0
+ for b in range(2**8):
+ if b not in bs:
+ bs.append(b)
+ cs.append(2**8+n)
+ n += 1
+ cs = [chr(n) for n in cs]
+ return dict(zip(bs, cs))
+
+
+def get_pairs(word):
+ """Return set of symbol pairs in a word.
+ Word is represented as tuple of symbols (symbols being variable-length strings).
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+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
+
+
+class SimpleTokenizer(object):
+ def __init__(self, bpe_path: str = default_bpe()):
+ self.byte_encoder = bytes_to_unicode()
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
+ merges = merges[1:49152-256-2+1]
+ merges = [tuple(merge.split()) for merge in merges]
+ vocab = list(bytes_to_unicode().values())
+ vocab = vocab + [v+'' for v in vocab]
+ for merge in merges:
+ vocab.append(''.join(merge))
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
+ self.encoder = dict(zip(vocab, range(len(vocab))))
+ self.decoder = {v: k for k, v in self.encoder.items()}
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
+ self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
+
+ def bpe(self, token):
+ if token in self.cache:
+ return self.cache[token]
+ word = tuple(token[:-1]) + ( token[-1] + '',)
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token+''
+
+ while True:
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ new_word.extend(word[i:j])
+ i = j
+ except:
+ new_word.extend(word[i:])
+ break
+
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
+ new_word.append(first+second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = ' '.join(word)
+ self.cache[token] = word
+ return word
+
+ def encode(self, text):
+ bpe_tokens = []
+ text = whitespace_clean(basic_clean(text)).lower()
+ for token in re.findall(self.pat, text):
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
+ return bpe_tokens
+
+ def decode(self, tokens):
+ text = ''.join([self.decoder[token] for token in tokens])
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ')
+ return text
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/text_encoder.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/text_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..777cd8c507cb023d24c2a47439308c26a5e34c62
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/text_encoder/text_encoder.py
@@ -0,0 +1,75 @@
+import hashlib
+import os
+import urllib
+import warnings
+from typing import Any, Union, List
+from pkg_resources import packaging
+from torch import nn
+import torch
+from PIL import Image
+from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
+
+from .model_text_encoder import build_model
+from .simple_tokenizer import SimpleTokenizer as _Tokenizer
+
+try:
+ from torchvision.transforms import InterpolationMode
+ BICUBIC = InterpolationMode.BICUBIC
+except ImportError:
+ BICUBIC = Image.BICUBIC
+
+
+_tokenizer = _Tokenizer()
+
+
+def _convert_image_to_rgb(image):
+ return image.convert("RGB")
+
+
+def load():
+ model = build_model(load_from_clip = False)
+
+ return model
+
+
+def tokenize(texts: Union[str, List[str]], context_length: int = 77*4-60, truncate: bool = False) -> Union[torch.IntTensor, torch.LongTensor]:
+ """
+ Returns the tokenized representation of given input string(s)
+
+ Parameters
+ ----------
+ texts : Union[str, List[str]]
+ An input string or a list of input strings to tokenize
+
+ context_length : int
+ The context length to use; all CLIP models use 77 as the context length
+
+ truncate: bool
+ Whether to truncate the text in case its encoding is longer than the context length
+
+ Returns
+ -------
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
+ """
+ if isinstance(texts, str):
+ texts = [texts]
+
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
+ else:
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
+
+ for i, tokens in enumerate(all_tokens):
+ if len(tokens) > context_length:
+ if truncate:
+ tokens = tokens[:context_length]
+ tokens[-1] = eot_token
+ else:
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
+ result[i, :len(tokens)] = torch.tensor(tokens)
+
+ return result
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/__init__.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..585859a0cede3099a2f4f5ceb3da2f60e53271d1
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/__init__.py
@@ -0,0 +1,11 @@
+import torch
+import numpy as np
+import cv2
+import os
+
+from .model_vision_encoder import VisionEncoder
+
+def get_vision_encoder():
+ vision_encoder = VisionEncoder()
+
+ return vision_encoder
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/clip_vision.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/clip_vision.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc4802a1afcda4b6de21273768a064b39cc40e2
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/clip_vision.py
@@ -0,0 +1,327 @@
+#!/usr/bin/env python
+import os
+import logging
+from collections import OrderedDict
+
+import torch
+from torch import nn
+from einops import rearrange
+from timm.models.layers import DropPath
+from timm.models.registry import register_model
+
+import torch.utils.checkpoint as checkpoint
+
+logger = logging.getLogger(__name__)
+
+def load_temp_embed_with_mismatch(temp_embed_old, temp_embed_new, add_zero=True):
+ """
+ Add/Remove extra temporal_embeddings as needed.
+ https://arxiv.org/abs/2104.00650 shows adding zero paddings works.
+
+ temp_embed_old: (1, num_frames_old, 1, d)
+ temp_embed_new: (1, num_frames_new, 1, d)
+ add_zero: bool, if True, add zero, else, interpolate trained embeddings.
+ """
+ # TODO zero pad
+ num_frms_new = temp_embed_new.shape[1]
+ num_frms_old = temp_embed_old.shape[1]
+ logger.info(f"Load temporal_embeddings, lengths: {num_frms_old}-->{num_frms_new}")
+ if num_frms_new > num_frms_old:
+ if add_zero:
+ temp_embed_new[
+ :, :num_frms_old
+ ] = temp_embed_old # untrained embeddings are zeros.
+ else:
+ temp_embed_new = interpolate_temporal_pos_embed(temp_embed_old, num_frms_new)
+ elif num_frms_new < num_frms_old:
+ temp_embed_new = temp_embed_old[:, :num_frms_new]
+ else: # =
+ temp_embed_new = temp_embed_old
+ return temp_embed_new
+
+
+class QuickGELU(nn.Module):
+ def forward(self, x):
+ return x * torch.sigmoid(1.702 * x)
+
+
+class ResidualAttentionBlock(nn.Module):
+ def __init__(self, d_model, n_head, drop_path=0., attn_mask=None, dropout=0.):
+ super().__init__()
+
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
+ # logger.info(f'Droppath: {drop_path}')
+ self.attn = nn.MultiheadAttention(d_model, n_head, dropout=dropout)
+ self.ln_1 = nn.LayerNorm(d_model)
+ self.mlp = nn.Sequential(OrderedDict([
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
+ ("gelu", QuickGELU()),
+ ("drop1", nn.Dropout(dropout)),
+ ("c_proj", nn.Linear(d_model * 4, d_model)),
+ ("drop2", nn.Dropout(dropout)),
+ ]))
+ self.ln_2 = nn.LayerNorm(d_model)
+ self.attn_mask = attn_mask
+
+ def attention(self, x):
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
+
+ def forward(self, x):
+ x = x + self.drop_path1(self.attention(self.ln_1(x)))
+ x = x + self.drop_path2(self.mlp(self.ln_2(x)))
+ return x
+
+
+class Transformer(nn.Module):
+ def __init__(self, width, layers, heads, drop_path=0., checkpoint_num=0, dropout=0.):
+ super().__init__()
+ dpr = [x.item() for x in torch.linspace(0, drop_path, layers)]
+ self.resblocks = nn.ModuleList()
+ for idx in range(layers):
+ self.resblocks.append(ResidualAttentionBlock(width, heads, drop_path=dpr[idx], dropout=dropout))
+ self.checkpoint_num = checkpoint_num
+
+ def forward(self, x):
+ for idx, blk in enumerate(self.resblocks):
+ if idx < self.checkpoint_num:
+ x = checkpoint.checkpoint(blk, x)
+ else:
+ x = blk(x)
+ return x
+
+
+class VisionTransformer(nn.Module):
+ def __init__(
+ self, input_resolution, patch_size, width, layers, heads, output_dim=None,
+ kernel_size=1, num_frames=8, drop_path=0, checkpoint_num=0, dropout=0.,
+ temp_embed=True,
+ ):
+ super().__init__()
+ self.output_dim = output_dim
+ self.conv1 = nn.Conv3d(
+ 3, width,
+ (kernel_size, patch_size, patch_size),
+ (kernel_size, patch_size, patch_size),
+ (0, 0, 0), bias=False
+ )
+
+ scale = width ** -0.5
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
+ self.ln_pre = nn.LayerNorm(width)
+ if temp_embed:
+ self.temporal_positional_embedding = nn.Parameter(torch.zeros(1, num_frames, width))
+
+ self.transformer = Transformer(
+ width, layers, heads, drop_path=drop_path, checkpoint_num=checkpoint_num,
+ dropout=dropout)
+
+ self.ln_post = nn.LayerNorm(width)
+ if output_dim is not None:
+ self.proj = nn.Parameter(torch.empty(width, output_dim))
+ else:
+ self.proj = None
+
+ self.dropout = nn.Dropout(dropout)
+
+ def get_num_layers(self):
+ return len(self.transformer.resblocks)
+
+ @torch.jit.ignore
+ def no_weight_decay(self):
+ return {'positional_embedding', 'class_embedding', 'temporal_positional_embedding'}
+
+ def mask_tokens(self, inputs, masking_prob=0.0):
+ B, L, _ = inputs.shape
+
+ # This is different from text as we are masking a fix number of tokens
+ Lm = int(masking_prob * L)
+ masked_indices = torch.zeros(B, L)
+ indices = torch.argsort(torch.rand_like(masked_indices), dim=-1)[:, :Lm]
+ batch_indices = (
+ torch.arange(masked_indices.shape[0]).unsqueeze(-1).expand_as(indices)
+ )
+ masked_indices[batch_indices, indices] = 1
+
+ masked_indices = masked_indices.bool()
+
+ return inputs[~masked_indices].reshape(B, -1, inputs.shape[-1])
+
+ def forward(self, x, masking_prob=0.0):
+ x = self.conv1(x) # shape = [*, width, grid, grid]
+ B, C, T, H, W = x.shape
+ x = x.permute(0, 2, 3, 4, 1).reshape(B * T, H * W, C)
+
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
+ x = x + self.positional_embedding.to(x.dtype)
+
+ # temporal pos
+ cls_tokens = x[:B, :1, :]
+ x = x[:, 1:]
+ x = rearrange(x, '(b t) n m -> (b n) t m', b=B, t=T)
+ if hasattr(self, 'temporal_positional_embedding'):
+ if x.size(1) == 1:
+ # This is a workaround for unused parameter issue
+ x = x + self.temporal_positional_embedding.mean(1)
+ else:
+ x = x + self.temporal_positional_embedding
+ x = rearrange(x, '(b n) t m -> b (n t) m', b=B, t=T)
+
+ if masking_prob > 0.0:
+ x = self.mask_tokens(x, masking_prob)
+
+ x = torch.cat((cls_tokens, x), dim=1)
+
+ x = self.ln_pre(x)
+
+ x = x.permute(1, 0, 2) #BND -> NBD
+ x = self.transformer(x)
+
+ x = self.ln_post(x)
+
+ if self.proj is not None:
+ x = self.dropout(x[0]) @ self.proj
+ else:
+ x = x.permute(1, 0, 2) #NBD -> BND
+
+ return x
+
+
+def inflate_weight(weight_2d, time_dim, center=True):
+ logger.info(f'Init center: {center}')
+ if center:
+ weight_3d = torch.zeros(*weight_2d.shape)
+ weight_3d = weight_3d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
+ middle_idx = time_dim // 2
+ weight_3d[:, :, middle_idx, :, :] = weight_2d
+ else:
+ weight_3d = weight_2d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
+ weight_3d = weight_3d / time_dim
+ return weight_3d
+
+
+def load_state_dict(model, state_dict, input_resolution=224, patch_size=16, center=True):
+ state_dict_3d = model.state_dict()
+ for k in state_dict.keys():
+ if k in state_dict_3d.keys() and state_dict[k].shape != state_dict_3d[k].shape:
+ if len(state_dict_3d[k].shape) <= 2:
+ logger.info(f'Ignore: {k}')
+ continue
+ logger.info(f'Inflate: {k}, {state_dict[k].shape} => {state_dict_3d[k].shape}')
+ time_dim = state_dict_3d[k].shape[2]
+ state_dict[k] = inflate_weight(state_dict[k], time_dim, center=center)
+
+ pos_embed_checkpoint = state_dict['positional_embedding']
+ embedding_size = pos_embed_checkpoint.shape[-1]
+ num_patches = (input_resolution // patch_size) ** 2
+ orig_size = int((pos_embed_checkpoint.shape[-2] - 1) ** 0.5)
+ new_size = int(num_patches ** 0.5)
+ if orig_size != new_size:
+ logger.info(f'Pos_emb from {orig_size} to {new_size}')
+ extra_tokens = pos_embed_checkpoint[:1]
+ pos_tokens = pos_embed_checkpoint[1:]
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
+ pos_tokens = torch.nn.functional.interpolate(
+ pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False)
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(0, 2)
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=0)
+ state_dict['positional_embedding'] = new_pos_embed
+
+ message = model.load_state_dict(state_dict, strict=False)
+ logger.info(f"Load pretrained weights: {message}")
+
+
+@register_model
+def clip_joint_b16(
+ pretrained=False, input_resolution=224, kernel_size=1,
+ center=True, num_frames=8, drop_path=0., checkpoint_num=0,
+ dropout=0.,
+):
+ model = VisionTransformer(
+ input_resolution=input_resolution, patch_size=16,
+ width=768, layers=12, heads=12, output_dim=512,
+ kernel_size=kernel_size, num_frames=num_frames,
+ drop_path=drop_path, checkpoint_num=checkpoint_num,
+ dropout=dropout,
+ )
+ if pretrained:
+ if isinstance(pretrained, str):
+ model_name = pretrained
+ else:
+ model_name = "ViT-B/16"
+
+ logger.info('load pretrained weights')
+ state_dict = torch.load(_MODELS[model_name], map_location='cpu')
+ load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=16, center=center)
+ return model.eval()
+
+
+@register_model
+def clip_joint_l14(
+ pretrained=False, input_resolution=224, kernel_size=1,
+ center=True, num_frames=8, drop_path=0., checkpoint_num=0,
+ dropout=0.,
+):
+ model = VisionTransformer(
+ input_resolution=input_resolution, patch_size=14,
+ width=1024, layers=24, heads=16, output_dim=768,
+ kernel_size=kernel_size, num_frames=num_frames,
+ drop_path=drop_path, checkpoint_num=checkpoint_num,
+ dropout=dropout,
+ )
+
+ if pretrained:
+ if isinstance(pretrained, str):
+ model_name = pretrained
+ else:
+ model_name = "ViT-L/14"
+ logger.info('load pretrained weights')
+ state_dict = torch.load(_MODELS[model_name], map_location='cpu')
+ load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center)
+ return model.eval()
+
+
+@register_model
+def clip_joint_l14_336(
+ pretrained=True, input_resolution=336, kernel_size=1,
+ center=True, num_frames=8, drop_path=0.
+):
+ raise NotImplementedError
+ model = VisionTransformer(
+ input_resolution=input_resolution, patch_size=14,
+ width=1024, layers=24, heads=16, output_dim=768,
+ kernel_size=kernel_size, num_frames=num_frames,
+ drop_path=drop_path,
+ )
+ if pretrained:
+ logger.info('load pretrained weights')
+ state_dict = torch.load(_MODELS["ViT-L/14_336"], map_location='cpu')
+ load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center)
+ return model.eval()
+
+
+def interpolate_pos_embed_vit(state_dict, new_model):
+ key = "vision_encoder.temporal_positional_embedding"
+ if key in state_dict:
+ vision_temp_embed_new = new_model.state_dict()[key]
+ vision_temp_embed_new = vision_temp_embed_new.unsqueeze(2) # [1, n, d] -> [1, n, 1, d]
+ vision_temp_embed_old = state_dict[key]
+ vision_temp_embed_old = vision_temp_embed_old.unsqueeze(2)
+
+ state_dict[key] = load_temp_embed_with_mismatch(
+ vision_temp_embed_old, vision_temp_embed_new, add_zero=False
+ ).squeeze(2)
+
+ key = "text_encoder.positional_embedding"
+ if key in state_dict:
+ text_temp_embed_new = new_model.state_dict()[key]
+ text_temp_embed_new = text_temp_embed_new.unsqueeze(0).unsqueeze(2) # [n, d] -> [1, n, 1, d]
+ text_temp_embed_old = state_dict[key]
+ text_temp_embed_old = text_temp_embed_old.unsqueeze(0).unsqueeze(2)
+
+ state_dict[key] = load_temp_embed_with_mismatch(
+ text_temp_embed_old, text_temp_embed_new, add_zero=False
+ ).squeeze(2).squeeze(0)
+ return state_dict
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/model_vision_encoder.py b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/model_vision_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..480404f9ca8090e0c60f0717217dc0d3100bc969
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/compliance/videoclipxl_utils/vision_encoder/model_vision_encoder.py
@@ -0,0 +1,84 @@
+import os
+import logging
+import torch
+from torch import nn
+import math
+
+from .clip_vision import clip_joint_l14, clip_joint_b16
+
+logger = logging.getLogger(__name__)
+
+
+class VisionEncoder(nn.Module):
+
+ def __init__(self):
+ super(VisionEncoder, self).__init__()
+
+ self.vision_encoder_name = 'vit_l14'
+ self.vision_encoder_pretrained = False
+ self.inputs_image_res = 224
+ self.vision_encoder_kernel_size = 1
+ self.vision_encoder_center = True
+ self.video_input_num_frames = 8
+ self.vision_encoder_drop_path_rate = 0.1
+ self.vision_encoder_checkpoint_num = 24
+
+ self.vision_width = 1024
+ self.embed_dim = 768
+ self.masking_prob = 0.9
+
+ self.vision_encoder = self.build_vision_encoder()
+
+ self.temp = nn.parameter.Parameter(torch.ones([]) * 1 / 100.0)
+ self.temp_min = 1 / 100.0
+
+ def no_weight_decay(self):
+ ret = {"temp"}
+ ret.update(
+ {"vision_encoder." + k for k in self.vision_encoder.no_weight_decay()}
+ )
+
+ return ret
+
+
+ def encode_vision(self, image, test=False):
+ if image.ndim == 5:
+ image = image.permute(0, 2, 1, 3, 4).contiguous()
+ else:
+ image = image.unsqueeze(2)
+
+ if not test and self.masking_prob > 0.0:
+ return self.vision_encoder(
+ image, masking_prob=self.masking_prob
+ )
+
+ return self.vision_encoder(image)
+
+
+ @torch.no_grad()
+ def clip_contrastive_temperature(self, min_val=0.001, max_val=0.5):
+ """Seems only used during pre-training"""
+ self.temp.clamp_(min=self.temp_min)
+
+ def build_vision_encoder(self):
+ """build vision encoder
+ Returns: (vision_encoder, vision_layernorm). Each is a `nn.Module`.
+
+ """
+ vision_encoder = clip_joint_l14(
+ pretrained=self.vision_encoder_pretrained,
+ input_resolution=self.inputs_image_res,
+ kernel_size=self.vision_encoder_kernel_size,
+ center=self.vision_encoder_center,
+ num_frames=self.video_input_num_frames,
+ drop_path=self.vision_encoder_drop_path_rate,
+ checkpoint_num=self.vision_encoder_checkpoint_num,
+ )
+
+ return vision_encoder
+
+
+ def get_vid_features(self, input_frames):
+ clip_feat = self.encode_vision(input_frames, test=True).float()
+
+ return clip_feat
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/__init__.py b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/__init__.py
@@ -0,0 +1,5 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
diff --git a/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/blocks.py b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/blocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..55e44809347055151cbf70bae73f79eac10768cd
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/blocks.py
@@ -0,0 +1,438 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from functools import partial
+from typing import Callable
+import collections
+from torch import Tensor
+from itertools import repeat
+
+from fidelity.cotracker.models.core.model_utils import bilinear_sampler
+
+
+# From PyTorch internals
+def _ntuple(n):
+ def parse(x):
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
+ return tuple(x)
+ return tuple(repeat(x, n))
+
+ return parse
+
+
+def exists(val):
+ return val is not None
+
+
+def default(val, d):
+ return val if exists(val) else d
+
+
+to_2tuple = _ntuple(2)
+
+
+class Mlp(nn.Module):
+ """MLP as used in Vision Transformer, MLP-Mixer and related networks"""
+
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ norm_layer=None,
+ bias=True,
+ drop=0.0,
+ use_conv=False,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ bias = to_2tuple(bias)
+ drop_probs = to_2tuple(drop)
+ linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear
+
+ self.fc1 = linear_layer(in_features, hidden_features, bias=bias[0])
+ self.act = act_layer()
+ self.drop1 = nn.Dropout(drop_probs[0])
+ self.norm = (
+ norm_layer(hidden_features) if norm_layer is not None else nn.Identity()
+ )
+ self.fc2 = linear_layer(hidden_features, out_features, bias=bias[1])
+ self.drop2 = nn.Dropout(drop_probs[1])
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop1(x)
+ x = self.fc2(x)
+ x = self.drop2(x)
+ return x
+
+
+class ResidualBlock(nn.Module):
+ def __init__(self, in_planes, planes, norm_fn="group", stride=1):
+ super(ResidualBlock, self).__init__()
+
+ self.conv1 = nn.Conv2d(
+ in_planes,
+ planes,
+ kernel_size=3,
+ padding=1,
+ stride=stride,
+ padding_mode="zeros",
+ )
+ self.conv2 = nn.Conv2d(
+ planes, planes, kernel_size=3, padding=1, padding_mode="zeros"
+ )
+ self.relu = nn.ReLU(inplace=True)
+
+ num_groups = planes // 8
+
+ if norm_fn == "group":
+ self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+ self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+ if not stride == 1:
+ self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+
+ elif norm_fn == "batch":
+ self.norm1 = nn.BatchNorm2d(planes)
+ self.norm2 = nn.BatchNorm2d(planes)
+ if not stride == 1:
+ self.norm3 = nn.BatchNorm2d(planes)
+
+ elif norm_fn == "instance":
+ self.norm1 = nn.InstanceNorm2d(planes)
+ self.norm2 = nn.InstanceNorm2d(planes)
+ if not stride == 1:
+ self.norm3 = nn.InstanceNorm2d(planes)
+
+ elif norm_fn == "none":
+ self.norm1 = nn.Sequential()
+ self.norm2 = nn.Sequential()
+ if not stride == 1:
+ self.norm3 = nn.Sequential()
+
+ if stride == 1:
+ self.downsample = None
+
+ else:
+ self.downsample = nn.Sequential(
+ nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3
+ )
+
+ def forward(self, x):
+ y = x
+ y = self.relu(self.norm1(self.conv1(y)))
+ y = self.relu(self.norm2(self.conv2(y)))
+
+ if self.downsample is not None:
+ x = self.downsample(x)
+
+ return self.relu(x + y)
+
+
+class BasicEncoder(nn.Module):
+ def __init__(self, input_dim=3, output_dim=128, stride=4):
+ super(BasicEncoder, self).__init__()
+ self.stride = stride
+ self.norm_fn = "instance"
+ self.in_planes = output_dim // 2
+ self.norm1 = nn.InstanceNorm2d(self.in_planes)
+ self.norm2 = nn.InstanceNorm2d(output_dim * 2)
+
+ self.conv1 = nn.Conv2d(
+ input_dim,
+ self.in_planes,
+ kernel_size=7,
+ stride=2,
+ padding=3,
+ padding_mode="zeros",
+ )
+ self.relu1 = nn.ReLU(inplace=True)
+ self.layer1 = self._make_layer(output_dim // 2, stride=1)
+ self.layer2 = self._make_layer(output_dim // 4 * 3, stride=2)
+ self.layer3 = self._make_layer(output_dim, stride=2)
+ self.layer4 = self._make_layer(output_dim, stride=2)
+
+ self.conv2 = nn.Conv2d(
+ output_dim * 3 + output_dim // 4,
+ output_dim * 2,
+ kernel_size=3,
+ padding=1,
+ padding_mode="zeros",
+ )
+ self.relu2 = nn.ReLU(inplace=True)
+ self.conv3 = nn.Conv2d(output_dim * 2, output_dim, kernel_size=1)
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
+ elif isinstance(m, (nn.InstanceNorm2d)):
+ if m.weight is not None:
+ nn.init.constant_(m.weight, 1)
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ def _make_layer(self, dim, stride=1):
+ layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride)
+ layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1)
+ layers = (layer1, layer2)
+
+ self.in_planes = dim
+ return nn.Sequential(*layers)
+
+ def forward(self, x):
+ _, _, H, W = x.shape
+
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu1(x)
+
+ a = self.layer1(x)
+ b = self.layer2(a)
+ c = self.layer3(b)
+ d = self.layer4(c)
+
+ def _bilinear_intepolate(x):
+ return F.interpolate(
+ x,
+ (H // self.stride, W // self.stride),
+ mode="bilinear",
+ align_corners=True,
+ )
+
+ a = _bilinear_intepolate(a)
+ b = _bilinear_intepolate(b)
+ c = _bilinear_intepolate(c)
+ d = _bilinear_intepolate(d)
+
+ x = self.conv2(torch.cat([a, b, c, d], dim=1))
+ x = self.norm2(x)
+ x = self.relu2(x)
+ x = self.conv3(x)
+ return x
+
+
+class EfficientCorrBlock:
+ def __init__(
+ self,
+ fmaps,
+ num_levels=4,
+ radius=4,
+ padding_mode="zeros",
+ ):
+ B, S, C, H, W = fmaps.shape
+ self.padding_mode = padding_mode
+ self.num_levels = num_levels
+ self.radius = radius
+ self.fmaps_pyramid = []
+
+ self.fmaps_pyramid.append(fmaps)
+ for i in range(self.num_levels - 1):
+ fmaps_ = fmaps.reshape(B * S, C, H, W)
+ fmaps_ = F.avg_pool2d(fmaps_, 2, stride=2)
+ _, _, H, W = fmaps_.shape
+ fmaps = fmaps_.reshape(B, S, C, H, W)
+ self.fmaps_pyramid.append(fmaps)
+
+ def sample(self, coords, target):
+ r = self.radius
+ device = coords.device
+ B, S, N, D = coords.shape
+ assert D == 2
+
+ target = target.permute(0, 1, 3, 2).unsqueeze(-1)
+
+ out_pyramid = []
+ for i in range(self.num_levels):
+ pyramid = self.fmaps_pyramid[i]
+ C, H, W = pyramid.shape[2:]
+ centroid_lvl = (
+ torch.cat(
+ [torch.zeros_like(coords[..., :1], device=device), coords], dim=-1
+ ).reshape(B * S, N, 1, 1, 3)
+ / 2**i
+ )
+
+ dx = torch.linspace(-r, r, 2 * r + 1, device=device)
+ dy = torch.linspace(-r, r, 2 * r + 1, device=device)
+
+ xgrid, ygrid = torch.meshgrid(dy, dx, indexing="ij")
+ zgrid = torch.zeros_like(xgrid, device=device)
+ delta = torch.stack([zgrid, xgrid, ygrid], axis=-1)
+ delta_lvl = delta.view(1, 1, 2 * r + 1, 2 * r + 1, 3)
+ coords_lvl = centroid_lvl + delta_lvl
+ pyramid_sample = bilinear_sampler(
+ pyramid.reshape(B * S, C, 1, H, W), coords_lvl
+ )
+
+ corr = torch.sum(target * pyramid_sample.reshape(B, S, C, N, -1), dim=2)
+ corr = corr / torch.sqrt(torch.tensor(C).float())
+ out_pyramid.append(corr)
+
+ out = torch.cat(out_pyramid, dim=-1) # B, S, N, LRR*2
+ out = out.permute(0, 2, 1, 3).contiguous().view(B * N, S, -1).float()
+ return out
+
+
+class CorrBlock:
+ def __init__(
+ self,
+ fmaps,
+ num_levels=4,
+ radius=4,
+ multiple_track_feats=False,
+ padding_mode="zeros",
+ ):
+ B, S, C, H, W = fmaps.shape
+ self.S, self.C, self.H, self.W = S, C, H, W
+ self.padding_mode = padding_mode
+ self.num_levels = num_levels
+ self.radius = radius
+ self.fmaps_pyramid = []
+ self.multiple_track_feats = multiple_track_feats
+
+ self.fmaps_pyramid.append(fmaps)
+ for i in range(self.num_levels - 1):
+ fmaps_ = fmaps.reshape(B * S, C, H, W)
+ fmaps_ = F.avg_pool2d(fmaps_, 2, stride=2)
+ _, _, H, W = fmaps_.shape
+ fmaps = fmaps_.reshape(B, S, C, H, W)
+ self.fmaps_pyramid.append(fmaps)
+
+ def sample(self, coords):
+ r = self.radius
+ B, S, N, D = coords.shape
+ assert D == 2
+
+ H, W = self.H, self.W
+ out_pyramid = []
+ for i in range(self.num_levels):
+ corrs = self.corrs_pyramid[i] # B, S, N, H, W
+ *_, H, W = corrs.shape
+
+ dx = torch.linspace(-r, r, 2 * r + 1)
+ dy = torch.linspace(-r, r, 2 * r + 1)
+ delta = torch.stack(torch.meshgrid(dy, dx, indexing="ij"), axis=-1).to(
+ coords.device
+ )
+
+ centroid_lvl = coords.reshape(B * S * N, 1, 1, 2) / 2**i
+ delta_lvl = delta.view(1, 2 * r + 1, 2 * r + 1, 2)
+ coords_lvl = centroid_lvl + delta_lvl
+
+ corrs = bilinear_sampler(
+ corrs.reshape(B * S * N, 1, H, W),
+ coords_lvl,
+ padding_mode=self.padding_mode,
+ )
+ corrs = corrs.view(B, S, N, -1)
+ out_pyramid.append(corrs)
+
+ out = torch.cat(out_pyramid, dim=-1) # B, S, N, LRR*2
+ out = out.permute(0, 2, 1, 3).contiguous().view(B * N, S, -1).float()
+ return out
+
+ def corr(self, targets):
+ B, S, N, C = targets.shape
+ if self.multiple_track_feats:
+ targets_split = targets.split(C // self.num_levels, dim=-1)
+ B, S, N, C = targets_split[0].shape
+
+ assert C == self.C
+ assert S == self.S
+
+ fmap1 = targets
+
+ self.corrs_pyramid = []
+ for i, fmaps in enumerate(self.fmaps_pyramid):
+ *_, H, W = fmaps.shape
+ fmap2s = fmaps.view(B, S, C, H * W) # B S C H W -> B S C (H W)
+ if self.multiple_track_feats:
+ fmap1 = targets_split[i]
+ corrs = torch.matmul(fmap1, fmap2s)
+ corrs = corrs.view(B, S, N, H, W) # B S N (H W) -> B S N H W
+ corrs = corrs / torch.sqrt(torch.tensor(C).float())
+ self.corrs_pyramid.append(corrs)
+
+
+class Attention(nn.Module):
+ def __init__(
+ self, query_dim, context_dim=None, num_heads=8, dim_head=48, qkv_bias=False
+ ):
+ super().__init__()
+ inner_dim = dim_head * num_heads
+ context_dim = default(context_dim, query_dim)
+ self.scale = dim_head**-0.5
+ self.heads = num_heads
+
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=qkv_bias)
+ self.to_kv = nn.Linear(context_dim, inner_dim * 2, bias=qkv_bias)
+ self.to_out = nn.Linear(inner_dim, query_dim)
+
+ def forward(self, x, context=None, attn_bias=None):
+ B, N1, C = x.shape
+ h = self.heads
+
+ q = self.to_q(x).reshape(B, N1, h, C // h).permute(0, 2, 1, 3)
+ context = default(context, x)
+ k, v = self.to_kv(context).chunk(2, dim=-1)
+
+ N2 = context.shape[1]
+ k = k.reshape(B, N2, h, C // h).permute(0, 2, 1, 3)
+ v = v.reshape(B, N2, h, C // h).permute(0, 2, 1, 3)
+
+ sim = (q @ k.transpose(-2, -1)) * self.scale
+
+ if attn_bias is not None:
+ sim = sim + attn_bias
+ attn = sim.softmax(dim=-1)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N1, C)
+ return self.to_out(x)
+
+
+class AttnBlock(nn.Module):
+ def __init__(
+ self,
+ hidden_size,
+ num_heads,
+ attn_class: Callable[..., nn.Module] = Attention,
+ mlp_ratio=4.0,
+ **block_kwargs
+ ):
+ super().__init__()
+ self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.attn = attn_class(
+ hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs
+ )
+
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ approx_gelu = lambda: nn.GELU(approximate="tanh")
+ self.mlp = Mlp(
+ in_features=hidden_size,
+ hidden_features=mlp_hidden_dim,
+ act_layer=approx_gelu,
+ drop=0,
+ )
+
+ def forward(self, x, mask=None):
+ attn_bias = mask
+ if mask is not None:
+ mask = (
+ (mask[:, None] * mask[:, :, None])
+ .unsqueeze(1)
+ .expand(-1, self.attn.num_heads, -1, -1)
+ )
+ max_neg_value = -torch.finfo(x.dtype).max
+ attn_bias = (~mask) * max_neg_value
+ x = x + self.attn(self.norm1(x), attn_bias=attn_bias)
+ x = x + self.mlp(self.norm2(x))
+ return x
diff --git a/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker.py b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..18c85aa9f713245cf1653c7c68d930789e08b09a
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker.py
@@ -0,0 +1,577 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from fidelity.cotracker.models.core.model_utils import sample_features4d, sample_features5d
+from fidelity.cotracker.models.core.embeddings import (
+ get_2d_embedding,
+ get_1d_sincos_pos_embed_from_grid,
+ get_2d_sincos_pos_embed,
+)
+
+from fidelity.cotracker.models.core.cotracker.blocks import (
+ Mlp,
+ BasicEncoder,
+ AttnBlock,
+ CorrBlock,
+ Attention,
+)
+
+torch.manual_seed(0)
+
+
+class CoTracker2(nn.Module):
+ def __init__(
+ self,
+ window_len=8,
+ stride=4,
+ add_space_attn=True,
+ num_virtual_tracks=64,
+ model_resolution=(384, 512),
+ ):
+ super(CoTracker2, self).__init__()
+ self.window_len = window_len
+ self.stride = stride
+ self.hidden_dim = 256
+ self.latent_dim = 128
+ self.add_space_attn = add_space_attn
+ self.fnet = BasicEncoder(output_dim=self.latent_dim)
+ self.num_virtual_tracks = num_virtual_tracks
+ self.model_resolution = model_resolution
+ self.input_dim = 456
+ self.updateformer = EfficientUpdateFormer(
+ space_depth=6,
+ time_depth=6,
+ input_dim=self.input_dim,
+ hidden_size=384,
+ output_dim=self.latent_dim + 2,
+ mlp_ratio=4.0,
+ add_space_attn=add_space_attn,
+ num_virtual_tracks=num_virtual_tracks,
+ )
+
+ time_grid = torch.linspace(0, window_len - 1, window_len).reshape(
+ 1, window_len, 1
+ )
+
+ self.register_buffer(
+ "time_emb", get_1d_sincos_pos_embed_from_grid(self.input_dim, time_grid[0])
+ )
+
+ self.register_buffer(
+ "pos_emb",
+ get_2d_sincos_pos_embed(
+ embed_dim=self.input_dim,
+ grid_size=(
+ model_resolution[0] // stride,
+ model_resolution[1] // stride,
+ ),
+ ),
+ )
+ self.norm = nn.GroupNorm(1, self.latent_dim)
+ self.track_feat_updater = nn.Sequential(
+ nn.Linear(self.latent_dim, self.latent_dim),
+ nn.GELU(),
+ )
+ self.vis_predictor = nn.Sequential(
+ nn.Linear(self.latent_dim, 1),
+ )
+
+ def forward_window(
+ self,
+ fmaps,
+ coords,
+ track_feat=None,
+ vis=None,
+ track_mask=None,
+ attention_mask=None,
+ iters=4,
+ ):
+ # B = batch size
+ # S = number of frames in the window)
+ # N = number of tracks
+ # C = channels of a point feature vector
+ # E = positional embedding size
+ # LRR = local receptive field radius
+ # D = dimension of the transformer input tokens
+
+ # track_feat = B S N C
+ # vis = B S N 1
+ # track_mask = B S N 1
+ # attention_mask = B S N
+
+ B, S_init, N, __ = track_mask.shape
+ B, S, *_ = fmaps.shape
+
+ track_mask = F.pad(track_mask, (0, 0, 0, 0, 0, S - S_init), "constant")
+ track_mask_vis = (
+ torch.cat([track_mask, vis], dim=-1)
+ .permute(0, 2, 1, 3)
+ .reshape(B * N, S, 2)
+ )
+
+ corr_block = CorrBlock(
+ fmaps,
+ num_levels=4,
+ radius=3,
+ padding_mode="border",
+ )
+
+ sampled_pos_emb = (
+ sample_features4d(self.pos_emb.repeat(B, 1, 1, 1), coords[:, 0])
+ .reshape(B * N, self.input_dim)
+ .unsqueeze(1)
+ ) # B E N -> (B N) 1 E
+
+ coord_preds = []
+ for __ in range(iters):
+ coords = coords.detach() # B S N 2
+ corr_block.corr(track_feat)
+
+ # Sample correlation features around each point
+ fcorrs = corr_block.sample(coords) # (B N) S LRR
+
+ # Get the flow embeddings
+ flows = (coords - coords[:, 0:1]).permute(0, 2, 1, 3).reshape(B * N, S, 2)
+ flow_emb = get_2d_embedding(flows, 64, cat_coords=True) # N S E
+
+ track_feat_ = track_feat.permute(0, 2, 1, 3).reshape(
+ B * N, S, self.latent_dim
+ )
+
+ transformer_input = torch.cat(
+ [flow_emb, fcorrs, track_feat_, track_mask_vis], dim=2
+ )
+ x = transformer_input + sampled_pos_emb + self.time_emb
+ x = x.view(B, N, S, -1) # (B N) S D -> B N S D
+
+ delta = self.updateformer(
+ x,
+ attention_mask.reshape(B * S, N), # B S N -> (B S) N
+ )
+
+ delta_coords = delta[..., :2].permute(0, 2, 1, 3)
+ coords = coords + delta_coords
+ coord_preds.append(coords * self.stride)
+
+ delta_feats_ = delta[..., 2:].reshape(B * N * S, self.latent_dim)
+ track_feat_ = track_feat.permute(0, 2, 1, 3).reshape(
+ B * N * S, self.latent_dim
+ )
+ track_feat_ = self.track_feat_updater(self.norm(delta_feats_)) + track_feat_
+ track_feat = track_feat_.reshape(B, N, S, self.latent_dim).permute(
+ 0, 2, 1, 3
+ ) # (B N S) C -> B S N C
+
+ vis_pred = self.vis_predictor(track_feat).reshape(B, S, N)
+ return coord_preds, vis_pred
+
+ def get_track_feat(self, fmaps, queried_frames, queried_coords):
+ sample_frames = queried_frames[:, None, :, None]
+ sample_coords = torch.cat(
+ [
+ sample_frames,
+ queried_coords[:, None],
+ ],
+ dim=-1,
+ )
+ sample_track_feats = sample_features5d(fmaps, sample_coords)
+ return sample_track_feats
+
+ def init_video_online_processing(self):
+ self.online_ind = 0
+ self.online_track_feat = None
+ self.online_coords_predicted = None
+ self.online_vis_predicted = None
+
+ def forward(self, video, queries, iters=4, is_train=False, is_online=False):
+ """Predict tracks
+
+ Args:
+ video (FloatTensor[B, T, 3]): input videos.
+ queries (FloatTensor[B, N, 3]): point queries.
+ iters (int, optional): number of updates. Defaults to 4.
+ is_train (bool, optional): enables training mode. Defaults to False.
+ is_online (bool, optional): enables online mode. Defaults to False. Before enabling, call model.init_video_online_processing().
+
+ Returns:
+ - coords_predicted (FloatTensor[B, T, N, 2]):
+ - vis_predicted (FloatTensor[B, T, N]):
+ - train_data: `None` if `is_train` is false, otherwise:
+ - all_vis_predictions (List[FloatTensor[B, S, N, 1]]):
+ - all_coords_predictions (List[FloatTensor[B, S, N, 2]]):
+ - mask (BoolTensor[B, T, N]):
+ """
+ B, T, C, H, W = video.shape
+ B, N, __ = queries.shape
+ S = self.window_len
+ device = queries.device
+
+ # B = batch size
+ # S = number of frames in the window of the padded video
+ # S_trimmed = actual number of frames in the window
+ # N = number of tracks
+ # C = color channels (3 for RGB)
+ # E = positional embedding size
+ # LRR = local receptive field radius
+ # D = dimension of the transformer input tokens
+
+ # video = B T C H W
+ # queries = B N 3
+ # coords_init = B S N 2
+ # vis_init = B S N 1
+
+ assert S >= 2 # A tracker needs at least two frames to track something
+ if is_online:
+ assert T <= S, "Online mode: video chunk must be <= window size."
+ assert (
+ self.online_ind is not None
+ ), "Call model.init_video_online_processing() first."
+ assert not is_train, "Training not supported in online mode."
+ step = S // 2 # How much the sliding window moves at every step
+ video = 2 * (video / 255.0) - 1.0
+
+ # The first channel is the frame number
+ # The rest are the coordinates of points we want to track
+ queried_frames = queries[:, :, 0].long()
+
+ queried_coords = queries[..., 1:]
+ queried_coords = queried_coords / self.stride
+
+ # We store our predictions here
+ coords_predicted = torch.zeros((B, T, N, 2), device=device)
+ vis_predicted = torch.zeros((B, T, N), device=device)
+ if is_online:
+ if self.online_coords_predicted is None:
+ # Init online predictions with zeros
+ self.online_coords_predicted = coords_predicted
+ self.online_vis_predicted = vis_predicted
+ else:
+ # Pad online predictions with zeros for the current window
+ pad = min(step, T - step)
+ coords_predicted = F.pad(
+ self.online_coords_predicted, (0, 0, 0, 0, 0, pad), "constant"
+ )
+ vis_predicted = F.pad(
+ self.online_vis_predicted, (0, 0, 0, pad), "constant"
+ )
+ all_coords_predictions, all_vis_predictions = [], []
+
+ # Pad the video so that an integer number of sliding windows fit into it
+ # TODO: we may drop this requirement because the transformer should not care
+ # TODO: pad the features instead of the video
+ pad = (
+ S - T if is_online else (S - T % S) % S
+ ) # We don't want to pad if T % S == 0
+ video = video.reshape(B, 1, T, C * H * W)
+ video_pad = video[:, :, -1:].repeat(1, 1, pad, 1)
+ video = torch.cat([video, video_pad], dim=2)
+
+ # Compute convolutional features for the video or for the current chunk in case of online mode
+ fmaps = self.fnet(video.reshape(-1, C, H, W)).reshape(
+ B, -1, self.latent_dim, H // self.stride, W // self.stride
+ )
+
+ # We compute track features
+ track_feat = self.get_track_feat(
+ fmaps,
+ queried_frames - self.online_ind if is_online else queried_frames,
+ queried_coords,
+ ).repeat(1, S, 1, 1)
+ if is_online:
+ # We update track features for the current window
+ sample_frames = queried_frames[:, None, :, None] # B 1 N 1
+ left = 0 if self.online_ind == 0 else self.online_ind + step
+ right = self.online_ind + S
+ sample_mask = (sample_frames >= left) & (sample_frames < right)
+ if self.online_track_feat is None:
+ self.online_track_feat = torch.zeros_like(track_feat, device=device)
+ self.online_track_feat += track_feat * sample_mask
+ track_feat = self.online_track_feat.clone()
+ # We process ((num_windows - 1) * step + S) frames in total, so there are
+ # (ceil((T - S) / step) + 1) windows
+ num_windows = (T - S + step - 1) // step + 1
+ # We process only the current video chunk in the online mode
+ indices = [self.online_ind] if is_online else range(0, step * num_windows, step)
+
+ coords_init = queried_coords.reshape(B, 1, N, 2).expand(B, S, N, 2).float()
+ vis_init = torch.ones((B, S, N, 1), device=device).float() * 10
+ for ind in indices:
+ # We copy over coords and vis for tracks that are queried
+ # by the end of the previous window, which is ind + overlap
+ if ind > 0:
+ overlap = S - step
+ copy_over = (queried_frames < ind + overlap)[
+ :, None, :, None
+ ] # B 1 N 1
+ coords_prev = torch.nn.functional.pad(
+ coords_predicted[:, ind : ind + overlap] / self.stride,
+ (0, 0, 0, 0, 0, step),
+ "replicate",
+ ) # B S N 2
+ vis_prev = torch.nn.functional.pad(
+ vis_predicted[:, ind : ind + overlap, :, None].clone(),
+ (0, 0, 0, 0, 0, step),
+ "replicate",
+ ) # B S N 1
+ coords_init = torch.where(
+ copy_over.expand_as(coords_init), coords_prev, coords_init
+ )
+ vis_init = torch.where(
+ copy_over.expand_as(vis_init), vis_prev, vis_init
+ )
+
+ # The attention mask is 1 for the spatio-temporal points within
+ # a track which is updated in the current window
+ attention_mask = (
+ (queried_frames < ind + S).reshape(B, 1, N).repeat(1, S, 1)
+ ) # B S N
+
+ # The track mask is 1 for the spatio-temporal points that actually
+ # need updating: only after begin queried, and not if contained
+ # in a previous window
+ track_mask = (
+ queried_frames[:, None, :, None]
+ <= torch.arange(ind, ind + S, device=device)[None, :, None, None]
+ ).contiguous() # B S N 1
+
+ if ind > 0:
+ track_mask[:, :overlap, :, :] = False
+
+ # Predict the coordinates and visibility for the current window
+ coords, vis = self.forward_window(
+ fmaps=fmaps if is_online else fmaps[:, ind : ind + S],
+ coords=coords_init,
+ track_feat=attention_mask.unsqueeze(-1) * track_feat,
+ vis=vis_init,
+ track_mask=track_mask,
+ attention_mask=attention_mask,
+ iters=iters,
+ )
+
+ S_trimmed = (
+ T if is_online else min(T - ind, S)
+ ) # accounts for last window duration
+ coords_predicted[:, ind : ind + S] = coords[-1][:, :S_trimmed]
+ vis_predicted[:, ind : ind + S] = vis[:, :S_trimmed]
+ if is_train:
+ all_coords_predictions.append(
+ [coord[:, :S_trimmed] for coord in coords]
+ )
+ all_vis_predictions.append(torch.sigmoid(vis[:, :S_trimmed]))
+
+ if is_online:
+ self.online_ind += step
+ self.online_coords_predicted = coords_predicted
+ self.online_vis_predicted = vis_predicted
+ vis_predicted = torch.sigmoid(vis_predicted)
+
+ if is_train:
+ mask = (
+ queried_frames[:, None]
+ <= torch.arange(0, T, device=device)[None, :, None]
+ )
+ train_data = (all_coords_predictions, all_vis_predictions, mask)
+ else:
+ train_data = None
+
+ return coords_predicted, vis_predicted, train_data
+
+
+class EfficientUpdateFormer(nn.Module):
+ """
+ Transformer model that updates track estimates.
+ """
+
+ def __init__(
+ self,
+ space_depth=6,
+ time_depth=6,
+ input_dim=320,
+ hidden_size=384,
+ num_heads=8,
+ output_dim=130,
+ mlp_ratio=4.0,
+ num_virtual_tracks=64,
+ add_space_attn=True,
+ linear_layer_for_vis_conf=False,
+ ):
+ super().__init__()
+ self.out_channels = 2
+ self.num_heads = num_heads
+ self.hidden_size = hidden_size
+ self.input_transform = torch.nn.Linear(input_dim, hidden_size, bias=True)
+ if linear_layer_for_vis_conf:
+ self.flow_head = torch.nn.Linear(hidden_size, output_dim - 2, bias=True)
+ self.vis_conf_head = torch.nn.Linear(hidden_size, 2, bias=True)
+ else:
+ self.flow_head = torch.nn.Linear(hidden_size, output_dim, bias=True)
+ self.num_virtual_tracks = num_virtual_tracks
+ self.virual_tracks = nn.Parameter(
+ torch.randn(1, num_virtual_tracks, 1, hidden_size)
+ )
+ self.add_space_attn = add_space_attn
+ self.linear_layer_for_vis_conf = linear_layer_for_vis_conf
+ self.time_blocks = nn.ModuleList(
+ [
+ AttnBlock(
+ hidden_size,
+ num_heads,
+ mlp_ratio=mlp_ratio,
+ attn_class=Attention,
+ )
+ for _ in range(time_depth)
+ ]
+ )
+
+ if add_space_attn:
+ self.space_virtual_blocks = nn.ModuleList(
+ [
+ AttnBlock(
+ hidden_size,
+ num_heads,
+ mlp_ratio=mlp_ratio,
+ attn_class=Attention,
+ )
+ for _ in range(space_depth)
+ ]
+ )
+ self.space_point2virtual_blocks = nn.ModuleList(
+ [
+ CrossAttnBlock(
+ hidden_size, hidden_size, num_heads, mlp_ratio=mlp_ratio
+ )
+ for _ in range(space_depth)
+ ]
+ )
+ self.space_virtual2point_blocks = nn.ModuleList(
+ [
+ CrossAttnBlock(
+ hidden_size, hidden_size, num_heads, mlp_ratio=mlp_ratio
+ )
+ for _ in range(space_depth)
+ ]
+ )
+ assert len(self.time_blocks) >= len(self.space_virtual2point_blocks)
+ self.initialize_weights()
+
+ def initialize_weights(self):
+ def _basic_init(module):
+ if isinstance(module, nn.Linear):
+ torch.nn.init.xavier_uniform_(module.weight)
+ if module.bias is not None:
+ nn.init.constant_(module.bias, 0)
+ torch.nn.init.trunc_normal_(self.flow_head.weight, std=0.001)
+ if self.linear_layer_for_vis_conf:
+ torch.nn.init.trunc_normal_(self.vis_conf_head.weight, std=0.001)
+
+ def _trunc_init(module):
+ """ViT weight initialization, original timm impl (for reproducibility)"""
+ if isinstance(module, nn.Linear):
+ torch.nn.init.trunc_normal_(module.weight, std=0.02)
+ if module.bias is not None:
+ nn.init.zeros_(module.bias)
+
+ self.apply(_basic_init)
+
+ def forward(self, input_tensor, mask=None, add_space_attn=True):
+ tokens = self.input_transform(input_tensor)
+
+ B, _, T, _ = tokens.shape
+ virtual_tokens = self.virual_tracks.repeat(B, 1, T, 1)
+ tokens = torch.cat([tokens, virtual_tokens], dim=1)
+
+ _, N, _, _ = tokens.shape
+ j = 0
+ layers = []
+ for i in range(len(self.time_blocks)):
+ time_tokens = tokens.contiguous().view(B * N, T, -1) # B N T C -> (B N) T C
+ time_tokens = self.time_blocks[i](time_tokens)
+
+ tokens = time_tokens.view(B, N, T, -1) # (B N) T C -> B N T C
+ if (
+ add_space_attn
+ and hasattr(self, "space_virtual_blocks")
+ and (i % (len(self.time_blocks) // len(self.space_virtual_blocks)) == 0)
+ ):
+ space_tokens = (
+ tokens.permute(0, 2, 1, 3).contiguous().view(B * T, N, -1)
+ ) # B N T C -> (B T) N C
+
+ point_tokens = space_tokens[:, : N - self.num_virtual_tracks]
+ virtual_tokens = space_tokens[:, N - self.num_virtual_tracks :]
+
+ virtual_tokens = self.space_virtual2point_blocks[j](
+ virtual_tokens, point_tokens, mask=mask
+ )
+
+ virtual_tokens = self.space_virtual_blocks[j](virtual_tokens)
+ point_tokens = self.space_point2virtual_blocks[j](
+ point_tokens, virtual_tokens, mask=mask
+ )
+
+ space_tokens = torch.cat([point_tokens, virtual_tokens], dim=1)
+ tokens = space_tokens.view(B, T, N, -1).permute(
+ 0, 2, 1, 3
+ ) # (B T) N C -> B N T C
+ j += 1
+ tokens = tokens[:, : N - self.num_virtual_tracks]
+
+ flow = self.flow_head(tokens)
+ if self.linear_layer_for_vis_conf:
+ vis_conf = self.vis_conf_head(tokens)
+ flow = torch.cat([flow, vis_conf], dim=-1)
+
+ return flow
+
+
+class CrossAttnBlock(nn.Module):
+ def __init__(
+ self, hidden_size, context_dim, num_heads=1, mlp_ratio=4.0, **block_kwargs
+ ):
+ super().__init__()
+ self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.norm_context = nn.LayerNorm(hidden_size)
+ self.cross_attn = Attention(
+ hidden_size,
+ context_dim=context_dim,
+ num_heads=num_heads,
+ qkv_bias=True,
+ **block_kwargs
+ )
+
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ approx_gelu = lambda: nn.GELU(approximate="tanh")
+ self.mlp = Mlp(
+ in_features=hidden_size,
+ hidden_features=mlp_hidden_dim,
+ act_layer=approx_gelu,
+ drop=0,
+ )
+
+ def forward(self, x, context, mask=None):
+ attn_bias = None
+ if mask is not None:
+ if mask.shape[1] == x.shape[1]:
+ mask = mask[:, None, :, None].expand(
+ -1, self.cross_attn.heads, -1, context.shape[1]
+ )
+ else:
+ mask = mask[:, None, None].expand(
+ -1, self.cross_attn.heads, x.shape[1], -1
+ )
+
+ max_neg_value = -torch.finfo(x.dtype).max
+ attn_bias = (~mask) * max_neg_value
+ x = x + self.cross_attn(
+ self.norm1(x), context=self.norm_context(context), attn_bias=attn_bias
+ )
+ x = x + self.mlp(self.norm2(x))
+ return x
diff --git a/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker3_offline.py b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker3_offline.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aac06f3d28f7ca2f9cf1564bac2d873d12fa5cd
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker3_offline.py
@@ -0,0 +1,233 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from fidelity.cotracker.models.core.cotracker.cotracker3_online import CoTrackerThreeBase, posenc
+
+torch.manual_seed(0)
+
+
+class CoTrackerThreeOffline(CoTrackerThreeBase):
+ def __init__(self, **args):
+ super(CoTrackerThreeOffline, self).__init__(**args)
+
+ def forward(
+ self,
+ video,
+ queries,
+ iters=4,
+ is_train=False,
+ add_space_attn=True,
+ fmaps_chunk_size=200,
+ ):
+ """Predict tracks
+
+ Args:
+ video (FloatTensor[B, T, 3]): input videos.
+ queries (FloatTensor[B, N, 3]): point queries.
+ iters (int, optional): number of updates. Defaults to 4.
+ is_train (bool, optional): enables training mode. Defaults to False.
+ Returns:
+ - coords_predicted (FloatTensor[B, T, N, 2]):
+ - vis_predicted (FloatTensor[B, T, N]):
+ - train_data: `None` if `is_train` is false, otherwise:
+ - all_vis_predictions (List[FloatTensor[B, S, N, 1]]):
+ - all_coords_predictions (List[FloatTensor[B, S, N, 2]]):
+ - mask (BoolTensor[B, T, N]):
+ """
+
+ B, T, C, H, W = video.shape
+ device = queries.device
+ assert H % self.stride == 0 and W % self.stride == 0
+
+ B, N, __ = queries.shape
+ # B = batch size
+ # S_trimmed = actual number of frames in the window
+ # N = number of tracks
+ # C = color channels (3 for RGB)
+ # E = positional embedding size
+ # LRR = local receptive field radius
+ # D = dimension of the transformer input tokens
+
+ # video = B T C H W
+ # queries = B N 3
+ # coords_init = B T N 2
+ # vis_init = B T N 1
+
+ assert T >= 1 # A tracker needs at least two frames to track something
+
+ video = 2 * (video / 255.0) - 1.0
+ dtype = video.dtype
+ queried_frames = queries[:, :, 0].long()
+
+ queried_coords = queries[..., 1:3]
+ queried_coords = queried_coords / self.stride
+
+ # We store our predictions here
+ all_coords_predictions, all_vis_predictions, all_confidence_predictions = (
+ [],
+ [],
+ [],
+ )
+ C_ = C
+ H4, W4 = H // self.stride, W // self.stride
+ # Compute convolutional features for the video or for the current chunk in case of online mode
+
+ if T > fmaps_chunk_size:
+ fmaps = []
+ for t in range(0, T, fmaps_chunk_size):
+ video_chunk = video[:, t : t + fmaps_chunk_size]
+ fmaps_chunk = self.fnet(video_chunk.reshape(-1, C_, H, W))
+ T_chunk = video_chunk.shape[1]
+ C_chunk, H_chunk, W_chunk = fmaps_chunk.shape[1:]
+ fmaps.append(fmaps_chunk.reshape(B, T_chunk, C_chunk, H_chunk, W_chunk))
+ fmaps = torch.cat(fmaps, dim=1).reshape(-1, C_chunk, H_chunk, W_chunk)
+ else:
+ fmaps = self.fnet(video.reshape(-1, C_, H, W))
+ fmaps = fmaps.permute(0, 2, 3, 1)
+ fmaps = fmaps / torch.sqrt(
+ torch.maximum(
+ torch.sum(torch.square(fmaps), axis=-1, keepdims=True),
+ torch.tensor(1e-12, device=fmaps.device),
+ )
+ )
+ fmaps = fmaps.permute(0, 3, 1, 2).reshape(
+ B, -1, self.latent_dim, H // self.stride, W // self.stride
+ )
+ fmaps = fmaps.to(dtype)
+
+ # We compute track features
+ fmaps_pyramid = []
+ track_feat_pyramid = []
+ track_feat_support_pyramid = []
+ fmaps_pyramid.append(fmaps)
+ for i in range(self.corr_levels - 1):
+ fmaps_ = fmaps.reshape(
+ B * T, self.latent_dim, fmaps.shape[-2], fmaps.shape[-1]
+ )
+ fmaps_ = F.avg_pool2d(fmaps_, 2, stride=2)
+ fmaps = fmaps_.reshape(
+ B, T, self.latent_dim, fmaps_.shape[-2], fmaps_.shape[-1]
+ )
+ fmaps_pyramid.append(fmaps)
+
+ for i in range(self.corr_levels):
+ track_feat, track_feat_support = self.get_track_feat(
+ fmaps_pyramid[i],
+ queried_frames,
+ queried_coords / 2**i,
+ support_radius=self.corr_radius,
+ )
+ track_feat_pyramid.append(track_feat.repeat(1, T, 1, 1))
+ track_feat_support_pyramid.append(track_feat_support.unsqueeze(1))
+
+ D_coords = 2
+
+ coord_preds, vis_preds, confidence_preds = [], [], []
+
+ vis = torch.zeros((B, T, N), device=device).float()
+ confidence = torch.zeros((B, T, N), device=device).float()
+ coords = queried_coords.reshape(B, 1, N, 2).expand(B, T, N, 2).float()
+
+ r = 2 * self.corr_radius + 1
+
+ for it in range(iters):
+ coords = coords.detach() # B T N 2
+ coords_init = coords.view(B * T, N, 2)
+ corr_embs = []
+ corr_feats = []
+ for i in range(self.corr_levels):
+ corr_feat = self.get_correlation_feat(
+ fmaps_pyramid[i], coords_init / 2**i
+ )
+ track_feat_support = (
+ track_feat_support_pyramid[i]
+ .view(B, 1, r, r, N, self.latent_dim)
+ .squeeze(1)
+ .permute(0, 3, 1, 2, 4)
+ )
+ corr_volume = torch.einsum(
+ "btnhwc,bnijc->btnhwij", corr_feat, track_feat_support
+ )
+ corr_emb = self.corr_mlp(corr_volume.reshape(B * T * N, r * r * r * r))
+ corr_embs.append(corr_emb)
+ corr_embs = torch.cat(corr_embs, dim=-1)
+ corr_embs = corr_embs.view(B, T, N, corr_embs.shape[-1])
+
+ transformer_input = [vis[..., None], confidence[..., None], corr_embs]
+
+ rel_coords_forward = coords[:, :-1] - coords[:, 1:]
+ rel_coords_backward = coords[:, 1:] - coords[:, :-1]
+
+ rel_coords_forward = torch.nn.functional.pad(
+ rel_coords_forward, (0, 0, 0, 0, 0, 1)
+ )
+ rel_coords_backward = torch.nn.functional.pad(
+ rel_coords_backward, (0, 0, 0, 0, 1, 0)
+ )
+ scale = (
+ torch.tensor(
+ [self.model_resolution[1], self.model_resolution[0]],
+ device=coords.device,
+ )
+ / self.stride
+ )
+ rel_coords_forward = rel_coords_forward / scale
+ rel_coords_backward = rel_coords_backward / scale
+
+ rel_pos_emb_input = posenc(
+ torch.cat([rel_coords_forward, rel_coords_backward], dim=-1),
+ min_deg=0,
+ max_deg=10,
+ ) # batch, num_points, num_frames, 84
+ transformer_input.append(rel_pos_emb_input)
+
+ x = (
+ torch.cat(transformer_input, dim=-1)
+ .permute(0, 2, 1, 3)
+ .reshape(B * N, T, -1)
+ )
+
+ x = x + self.interpolate_time_embed(x, T)
+ x = x.view(B, N, T, -1) # (B N) T D -> B N T D
+
+ delta = self.updateformer(
+ x,
+ add_space_attn=add_space_attn,
+ )
+
+ delta_coords = delta[..., :D_coords].permute(0, 2, 1, 3)
+ delta_vis = delta[..., D_coords].permute(0, 2, 1)
+ delta_confidence = delta[..., D_coords + 1].permute(0, 2, 1)
+
+ vis = vis + delta_vis
+ confidence = confidence + delta_confidence
+
+ coords = coords + delta_coords
+ coords_append = coords.clone()
+ coords_append[..., :2] = coords_append[..., :2] * float(self.stride)
+ coord_preds.append(coords_append)
+ vis_preds.append(torch.sigmoid(vis))
+ confidence_preds.append(torch.sigmoid(confidence))
+
+ if is_train:
+ all_coords_predictions.append([coord[..., :2] for coord in coord_preds])
+ all_vis_predictions.append(vis_preds)
+ all_confidence_predictions.append(confidence_preds)
+
+ if is_train:
+ train_data = (
+ all_coords_predictions,
+ all_vis_predictions,
+ all_confidence_predictions,
+ torch.ones_like(vis_preds[-1], device=vis_preds[-1].device),
+ )
+ else:
+ train_data = None
+
+ return coord_preds[-1][..., :2], vis_preds[-1], confidence_preds[-1], train_data
diff --git a/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker3_online.py b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker3_online.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c3b2e72229a87b0c17e835529677ecbf5c9789e
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/cotracker3_online.py
@@ -0,0 +1,541 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from fidelity.cotracker.models.core.model_utils import sample_features5d, bilinear_sampler
+from fidelity.cotracker.models.core.embeddings import get_1d_sincos_pos_embed_from_grid
+
+from fidelity.cotracker.models.core.cotracker.blocks import Mlp, BasicEncoder
+from fidelity.cotracker.models.core.cotracker.cotracker import EfficientUpdateFormer
+
+torch.manual_seed(0)
+
+
+def posenc(x, min_deg, max_deg):
+ """Cat x with a positional encoding of x with scales 2^[min_deg, max_deg-1].
+ Instead of computing [sin(x), cos(x)], we use the trig identity
+ cos(x) = sin(x + pi/2) and do one vectorized call to sin([x, x+pi/2]).
+ Args:
+ x: torch.Tensor, variables to be encoded. Note that x should be in [-pi, pi].
+ min_deg: int, the minimum (inclusive) degree of the encoding.
+ max_deg: int, the maximum (exclusive) degree of the encoding.
+ legacy_posenc_order: bool, keep the same ordering as the original tf code.
+ Returns:
+ encoded: torch.Tensor, encoded variables.
+ """
+ if min_deg == max_deg:
+ return x
+ scales = torch.tensor(
+ [2**i for i in range(min_deg, max_deg)], dtype=x.dtype, device=x.device
+ )
+
+ xb = (x[..., None, :] * scales[:, None]).reshape(list(x.shape[:-1]) + [-1])
+ four_feat = torch.sin(torch.cat([xb, xb + 0.5 * torch.pi], dim=-1))
+ return torch.cat([x] + [four_feat], dim=-1)
+
+
+class CoTrackerThreeBase(nn.Module):
+ def __init__(
+ self,
+ window_len=8,
+ stride=4,
+ corr_radius=3,
+ corr_levels=4,
+ num_virtual_tracks=64,
+ model_resolution=(384, 512),
+ add_space_attn=True,
+ linear_layer_for_vis_conf=True,
+ ):
+ super(CoTrackerThreeBase, self).__init__()
+ self.window_len = window_len
+ self.stride = stride
+ self.corr_radius = corr_radius
+ self.corr_levels = corr_levels
+ self.hidden_dim = 256
+ self.latent_dim = 128
+
+ self.linear_layer_for_vis_conf = linear_layer_for_vis_conf
+ self.fnet = BasicEncoder(input_dim=3, output_dim=self.latent_dim, stride=stride)
+
+ highres_dim = 128
+ lowres_dim = 256
+
+ self.num_virtual_tracks = num_virtual_tracks
+ self.model_resolution = model_resolution
+
+ self.input_dim = 1110
+
+ self.updateformer = EfficientUpdateFormer(
+ space_depth=3,
+ time_depth=3,
+ input_dim=self.input_dim,
+ hidden_size=384,
+ output_dim=4,
+ mlp_ratio=4.0,
+ num_virtual_tracks=num_virtual_tracks,
+ add_space_attn=add_space_attn,
+ linear_layer_for_vis_conf=linear_layer_for_vis_conf,
+ )
+ self.corr_mlp = Mlp(in_features=49 * 49, hidden_features=384, out_features=256)
+
+ time_grid = torch.linspace(0, window_len - 1, window_len).reshape(
+ 1, window_len, 1
+ )
+
+ self.register_buffer(
+ "time_emb", get_1d_sincos_pos_embed_from_grid(self.input_dim, time_grid[0])
+ )
+
+ def get_support_points(self, coords, r, reshape_back=True):
+ B, _, N, _ = coords.shape
+ device = coords.device
+ centroid_lvl = coords.reshape(B, N, 1, 1, 3)
+
+ dx = torch.linspace(-r, r, 2 * r + 1, device=device)
+ dy = torch.linspace(-r, r, 2 * r + 1, device=device)
+
+ xgrid, ygrid = torch.meshgrid(dy, dx, indexing="ij")
+ zgrid = torch.zeros_like(xgrid, device=device)
+ delta = torch.stack([zgrid, xgrid, ygrid], axis=-1)
+ delta_lvl = delta.view(1, 1, 2 * r + 1, 2 * r + 1, 3)
+ coords_lvl = centroid_lvl + delta_lvl
+
+ if reshape_back:
+ return coords_lvl.reshape(B, N, (2 * r + 1) ** 2, 3).permute(0, 2, 1, 3)
+ else:
+ return coords_lvl
+
+ def get_track_feat(self, fmaps, queried_frames, queried_coords, support_radius=0):
+
+ sample_frames = queried_frames[:, None, :, None]
+ sample_coords = torch.cat(
+ [
+ sample_frames,
+ queried_coords[:, None],
+ ],
+ dim=-1,
+ )
+ support_points = self.get_support_points(sample_coords, support_radius)
+ support_track_feats = sample_features5d(fmaps, support_points)
+ return (
+ support_track_feats[:, None, support_track_feats.shape[1] // 2],
+ support_track_feats,
+ )
+
+ def get_correlation_feat(self, fmaps, queried_coords):
+ B, T, D, H_, W_ = fmaps.shape
+ N = queried_coords.shape[1]
+ r = self.corr_radius
+ sample_coords = torch.cat(
+ [torch.zeros_like(queried_coords[..., :1]), queried_coords], dim=-1
+ )[:, None]
+ support_points = self.get_support_points(sample_coords, r, reshape_back=False)
+ correlation_feat = bilinear_sampler(
+ fmaps.reshape(B * T, D, 1, H_, W_), support_points
+ )
+ return correlation_feat.view(B, T, D, N, (2 * r + 1), (2 * r + 1)).permute(
+ 0, 1, 3, 4, 5, 2
+ )
+
+ def interpolate_time_embed(self, x, t):
+ previous_dtype = x.dtype
+ T = self.time_emb.shape[1]
+
+ if t == T:
+ return self.time_emb
+
+ time_emb = self.time_emb.float()
+ time_emb = F.interpolate(
+ time_emb.permute(0, 2, 1), size=t, mode="linear"
+ ).permute(0, 2, 1)
+ return time_emb.to(previous_dtype)
+
+
+class CoTrackerThreeOnline(CoTrackerThreeBase):
+ def __init__(self, **args):
+ super(CoTrackerThreeOnline, self).__init__(**args)
+
+ def init_video_online_processing(self):
+ self.online_ind = 0
+ self.online_track_feat = [None] * self.corr_levels
+ self.online_track_support = [None] * self.corr_levels
+ self.online_coords_predicted = None
+ self.online_vis_predicted = None
+ self.online_conf_predicted = None
+
+ def forward_window(
+ self,
+ fmaps_pyramid,
+ coords,
+ track_feat_support_pyramid,
+ vis=None,
+ conf=None,
+ attention_mask=None,
+ iters=4,
+ add_space_attn=False,
+ ):
+ B, S, *_ = fmaps_pyramid[0].shape
+ N = coords.shape[2]
+ r = 2 * self.corr_radius + 1
+
+ coord_preds, vis_preds, conf_preds = [], [], []
+ for it in range(iters):
+ coords = coords.detach() # B T N 2
+ coords_init = coords.view(B * S, N, 2)
+ corr_embs = []
+ corr_feats = []
+ for i in range(self.corr_levels):
+ corr_feat = self.get_correlation_feat(
+ fmaps_pyramid[i], coords_init / 2**i
+ )
+ track_feat_support = (
+ track_feat_support_pyramid[i]
+ .view(B, 1, r, r, N, self.latent_dim)
+ .squeeze(1)
+ .permute(0, 3, 1, 2, 4)
+ )
+ corr_volume = torch.einsum(
+ "btnhwc,bnijc->btnhwij", corr_feat, track_feat_support
+ )
+ corr_emb = self.corr_mlp(corr_volume.reshape(B * S * N, r * r * r * r))
+
+ corr_embs.append(corr_emb)
+
+ corr_embs = torch.cat(corr_embs, dim=-1)
+ corr_embs = corr_embs.view(B, S, N, corr_embs.shape[-1])
+
+ transformer_input = [vis, conf, corr_embs]
+
+ rel_coords_forward = coords[:, :-1] - coords[:, 1:]
+ rel_coords_backward = coords[:, 1:] - coords[:, :-1]
+
+ rel_coords_forward = torch.nn.functional.pad(
+ rel_coords_forward, (0, 0, 0, 0, 0, 1)
+ )
+ rel_coords_backward = torch.nn.functional.pad(
+ rel_coords_backward, (0, 0, 0, 0, 1, 0)
+ )
+
+ scale = (
+ torch.tensor(
+ [self.model_resolution[1], self.model_resolution[0]],
+ device=coords.device,
+ )
+ / self.stride
+ )
+ rel_coords_forward = rel_coords_forward / scale
+ rel_coords_backward = rel_coords_backward / scale
+
+ rel_pos_emb_input = posenc(
+ torch.cat([rel_coords_forward, rel_coords_backward], dim=-1),
+ min_deg=0,
+ max_deg=10,
+ ) # batch, num_points, num_frames, 84
+ transformer_input.append(rel_pos_emb_input)
+
+ x = (
+ torch.cat(transformer_input, dim=-1)
+ .permute(0, 2, 1, 3)
+ .reshape(B * N, S, -1)
+ )
+
+ x = x + self.interpolate_time_embed(x, S)
+ x = x.view(B, N, S, -1) # (B N) T D -> B N T D
+
+ delta = self.updateformer(x, add_space_attn=add_space_attn)
+
+ delta_coords = delta[..., :2].permute(0, 2, 1, 3)
+ delta_vis = delta[..., 2:3].permute(0, 2, 1, 3)
+ delta_conf = delta[..., 3:].permute(0, 2, 1, 3)
+
+ vis = vis + delta_vis
+ conf = conf + delta_conf
+
+ coords = coords + delta_coords
+ coord_preds.append(coords[..., :2] * float(self.stride))
+
+ vis_preds.append(vis[..., 0])
+ conf_preds.append(conf[..., 0])
+ return coord_preds, vis_preds, conf_preds
+
+ def forward(
+ self,
+ video,
+ queries,
+ iters=4,
+ is_train=False,
+ add_space_attn=True,
+ fmaps_chunk_size=200,
+ is_online=False,
+ ):
+ """Predict tracks
+
+ Args:
+ video (FloatTensor[B, T, 3]): input videos.
+ queries (FloatTensor[B, N, 3]): point queries.
+ iters (int, optional): number of updates. Defaults to 4.
+ is_train (bool, optional): enables training mode. Defaults to False.
+ Returns:
+ - coords_predicted (FloatTensor[B, T, N, 2]):
+ - vis_predicted (FloatTensor[B, T, N]):
+ - train_data: `None` if `is_train` is false, otherwise:
+ - all_vis_predictions (List[FloatTensor[B, S, N, 1]]):
+ - all_coords_predictions (List[FloatTensor[B, S, N, 2]]):
+ - mask (BoolTensor[B, T, N]):
+ """
+
+ B, T, C, H, W = video.shape
+ device = queries.device
+ assert H % self.stride == 0 and W % self.stride == 0
+
+ B, N, __ = queries.shape
+ # B = batch size
+ # S_trimmed = actual number of frames in the window
+ # N = number of tracks
+ # C = color channels (3 for RGB)
+ # E = positional embedding size
+ # LRR = local receptive field radius
+ # D = dimension of the transformer input tokens
+
+ # video = B T C H W
+ # queries = B N 3
+ # coords_init = B T N 2
+ # vis_init = B T N 1
+ S = self.window_len
+ assert S >= 2 # A tracker needs at least two frames to track something
+ if is_online:
+ assert T <= S, "Online mode: video chunk must be <= window size."
+ assert (
+ self.online_ind is not None
+ ), "Call model.init_video_online_processing() first."
+ assert not is_train, "Training not supported in online mode."
+
+ step = S // 2 # How much the sliding window moves at every step
+
+ video = 2 * (video / 255.0) - 1.0
+ pad = (
+ S - T if is_online else (S - T % S) % S
+ ) # We don't want to pad if T % S == 0
+ video = video.reshape(B, 1, T, C * H * W)
+ if pad > 0:
+ padding_tensor = video[:, :, -1:, :].expand(B, 1, pad, C * H * W)
+ video = torch.cat([video, padding_tensor], dim=2)
+ video = video.reshape(B, -1, C, H, W)
+ T_pad = video.shape[1]
+ # The first channel is the frame number
+ # The rest are the coordinates of points we want to track
+ dtype = video.dtype
+ queried_frames = queries[:, :, 0].long()
+
+ queried_coords = queries[..., 1:3]
+ queried_coords = queried_coords / self.stride
+
+ # We store our predictions here
+ coords_predicted = torch.zeros((B, T, N, 2), device=device)
+ vis_predicted = torch.zeros((B, T, N), device=device)
+ conf_predicted = torch.zeros((B, T, N), device=device)
+
+ if is_online:
+ if self.online_coords_predicted is None:
+ # Init online predictions with zeros
+ self.online_coords_predicted = coords_predicted
+ self.online_vis_predicted = vis_predicted
+ self.online_conf_predicted = conf_predicted
+ else:
+ # Pad online predictions with zeros for the current window
+ pad = min(step, T - step)
+ coords_predicted = F.pad(
+ self.online_coords_predicted, (0, 0, 0, 0, 0, pad), "constant"
+ )
+ vis_predicted = F.pad(
+ self.online_vis_predicted, (0, 0, 0, pad), "constant"
+ )
+ conf_predicted = F.pad(
+ self.online_conf_predicted, (0, 0, 0, pad), "constant"
+ )
+
+ # We store our predictions here
+ all_coords_predictions, all_vis_predictions, all_confidence_predictions = (
+ [],
+ [],
+ [],
+ )
+
+ C_ = C
+ H4, W4 = H // self.stride, W // self.stride
+
+ # Compute convolutional features for the video or for the current chunk in case of online mode
+ if (not is_train) and (T > fmaps_chunk_size):
+ fmaps = []
+ for t in range(0, T, fmaps_chunk_size):
+ video_chunk = video[:, t : t + fmaps_chunk_size]
+ fmaps_chunk = self.fnet(video_chunk.reshape(-1, C_, H, W))
+ T_chunk = video_chunk.shape[1]
+ C_chunk, H_chunk, W_chunk = fmaps_chunk.shape[1:]
+ fmaps.append(fmaps_chunk.reshape(B, T_chunk, C_chunk, H_chunk, W_chunk))
+ fmaps = torch.cat(fmaps, dim=1).reshape(-1, C_chunk, H_chunk, W_chunk)
+ else:
+ fmaps = self.fnet(video.reshape(-1, C_, H, W))
+ fmaps = fmaps.permute(0, 2, 3, 1)
+ fmaps = fmaps / torch.sqrt(
+ torch.maximum(
+ torch.sum(torch.square(fmaps), axis=-1, keepdims=True),
+ torch.tensor(1e-12, device=fmaps.device),
+ )
+ )
+ fmaps = fmaps.permute(0, 3, 1, 2).reshape(
+ B, -1, self.latent_dim, H // self.stride, W // self.stride
+ )
+ fmaps = fmaps.to(dtype)
+
+ # We compute track features
+ fmaps_pyramid = []
+ track_feat_pyramid = []
+ track_feat_support_pyramid = []
+ fmaps_pyramid.append(fmaps)
+ for i in range(self.corr_levels - 1):
+ fmaps_ = fmaps.reshape(
+ B * T_pad, self.latent_dim, fmaps.shape[-2], fmaps.shape[-1]
+ )
+ fmaps_ = F.avg_pool2d(fmaps_, 2, stride=2)
+ fmaps = fmaps_.reshape(
+ B, T_pad, self.latent_dim, fmaps_.shape[-2], fmaps_.shape[-1]
+ )
+ fmaps_pyramid.append(fmaps)
+ if is_online:
+ sample_frames = queried_frames[:, None, :, None] # B 1 N 1
+ left = 0 if self.online_ind == 0 else self.online_ind + step
+ right = self.online_ind + S
+ sample_mask = (sample_frames >= left) & (sample_frames < right)
+
+ for i in range(self.corr_levels):
+ track_feat, track_feat_support = self.get_track_feat(
+ fmaps_pyramid[i],
+ queried_frames - self.online_ind if is_online else queried_frames,
+ queried_coords / 2**i,
+ support_radius=self.corr_radius,
+ )
+
+ if is_online:
+ if self.online_track_feat[i] is None:
+ self.online_track_feat[i] = torch.zeros_like(
+ track_feat, device=device
+ )
+ self.online_track_support[i] = torch.zeros_like(
+ track_feat_support, device=device
+ )
+
+ self.online_track_feat[i] += track_feat * sample_mask
+ self.online_track_support[i] += track_feat_support * sample_mask
+ track_feat_pyramid.append(
+ self.online_track_feat[i].repeat(1, T_pad, 1, 1)
+ )
+ track_feat_support_pyramid.append(
+ self.online_track_support[i].unsqueeze(1)
+ )
+ else:
+ track_feat_pyramid.append(track_feat.repeat(1, T_pad, 1, 1))
+ track_feat_support_pyramid.append(track_feat_support.unsqueeze(1))
+
+ D_coords = 2
+ coord_preds, vis_preds, confidence_preds = [], [], []
+
+ vis_init = torch.zeros((B, S, N, 1), device=device).float()
+ conf_init = torch.zeros((B, S, N, 1), device=device).float()
+ coords_init = queried_coords.reshape(B, 1, N, 2).expand(B, S, N, 2).float()
+
+ num_windows = (T - S + step - 1) // step + 1
+ # We process only the current video chunk in the online mode
+ indices = [self.online_ind] if is_online else range(0, step * num_windows, step)
+
+ for ind in indices:
+ if ind > 0:
+ overlap = S - step
+ copy_over = (queried_frames < ind + overlap)[
+ :, None, :, None
+ ] # B 1 N 1
+ coords_prev = coords_predicted[:, ind : ind + overlap] / self.stride
+ padding_tensor = coords_prev[:, -1:, :, :].expand(-1, step, -1, -1)
+ coords_prev = torch.cat([coords_prev, padding_tensor], dim=1)
+
+ vis_prev = vis_predicted[:, ind : ind + overlap, :, None].clone()
+ padding_tensor = vis_prev[:, -1:, :, :].expand(-1, step, -1, -1)
+ vis_prev = torch.cat([vis_prev, padding_tensor], dim=1)
+
+ conf_prev = conf_predicted[:, ind : ind + overlap, :, None].clone()
+ padding_tensor = conf_prev[:, -1:, :, :].expand(-1, step, -1, -1)
+ conf_prev = torch.cat([conf_prev, padding_tensor], dim=1)
+
+ coords_init = torch.where(
+ copy_over.expand_as(coords_init), coords_prev, coords_init
+ )
+ vis_init = torch.where(
+ copy_over.expand_as(vis_init), vis_prev, vis_init
+ )
+ conf_init = torch.where(
+ copy_over.expand_as(conf_init), conf_prev, conf_init
+ )
+
+ attention_mask = (queried_frames < ind + S).reshape(B, 1, N) # B S N
+ # import ipdb; ipdb.set_trace()
+ coords, viss, confs = self.forward_window(
+ fmaps_pyramid=(
+ fmaps_pyramid
+ if is_online
+ else [fmap[:, ind : ind + S] for fmap in fmaps_pyramid]
+ ),
+ coords=coords_init,
+ track_feat_support_pyramid=[
+ attention_mask[:, None, :, :, None] * tfeat
+ for tfeat in track_feat_support_pyramid
+ ],
+ vis=vis_init,
+ conf=conf_init,
+ attention_mask=attention_mask.repeat(1, S, 1),
+ iters=iters,
+ add_space_attn=add_space_attn,
+ )
+ S_trimmed = (
+ T if is_online else min(T - ind, S)
+ ) # accounts for last window duration
+ coords_predicted[:, ind : ind + S] = coords[-1][:, :S_trimmed]
+ vis_predicted[:, ind : ind + S] = viss[-1][:, :S_trimmed]
+ conf_predicted[:, ind : ind + S] = confs[-1][:, :S_trimmed]
+ if is_train:
+ all_coords_predictions.append(
+ [coord[:, :S_trimmed] for coord in coords]
+ )
+ all_vis_predictions.append(
+ [torch.sigmoid(vis[:, :S_trimmed]) for vis in viss]
+ )
+ all_confidence_predictions.append(
+ [torch.sigmoid(conf[:, :S_trimmed]) for conf in confs]
+ )
+ if is_online:
+ self.online_ind += step
+ self.online_coords_predicted = coords_predicted
+ self.online_vis_predicted = vis_predicted
+ self.online_conf_predicted = conf_predicted
+ vis_predicted = torch.sigmoid(vis_predicted)
+ conf_predicted = torch.sigmoid(conf_predicted)
+
+ if is_train:
+ valid_mask = (
+ queried_frames[:, None]
+ <= torch.arange(0, T, device=device)[None, :, None]
+ )
+ train_data = (
+ all_coords_predictions,
+ all_vis_predictions,
+ all_confidence_predictions,
+ valid_mask,
+ )
+ else:
+ train_data = None
+
+ return coords_predicted, vis_predicted, conf_predicted, train_data
diff --git a/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/losses.py b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/losses.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9286ec8951404fb20c509cfd6ee08b0a32ab66d
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/cotracker/losses.py
@@ -0,0 +1,118 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn.functional as F
+from cotracker.models.core.model_utils import reduce_masked_mean
+import torch.nn as nn
+from typing import List
+
+
+def sequence_loss(
+ flow_preds,
+ flow_gt,
+ valids,
+ vis=None,
+ gamma=0.8,
+ add_huber_loss=False,
+ loss_only_for_visible=False,
+):
+ """Loss function defined over sequence of flow predictions"""
+ total_flow_loss = 0.0
+ for j in range(len(flow_gt)):
+ B, S, N, D = flow_gt[j].shape
+ B, S2, N = valids[j].shape
+ assert S == S2
+ n_predictions = len(flow_preds[j])
+ flow_loss = 0.0
+ for i in range(n_predictions):
+ i_weight = gamma ** (n_predictions - i - 1)
+ flow_pred = flow_preds[j][i]
+ if add_huber_loss:
+ i_loss = huber_loss(flow_pred, flow_gt[j], delta=6.0)
+ else:
+ i_loss = (flow_pred - flow_gt[j]).abs() # B, S, N, 2
+ i_loss = torch.mean(i_loss, dim=3) # B, S, N
+ valid_ = valids[j].clone()
+ if loss_only_for_visible:
+ valid_ = valid_ * vis[j]
+ flow_loss += i_weight * reduce_masked_mean(i_loss, valid_)
+ flow_loss = flow_loss / n_predictions
+ total_flow_loss += flow_loss
+ return total_flow_loss / len(flow_gt)
+
+
+def huber_loss(x, y, delta=1.0):
+ """Calculate element-wise Huber loss between x and y"""
+ diff = x - y
+ abs_diff = diff.abs()
+ flag = (abs_diff <= delta).float()
+ return flag * 0.5 * diff**2 + (1 - flag) * delta * (abs_diff - 0.5 * delta)
+
+
+def sequence_BCE_loss(vis_preds, vis_gts):
+ total_bce_loss = 0.0
+ for j in range(len(vis_preds)):
+ n_predictions = len(vis_preds[j])
+ bce_loss = 0.0
+ for i in range(n_predictions):
+ vis_loss = F.binary_cross_entropy(vis_preds[j][i], vis_gts[j])
+ bce_loss += vis_loss
+ bce_loss = bce_loss / n_predictions
+ total_bce_loss += bce_loss
+ return total_bce_loss / len(vis_preds)
+
+
+def sequence_prob_loss(
+ tracks: torch.Tensor,
+ confidence: torch.Tensor,
+ target_points: torch.Tensor,
+ visibility: torch.Tensor,
+ expected_dist_thresh: float = 12.0,
+):
+ """Loss for classifying if a point is within pixel threshold of its target."""
+ # Points with an error larger than 12 pixels are likely to be useless; marking
+ # them as occluded will actually improve Jaccard metrics and give
+ # qualitatively better results.
+ total_logprob_loss = 0.0
+ for j in range(len(tracks)):
+ n_predictions = len(tracks[j])
+ logprob_loss = 0.0
+ for i in range(n_predictions):
+ err = torch.sum((tracks[j][i].detach() - target_points[j]) ** 2, dim=-1)
+ valid = (err <= expected_dist_thresh**2).float()
+ logprob = F.binary_cross_entropy(confidence[j][i], valid, reduction="none")
+ logprob *= visibility[j]
+ logprob = torch.mean(logprob, dim=[1, 2])
+ logprob_loss += logprob
+ logprob_loss = logprob_loss / n_predictions
+ total_logprob_loss += logprob_loss
+ return total_logprob_loss / len(tracks)
+
+
+def masked_mean(data: torch.Tensor, mask: torch.Tensor | None, dim: List[int]):
+ if mask is None:
+ return data.mean(dim=dim, keepdim=True)
+ mask = mask.float()
+ mask_sum = torch.sum(mask, dim=dim, keepdim=True)
+ mask_mean = torch.sum(data * mask, dim=dim, keepdim=True) / torch.clamp(
+ mask_sum, min=1.0
+ )
+ return mask_mean
+
+
+def masked_mean_var(data: torch.Tensor, mask: torch.Tensor, dim: List[int]):
+ if mask is None:
+ return data.mean(dim=dim, keepdim=True), data.var(dim=dim, keepdim=True)
+ mask = mask.float()
+ mask_sum = torch.sum(mask, dim=dim, keepdim=True)
+ mask_mean = torch.sum(data * mask, dim=dim, keepdim=True) / torch.clamp(
+ mask_sum, min=1.0
+ )
+ mask_var = torch.sum(
+ mask * (data - mask_mean) ** 2, dim=dim, keepdim=True
+ ) / torch.clamp(mask_sum, min=1.0)
+ return mask_mean.squeeze(dim), mask_var.squeeze(dim)
diff --git a/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/embeddings.py b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/embeddings.py
new file mode 100644
index 0000000000000000000000000000000000000000..897cd5d9f41121a9692281a719a2d24914293318
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/fidelity/cotracker/models/core/embeddings.py
@@ -0,0 +1,120 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+from typing import Tuple, Union
+import torch
+
+
+def get_2d_sincos_pos_embed(
+ embed_dim: int, grid_size: Union[int, Tuple[int, int]]
+) -> torch.Tensor:
+ """
+ This function initializes a grid and generates a 2D positional embedding using sine and cosine functions.
+ It is a wrapper of get_2d_sincos_pos_embed_from_grid.
+ Args:
+ - embed_dim: The embedding dimension.
+ - grid_size: The grid size.
+ Returns:
+ - pos_embed: The generated 2D positional embedding.
+ """
+ if isinstance(grid_size, tuple):
+ grid_size_h, grid_size_w = grid_size
+ else:
+ grid_size_h = grid_size_w = grid_size
+ grid_h = torch.arange(grid_size_h, dtype=torch.float)
+ grid_w = torch.arange(grid_size_w, dtype=torch.float)
+ grid = torch.meshgrid(grid_w, grid_h, indexing="xy")
+ grid = torch.stack(grid, dim=0)
+ grid = grid.reshape([2, 1, grid_size_h, grid_size_w])
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
+ return pos_embed.reshape(1, grid_size_h, grid_size_w, -1).permute(0, 3, 1, 2)
+
+
+def get_2d_sincos_pos_embed_from_grid(
+ embed_dim: int, grid: torch.Tensor
+) -> torch.Tensor:
+ """
+ This function generates a 2D positional embedding from a given grid using sine and cosine functions.
+
+ Args:
+ - embed_dim: The embedding dimension.
+ - grid: The grid to generate the embedding from.
+
+ Returns:
+ - emb: The generated 2D positional embedding.
+ """
+ assert embed_dim % 2 == 0
+
+ # use half of dimensions to encode grid_h
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
+
+ emb = torch.cat([emb_h, emb_w], dim=2) # (H*W, D)
+ return emb
+
+
+def get_1d_sincos_pos_embed_from_grid(
+ embed_dim: int, pos: torch.Tensor
+) -> torch.Tensor:
+ """
+ This function generates a 1D positional embedding from a given grid using sine and cosine functions.
+
+ Args:
+ - embed_dim: The embedding dimension.
+ - pos: The position to generate the embedding from.
+
+ Returns:
+ - emb: The generated 1D positional embedding.
+ """
+ assert embed_dim % 2 == 0
+ omega = torch.arange(embed_dim // 2, dtype=torch.double)
+ omega /= embed_dim / 2.0
+ omega = 1.0 / 10000**omega # (D/2,)
+
+ pos = pos.reshape(-1) # (M,)
+ out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product
+
+ emb_sin = torch.sin(out) # (M, D/2)
+ emb_cos = torch.cos(out) # (M, D/2)
+
+ emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D)
+ return emb[None].float()
+
+
+def get_2d_embedding(xy: torch.Tensor, C: int, cat_coords: bool = True) -> torch.Tensor:
+ """
+ This function generates a 2D positional embedding from given coordinates using sine and cosine functions.
+
+ Args:
+ - xy: The coordinates to generate the embedding from.
+ - C: The size of the embedding.
+ - cat_coords: A flag to indicate whether to concatenate the original coordinates to the embedding.
+
+ Returns:
+ - pe: The generated 2D positional embedding.
+ """
+ B, N, D = xy.shape
+ assert D == 2
+
+ x = xy[:, :, 0:1]
+ y = xy[:, :, 1:2]
+ div_term = (
+ torch.arange(0, C, 2, device=xy.device, dtype=torch.float32) * (1000.0 / C)
+ ).reshape(1, 1, int(C / 2))
+
+ pe_x = torch.zeros(B, N, C, device=xy.device, dtype=torch.float32)
+ pe_y = torch.zeros(B, N, C, device=xy.device, dtype=torch.float32)
+
+ pe_x[:, :, 0::2] = torch.sin(x * div_term)
+ pe_x[:, :, 1::2] = torch.cos(x * div_term)
+
+ pe_y[:, :, 0::2] = torch.sin(y * div_term)
+ pe_y[:, :, 1::2] = torch.cos(y * div_term)
+
+ pe = torch.cat([pe_x, pe_y], dim=2) # (B, N, C*3)
+ if cat_coords:
+ pe = torch.cat([xy, pe], dim=2) # (B, N, C*3+3)
+ return pe
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/LICENSE b/benchmarks/edit/code/IVEBench/metrics/quality/amt/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..c9cecbde136da03a4ceb1a6e90230900cd33828d
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/LICENSE
@@ -0,0 +1,176 @@
+## creative commons
+
+# Attribution-NonCommercial 4.0 International
+
+Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
+
+### Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
+
+* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
+
+* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
+
+## Creative Commons Attribution-NonCommercial 4.0 International Public License
+
+By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
+
+### Section 1 – Definitions.
+
+a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
+
+b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
+
+c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
+
+d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
+
+e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
+
+f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
+
+g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
+
+h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
+
+i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
+
+j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
+
+k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
+
+l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
+
+### Section 2 – Scope.
+
+a. ___License grant.___
+
+ 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
+
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
+
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
+
+ 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
+
+ 3. __Term.__ The term of this Public License is specified in Section 6(a).
+
+ 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
+
+ 5. __Downstream recipients.__
+
+ A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
+
+ B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
+
+ 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
+
+b. ___Other rights.___
+
+ 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this Public License.
+
+ 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
+
+### Section 3 – License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the following conditions.
+
+a. ___Attribution.___
+
+ 1. If You Share the Licensed Material (including in modified form), You must:
+
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
+
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
+
+ C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
+
+ 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
+
+ 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
+
+### Section 4 – Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
+
+a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
+
+b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
+
+c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
+
+### Section 5 – Disclaimer of Warranties and Limitation of Liability.
+
+a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
+
+b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
+
+c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
+
+### Section 6 – Term and Termination.
+
+a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
+
+b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
+
+c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
+
+d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
+
+### Section 7 – Other Terms and Conditions.
+
+a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
+
+b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
+
+### Section 8 – Interpretation.
+
+a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
+
+b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
+
+c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
+
+d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
+
+> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
+>
+> Creative Commons may be contacted at creativecommons.org
+
+
+### Commercial licensing opportunities
+For commercial uses of the Model & Software, please send email to cmm[AT]nankai.edu.cn
+
+Citation:
+
+@inproceedings{licvpr23amt,
+ title = {AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation},
+ author = {Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming},
+ booktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
+ year = {2023}
+}
+
+Copyright (c) 2023 MCG-NKU
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/README.md b/benchmarks/edit/code/IVEBench/metrics/quality/amt/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..2f3224318fa319dc39b86e6bf9ec74ce3dee2e3e
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/README.md
@@ -0,0 +1,167 @@
+# AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation
+
+
+This repository contains the official implementation of the following paper:
+> **AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation**
+> [Zhen Li](https://paper99.github.io/)\*, [Zuo-Liang Zhu](https://nk-cs-zzl.github.io/)\*, [Ling-Hao Han](https://scholar.google.com/citations?user=0ooNdgUAAAAJ&hl=en), [Qibin Hou](https://scholar.google.com/citations?hl=en&user=fF8OFV8AAAAJ&view_op=list_works), [Chun-Le Guo](https://scholar.google.com/citations?hl=en&user=RZLYwR0AAAAJ), [Ming-Ming Cheng](https://mmcheng.net/cmm)
+> (\* denotes equal contribution)
+> Nankai University
+> In CVPR 2023
+
+[[Paper](https://arxiv.org/abs/2304.09790)]
+[[Project Page](https://nk-cs-zzl.github.io/projects/amt/index.html)]
+[[Web demos](#web-demos)]
+[Video]
+
+AMT is a **lightweight, fast, and accurate** algorithm for Frame Interpolation.
+It aims to provide practical solutions for **video generation** from **a few given frames (at least two frames)**.
+
+
+* More examples can be found in our [project page](https://nk-cs-zzl.github.io/projects/amt/index.html).
+
+## Web demos
+Integrated into [Hugging Face Spaces 🤗](https://huggingface.co/spaces) using [Gradio](https://github.com/gradio-app/gradio). Try out the Web Demo: [](https://huggingface.co/spaces/NKU-AMT/AMT)
+
+Try AMT to interpolate between two or more images at [](https://colab.research.google.com/drive/1IeVO5BmLouhRh6fL2z_y18kgubotoaBq?usp=sharing)
+
+
+## Change Log
+- **Apr 20, 2023**: Our code is publicly available.
+
+
+## Method Overview
+
+
+For technical details, please refer to the [method.md](docs/method.md) file, or read the full report on [arXiv](https://arxiv.org/abs/2304.09790).
+
+## Dependencies and Installation
+1. Clone Repo
+
+ ```bash
+ git clone https://github.com/MCG-NKU/AMT.git
+ ```
+
+2. Create Conda Environment and Install Dependencies
+
+ ```bash
+ conda env create -f environment.yaml
+ conda activate amt
+ ```
+3. Download pretrained models for demos from [Pretrained Models](#pretrained-models) and place them to the `pretrained` folder
+
+## Quick Demo
+
+**Note that the selected pretrained model (`[CKPT_PATH]`) needs to match the config file (`[CFG]`).**
+
+ > Creating a video demo, increasing $n$ will slow down the motion in the video. (With $m$ input frames, `[N_ITER]` $=n$ corresponds to $2^n\times (m-1)+1$ output frames.)
+
+
+ ```bash
+ python demos/demo_2x.py -c [CFG] -p [CKPT] -n [N_ITER] -i [INPUT] -o [OUT_PATH] -r [FRAME_RATE]
+ # e.g. [INPUT]
+ # -i could be a video / a regular expression / a folder contains multiple images
+ # -i demo.mp4 (video)/img_*.png (regular expression)/img0.png img1.png (images)/demo_input (folder)
+
+ # e.g. a simple usage
+ python demos/demo_2x.py -c cfgs/AMT-S.yaml -p pretrained/amt-s.pth -n 6 -i assets/quick_demo/img0.png assets/quick_demo/img1.png
+
+ ```
+
+ + Note: Please enable `--save_images` for saving the output images (Save speed will be slowed down if there are too many output images)
+ + Input type supported: `a video` / `a regular expression` / `multiple images` / `a folder containing input frames`.
+ + Results are in the `[OUT_PATH]` (default is `results/2x`) folder.
+
+## Pretrained Models
+
+
+
+
+
+## Training and Evaluation
+
+Please refer to [develop.md](docs/develop.md) to learn how to benchmark the AMT and how to train a new AMT model from scratch.
+
+
+## Citation
+ If you find our repo useful for your research, please consider citing our paper:
+
+ ```bibtex
+ @inproceedings{licvpr23amt,
+ title={AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation},
+ author={Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming},
+ booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
+ year={2023}
+ }
+ ```
+
+
+## License
+This code is licensed under the [Creative Commons Attribution-NonCommercial 4.0 International](https://creativecommons.org/licenses/by-nc/4.0/) for non-commercial use only.
+Please note that any commercial use of this code requires formal permission prior to use.
+
+## Contact
+
+For technical questions, please contact `zhenli1031[AT]gmail.com` and `nkuzhuzl[AT]gmail.com`.
+
+For commercial licensing, please contact `cmm[AT]nankai.edu.cn`
+
+## Acknowledgement
+
+We thank Jia-Wen Xiao, Zheng-Peng Duan, Rui-Qi Wu, and Xin Jin for proof reading.
+We thank [Zhewei Huang](https://github.com/hzwer) for his suggestions.
+
+Here are some great resources we benefit from:
+
+- [IFRNet](https://github.com/ltkong218/IFRNet) and [RIFE](https://github.com/megvii-research/ECCV2022-RIFE) for data processing, benchmarking, and loss designs.
+- [RAFT](https://github.com/princeton-vl/RAFT), [M2M-VFI](https://github.com/feinanshan/M2M_VFI), and [GMFlow](https://github.com/haofeixu/gmflow) for inspirations.
+- [FILM](https://github.com/google-research/frame-interpolation) for Web demo reference.
+
+
+**If you develop/use AMT in your projects, welcome to let us know. We will list your projects in this repository.**
+
+We also thank all of our contributors.
+
+
+
+
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/adobe240.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/adobe240.py
new file mode 100644
index 0000000000000000000000000000000000000000..2faf098946924a56942f673c5165a7d3ca93c245
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/adobe240.py
@@ -0,0 +1,56 @@
+import sys
+import tqdm
+import torch
+import argparse
+import numpy as np
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.build_utils import build_from_cfg
+from datasets.adobe_datasets import Adobe240_Dataset
+from metrics.psnr_ssim import calculate_psnr, calculate_ssim
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'Adobe240 evaluation',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S_gopro.yaml')
+parser.add_argument('-p', '--ckpt', default='pretrained/gopro_amt-s.pth',)
+parser.add_argument('-r', '--root', default='data/Adobe240/test_frames',)
+args = parser.parse_args()
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+cfg_path = args.config
+ckpt_path = args.ckpt
+root = args.root
+
+network_cfg = OmegaConf.load(cfg_path).network
+network_name = network_cfg.name
+model = build_from_cfg(network_cfg)
+ckpt = torch.load(ckpt_path)
+model.load_state_dict(ckpt['state_dict'])
+model = model.to(device)
+model.eval()
+
+dataset = Adobe240_Dataset(dataset_dir=root, augment=False)
+
+psnr_list = []
+ssim_list = []
+pbar = tqdm.tqdm(dataset, total=len(dataset))
+for data in pbar:
+ input_dict = {}
+ for k, v in data.items():
+ input_dict[k] = v.to(device).unsqueeze(0)
+ with torch.no_grad():
+ imgt_pred = model(**input_dict)['imgt_pred']
+ psnr = calculate_psnr(imgt_pred, input_dict['imgt'])
+ ssim = calculate_ssim(imgt_pred, input_dict['imgt'])
+ psnr_list.append(psnr)
+ ssim_list.append(ssim)
+ avg_psnr = np.mean(psnr_list)
+ avg_ssim = np.mean(ssim_list)
+ desc_str = f'[{network_name}/Adobe240] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}'
+ pbar.set_description_str(desc_str)
+
+
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/gopro.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/gopro.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d049a58fb77b59cc79bc5b8c9b6ab1960e4dfb8
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/gopro.py
@@ -0,0 +1,55 @@
+import sys
+import tqdm
+import torch
+import argparse
+import numpy as np
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.build_utils import build_from_cfg
+from datasets.gopro_datasets import GoPro_Test_Dataset
+from metrics.psnr_ssim import calculate_psnr, calculate_ssim
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'GOPRO evaluation',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S_gopro.yaml')
+parser.add_argument('-p', '--ckpt', default='pretrained/gopro_amt-s.pth',)
+parser.add_argument('-r', '--root', default='data/GOPRO',)
+args = parser.parse_args()
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+cfg_path = args.config
+ckpt_path = args.ckpt
+root = args.root
+
+network_cfg = OmegaConf.load(cfg_path).network
+network_name = network_cfg.name
+model = build_from_cfg(network_cfg)
+ckpt = torch.load(ckpt_path)
+model.load_state_dict(ckpt['state_dict'])
+model = model.to(device)
+model.eval()
+
+dataset = GoPro_Test_Dataset(dataset_dir=root)
+
+psnr_list = []
+ssim_list = []
+pbar = tqdm.tqdm(dataset, total=len(dataset))
+for data in pbar:
+ input_dict = {}
+ for k, v in data.items():
+ input_dict[k] = v.to(device).unsqueeze(0)
+ with torch.no_grad():
+ imgt_pred = model(**input_dict)['imgt_pred']
+ psnr = calculate_psnr(imgt_pred, input_dict['imgt'])
+ ssim = calculate_ssim(imgt_pred, input_dict['imgt'])
+ psnr_list.append(psnr)
+ ssim_list.append(ssim)
+ avg_psnr = np.mean(psnr_list)
+ avg_ssim = np.mean(ssim_list)
+ desc_str = f'[{network_name}/GOPRO] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}'
+ pbar.set_description_str(desc_str)
+
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/snu_film.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/snu_film.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ab7d1a9d58cc708c9e78d0c4a27f6b624ed1796
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/snu_film.py
@@ -0,0 +1,70 @@
+import os
+import sys
+import tqdm
+import torch
+import argparse
+import numpy as np
+import os.path as osp
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.build_utils import build_from_cfg
+from metrics.psnr_ssim import calculate_psnr, calculate_ssim
+from utils.utils import InputPadder, read, img2tensor
+
+
+def parse_path(path):
+ path_list = path.split('/')
+ new_path = osp.join(*path_list[-3:])
+ return new_path
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'SNU-FILM evaluation',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S.yaml')
+parser.add_argument('-p', '--ckpt', default='pretrained/amt-s.pth')
+parser.add_argument('-r', '--root', default='data/SNU_FILM')
+args = parser.parse_args()
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+cfg_path = args.config
+ckpt_path = args.ckpt
+root = args.root
+
+network_cfg = OmegaConf.load(cfg_path).network
+network_name = network_cfg.name
+model = build_from_cfg(network_cfg)
+ckpt = torch.load(ckpt_path)
+model.load_state_dict(ckpt['state_dict'])
+model = model.to(device)
+model.eval()
+
+divisor = 20; scale_factor = 0.8
+splits = ['easy', 'medium', 'hard', 'extreme']
+for split in splits:
+ with open(os.path.join(root, f'test-{split}.txt'), "r") as fr:
+ file_list = [l.strip().split(' ') for l in fr.readlines()]
+ pbar = tqdm.tqdm(file_list, total=len(file_list))
+
+ psnr_list = []; ssim_list = []
+ for name in pbar:
+ img0 = img2tensor(read(osp.join(root, parse_path(name[0])))).to(device)
+ imgt = img2tensor(read(osp.join(root, parse_path(name[1])))).to(device)
+ img1 = img2tensor(read(osp.join(root, parse_path(name[2])))).to(device)
+ padder = InputPadder(img0.shape, divisor)
+ img0, img1 = padder.pad(img0, img1)
+
+ embt = torch.tensor(1/2).float().view(1, 1, 1, 1).to(device)
+ imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)['imgt_pred']
+ imgt_pred = padder.unpad(imgt_pred)
+
+ psnr = calculate_psnr(imgt_pred, imgt).detach().cpu().numpy()
+ ssim = calculate_ssim(imgt_pred, imgt).detach().cpu().numpy()
+
+ psnr_list.append(psnr)
+ ssim_list.append(ssim)
+ avg_psnr = np.mean(psnr_list)
+ avg_ssim = np.mean(ssim_list)
+ desc_str = f'[{network_name}/SNU-FILM] [{split}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}'
+ pbar.set_description_str(desc_str)
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/speed_parameters.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/speed_parameters.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5b233095dd3d7160ebb453d7a8f8d392acd2b72
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/speed_parameters.py
@@ -0,0 +1,38 @@
+import sys
+import time
+import torch
+import argparse
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.build_utils import build_from_cfg
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'Speed¶meter benchmark',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S.yaml')
+args = parser.parse_args()
+
+cfg_path = args.config
+network_cfg = OmegaConf.load(cfg_path).network
+model = build_from_cfg(network_cfg)
+model = model.cuda()
+model.eval()
+
+img0 = torch.randn(1, 3, 256, 448).cuda()
+img1 = torch.randn(1, 3, 256, 448).cuda()
+embt = torch.tensor(1/2).float().view(1, 1, 1, 1).cuda()
+
+with torch.no_grad():
+ for i in range(100):
+ out = model(img0, img1, embt, eval=True)
+ torch.cuda.synchronize()
+ time_stamp = time.time()
+ for i in range(1000):
+ out = model(img0, img1, embt, eval=True)
+ torch.cuda.synchronize()
+ print('Time: {:.5f}s'.format((time.time() - time_stamp) / 1))
+
+total = sum([param.nelement() for param in model.parameters()])
+print('Parameters: {:.2f}M'.format(total / 1e6))
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/ucf101.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/ucf101.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d29b0e77040cef801dbbee79a089eb224830cf2
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/ucf101.py
@@ -0,0 +1,59 @@
+import os
+import sys
+import tqdm
+import torch
+import argparse
+import numpy as np
+import os.path as osp
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.utils import read, img2tensor
+from utils.build_utils import build_from_cfg
+from metrics.psnr_ssim import calculate_psnr, calculate_ssim
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'UCF101 evaluation',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S.yaml')
+parser.add_argument('-p', '--ckpt', default='pretrained/amt-s.pth')
+parser.add_argument('-r', '--root', default='data/ucf101_interp_ours')
+args = parser.parse_args()
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+cfg_path = args.config
+ckpt_path = args.ckpt
+root = args.root
+
+network_cfg = OmegaConf.load(cfg_path).network
+network_name = network_cfg.name
+model = build_from_cfg(network_cfg)
+ckpt = torch.load(ckpt_path)
+model.load_state_dict(ckpt['state_dict'])
+model = model.to(device)
+model.eval()
+
+dirs = sorted(os.listdir(root))
+psnr_list = []
+ssim_list = []
+pbar = tqdm.tqdm(dirs, total=len(dirs))
+for d in pbar:
+ dir_path = osp.join(root, d)
+ I0 = img2tensor(read(osp.join(dir_path, 'frame_00.png'))).to(device)
+ I1 = img2tensor(read(osp.join(dir_path, 'frame_01_gt.png'))).to(device)
+ I2 = img2tensor(read(osp.join(dir_path, 'frame_02.png'))).to(device)
+ embt = torch.tensor(1/2).float().view(1, 1, 1, 1).to(device)
+
+ I1_pred = model(I0, I2, embt, eval=True)['imgt_pred']
+
+ psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy()
+ ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy()
+
+ psnr_list.append(psnr)
+ ssim_list.append(ssim)
+
+ avg_psnr = np.mean(psnr_list)
+ avg_ssim = np.mean(ssim_list)
+ desc_str = f'[{network_name}/UCF101] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}'
+ pbar.set_description_str(desc_str)
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/vimeo90k.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/vimeo90k.py
new file mode 100644
index 0000000000000000000000000000000000000000..c598e8c8f08ae333bd77bfdfd6036f2fd35305a2
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/vimeo90k.py
@@ -0,0 +1,65 @@
+import sys
+import tqdm
+import torch
+import argparse
+import numpy as np
+import os.path as osp
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.utils import read, img2tensor
+from utils.build_utils import build_from_cfg
+from metrics.psnr_ssim import calculate_psnr, calculate_ssim
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'Vimeo90K evaluation',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S.yaml')
+parser.add_argument('-p', '--ckpt', default='pretrained/amt-s.pth',)
+parser.add_argument('-r', '--root', default='data/vimeo_triplet',)
+args = parser.parse_args()
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+cfg_path = args.config
+ckpt_path = args.ckpt
+root = args.root
+
+network_cfg = OmegaConf.load(cfg_path).network
+network_name = network_cfg.name
+model = build_from_cfg(network_cfg)
+ckpt = torch.load(ckpt_path)
+model.load_state_dict(ckpt['state_dict'])
+model = model.to(device)
+model.eval()
+
+with open(osp.join(root, 'tri_testlist.txt'), 'r') as fr:
+ file_list = fr.readlines()
+
+psnr_list = []
+ssim_list = []
+
+pbar = tqdm.tqdm(file_list, total=len(file_list))
+for name in pbar:
+ name = str(name).strip()
+ if(len(name) <= 1):
+ continue
+ dir_path = osp.join(root, 'sequences', name)
+ I0 = img2tensor(read(osp.join(dir_path, 'im1.png'))).to(device)
+ I1 = img2tensor(read(osp.join(dir_path, 'im2.png'))).to(device)
+ I2 = img2tensor(read(osp.join(dir_path, 'im3.png'))).to(device)
+ embt = torch.tensor(1/2).float().view(1, 1, 1, 1).to(device)
+
+ I1_pred = model(I0, I2, embt,
+ scale_factor=1.0, eval=True)['imgt_pred']
+
+ psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy()
+ ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy()
+
+ psnr_list.append(psnr)
+ ssim_list.append(ssim)
+ avg_psnr = np.mean(psnr_list)
+ avg_ssim = np.mean(ssim_list)
+ desc_str = f'[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}'
+ pbar.set_description_str(desc_str)
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/vimeo90k_tta.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/vimeo90k_tta.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebadad1f7687958f43e36cb3d8a5735ebf1944b2
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/vimeo90k_tta.py
@@ -0,0 +1,67 @@
+import sys
+import tqdm
+import torch
+import argparse
+import numpy as np
+import os.path as osp
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.utils import read, img2tensor
+from utils.build_utils import build_from_cfg
+from metrics.psnr_ssim import calculate_psnr, calculate_ssim
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'Vimeo90K evaluation (with Test-Time Augmentation)',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S.yaml')
+parser.add_argument('p', '--ckpt', default='pretrained/amt-s.pth',)
+parser.add_argument('-r', '--root', default='data/vimeo_triplet',)
+args = parser.parse_args()
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+cfg_path = args.config
+ckpt_path = args.ckpt
+root = args.root
+
+network_cfg = OmegaConf.load(cfg_path).network
+network_name = network_cfg.name
+model = build_from_cfg(network_cfg)
+ckpt = torch.load(ckpt_path)
+model.load_state_dict(ckpt['state_dict'])
+model = model.to(device)
+model.eval()
+
+with open(osp.join(root, 'tri_testlist.txt'), 'r') as fr:
+ file_list = fr.readlines()
+
+psnr_list = []
+ssim_list = []
+
+pbar = tqdm.tqdm(file_list, total=len(file_list))
+for name in pbar:
+ name = str(name).strip()
+ if(len(name) <= 1):
+ continue
+ dir_path = osp.join(root, 'sequences', name)
+ I0 = img2tensor(read(osp.join(dir_path, 'im1.png'))).to(device)
+ I1 = img2tensor(read(osp.join(dir_path, 'im2.png'))).to(device)
+ I2 = img2tensor(read(osp.join(dir_path, 'im3.png'))).to(device)
+ embt = torch.tensor(1/2).float().view(1, 1, 1, 1).to(device)
+
+ I1_pred1 = model(I0, I2, embt,
+ scale_factor=1.0, eval=True)['imgt_pred']
+ I1_pred2 = model(torch.flip(I0, [2]), torch.flip(I2, [2]), embt,
+ scale_factor=1.0, eval=True)['imgt_pred']
+ I1_pred = I1_pred1 / 2 + torch.flip(I1_pred2, [2]) / 2
+ psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy()
+ ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy()
+
+ psnr_list.append(psnr)
+ ssim_list.append(ssim)
+ avg_psnr = np.mean(psnr_list)
+ avg_ssim = np.mean(ssim_list)
+ desc_str = f'[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}'
+ pbar.set_description_str(desc_str)
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/xiph.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/xiph.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8bd732748802371850c4af6fd7b56bb50f08f3e
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/benchmarks/xiph.py
@@ -0,0 +1,104 @@
+import os
+import sys
+import cv2
+import tqdm
+import glob
+import torch
+import argparse
+import numpy as np
+import os.path as osp
+from omegaconf import OmegaConf
+
+sys.path.append('.')
+from utils.utils import InputPadder, read, img2tensor
+from utils.build_utils import build_from_cfg
+from metrics.psnr_ssim import calculate_psnr, calculate_ssim
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'Xiph evaluation',
+ )
+parser.add_argument('-c', '--config', default='cfgs/AMT-S.yaml')
+parser.add_argument('-p', '--ckpt', default='pretrained/amt-s.pth')
+parser.add_argument('-r', '--root', default='data/xiph')
+args = parser.parse_args()
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+cfg_path = args.config
+ckpt_path = args.ckpt
+root = args.root
+
+network_cfg = OmegaConf.load(cfg_path).network
+network_name = network_cfg.name
+model = build_from_cfg(network_cfg)
+ckpt = torch.load(ckpt_path)
+model.load_state_dict(ckpt['state_dict'], False)
+model = model.to(device)
+model.eval()
+
+############################################# Prepare Dataset #############################################
+download_links = [
+ 'https://media.xiph.org/video/derf/ElFuente/Netflix_BoxingPractice_4096x2160_60fps_10bit_420.y4m',
+ 'https://media.xiph.org/video/derf/ElFuente/Netflix_Crosswalk_4096x2160_60fps_10bit_420.y4m',
+ 'https://media.xiph.org/video/derf/Chimera/Netflix_DrivingPOV_4096x2160_60fps_10bit_420.y4m',
+ 'https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket_4096x2160_60fps_10bit_420.y4m',
+ 'https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket2_4096x2160_60fps_10bit_420.y4m',
+ 'https://media.xiph.org/video/derf/ElFuente/Netflix_RitualDance_4096x2160_60fps_10bit_420.y4m',
+ 'https://media.xiph.org/video/derf/ElFuente/Netflix_SquareAndTimelapse_4096x2160_60fps_10bit_420.y4m',
+ 'https://media.xiph.org/video/derf/ElFuente/Netflix_Tango_4096x2160_60fps_10bit_420.y4m',
+]
+file_list = ['BoxingPractice', 'Crosswalk', 'DrivingPOV', 'FoodMarket', 'FoodMarket2', 'RitualDance',
+ 'SquareAndTimelapse', 'Tango']
+
+for file_name, link in zip(file_list, download_links):
+ data_dir = osp.join(root, file_name)
+ if osp.exists(data_dir) is False:
+ os.makedirs(data_dir)
+ if len(glob.glob(f'{data_dir}/*.png')) < 100:
+ os.system(f'ffmpeg -i {link} -pix_fmt rgb24 -vframes 100 {data_dir}/%03d.png')
+############################################### Prepare End ###############################################
+
+
+divisor = 32; scale_factor = 0.5
+for category in ['resized-2k', 'cropped-4k']:
+ psnr_list = []
+ ssim_list = []
+ pbar = tqdm.tqdm(file_list, total=len(file_list))
+ for flie_name in pbar:
+ dir_name = osp.join(root, flie_name)
+ for intFrame in range(2, 99, 2):
+ img0 = read(f'{dir_name}/{intFrame - 1:03d}.png')
+ img1 = read(f'{dir_name}/{intFrame + 1:03d}.png')
+ imgt = read(f'{dir_name}/{intFrame:03d}.png')
+
+ if category == 'resized-2k':
+ img0 = cv2.resize(src=img0, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
+ img1 = cv2.resize(src=img1, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
+ imgt = cv2.resize(src=imgt, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
+
+ elif category == 'cropped-4k':
+ img0 = img0[540:-540, 1024:-1024, :]
+ img1 = img1[540:-540, 1024:-1024, :]
+ imgt = imgt[540:-540, 1024:-1024, :]
+ img0 = img2tensor(img0).to(device)
+ imgt = img2tensor(imgt).to(device)
+ img1 = img2tensor(img1).to(device)
+ embt = torch.tensor(1/2).float().view(1, 1, 1, 1).to(device)
+
+ padder = InputPadder(img0.shape, divisor)
+ img0, img1 = padder.pad(img0, img1)
+
+ with torch.no_grad():
+ imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)['imgt_pred']
+ imgt_pred = padder.unpad(imgt_pred)
+
+ psnr = calculate_psnr(imgt_pred, imgt)
+ ssim = calculate_ssim(imgt_pred, imgt)
+
+ avg_psnr = np.mean(psnr_list)
+ avg_ssim = np.mean(ssim_list)
+ psnr_list.append(psnr)
+ ssim_list.append(ssim)
+ desc_str = f'[{network_name}/Xiph] [{category}/{flie_name}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}'
+
+ pbar.set_description_str(desc_str)
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-G.yaml b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-G.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7b3bb39bda6b41dc5cdc3300ffccb7b4e7d537ce
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-G.yaml
@@ -0,0 +1,62 @@
+exp_name: floloss1e-2_300epoch_bs24_lr1p5e-4
+seed: 2023
+epochs: 300
+distributed: true
+lr: 1.5e-4
+lr_min: 2e-5
+weight_decay: 0.0
+resume_state: null
+save_dir: work_dir
+eval_interval: 1
+
+network:
+ name: networks.AMT-G.Model
+ params:
+ corr_radius: 3
+ corr_lvls: 4
+ num_flows: 5
+data:
+ train:
+ name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ val:
+ name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ train_loader:
+ batch_size: 24
+ num_workers: 12
+ val_loader:
+ batch_size: 24
+ num_workers: 3
+
+logger:
+ use_wandb: true
+ resume_id: null
+
+losses:
+ - {
+ name: losses.loss.CharbonnierLoss,
+ nickname: l_rec,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.TernaryLoss,
+ nickname: l_ter,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.MultipleFlowLoss,
+ nickname: l_flo,
+ params: {
+ loss_weight: 0.005,
+ keys: [flow0_pred, flow1_pred, flow]
+ }
+ }
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-L.yaml b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-L.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..0cd60ce868ad98a9dea74dd77227f556738715e8
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-L.yaml
@@ -0,0 +1,62 @@
+exp_name: floloss1e-2_300epoch_bs24_lr2e-4
+seed: 2023
+epochs: 300
+distributed: true
+lr: 2e-4
+lr_min: 2e-5
+weight_decay: 0.0
+resume_state: null
+save_dir: work_dir
+eval_interval: 1
+
+network:
+ name: networks.AMT-L.Model
+ params:
+ corr_radius: 3
+ corr_lvls: 4
+ num_flows: 5
+data:
+ train:
+ name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ val:
+ name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ train_loader:
+ batch_size: 24
+ num_workers: 12
+ val_loader:
+ batch_size: 24
+ num_workers: 3
+
+logger:
+ use_wandb: true
+ resume_id: null
+
+losses:
+ - {
+ name: losses.loss.CharbonnierLoss,
+ nickname: l_rec,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.TernaryLoss,
+ nickname: l_ter,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.MultipleFlowLoss,
+ nickname: l_flo,
+ params: {
+ loss_weight: 0.002,
+ keys: [flow0_pred, flow1_pred, flow]
+ }
+ }
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-S.yaml b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-S.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f0673557e12360f960cb2c7b2071a85c2aa6aa14
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-S.yaml
@@ -0,0 +1,63 @@
+exp_name: floloss1e-2_300epoch_bs24_lr2e-4
+seed: 2023
+epochs: 300
+distributed: true
+lr: 2e-4
+lr_min: 2e-5
+weight_decay: 0.0
+resume_state: null
+save_dir: work_dir
+eval_interval: 1
+
+network:
+ name: networks.AMT-S.Model
+ params:
+ corr_radius: 3
+ corr_lvls: 4
+ num_flows: 3
+
+data:
+ train:
+ name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ val:
+ name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ train_loader:
+ batch_size: 24
+ num_workers: 12
+ val_loader:
+ batch_size: 24
+ num_workers: 3
+
+logger:
+ use_wandb: false
+ resume_id: null
+
+losses:
+ - {
+ name: losses.loss.CharbonnierLoss,
+ nickname: l_rec,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.TernaryLoss,
+ nickname: l_ter,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.MultipleFlowLoss,
+ nickname: l_flo,
+ params: {
+ loss_weight: 0.002,
+ keys: [flow0_pred, flow1_pred, flow]
+ }
+ }
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-S_gopro.yaml b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-S_gopro.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..bb50cfb04ed509e7766bbd279e0308d03db98d62
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/AMT-S_gopro.yaml
@@ -0,0 +1,56 @@
+exp_name: wofloloss_400epoch_bs24_lr2e-4
+seed: 2023
+epochs: 400
+distributed: true
+lr: 2e-4
+lr_min: 2e-5
+weight_decay: 0.0
+resume_state: null
+save_dir: work_dir
+eval_interval: 1
+
+network:
+ name: networks.AMT-S.Model
+ params:
+ corr_radius: 3
+ corr_lvls: 4
+ num_flows: 3
+
+data:
+ train:
+ name: datasets.gopro_datasets.GoPro_Train_Dataset
+ params:
+ dataset_dir: data/GOPRO
+ val:
+ name: datasets.gopro_datasets.GoPro_Test_Dataset
+ params:
+ dataset_dir: data/GOPRO
+ train_loader:
+ batch_size: 24
+ num_workers: 12
+ val_loader:
+ batch_size: 24
+ num_workers: 3
+
+logger:
+ use_wandb: false
+ resume_id: null
+
+losses:
+ - {
+ name: losses.loss.CharbonnierLoss,
+ nickname: l_rec,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.TernaryLoss,
+ nickname: l_ter,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/IFRNet.yaml b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/IFRNet.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..1ce67ca48901e501956ea0d07b2373b5d7af74df
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/cfgs/IFRNet.yaml
@@ -0,0 +1,67 @@
+exp_name: floloss1e-2_geoloss1e-2_300epoch_bs24_lr1e-4
+seed: 2023
+epochs: 300
+distributed: true
+lr: 1e-4
+lr_min: 1e-5
+weight_decay: 1e-6
+resume_state: null
+save_dir: work_dir
+eval_interval: 1
+
+network:
+ name: networks.IFRNet.Model
+
+data:
+ train:
+ name: datasets.datasets.Vimeo90K_Train_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ val:
+ name: datasets.datasets.Vimeo90K_Test_Dataset
+ params:
+ dataset_dir: data/vimeo_triplet
+ train_loader:
+ batch_size: 24
+ num_workers: 12
+ val_loader:
+ batch_size: 24
+ num_workers: 3
+
+logger:
+ use_wandb: true
+ resume_id: null
+
+losses:
+ - {
+ name: losses.loss.CharbonnierLoss,
+ nickname: l_rec,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.TernaryLoss,
+ nickname: l_ter,
+ params: {
+ loss_weight: 1.0,
+ keys: [imgt_pred, imgt]
+ }
+ }
+ - {
+ name: losses.loss.IFRFlowLoss,
+ nickname: l_flo,
+ params: {
+ loss_weight: 0.01,
+ keys: [flow0_pred, flow1_pred, flow]
+ }
+ }
+ - {
+ name: losses.loss.GeometryLoss,
+ nickname: l_geo,
+ params: {
+ loss_weight: 0.01,
+ keys: [ft_pred, ft_gt]
+ }
+ }
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/adobe_datasets.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/adobe_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ffa857ac98e7e106f965d007fdffa6b0a7ddb1f
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/adobe_datasets.py
@@ -0,0 +1,75 @@
+'''
+ This code is partially borrowed from IFRNet (https://github.com/ltkong218/IFRNet).
+'''
+import os
+import sys
+import torch
+import numpy as np
+from torch.utils.data import Dataset
+sys.path.append('.')
+from utils.utils import read, img2tensor
+from datasets.gopro_datasets import (
+ random_resize_woflow, random_crop_woflow, center_crop_woflow,
+ random_reverse_channel_woflow, random_vertical_flip_woflow,
+ random_horizontal_flip_woflow, random_rotate_woflow,
+ random_reverse_time_woflow
+)
+
+
+class Adobe240_Dataset(Dataset):
+ def __init__(self, dataset_dir='data/adobe240/test_frames', interFrames=7, augment=True):
+ super().__init__()
+ self.augment = augment
+ self.interFrames = interFrames
+ self.setLength = interFrames + 2
+ self.dataset_dir = os.path.join(dataset_dir)
+ video_list = os.listdir(self.dataset_dir)[9::10]
+ self.frames_list = []
+ self.file_list = []
+ for video in video_list:
+ frames = sorted(os.listdir(os.path.join(self.dataset_dir, video)))
+ n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1
+ videoInputs = [frames[(interFrames + 1) * i: (interFrames + 1) * i + self.setLength] for i in range(n_sets)]
+ videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs]
+ self.file_list.extend(videoInputs)
+
+ def __getitem__(self, idx):
+ clip_idx = idx // self.interFrames
+ embt_idx = idx % self.interFrames
+ imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]]
+ pick_idxs = list(range(0, self.setLength, self.interFrames + 1))
+ imgt_beg = self.setLength // 2 - self.interFrames // 2
+ imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2
+ imgt_idx = list(range(imgt_beg, imgt_end))
+ input_paths = [imgpaths[idx] for idx in pick_idxs]
+ imgt_paths = [imgpaths[idx] for idx in imgt_idx]
+
+ img0 = np.array(read(input_paths[0]))
+ imgt = np.array(read(imgt_paths[embt_idx]))
+ img1 = np.array(read(input_paths[1]))
+ embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)
+ ).reshape(1, 1, 1).astype(np.float32))
+
+ if self.augment == True:
+ img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1)
+ img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224))
+ img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5)
+ img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3)
+ img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5)
+ img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05)
+ img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1,
+ embt=embt, p=0.5)
+ else:
+ img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512))
+
+ img0 = img2tensor(img0).squeeze(0)
+ imgt = img2tensor(imgt).squeeze(0)
+ img1 = img2tensor(img1).squeeze(0)
+
+ return {'img0': img0.float(),
+ 'imgt': imgt.float(),
+ 'img1': img1.float(),
+ 'embt': embt}
+
+ def __len__(self):
+ return len(self.file_list) * self.interFrames
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/gopro_datasets.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/gopro_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fa5540adb3fbe1fd77bb6728019b99d6d97cdca
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/gopro_datasets.py
@@ -0,0 +1,188 @@
+'''
+ This code is partially borrowed from IFRNet (https://github.com/ltkong218/IFRNet).
+ In the consideration of the difficulty in flow supervision generation, we abort
+ flow loss in the 8x case.
+'''
+import os
+import cv2
+import torch
+import random
+import numpy as np
+from torch.utils.data import Dataset
+from utils.utils import read, img2tensor
+
+def random_resize_woflow(img0, imgt, img1, p=0.1):
+ if random.uniform(0, 1) < p:
+ img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
+ imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
+ img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
+ return img0, imgt, img1
+
+def random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)):
+ h, w = crop_size[0], crop_size[1]
+ ih, iw, _ = img0.shape
+ x = np.random.randint(0, ih-h+1)
+ y = np.random.randint(0, iw-w+1)
+ img0 = img0[x: x + h, y : y + w, :]
+ imgt = imgt[x: x + h, y : y + w, :]
+ img1 = img1[x: x + h, y : y + w, :]
+ return img0, imgt, img1
+
+def center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)):
+ h, w = crop_size[0], crop_size[1]
+ ih, iw, _ = img0.shape
+ img0 = img0[ih // 2 - h // 2: ih // 2 + h // 2, iw // 2 - w // 2: iw // 2 + w // 2, :]
+ imgt = imgt[ih // 2 - h // 2: ih // 2 + h // 2, iw // 2 - w // 2: iw // 2 + w // 2, :]
+ img1 = img1[ih // 2 - h // 2: ih // 2 + h // 2, iw // 2 - w // 2: iw // 2 + w // 2, :]
+ return img0, imgt, img1
+
+def random_reverse_channel_woflow(img0, imgt, img1, p=0.5):
+ if random.uniform(0, 1) < p:
+ img0 = img0[:, :, ::-1]
+ imgt = imgt[:, :, ::-1]
+ img1 = img1[:, :, ::-1]
+ return img0, imgt, img1
+
+def random_vertical_flip_woflow(img0, imgt, img1, p=0.3):
+ if random.uniform(0, 1) < p:
+ img0 = img0[::-1]
+ imgt = imgt[::-1]
+ img1 = img1[::-1]
+ return img0, imgt, img1
+
+def random_horizontal_flip_woflow(img0, imgt, img1, p=0.5):
+ if random.uniform(0, 1) < p:
+ img0 = img0[:, ::-1]
+ imgt = imgt[:, ::-1]
+ img1 = img1[:, ::-1]
+ return img0, imgt, img1
+
+def random_rotate_woflow(img0, imgt, img1, p=0.05):
+ if random.uniform(0, 1) < p:
+ img0 = img0.transpose((1, 0, 2))
+ imgt = imgt.transpose((1, 0, 2))
+ img1 = img1.transpose((1, 0, 2))
+ return img0, imgt, img1
+
+def random_reverse_time_woflow(img0, imgt, img1, embt, p=0.5):
+ if random.uniform(0, 1) < p:
+ tmp = img1
+ img1 = img0
+ img0 = tmp
+ embt = 1 - embt
+ return img0, imgt, img1, embt
+
+class GoPro_Train_Dataset(Dataset):
+ def __init__(self, dataset_dir='data/GOPRO', interFrames=7, augment=True):
+ self.dataset_dir = dataset_dir + '/train'
+ self.interFrames = interFrames
+ self.augment = augment
+ self.setLength = interFrames + 2
+ video_list = [
+ 'GOPR0372_07_00', 'GOPR0374_11_01', 'GOPR0378_13_00', 'GOPR0384_11_01',
+ 'GOPR0384_11_04', 'GOPR0477_11_00', 'GOPR0868_11_02', 'GOPR0884_11_00',
+ 'GOPR0372_07_01', 'GOPR0374_11_02', 'GOPR0379_11_00', 'GOPR0384_11_02',
+ 'GOPR0385_11_00', 'GOPR0857_11_00', 'GOPR0871_11_01', 'GOPR0374_11_00',
+ 'GOPR0374_11_03', 'GOPR0380_11_00', 'GOPR0384_11_03', 'GOPR0386_11_00',
+ 'GOPR0868_11_01', 'GOPR0881_11_00']
+ self.frames_list = []
+ self.file_list = []
+ for video in video_list:
+ frames = sorted(os.listdir(os.path.join(self.dataset_dir, video)))
+ n_sets = (len(frames) - self.setLength) // (interFrames+1) + 1
+ videoInputs = [frames[(interFrames + 1) * i: (interFrames + 1) * i + self.setLength
+ ] for i in range(n_sets)]
+ videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs]
+ self.file_list.extend(videoInputs)
+
+ def __len__(self):
+ return len(self.file_list) * self.interFrames
+
+ def __getitem__(self, idx):
+ clip_idx = idx // self.interFrames
+ embt_idx = idx % self.interFrames
+ imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]]
+ pick_idxs = list(range(0, self.setLength, self.interFrames + 1))
+ imgt_beg = self.setLength // 2 - self.interFrames // 2
+ imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2
+ imgt_idx = list(range(imgt_beg, imgt_end))
+ input_paths = [imgpaths[idx] for idx in pick_idxs]
+ imgt_paths = [imgpaths[idx] for idx in imgt_idx]
+
+ embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames+1)
+ ).reshape(1, 1, 1).astype(np.float32))
+ img0 = np.array(read(input_paths[0]))
+ imgt = np.array(read(imgt_paths[embt_idx]))
+ img1 = np.array(read(input_paths[1]))
+
+ if self.augment == True:
+ img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1)
+ img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224))
+ img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5)
+ img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3)
+ img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5)
+ img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05)
+ img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1,
+ embt=embt, p=0.5)
+ else:
+ img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512))
+
+ img0 = img2tensor(img0.copy()).squeeze(0)
+ imgt = img2tensor(imgt.copy()).squeeze(0)
+ img1 = img2tensor(img1.copy()).squeeze(0)
+
+ return {'img0': img0.float(),
+ 'imgt': imgt.float(),
+ 'img1': img1.float(),
+ 'embt': embt}
+
+class GoPro_Test_Dataset(Dataset):
+ def __init__(self, dataset_dir='data/GOPRO', interFrames=7):
+ self.dataset_dir = dataset_dir + '/test'
+ self.interFrames = interFrames
+ self.setLength = interFrames + 2
+ video_list = [
+ 'GOPR0384_11_00', 'GOPR0385_11_01', 'GOPR0410_11_00',
+ 'GOPR0862_11_00', 'GOPR0869_11_00', 'GOPR0881_11_01',
+ 'GOPR0384_11_05', 'GOPR0396_11_00', 'GOPR0854_11_00',
+ 'GOPR0868_11_00', 'GOPR0871_11_00']
+ self.frames_list = []
+ self.file_list = []
+ for video in video_list:
+ frames = sorted(os.listdir(os.path.join(self.dataset_dir, video)))
+ n_sets = (len(frames) - self.setLength)//(interFrames+1) + 1
+ videoInputs = [frames[(interFrames + 1) * i:(interFrames + 1) * i + self.setLength
+ ] for i in range(n_sets)]
+ videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs]
+ self.file_list.extend(videoInputs)
+
+ def __len__(self):
+ return len(self.file_list) * self.interFrames
+
+ def __getitem__(self, idx):
+ clip_idx = idx // self.interFrames
+ embt_idx = idx % self.interFrames
+ imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]]
+ pick_idxs = list(range(0, self.setLength, self.interFrames + 1))
+ imgt_beg = self.setLength // 2 - self.interFrames // 2
+ imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2
+ imgt_idx = list(range(imgt_beg, imgt_end))
+ input_paths = [imgpaths[idx] for idx in pick_idxs]
+ imgt_paths = [imgpaths[idx] for idx in imgt_idx]
+
+ img0 = np.array(read(input_paths[0]))
+ imgt = np.array(read(imgt_paths[embt_idx]))
+ img1 = np.array(read(input_paths[1]))
+
+ img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512))
+
+ img0 = img2tensor(img0).squeeze(0)
+ imgt = img2tensor(imgt).squeeze(0)
+ img1 = img2tensor(img1).squeeze(0)
+
+ embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)
+ ).reshape(1, 1, 1).astype(np.float32))
+ return {'img0': img0.float(),
+ 'imgt': imgt.float(),
+ 'img1': img1.float(),
+ 'embt': embt}
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/vimeo_datasets.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/vimeo_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..03da0f53438d91d16e2d0f45bb7a5e57bfcc3ace
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/datasets/vimeo_datasets.py
@@ -0,0 +1,176 @@
+'''
+ This code is partially borrowed from IFRNet (https://github.com/ltkong218/IFRNet).
+'''
+import os
+import cv2
+import torch
+import random
+import numpy as np
+from torch.utils.data import Dataset
+from utils.utils import read
+
+
+def random_resize(img0, imgt, img1, flow, p=0.1):
+ if random.uniform(0, 1) < p:
+ img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
+ imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
+ img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
+ flow = cv2.resize(flow, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) * 2.0
+ return img0, imgt, img1, flow
+
+def random_crop(img0, imgt, img1, flow, crop_size=(224, 224)):
+ h, w = crop_size[0], crop_size[1]
+ ih, iw, _ = img0.shape
+ x = np.random.randint(0, ih-h+1)
+ y = np.random.randint(0, iw-w+1)
+ img0 = img0[x:x+h, y:y+w, :]
+ imgt = imgt[x:x+h, y:y+w, :]
+ img1 = img1[x:x+h, y:y+w, :]
+ flow = flow[x:x+h, y:y+w, :]
+ return img0, imgt, img1, flow
+
+def random_reverse_channel(img0, imgt, img1, flow, p=0.5):
+ if random.uniform(0, 1) < p:
+ img0 = img0[:, :, ::-1]
+ imgt = imgt[:, :, ::-1]
+ img1 = img1[:, :, ::-1]
+ return img0, imgt, img1, flow
+
+def random_vertical_flip(img0, imgt, img1, flow, p=0.3):
+ if random.uniform(0, 1) < p:
+ img0 = img0[::-1]
+ imgt = imgt[::-1]
+ img1 = img1[::-1]
+ flow = flow[::-1]
+ flow = np.concatenate((flow[:, :, 0:1], -flow[:, :, 1:2], flow[:, :, 2:3], -flow[:, :, 3:4]), 2)
+ return img0, imgt, img1, flow
+
+def random_horizontal_flip(img0, imgt, img1, flow, p=0.5):
+ if random.uniform(0, 1) < p:
+ img0 = img0[:, ::-1]
+ imgt = imgt[:, ::-1]
+ img1 = img1[:, ::-1]
+ flow = flow[:, ::-1]
+ flow = np.concatenate((-flow[:, :, 0:1], flow[:, :, 1:2], -flow[:, :, 2:3], flow[:, :, 3:4]), 2)
+ return img0, imgt, img1, flow
+
+def random_rotate(img0, imgt, img1, flow, p=0.05):
+ if random.uniform(0, 1) < p:
+ img0 = img0.transpose((1, 0, 2))
+ imgt = imgt.transpose((1, 0, 2))
+ img1 = img1.transpose((1, 0, 2))
+ flow = flow.transpose((1, 0, 2))
+ flow = np.concatenate((flow[:, :, 1:2], flow[:, :, 0:1], flow[:, :, 3:4], flow[:, :, 2:3]), 2)
+ return img0, imgt, img1, flow
+
+def random_reverse_time(img0, imgt, img1, flow, p=0.5):
+ if random.uniform(0, 1) < p:
+ tmp = img1
+ img1 = img0
+ img0 = tmp
+ flow = np.concatenate((flow[:, :, 2:4], flow[:, :, 0:2]), 2)
+ return img0, imgt, img1, flow
+
+
+class Vimeo90K_Train_Dataset(Dataset):
+ def __init__(self,
+ dataset_dir='data/vimeo_triplet',
+ flow_dir=None,
+ augment=True,
+ crop_size=(224, 224)):
+ self.dataset_dir = dataset_dir
+ self.augment = augment
+ self.crop_size = crop_size
+ self.img0_list = []
+ self.imgt_list = []
+ self.img1_list = []
+ self.flow_t0_list = []
+ self.flow_t1_list = []
+ if flow_dir is None:
+ flow_dir = 'flow'
+ with open(os.path.join(dataset_dir, 'tri_trainlist.txt'), 'r') as f:
+ for i in f:
+ name = str(i).strip()
+ if(len(name) <= 1):
+ continue
+ self.img0_list.append(os.path.join(dataset_dir, 'sequences', name, 'im1.png'))
+ self.imgt_list.append(os.path.join(dataset_dir, 'sequences', name, 'im2.png'))
+ self.img1_list.append(os.path.join(dataset_dir, 'sequences', name, 'im3.png'))
+ self.flow_t0_list.append(os.path.join(dataset_dir, flow_dir, name, 'flow_t0.flo'))
+ self.flow_t1_list.append(os.path.join(dataset_dir, flow_dir, name, 'flow_t1.flo'))
+
+ def __len__(self):
+ return len(self.imgt_list)
+
+ def __getitem__(self, idx):
+ img0 = read(self.img0_list[idx])
+ imgt = read(self.imgt_list[idx])
+ img1 = read(self.img1_list[idx])
+ flow_t0 = read(self.flow_t0_list[idx])
+ flow_t1 = read(self.flow_t1_list[idx])
+ flow = np.concatenate((flow_t0, flow_t1), 2).astype(np.float64)
+
+ if self.augment == True:
+ img0, imgt, img1, flow = random_resize(img0, imgt, img1, flow, p=0.1)
+ img0, imgt, img1, flow = random_crop(img0, imgt, img1, flow, crop_size=self.crop_size)
+ img0, imgt, img1, flow = random_reverse_channel(img0, imgt, img1, flow, p=0.5)
+ img0, imgt, img1, flow = random_vertical_flip(img0, imgt, img1, flow, p=0.3)
+ img0, imgt, img1, flow = random_horizontal_flip(img0, imgt, img1, flow, p=0.5)
+ img0, imgt, img1, flow = random_rotate(img0, imgt, img1, flow, p=0.05)
+ img0, imgt, img1, flow = random_reverse_time(img0, imgt, img1, flow, p=0.5)
+
+
+ img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0)
+ imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0)
+ img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0)
+ flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32))
+ embt = torch.from_numpy(np.array(1/2).reshape(1, 1, 1).astype(np.float32))
+
+ return {'img0': img0.float(), 'imgt': imgt.float(), 'img1': img1.float(), 'flow': flow.float(), 'embt': embt}
+
+
+class Vimeo90K_Test_Dataset(Dataset):
+ def __init__(self, dataset_dir='data/vimeo_triplet'):
+ self.dataset_dir = dataset_dir
+ self.img0_list = []
+ self.imgt_list = []
+ self.img1_list = []
+ self.flow_t0_list = []
+ self.flow_t1_list = []
+ with open(os.path.join(dataset_dir, 'tri_testlist.txt'), 'r') as f:
+ for i in f:
+ name = str(i).strip()
+ if(len(name) <= 1):
+ continue
+ self.img0_list.append(os.path.join(dataset_dir, 'sequences', name, 'im1.png'))
+ self.imgt_list.append(os.path.join(dataset_dir, 'sequences', name, 'im2.png'))
+ self.img1_list.append(os.path.join(dataset_dir, 'sequences', name, 'im3.png'))
+ self.flow_t0_list.append(os.path.join(dataset_dir, 'flow', name, 'flow_t0.flo'))
+ self.flow_t1_list.append(os.path.join(dataset_dir, 'flow', name, 'flow_t1.flo'))
+
+ def __len__(self):
+ return len(self.imgt_list)
+
+ def __getitem__(self, idx):
+ img0 = read(self.img0_list[idx])
+ imgt = read(self.imgt_list[idx])
+ img1 = read(self.img1_list[idx])
+ flow_t0 = read(self.flow_t0_list[idx])
+ flow_t1 = read(self.flow_t1_list[idx])
+ flow = np.concatenate((flow_t0, flow_t1), 2)
+
+ img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0)
+ imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0)
+ img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0)
+ flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32))
+ embt = torch.from_numpy(np.array(1/2).reshape(1, 1, 1).astype(np.float32))
+
+ return {'img0': img0.float(),
+ 'imgt': imgt.float(),
+ 'img1': img1.float(),
+ 'flow': flow.float(),
+ 'embt': embt}
+
+
+
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/docs/develop.md b/benchmarks/edit/code/IVEBench/metrics/quality/amt/docs/develop.md
new file mode 100644
index 0000000000000000000000000000000000000000..e927e97632041b7da0adca95e944d9570cfe440c
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/docs/develop.md
@@ -0,0 +1,239 @@
+# Development for evaluation and training
+
+- [Datasets](#Datasets)
+- [Pretrained Models](#pretrained-models)
+- [Evaluation](#evaluation)
+- [Training](#training)
+
+## Datasets
+First, please prepare standard datasets for evaluation and training.
+
+We present most of prevailing datasets in video frame interpolation, though some are not used in our project. Hope this collection could help your research.
+
+
+
+
+## Pretrained Models
+
+
+
+
+
+## Evaluation
+Before evaluation, you should:
+
+1. Check the dataroot is organized as follows:
+
+```shell
+./data
+├── Adobe240
+│ ├── original_high_fps_videos
+│ └── test_frames # using ffmpeg to extract 240 fps frames from `original_high_fps_videos`
+├── GOPRO
+│ ├── test
+│ └── train
+├── SNU_FILM
+│ ├── GOPRO_test
+│ ├── test-easy.txt
+│ ├── test-extreme.txt
+│ ├── test-hard.txt
+│ ├── test-medium.txt
+│ └── YouTube_test
+├── ucf101_interp_ours
+│ ├── 1
+│ ├── 1001
+│ └── ...
+└── vimeo_triplet
+ ├── readme.txt
+ ├── sequences
+ ├── tri_testlist.txt
+ └── tri_trainlist.txt
+```
+
+2. Download the provided [pretrained models](#pretrained-models).
+
+Then, you can perform evaluation as follows:
+
++ Run all benchmarks for fixed-time models.
+
+ ```shell
+ sh ./scripts/benchmark_fixed.sh [CFG] [CKPT_PATH]
+ ## e.g.
+ sh ./scripts/benchmark_fixed.sh cfgs/AMT-S.yaml pretrained/amt-s.pth
+ ```
+
++ Run all benchmarks for arbitrary-time models.
+
+ ```shell
+ sh ./scripts/benchmark_arbitrary.sh [CFG] [CKPT_PATH]
+ ## e.g.
+ sh ./scripts/benchmark_arbitrary.sh cfgs/AMT-S.yaml pretrained/gopro_amt-s.pth
+ ```
+
++ Run a single benchmark for fixed-time models. *You can custom data paths in this case*.
+
+ ```shell
+ python [BENCHMARK] -c [CFG] -p [CKPT_PATH] -r [DATAROOT]
+ ## e.g.
+ python benchmarks/vimeo90k.py -c cfgs/AMT-S.yaml -p pretrained/amt-s.pth -r data/vimeo_triplet
+ ```
+
++ Run the inference speed & model size comparisons using:
+
+ ```shell
+ python speed_parameters.py -c [CFG]
+ ## e.g.
+ python speed_parameters.py -c cfgs/AMT-S.yaml
+ ```
+
+
+## Training
+
+Before training, please first prepare the optical flows (which are used for supervision).
+
+We need to install `cupy` first before flow generation:
+
+```shell
+conda activate amt # satisfying `requirement.txt`
+conda install -c conda-forge cupy
+```
+
+
+After installing `cupy`, we can generate optical flows by the following command:
+
+```shell
+python flow_generation/gen_flow.py -r [DATA_ROOT]
+## e.g.
+python flow_generation/gen_flow.py -r data/vimeo_triplet
+```
+
+After obtaining the optical flow of the training data,
+run the following commands for training (DDP mode):
+
+```shell
+ sh ./scripts/train.sh [NUM_GPU] [CFG] [MASTER_PORT]
+ ## e.g.
+ sh ./scripts/train.sh 2 cfgs/AMT-S.yaml 14514
+```
+
+Our training configuration files are provided in [`cfgs`](../cfgs). Please carefully check the `dataset_dir` is suitable for you.
+
+
+Note:
+
+- If you intend to turn off DDP training, you can switch the key `distributed` from `true`
+to `false` in the config file.
+
+- If you do not use wandb, you can switch the key `logger.use_wandb` from `true`
+to `false` in the config file.
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/docs/method.md b/benchmarks/edit/code/IVEBench/metrics/quality/amt/docs/method.md
new file mode 100644
index 0000000000000000000000000000000000000000..1343649b503f807a0e6c46f0895d78c3fc6f4e79
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/docs/method.md
@@ -0,0 +1,126 @@
+# Illustration of AMT
+
+
+
+
+
+### :rocket: Highlights:
+
++ [**Good tradeoff**](#good-tradeoff) between performance and efficiency.
+
++ [**All-pairs correlation**](#all-pairs-correlation) for modeling large motions during interpolation.
+
++ A [**plug-and-play operator**](#multi-field-refinement) to improve the diversity of predicted task-oriented flows, further **boosting the interpolation performance**.
+
+
+## Good Tradeoff
+
+
+
+
+
+We examine the proposed AMT on several public benchmarks with different model scales, showing strong performance and high efficiency in contrast to the SOTA methods (see Figure). Our small model outperforms [IFRNet-B](https://arxiv.org/abs/2205.14620), a SOTA lightweight model, by **\+0.17dB PSNR** on Vimeo90K with **only 60% of its FLOPs and parameters**. For large-scale setting, our AMT exceeds the previous SOTA (i.e., [IFRNet-L](https://arxiv.org/abs/2205.14620)) by **+0.15 dB PSNR** on Vimeo90K with **75% of its FLOPs and 65% of its parameters**. Besides, we provide a huge model for comparison
+with the SOTA transformer-based method [VFIFormer](https://arxiv.org/abs/2205.07230). Our convolution-based AMT shows a **comparable performance** but only needs **nearly 23× less computational cost** compared to VFIFormer.
+
+Considering its effectiveness, we hope our AMT could bring a new perspective for the architecture design in efficient frame interpolation.
+
+## All-pairs correlation
+
+We build all-pairs correlation to effectively model large motions during interpolation.
+
+Here is an example about the update operation at a single scale in AMT:
+
+```python
+ # Construct bidirectional correlation volumes
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [B, C, H//8, W//8]
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
+
+ # Correlation scaled lookup (bilateral -> bidirectional)
+ t1_scale = 1. / embt
+ t0_scale = 1. / (1. - embt)
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
+ corr = torch.cat([corr0, corr1], dim=1)
+ flow = torch.cat([flow0, flow1], dim=1)
+
+ # Update both intermediate feature and bilateral flows
+ delta_feat, delta_flow = self.update(feat, flow, corr)
+ delta_flow0, delta_flow1 = torch.chunk(delta_flow, 2, 1)
+ flow0 = flow0 + delta_flow0
+ flow1= flow1 + delta_flow1
+ feat = feat + delta_feat
+
+```
+
+Note: we extend above operations to each pyramid scale (except for the last one), which guarantees the consistency of flows on the coarse scale.
+
+### ⏫ performance gain
+| | Vimeo 90k | Hard | Extreme |
+|-------------------------|-----------|-------|---------|
+| Baseline | 35.60 | 30.39 | 25.06 |
+| + All-pairs correlation | 35.97 (**+0.37**) | 30.60 (**+0.21**) | 25.30 (**+0.24**) |
+
+More ablations can be found in the [paper](https://arxiv.org/abs/2304.09790).
+
+## Multi-field Refinement
+
+For most frame interpolation methods which are based on backward warping, the common formulation for
+interpolating the final intermediate frame $I_{t}$ is:
+
+$I_{t} = M \odot \mathcal{W}(I_{0}, F_{t\rightarrow 0}) + (1 - M) \odot \mathcal{W}(I_{1}, F_{t\rightarrow 1}) + R$
+
+Above formualtion only utilizes **one set of** bilateral optical flows $F_{t\rightarrow 0}$ and $F_{t\rightarrow 1}$, occulusion masks $M$, and residuals $R$.
+
+Multi-field refinement aims to improve the common formulation of backward warping.
+Specifically, we first predict **multiple** bilateral optical flows (accompanied by the corresponding masks and residuals) through simply enlarging the output channels of the last decoder.
+Then, we use aforementioned equation to genearate each interpolated candidate frame. Finally, we obtain the final interpolated frame through combining candidate frames using stacked convolutional layers.
+
+Please refer to [this code snippet](../networks/blocks/multi_flow.py#L46) for the details of the first step.
+Please refer to [this code snippet](../networks/blocks/multi_flow.py#L10) for the details of the last two steps.
+
+### 🌟 easy to use
+The proposed multi-field refinement can be **easily migrated to any frame interpolation model** to improve the performance.
+
+Code examples are shown below:
+
+```python
+
+# (At the __init__ stage) Initialize a decoder that predicts multiple flow fields (accompanied by the corresponding masks and residuals)
+self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
+...
+
+# (At the forward stage) Predict multiple flow fields (accompanied by the corresponding masks and residuals)
+up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
+# Merge multiple predictions
+imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, # self.comb_block stacks two convolutional layers
+ mask, img_res, mean_)
+
+```
+
+### ⏫ performance gain
+
+| # Number of flow pairs | Vimeo 90k | Hard | Extreme |
+|------------------------|---------------|---------------|---------------|
+| Baseline (1 pair) | 35.84 | 30.52 | 25.25 |
+| 3 pairs | 35.97 (**+0.13**) | 30.60 (**+0.08**) | 25.30 (**+0.05**) |
+| 5 pairs | 36.00 (**+0.16**) | 30.63 (**+0.11**) | 25.33 (**+0.08**) |
+
+## Comparison with SOTA methods
+
+
+
+
+
+## Discussions
+
+We encountered the challenges about the novelty issue during the rebuttal process.
+
+We are ready to clarify again here:
+
+1. We consider the estimation of task-oriented flows from **the perspective of architecture formulation rather than loss function designs** in previous works. The detailed analysis can be found in Sec. 1 of the main paper. We introduce all-pairs correlation to strengthen the ability
+in motion modeling, which guarantees **the consistency of flows on the coarse scale**. We employ multi-field refinement to **ensure diversity for the flow regions that need to be task-specific at the finest scale**. The two designs also enable our AMT to capture large motions and successfully handle occlusion regions with high efficiency. As a consequence, they both bring noticeable performance improvements, as shown in the ablations.
+2. The frame interpolation task is closely related to the **motion modeling**. We strongly believe that a [RAFT-style](https://arxiv.org/abs/2003.12039) approach to motion modeling would be beneficial for the frame interpolation task. However, such style **has not been well studied** in the recent frame interpolation literature. Experimental results show that **all-pairs correlation is very important for the performance gain**. We also involve many novel and task-specific designs
+beyond the original RAFT. For other task-related design choices, our volume design, scaled lookup strategy, content update, and cross-scale update way have good performance gains on challenging cases (i.e., Hard and Extreme). Besides, if we discard all design choices (but remaining multi-field refinement) and follow the original RAFT to retrain a new model, **the PSNR values will dramatically decrease** (-0.20dB on Vimeo, -0.33dB on Hard, and -0.39dB on Extreme).
+3. [M2M-VFI](https://arxiv.org/abs/2204.03513) is the most relevant to our multi-field refinement. It also generates multiple flows through the decoder and prepares warped candidates in the image domain. However, there are **five key differences** between our multi-field refinement and M2M-VFI. **First**, our method generates the candidate frames by backward warping rather than forward warping in M2M-VFI. The proposed multi-field refinement aims to improve the common formulation of backward warping (see Eqn.~(4) in the main paper). **Second**, while M2M-VFI predicts multiple flows to overcome the hole issue and artifacts in overlapped regions caused by forward warping, we aim to alleviate the ambiguity issue in the occluded areas and motion boundaries by enhancing the diversity of flows. **Third**, M2M-VFI needs to estimate bidirectional flows first through an off-the-shelf optical flow estimator and then predict multiple bilateral flows through a motion refinement network. On the contrary, we directly estimate multiple bilateral flows in a one-stage network. In this network, we first estimate one pair of bilateral flows at the coarse scale and then derive multiple groups of fine-grained bilateral flows from the coarse flow pairs. **Fourth**, M2M-VFI jointly estimates two reliability maps together with all pairs of bilateral flows, which can be further used to fuse the overlapping pixels caused by forward warping. As shown in Eqn. (5) of the main paper, we estimate not only an occlusion mask but a residual content for cooperating with each pair of bilateral flows. The residual content is used to compensate for the unreliable details after warping. This design has been investigated in Tab. 2e of the main paper. **Fifth**, we stack two convolutional layers to adaptively merge candidate frames, while M2M-VFI normalizes the sum of all candidate frames through a pre-computed weighting map
+
+More discussions and details can be found in the [appendix](https://arxiv.org/abs/2304.09790) of our paper.
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/environment.yaml b/benchmarks/edit/code/IVEBench/metrics/quality/amt/environment.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..cd402d0bcdc80996e6ef504a7ef607b3d3e840f3
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/environment.yaml
@@ -0,0 +1,19 @@
+name: amt
+channels:
+ - pytorch
+ - conda-forge
+ - defaults
+dependencies:
+ - python=3.8.5
+ - pip=20.3
+ - cudatoolkit=11.3
+ - pytorch=1.11.0
+ - torchvision=0.12.0
+ - numpy=1.21.5
+ - pip:
+ - opencv-python==4.1.2.30
+ - imageio==2.19.3
+ - omegaconf==2.3.0
+ - Pillow==9.4.0
+ - tqdm==4.64.1
+ - wandb==0.12.21
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/gen_flow.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/gen_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9d393b3de59e715c484362b762e9de5a24b65e7
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/gen_flow.py
@@ -0,0 +1,72 @@
+import os
+import sys
+import torch
+import argparse
+import numpy as np
+import os.path as osp
+import torch.nn.functional as F
+
+sys.path.append('.')
+from utils.utils import read, write
+from flow_generation.liteflownet.run import estimate
+
+parser = argparse.ArgumentParser(
+ prog = 'AMT',
+ description = 'Flow generation',
+ )
+parser.add_argument('-r', '--root', default='data/vimeo_triplet')
+args = parser.parse_args()
+
+vimeo90k_dir = args.root
+vimeo90k_sequences_dir = osp.join(vimeo90k_dir, 'sequences')
+vimeo90k_flow_dir = osp.join(vimeo90k_dir, 'flow')
+
+def pred_flow(img1, img2):
+ img1 = torch.from_numpy(img1).float().permute(2, 0, 1) / 255.0
+ img2 = torch.from_numpy(img2).float().permute(2, 0, 1) / 255.0
+
+ flow = estimate(img1, img2)
+
+ flow = flow.permute(1, 2, 0).cpu().numpy()
+ return flow
+
+print('Built Flow Path')
+if not osp.exists(vimeo90k_flow_dir):
+ os.makedirs(vimeo90k_flow_dir)
+
+for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)):
+ vimeo90k_sequences_path_dir = osp.join(vimeo90k_sequences_dir, sequences_path)
+ vimeo90k_flow_path_dir = osp.join(vimeo90k_flow_dir, sequences_path)
+ if not osp.exists(vimeo90k_flow_path_dir):
+ os.mkdir(vimeo90k_flow_path_dir)
+
+ for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)):
+ vimeo90k_flow_id_dir = osp.join(vimeo90k_flow_path_dir, sequences_id)
+ if not osp.exists(vimeo90k_flow_id_dir):
+ os.mkdir(vimeo90k_flow_id_dir)
+
+for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)):
+ vimeo90k_sequences_path_dir = os.path.join(vimeo90k_sequences_dir, sequences_path)
+ vimeo90k_flow_path_dir = os.path.join(vimeo90k_flow_dir, sequences_path)
+
+ for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)):
+ vimeo90k_sequences_id_dir = os.path.join(vimeo90k_sequences_path_dir, sequences_id)
+ vimeo90k_flow_id_dir = os.path.join(vimeo90k_flow_path_dir, sequences_id)
+
+ img0_path = vimeo90k_sequences_id_dir + '/im1.png'
+ imgt_path = vimeo90k_sequences_id_dir + '/im2.png'
+ img1_path = vimeo90k_sequences_id_dir + '/im3.png'
+ flow_t0_path = vimeo90k_flow_id_dir + '/flow_t0.flo'
+ flow_t1_path = vimeo90k_flow_id_dir + '/flow_t1.flo'
+
+ img0 = read(img0_path)
+ imgt = read(imgt_path)
+ img1 = read(img1_path)
+
+ flow_t0 = pred_flow(imgt, img0)
+ flow_t1 = pred_flow(imgt, img1)
+
+ write(flow_t0_path, flow_t0)
+ write(flow_t1_path, flow_t1)
+
+ print('Written Sequences {}'.format(sequences_path))
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/README.md b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..9511ad984f0209048ad912250b611f8e0459668b
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/README.md
@@ -0,0 +1,45 @@
+# pytorch-liteflownet
+This is a personal reimplementation of LiteFlowNet [1] using PyTorch. Should you be making use of this work, please cite the paper accordingly. Also, make sure to adhere to the licensing terms of the authors. Should you be making use of this particular implementation, please acknowledge it appropriately [2].
+
+
+
+For the original Caffe version of this work, please see: https://github.com/twhui/LiteFlowNet
+
+Other optical flow implementations from me: [pytorch-pwc](https://github.com/sniklaus/pytorch-pwc), [pytorch-unflow](https://github.com/sniklaus/pytorch-unflow), [pytorch-spynet](https://github.com/sniklaus/pytorch-spynet)
+
+## setup
+The correlation layer is implemented in CUDA using CuPy, which is why CuPy is a required dependency. It can be installed using `pip install cupy` or alternatively using one of the provided [binary packages](https://docs.cupy.dev/en/stable/install.html#installing-cupy) as outlined in the CuPy repository. If you would like to use Docker, you can take a look at [this](https://github.com/sniklaus/pytorch-liteflownet/pull/43) pull request to get started.
+
+## usage
+To run it on your own pair of images, use the following command. You can choose between three models, please make sure to see their paper / the code for more details.
+
+```
+python run.py --model default --one ./images/one.png --two ./images/two.png --out ./out.flo
+```
+
+I am afraid that I cannot guarantee that this reimplementation is correct. However, it produced results pretty much identical to the implementation of the original authors in the examples that I tried. There are some numerical deviations that stem from differences in the `DownsampleLayer` of Caffe and the `torch.nn.functional.interpolate` function of PyTorch. Please feel free to contribute to this repository by submitting issues and pull requests.
+
+## comparison
+
+
+## license
+As stated in the licensing terms of the authors of the paper, their material is provided for research purposes only. Please make sure to further consult their licensing terms.
+
+## references
+```
+[1] @inproceedings{Hui_CVPR_2018,
+ author = {Tak-Wai Hui and Xiaoou Tang and Chen Change Loy},
+ title = {{LiteFlowNet}: A Lightweight Convolutional Neural Network for Optical Flow Estimation},
+ booktitle = {IEEE Conference on Computer Vision and Pattern Recognition},
+ year = {2018}
+ }
+```
+
+```
+[2] @misc{pytorch-liteflownet,
+ author = {Simon Niklaus},
+ title = {A Reimplementation of {LiteFlowNet} Using {PyTorch}},
+ year = {2019},
+ howpublished = {\url{https://github.com/sniklaus/pytorch-liteflownet}}
+ }
+```
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/README.md_0df1462254df4f6eb8708d8a8583fd8d b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/README.md_0df1462254df4f6eb8708d8a8583fd8d
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/correlation/README.md b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/correlation/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..e80f923bfa484ff505366c30f66fa88da0bfd566
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/correlation/README.md
@@ -0,0 +1 @@
+This is an adaptation of the FlowNet2 implementation in order to compute cost volumes. Should you be making use of this work, please make sure to adhere to the licensing terms of the original authors. Should you be making use or modify this particular implementation, please acknowledge it appropriately.
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/correlation/correlation.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/correlation/correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..212af7103a8bffd024cf7e8e43c4a96997157f53
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/correlation/correlation.py
@@ -0,0 +1,396 @@
+#!/usr/bin/env python
+
+import cupy
+import math
+import re
+import torch
+
+kernel_Correlation_rearrange = '''
+ extern "C" __global__ void kernel_Correlation_rearrange(
+ const int n,
+ const float* input,
+ float* output
+ ) {
+ int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x;
+ if (intIndex >= n) {
+ return;
+ }
+ int intSample = blockIdx.z;
+ int intChannel = blockIdx.y;
+ float fltValue = input[(((intSample * SIZE_1(input)) + intChannel) * SIZE_2(input) * SIZE_3(input)) + intIndex];
+ __syncthreads();
+ int intPaddedY = (intIndex / SIZE_3(input)) + 3*{{intStride}};
+ int intPaddedX = (intIndex % SIZE_3(input)) + 3*{{intStride}};
+ int intRearrange = ((SIZE_3(input) + 6*{{intStride}}) * intPaddedY) + intPaddedX;
+ output[(((intSample * SIZE_1(output) * SIZE_2(output)) + intRearrange) * SIZE_1(input)) + intChannel] = fltValue;
+ }
+'''
+
+kernel_Correlation_updateOutput = '''
+ extern "C" __global__ void kernel_Correlation_updateOutput(
+ const int n,
+ const float* rbot0,
+ const float* rbot1,
+ float* top
+ ) {
+ extern __shared__ char patch_data_char[];
+
+ float *patch_data = (float *)patch_data_char;
+
+ // First (upper left) position of kernel upper-left corner in current center position of neighborhood in image 1
+ int x1 = (blockIdx.x + 3) * {{intStride}};
+ int y1 = (blockIdx.y + 3) * {{intStride}};
+ int item = blockIdx.z;
+ int ch_off = threadIdx.x;
+
+ // Load 3D patch into shared shared memory
+ for (int j = 0; j < 1; j++) { // HEIGHT
+ for (int i = 0; i < 1; i++) { // WIDTH
+ int ji_off = (j + i) * SIZE_3(rbot0);
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
+ int idx1 = ((item * SIZE_1(rbot0) + y1+j) * SIZE_2(rbot0) + x1+i) * SIZE_3(rbot0) + ch;
+ int idxPatchData = ji_off + ch;
+ patch_data[idxPatchData] = rbot0[idx1];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ __shared__ float sum[32];
+
+ // Compute correlation
+ for (int top_channel = 0; top_channel < SIZE_1(top); top_channel++) {
+ sum[ch_off] = 0;
+
+ int s2o = (top_channel % 7 - 3) * {{intStride}};
+ int s2p = (top_channel / 7 - 3) * {{intStride}};
+
+ for (int j = 0; j < 1; j++) { // HEIGHT
+ for (int i = 0; i < 1; i++) { // WIDTH
+ int ji_off = (j + i) * SIZE_3(rbot0);
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
+ int x2 = x1 + s2o;
+ int y2 = y1 + s2p;
+
+ int idxPatchData = ji_off + ch;
+ int idx2 = ((item * SIZE_1(rbot0) + y2+j) * SIZE_2(rbot0) + x2+i) * SIZE_3(rbot0) + ch;
+
+ sum[ch_off] += patch_data[idxPatchData] * rbot1[idx2];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ if (ch_off == 0) {
+ float total_sum = 0;
+ for (int idx = 0; idx < 32; idx++) {
+ total_sum += sum[idx];
+ }
+ const int sumelems = SIZE_3(rbot0);
+ const int index = ((top_channel*SIZE_2(top) + blockIdx.y)*SIZE_3(top))+blockIdx.x;
+ top[index + item*SIZE_1(top)*SIZE_2(top)*SIZE_3(top)] = total_sum / (float)sumelems;
+ }
+ }
+ }
+'''
+
+kernel_Correlation_updateGradOne = '''
+ #define ROUND_OFF 50000
+ extern "C" __global__ void kernel_Correlation_updateGradOne(
+ const int n,
+ const int intSample,
+ const float* rbot0,
+ const float* rbot1,
+ const float* gradOutput,
+ float* gradOne,
+ float* gradTwo
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
+ int n = intIndex % SIZE_1(gradOne); // channels
+ int l = (intIndex / SIZE_1(gradOne)) % SIZE_3(gradOne) + 3*{{intStride}}; // w-pos
+ int m = (intIndex / SIZE_1(gradOne) / SIZE_3(gradOne)) % SIZE_2(gradOne) + 3*{{intStride}}; // h-pos
+
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
+ // We use a large offset, for the inner part not to become negative.
+ const int round_off = ROUND_OFF;
+ const int round_off_s1 = {{intStride}} * round_off;
+
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
+ int xmin = (l - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}}
+ int ymin = (m - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}}
+
+ // Same here:
+ int xmax = (l - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}}) / {{intStride}}
+ int ymax = (m - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}}) / {{intStride}}
+
+ float sum = 0;
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
+ xmin = max(0,xmin);
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
+
+ ymin = max(0,ymin);
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
+
+ for (int p = -3; p <= 3; p++) {
+ for (int o = -3; o <= 3; o++) {
+ // Get rbot1 data:
+ int s2o = {{intStride}} * o;
+ int s2p = {{intStride}} * p;
+ int idxbot1 = ((intSample * SIZE_1(rbot0) + (m+s2p)) * SIZE_2(rbot0) + (l+s2o)) * SIZE_3(rbot0) + n;
+ float bot1tmp = rbot1[idxbot1]; // rbot1[l+s2o,m+s2p,n]
+
+ // Index offset for gradOutput in following loops:
+ int op = (p+3) * 7 + (o+3); // index[o,p]
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
+
+ for (int y = ymin; y <= ymax; y++) {
+ for (int x = xmin; x <= xmax; x++) {
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
+ sum += gradOutput[idxgradOutput] * bot1tmp;
+ }
+ }
+ }
+ }
+ }
+ const int sumelems = SIZE_1(gradOne);
+ const int bot0index = ((n * SIZE_2(gradOne)) + (m-3*{{intStride}})) * SIZE_3(gradOne) + (l-3*{{intStride}});
+ gradOne[bot0index + intSample*SIZE_1(gradOne)*SIZE_2(gradOne)*SIZE_3(gradOne)] = sum / (float)sumelems;
+ } }
+'''
+
+kernel_Correlation_updateGradTwo = '''
+ #define ROUND_OFF 50000
+ extern "C" __global__ void kernel_Correlation_updateGradTwo(
+ const int n,
+ const int intSample,
+ const float* rbot0,
+ const float* rbot1,
+ const float* gradOutput,
+ float* gradOne,
+ float* gradTwo
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
+ int n = intIndex % SIZE_1(gradTwo); // channels
+ int l = (intIndex / SIZE_1(gradTwo)) % SIZE_3(gradTwo) + 3*{{intStride}}; // w-pos
+ int m = (intIndex / SIZE_1(gradTwo) / SIZE_3(gradTwo)) % SIZE_2(gradTwo) + 3*{{intStride}}; // h-pos
+
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
+ // We use a large offset, for the inner part not to become negative.
+ const int round_off = ROUND_OFF;
+ const int round_off_s1 = {{intStride}} * round_off;
+
+ float sum = 0;
+ for (int p = -3; p <= 3; p++) {
+ for (int o = -3; o <= 3; o++) {
+ int s2o = {{intStride}} * o;
+ int s2p = {{intStride}} * p;
+
+ //Get X,Y ranges and clamp
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
+ int xmin = (l - 3*{{intStride}} - s2o + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}}
+ int ymin = (m - 3*{{intStride}} - s2p + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}}
+
+ // Same here:
+ int xmax = (l - 3*{{intStride}} - s2o + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}} - s2o) / {{intStride}}
+ int ymax = (m - 3*{{intStride}} - s2p + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}} - s2p) / {{intStride}}
+
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
+ xmin = max(0,xmin);
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
+
+ ymin = max(0,ymin);
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
+
+ // Get rbot0 data:
+ int idxbot0 = ((intSample * SIZE_1(rbot0) + (m-s2p)) * SIZE_2(rbot0) + (l-s2o)) * SIZE_3(rbot0) + n;
+ float bot0tmp = rbot0[idxbot0]; // rbot1[l+s2o,m+s2p,n]
+
+ // Index offset for gradOutput in following loops:
+ int op = (p+3) * 7 + (o+3); // index[o,p]
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
+
+ for (int y = ymin; y <= ymax; y++) {
+ for (int x = xmin; x <= xmax; x++) {
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
+ sum += gradOutput[idxgradOutput] * bot0tmp;
+ }
+ }
+ }
+ }
+ }
+ const int sumelems = SIZE_1(gradTwo);
+ const int bot1index = ((n * SIZE_2(gradTwo)) + (m-3*{{intStride}})) * SIZE_3(gradTwo) + (l-3*{{intStride}});
+ gradTwo[bot1index + intSample*SIZE_1(gradTwo)*SIZE_2(gradTwo)*SIZE_3(gradTwo)] = sum / (float)sumelems;
+ } }
+'''
+
+def cupy_kernel(strFunction, objVariables):
+ strKernel = globals()[strFunction].replace('{{intStride}}', str(objVariables['intStride']))
+
+ while True:
+ objMatch = re.search('(SIZE_)([0-4])(\()([^\)]*)(\))', strKernel)
+
+ if objMatch is None:
+ break
+ # end
+
+ intArg = int(objMatch.group(2))
+
+ strTensor = objMatch.group(4)
+ intSizes = objVariables[strTensor].size()
+
+ strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg] if torch.is_tensor(intSizes[intArg]) == False else intSizes[intArg].item()))
+ # end
+
+ while True:
+ objMatch = re.search('(VALUE_)([0-4])(\()([^\)]+)(\))', strKernel)
+
+ if objMatch is None:
+ break
+ # end
+
+ intArgs = int(objMatch.group(2))
+ strArgs = objMatch.group(4).split(',')
+
+ strTensor = strArgs[0]
+ intStrides = objVariables[strTensor].stride()
+ strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg] if torch.is_tensor(intStrides[intArg]) == False else intStrides[intArg].item()) + ')' for intArg in range(intArgs) ]
+
+ strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')
+ # end
+
+ return strKernel
+# end
+
+@cupy.memoize(for_each_device=True)
+def cupy_launch(strFunction, strKernel):
+ return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction)
+# end
+
+class _FunctionCorrelation(torch.autograd.Function):
+ @staticmethod
+ def forward(self, one, two, intStride):
+ rbot0 = one.new_zeros([ one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1] ])
+ rbot1 = one.new_zeros([ one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1] ])
+
+ self.intStride = intStride
+
+ one = one.contiguous(); assert(one.is_cuda == True)
+ two = two.contiguous(); assert(two.is_cuda == True)
+
+ output = one.new_zeros([ one.shape[0], 49, int(math.ceil(one.shape[2] / intStride)), int(math.ceil(one.shape[3] / intStride)) ])
+
+ if one.is_cuda == True:
+ n = one.shape[2] * one.shape[3]
+ cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
+ 'intStride': self.intStride,
+ 'input': one,
+ 'output': rbot0
+ }))(
+ grid=tuple([ int((n + 16 - 1) / 16), one.shape[1], one.shape[0] ]),
+ block=tuple([ 16, 1, 1 ]),
+ args=[ cupy.int32(n), one.data_ptr(), rbot0.data_ptr() ]
+ )
+
+ n = two.shape[2] * two.shape[3]
+ cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
+ 'intStride': self.intStride,
+ 'input': two,
+ 'output': rbot1
+ }))(
+ grid=tuple([ int((n + 16 - 1) / 16), two.shape[1], two.shape[0] ]),
+ block=tuple([ 16, 1, 1 ]),
+ args=[ cupy.int32(n), two.data_ptr(), rbot1.data_ptr() ]
+ )
+
+ n = output.shape[1] * output.shape[2] * output.shape[3]
+ cupy_launch('kernel_Correlation_updateOutput', cupy_kernel('kernel_Correlation_updateOutput', {
+ 'intStride': self.intStride,
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'top': output
+ }))(
+ grid=tuple([ output.shape[3], output.shape[2], output.shape[0] ]),
+ block=tuple([ 32, 1, 1 ]),
+ shared_mem=one.shape[1] * 4,
+ args=[ cupy.int32(n), rbot0.data_ptr(), rbot1.data_ptr(), output.data_ptr() ]
+ )
+
+ elif one.is_cuda == False:
+ raise NotImplementedError()
+
+ # end
+
+ self.save_for_backward(one, two, rbot0, rbot1)
+
+ return output
+ # end
+
+ @staticmethod
+ def backward(self, gradOutput):
+ one, two, rbot0, rbot1 = self.saved_tensors
+
+ gradOutput = gradOutput.contiguous(); assert(gradOutput.is_cuda == True)
+
+ gradOne = one.new_zeros([ one.shape[0], one.shape[1], one.shape[2], one.shape[3] ]) if self.needs_input_grad[0] == True else None
+ gradTwo = one.new_zeros([ one.shape[0], one.shape[1], one.shape[2], one.shape[3] ]) if self.needs_input_grad[1] == True else None
+
+ if one.is_cuda == True:
+ if gradOne is not None:
+ for intSample in range(one.shape[0]):
+ n = one.shape[1] * one.shape[2] * one.shape[3]
+ cupy_launch('kernel_Correlation_updateGradOne', cupy_kernel('kernel_Correlation_updateGradOne', {
+ 'intStride': self.intStride,
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'gradOutput': gradOutput,
+ 'gradOne': gradOne,
+ 'gradTwo': None
+ }))(
+ grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
+ block=tuple([ 512, 1, 1 ]),
+ args=[ cupy.int32(n), intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), gradOne.data_ptr(), None ]
+ )
+ # end
+ # end
+
+ if gradTwo is not None:
+ for intSample in range(one.shape[0]):
+ n = one.shape[1] * one.shape[2] * one.shape[3]
+ cupy_launch('kernel_Correlation_updateGradTwo', cupy_kernel('kernel_Correlation_updateGradTwo', {
+ 'intStride': self.intStride,
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'gradOutput': gradOutput,
+ 'gradOne': None,
+ 'gradTwo': gradTwo
+ }))(
+ grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
+ block=tuple([ 512, 1, 1 ]),
+ args=[ cupy.int32(n), intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), None, gradTwo.data_ptr() ]
+ )
+ # end
+ # end
+
+ elif one.is_cuda == False:
+ raise NotImplementedError()
+
+ # end
+
+ return gradOne, gradTwo, None
+ # end
+# end
+
+def FunctionCorrelation(tenOne, tenTwo, intStride):
+ return _FunctionCorrelation.apply(tenOne, tenTwo, intStride)
+# end
+
+class ModuleCorrelation(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ # end
+
+ def forward(self, tenOne, tenTwo, intStride):
+ return _FunctionCorrelation.apply(tenOne, tenTwo, intStride)
+ # end
+# end
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/run.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/run.py
new file mode 100644
index 0000000000000000000000000000000000000000..1957621f3bd9cae2651f8767466f5c1542df3299
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/flow_generation/liteflownet/run.py
@@ -0,0 +1,385 @@
+#!/usr/bin/env python
+
+import getopt
+import math
+import numpy
+import PIL
+import PIL.Image
+import sys
+import torch
+
+try:
+ from .correlation import correlation # the custom cost volume layer
+except:
+ sys.path.insert(0, './correlation'); import correlation # you should consider upgrading python
+# end
+
+##########################################################
+
+assert(int(str('').join(torch.__version__.split('.')[0:2])) >= 13) # requires at least pytorch version 1.3.0
+
+torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance
+
+torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance
+
+##########################################################
+
+arguments_strModel = 'default' # 'default', or 'kitti', or 'sintel'
+arguments_strOne = './images/one.png'
+arguments_strTwo = './images/two.png'
+arguments_strOut = './out.flo'
+
+for strOption, strArgument in getopt.getopt(sys.argv[1:], '', [ strParameter[2:] + '=' for strParameter in sys.argv[1::2] ])[0]:
+ if strOption == '--model' and strArgument != '': arguments_strModel = strArgument # which model to use
+ if strOption == '--one' and strArgument != '': arguments_strOne = strArgument # path to the first frame
+ if strOption == '--two' and strArgument != '': arguments_strTwo = strArgument # path to the second frame
+ if strOption == '--out' and strArgument != '': arguments_strOut = strArgument # path to where the output should be stored
+# end
+
+##########################################################
+
+backwarp_tenGrid = {}
+
+def backwarp(tenInput, tenFlow):
+ if str(tenFlow.shape) not in backwarp_tenGrid:
+ tenHor = torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3]).view(1, 1, 1, -1).repeat(1, 1, tenFlow.shape[2], 1)
+ tenVer = torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2]).view(1, 1, -1, 1).repeat(1, 1, 1, tenFlow.shape[3])
+
+ backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([ tenHor, tenVer ], 1).cuda()
+ # end
+
+ tenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)
+
+ return torch.nn.functional.grid_sample(input=tenInput, grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros', align_corners=False)
+# end
+
+##########################################################
+
+class Network(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+
+ class Features(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+
+ self.netOne = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=7, stride=1, padding=3),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netTwo = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netThr = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFou = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFiv = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netSix = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=128, out_channels=192, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+ # end
+
+ def forward(self, tenInput):
+ tenOne = self.netOne(tenInput)
+ tenTwo = self.netTwo(tenOne)
+ tenThr = self.netThr(tenTwo)
+ tenFou = self.netFou(tenThr)
+ tenFiv = self.netFiv(tenFou)
+ tenSix = self.netSix(tenFiv)
+
+ return [ tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix ]
+ # end
+ # end
+
+ class Matching(torch.nn.Module):
+ def __init__(self, intLevel):
+ super().__init__()
+
+ self.fltBackwarp = [ 0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625 ][intLevel]
+
+ if intLevel != 2:
+ self.netFeat = torch.nn.Sequential()
+
+ elif intLevel == 2:
+ self.netFeat = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ # end
+
+ if intLevel == 6:
+ self.netUpflow = None
+
+ elif intLevel != 6:
+ self.netUpflow = torch.nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1, bias=False, groups=2)
+
+ # end
+
+ if intLevel >= 4:
+ self.netUpcorr = None
+
+ elif intLevel < 4:
+ self.netUpcorr = torch.nn.ConvTranspose2d(in_channels=49, out_channels=49, kernel_size=4, stride=2, padding=1, bias=False, groups=49)
+
+ # end
+
+ self.netMain = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=49, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=[ 0, 0, 7, 5, 5, 3, 3 ][intLevel], stride=1, padding=[ 0, 0, 3, 2, 2, 1, 1 ][intLevel])
+ )
+ # end
+
+ def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow):
+ tenFeaturesOne = self.netFeat(tenFeaturesOne)
+ tenFeaturesTwo = self.netFeat(tenFeaturesTwo)
+
+ if tenFlow is not None:
+ tenFlow = self.netUpflow(tenFlow)
+ # end
+
+ if tenFlow is not None:
+ tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackwarp)
+ # end
+
+ if self.netUpcorr is None:
+ tenCorrelation = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=1), negative_slope=0.1, inplace=False)
+
+ elif self.netUpcorr is not None:
+ tenCorrelation = self.netUpcorr(torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=2), negative_slope=0.1, inplace=False))
+
+ # end
+
+ return (tenFlow if tenFlow is not None else 0.0) + self.netMain(tenCorrelation)
+ # end
+ # end
+
+ class Subpixel(torch.nn.Module):
+ def __init__(self, intLevel):
+ super().__init__()
+
+ self.fltBackward = [ 0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625 ][intLevel]
+
+ if intLevel != 2:
+ self.netFeat = torch.nn.Sequential()
+
+ elif intLevel == 2:
+ self.netFeat = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ # end
+
+ self.netMain = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=[ 0, 0, 130, 130, 194, 258, 386 ][intLevel], out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=[ 0, 0, 7, 5, 5, 3, 3 ][intLevel], stride=1, padding=[ 0, 0, 3, 2, 2, 1, 1 ][intLevel])
+ )
+ # end
+
+ def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow):
+ tenFeaturesOne = self.netFeat(tenFeaturesOne)
+ tenFeaturesTwo = self.netFeat(tenFeaturesTwo)
+
+ if tenFlow is not None:
+ tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackward)
+ # end
+
+ return (tenFlow if tenFlow is not None else 0.0) + self.netMain(torch.cat([ tenFeaturesOne, tenFeaturesTwo, tenFlow ], 1))
+ # end
+ # end
+
+ class Regularization(torch.nn.Module):
+ def __init__(self, intLevel):
+ super().__init__()
+
+ self.fltBackward = [ 0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625 ][intLevel]
+
+ self.intUnfold = [ 0, 0, 7, 5, 5, 3, 3 ][intLevel]
+
+ if intLevel >= 5:
+ self.netFeat = torch.nn.Sequential()
+
+ elif intLevel < 5:
+ self.netFeat = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=[ 0, 0, 32, 64, 96, 128, 192 ][intLevel], out_channels=128, kernel_size=1, stride=1, padding=0),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ # end
+
+ self.netMain = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=[ 0, 0, 131, 131, 131, 131, 195 ][intLevel], out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ if intLevel >= 5:
+ self.netDist = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=[ 0, 0, 49, 25, 25, 9, 9 ][intLevel], kernel_size=[ 0, 0, 7, 5, 5, 3, 3 ][intLevel], stride=1, padding=[ 0, 0, 3, 2, 2, 1, 1 ][intLevel])
+ )
+
+ elif intLevel < 5:
+ self.netDist = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=[ 0, 0, 49, 25, 25, 9, 9 ][intLevel], kernel_size=([ 0, 0, 7, 5, 5, 3, 3 ][intLevel], 1), stride=1, padding=([ 0, 0, 3, 2, 2, 1, 1 ][intLevel], 0)),
+ torch.nn.Conv2d(in_channels=[ 0, 0, 49, 25, 25, 9, 9 ][intLevel], out_channels=[ 0, 0, 49, 25, 25, 9, 9 ][intLevel], kernel_size=(1, [ 0, 0, 7, 5, 5, 3, 3 ][intLevel]), stride=1, padding=(0, [ 0, 0, 3, 2, 2, 1, 1 ][intLevel]))
+ )
+
+ # end
+
+ self.netScaleX = torch.nn.Conv2d(in_channels=[ 0, 0, 49, 25, 25, 9, 9 ][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0)
+ self.netScaleY = torch.nn.Conv2d(in_channels=[ 0, 0, 49, 25, 25, 9, 9 ][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0)
+ # eny
+
+ def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow):
+ tenDifference = ((tenOne - backwarp(tenInput=tenTwo, tenFlow=tenFlow * self.fltBackward)) ** 2).sum(1, True).sqrt().detach()
+
+ tenDist = self.netDist(self.netMain(torch.cat([ tenDifference, tenFlow - tenFlow.view(tenFlow.shape[0], 2, -1).mean(2, True).view(tenFlow.shape[0], 2, 1, 1), self.netFeat(tenFeaturesOne) ], 1)))
+ tenDist = (tenDist ** 2).neg()
+ tenDist = (tenDist - tenDist.max(1, True)[0]).exp()
+
+ tenDivisor = tenDist.sum(1, True).reciprocal()
+
+ tenScaleX = self.netScaleX(tenDist * torch.nn.functional.unfold(input=tenFlow[:, 0:1, :, :], kernel_size=self.intUnfold, stride=1, padding=int((self.intUnfold - 1) / 2)).view_as(tenDist)) * tenDivisor
+ tenScaleY = self.netScaleY(tenDist * torch.nn.functional.unfold(input=tenFlow[:, 1:2, :, :], kernel_size=self.intUnfold, stride=1, padding=int((self.intUnfold - 1) / 2)).view_as(tenDist)) * tenDivisor
+
+ return torch.cat([ tenScaleX, tenScaleY ], 1)
+ # end
+ # end
+
+ self.netFeatures = Features()
+ self.netMatching = torch.nn.ModuleList([ Matching(intLevel) for intLevel in [ 2, 3, 4, 5, 6 ] ])
+ self.netSubpixel = torch.nn.ModuleList([ Subpixel(intLevel) for intLevel in [ 2, 3, 4, 5, 6 ] ])
+ self.netRegularization = torch.nn.ModuleList([ Regularization(intLevel) for intLevel in [ 2, 3, 4, 5, 6 ] ])
+
+ self.load_state_dict({ strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.hub.load_state_dict_from_url(url='http://content.sniklaus.com/github/pytorch-liteflownet/network-' + arguments_strModel + '.pytorch').items() })
+ # self.load_state_dict(torch.load('./liteflownet/network-default.pth'))
+ # end
+
+ def forward(self, tenOne, tenTwo):
+ tenOne[:, 0, :, :] = tenOne[:, 0, :, :] - 0.411618
+ tenOne[:, 1, :, :] = tenOne[:, 1, :, :] - 0.434631
+ tenOne[:, 2, :, :] = tenOne[:, 2, :, :] - 0.454253
+
+ tenTwo[:, 0, :, :] = tenTwo[:, 0, :, :] - 0.410782
+ tenTwo[:, 1, :, :] = tenTwo[:, 1, :, :] - 0.433645
+ tenTwo[:, 2, :, :] = tenTwo[:, 2, :, :] - 0.452793
+
+ tenFeaturesOne = self.netFeatures(tenOne)
+ tenFeaturesTwo = self.netFeatures(tenTwo)
+
+ tenOne = [ tenOne ]
+ tenTwo = [ tenTwo ]
+
+ for intLevel in [ 1, 2, 3, 4, 5 ]:
+ tenOne.append(torch.nn.functional.interpolate(input=tenOne[-1], size=(tenFeaturesOne[intLevel].shape[2], tenFeaturesOne[intLevel].shape[3]), mode='bilinear', align_corners=False))
+ tenTwo.append(torch.nn.functional.interpolate(input=tenTwo[-1], size=(tenFeaturesTwo[intLevel].shape[2], tenFeaturesTwo[intLevel].shape[3]), mode='bilinear', align_corners=False))
+ # end
+
+ tenFlow = None
+
+ for intLevel in [ -1, -2, -3, -4, -5 ]:
+ tenFlow = self.netMatching[intLevel](tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow)
+ tenFlow = self.netSubpixel[intLevel](tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow)
+ tenFlow = self.netRegularization[intLevel](tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow)
+ # end
+
+ return tenFlow * 20.0
+ # end
+# end
+
+netNetwork = None
+
+##########################################################
+
+def estimate(tenOne, tenTwo):
+ global netNetwork
+
+ if netNetwork is None:
+ netNetwork = Network().cuda().eval()
+ # end
+
+ assert(tenOne.shape[1] == tenTwo.shape[1])
+ assert(tenOne.shape[2] == tenTwo.shape[2])
+
+ intWidth = tenOne.shape[2]
+ intHeight = tenOne.shape[1]
+
+ # assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
+ # assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
+
+ tenPreprocessedOne = tenOne.cuda().view(1, 3, intHeight, intWidth)
+ tenPreprocessedTwo = tenTwo.cuda().view(1, 3, intHeight, intWidth)
+
+ intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 32.0) * 32.0))
+ intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 32.0) * 32.0))
+
+ tenPreprocessedOne = torch.nn.functional.interpolate(input=tenPreprocessedOne, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+ tenPreprocessedTwo = torch.nn.functional.interpolate(input=tenPreprocessedTwo, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+
+ tenFlow = torch.nn.functional.interpolate(input=netNetwork(tenPreprocessedOne, tenPreprocessedTwo), size=(intHeight, intWidth), mode='bilinear', align_corners=False)
+
+ tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
+ tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
+
+ return tenFlow[0, :, :, :].cpu()
+# end
+
+##########################################################
+
+if __name__ == '__main__':
+ tenOne = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strOne))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
+ tenTwo = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strTwo))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
+
+ tenOutput = estimate(tenOne, tenTwo)
+
+ objOutput = open(arguments_strOut, 'wb')
+
+ numpy.array([ 80, 73, 69, 72 ], numpy.uint8).tofile(objOutput)
+ numpy.array([ tenOutput.shape[2], tenOutput.shape[1] ], numpy.int32).tofile(objOutput)
+ numpy.array(tenOutput.numpy().transpose(1, 2, 0), numpy.float32).tofile(objOutput)
+
+ objOutput.close()
+# end
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/losses/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/losses/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/losses/loss.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/losses/loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d6ff33d66e071dda020f1fe0ce045f8a578e347
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/losses/loss.py
@@ -0,0 +1,196 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+
+class Loss(nn.Module):
+ def __init__(self, loss_weight, keys, mapping=None) -> None:
+ '''
+ mapping: map the kwargs keys into desired ones.
+ '''
+ super().__init__()
+ self.loss_weight = loss_weight
+ self.keys = keys
+ self.mapping = mapping
+ if isinstance(mapping, dict):
+ self.mapping = {k: v for k, v in mapping if v in keys}
+
+
+ def forward(self, **kwargs):
+ params = {k: v for k, v in kwargs.items() if k in self.keys}
+ if self.mapping is not None:
+ for k, v in kwargs.items():
+ if self.mapping.get(k) is not None:
+ params[self.mapping[k]] = v
+
+ return self._forward(**params) * self.loss_weight
+
+ def _forward(self, **kwargs):
+ pass
+
+
+class CharbonnierLoss(Loss):
+ def __init__(self, loss_weight, keys) -> None:
+ super().__init__(loss_weight, keys)
+
+ def _forward(self, imgt_pred, imgt):
+ diff = imgt_pred - imgt
+ loss = ((diff ** 2 + 1e-6) ** 0.5).mean()
+ return loss
+
+
+class AdaCharbonnierLoss(Loss):
+ def __init__(self, loss_weight, keys) -> None:
+ super().__init__(loss_weight, keys)
+
+ def _forward(self, imgt_pred, imgt, weight):
+ alpha = weight / 2
+ epsilon = 10 ** (-(10 * weight - 1) / 3)
+
+ diff = imgt_pred - imgt
+ loss = ((diff ** 2 + epsilon ** 2) ** alpha).mean()
+ return loss
+
+
+class TernaryLoss(Loss):
+ def __init__(self, loss_weight, keys, patch_size=7):
+ super().__init__(loss_weight, keys)
+ self.patch_size = patch_size
+ out_channels = patch_size * patch_size
+ self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels))
+ self.w = np.transpose(self.w, (3, 2, 0, 1))
+ self.w = torch.tensor(self.w, dtype=torch.float32)
+
+ def transform(self, tensor):
+ self.w = self.w.to(tensor.device)
+ tensor_ = tensor.mean(dim=1, keepdim=True)
+ patches = F.conv2d(tensor_, self.w, padding=self.patch_size//2, bias=None)
+ loc_diff = patches - tensor_
+ loc_diff_norm = loc_diff / torch.sqrt(0.81 + loc_diff ** 2)
+ return loc_diff_norm
+
+ def valid_mask(self, tensor):
+ padding = self.patch_size//2
+ b, c, h, w = tensor.size()
+ inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor)
+ mask = F.pad(inner, [padding] * 4)
+ return mask
+
+ def _forward(self, imgt_pred, imgt):
+ loc_diff_x = self.transform(imgt_pred)
+ loc_diff_y = self.transform(imgt)
+ diff = loc_diff_x - loc_diff_y.detach()
+ dist = (diff ** 2 / (0.1 + diff ** 2)).mean(dim=1, keepdim=True)
+ mask = self.valid_mask(imgt_pred)
+ loss = (dist * mask).mean()
+ return loss
+
+
+class GeometryLoss(Loss):
+ def __init__(self, loss_weight, keys, patch_size=3):
+ super().__init__(loss_weight, keys)
+ self.patch_size = patch_size
+ out_channels = patch_size * patch_size
+ self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels))
+ self.w = np.transpose(self.w, (3, 2, 0, 1))
+ self.w = torch.tensor(self.w).float()
+
+ def transform(self, tensor):
+ b, c, h, w = tensor.size()
+ self.w = self.w.to(tensor.device)
+ tensor_ = tensor.reshape(b*c, 1, h, w)
+ patches = F.conv2d(tensor_, self.w, padding=self.patch_size // 2, bias=None)
+ loc_diff = patches - tensor_
+ loc_diff_ = loc_diff.reshape(b, c*(self.patch_size ** 2), h, w)
+ loc_diff_norm = loc_diff_ / torch.sqrt(0.81 + loc_diff_ ** 2)
+ return loc_diff_norm
+
+ def valid_mask(self, tensor):
+ padding = self.patch_size // 2
+ b, c, h, w = tensor.size()
+ inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor)
+ mask = F.pad(inner, [padding] * 4)
+ return mask
+
+ def _forward(self, ft_pred, ft_gt):
+ loss = 0.
+ for pred, gt in zip(ft_pred, ft_gt):
+ loc_diff_x = self.transform(pred)
+ loc_diff_y = self.transform(gt)
+ diff = loc_diff_x - loc_diff_y
+ dist = (diff ** 2 / (0.1 + diff ** 2)).mean(dim=1, keepdim=True)
+ mask = self.valid_mask(pred)
+ loss = loss + (dist * mask).mean()
+ return loss
+
+
+class IFRFlowLoss(Loss):
+ def __init__(self, loss_weight, keys, beta=0.3) -> None:
+ super().__init__(loss_weight, keys)
+ self.beta = beta
+ self.ada_cb_loss = AdaCharbonnierLoss(1.0, ['imgt_pred', 'imgt', 'weight'])
+
+ def _forward(self, flow0_pred, flow1_pred, flow):
+
+ robust_weight0 = self.get_robust_weight(flow0_pred[0], flow[:, 0:2])
+ robust_weight1 = self.get_robust_weight(flow1_pred[0], flow[:, 2:4])
+ loss = 0
+ for lvl in range(1, len(flow0_pred)):
+ scale_factor = 2**lvl
+ loss = loss + self.ada_cb_loss(**{
+ 'imgt_pred': self.resize(flow0_pred[lvl], scale_factor),
+ 'imgt': flow[:, 0:2],
+ 'weight': robust_weight0
+ })
+ loss = loss + self.ada_cb_loss(**{
+ 'imgt_pred': self.resize(flow1_pred[lvl], scale_factor),
+ 'imgt': flow[:, 2:4],
+ 'weight': robust_weight1
+ })
+ return loss
+
+ def resize(self, x, scale_factor):
+ return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
+
+ def get_robust_weight(self, flow_pred, flow_gt):
+ epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=1, keepdim=True) ** 0.5
+ robust_weight = torch.exp(-self.beta * epe)
+ return robust_weight
+
+
+class MultipleFlowLoss(Loss):
+ def __init__(self, loss_weight, keys, beta=0.3) -> None:
+ super().__init__(loss_weight, keys)
+ self.beta = beta
+ self.ada_cb_loss = AdaCharbonnierLoss(1.0, ['imgt_pred', 'imgt', 'weight'])
+
+ def _forward(self, flow0_pred, flow1_pred, flow):
+
+ robust_weight0 = self.get_mutli_flow_robust_weight(flow0_pred[0], flow[:, 0:2])
+ robust_weight1 = self.get_mutli_flow_robust_weight(flow1_pred[0], flow[:, 2:4])
+ loss = 0
+ for lvl in range(1, len(flow0_pred)):
+ scale_factor = 2**lvl
+ loss = loss + self.ada_cb_loss(**{
+ 'imgt_pred': self.resize(flow0_pred[lvl], scale_factor),
+ 'imgt': flow[:, 0:2],
+ 'weight': robust_weight0
+ })
+ loss = loss + self.ada_cb_loss(**{
+ 'imgt_pred': self.resize(flow1_pred[lvl], scale_factor),
+ 'imgt': flow[:, 2:4],
+ 'weight': robust_weight1
+ })
+ return loss
+
+ def resize(self, x, scale_factor):
+ return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
+
+ def get_mutli_flow_robust_weight(self, flow_pred, flow_gt):
+ b, num_flows, c, h, w = flow_pred.shape
+ flow_pred = flow_pred.view(b, num_flows, c, h, w)
+ flow_gt = flow_gt.repeat(1, num_flows, 1, 1).view(b, num_flows, c, h, w)
+ epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=2, keepdim=True).max(1)[0] ** 0.5
+ robust_weight = torch.exp(-self.beta * epe)
+ return robust_weight
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/metrics/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/metrics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/metrics/psnr_ssim.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/metrics/psnr_ssim.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb9347720083018b48bdd8a5f8d693054558bdf7
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/metrics/psnr_ssim.py
@@ -0,0 +1,140 @@
+import torch
+import torch.nn.functional as F
+from math import exp
+
+device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+
+def gaussian(window_size, sigma):
+ gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
+ return gauss/gauss.sum()
+
+
+def create_window(window_size, channel=1):
+ _1D_window = gaussian(window_size, 1.5).unsqueeze(1)
+ _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0).to(device)
+ window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
+ return window
+
+
+def create_window_3d(window_size, channel=1):
+ _1D_window = gaussian(window_size, 1.5).unsqueeze(1)
+ _2D_window = _1D_window.mm(_1D_window.t())
+ _3D_window = _2D_window.unsqueeze(2) @ (_1D_window.t())
+ window = _3D_window.expand(1, channel, window_size, window_size, window_size).contiguous().to(device)
+ return window
+
+
+def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
+ if val_range is None:
+ if torch.max(img1) > 128:
+ max_val = 255
+ else:
+ max_val = 1
+
+ if torch.min(img1) < -0.5:
+ min_val = -1
+ else:
+ min_val = 0
+ L = max_val - min_val
+ else:
+ L = val_range
+
+ padd = 0
+ (_, channel, height, width) = img1.size()
+ if window is None:
+ real_size = min(window_size, height, width)
+ window = create_window(real_size, channel=channel).to(img1.device)
+
+ mu1 = F.conv2d(F.pad(img1, (5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=channel)
+ mu2 = F.conv2d(F.pad(img2, (5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=channel)
+
+ mu1_sq = mu1.pow(2)
+ mu2_sq = mu2.pow(2)
+ mu1_mu2 = mu1 * mu2
+
+ sigma1_sq = F.conv2d(F.pad(img1 * img1, (5, 5, 5, 5), 'replicate'), window, padding=padd, groups=channel) - mu1_sq
+ sigma2_sq = F.conv2d(F.pad(img2 * img2, (5, 5, 5, 5), 'replicate'), window, padding=padd, groups=channel) - mu2_sq
+ sigma12 = F.conv2d(F.pad(img1 * img2, (5, 5, 5, 5), 'replicate'), window, padding=padd, groups=channel) - mu1_mu2
+
+ C1 = (0.01 * L) ** 2
+ C2 = (0.03 * L) ** 2
+
+ v1 = 2.0 * sigma12 + C2
+ v2 = sigma1_sq + sigma2_sq + C2
+ cs = torch.mean(v1 / v2)
+
+ ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
+
+ if size_average:
+ ret = ssim_map.mean()
+ else:
+ ret = ssim_map.mean(1).mean(1).mean(1)
+
+ if full:
+ return ret, cs
+ return ret
+
+
+def calculate_ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
+ if val_range is None:
+ if torch.max(img1) > 128:
+ max_val = 255
+ else:
+ max_val = 1
+
+ if torch.min(img1) < -0.5:
+ min_val = -1
+ else:
+ min_val = 0
+ L = max_val - min_val
+ else:
+ L = val_range
+
+ padd = 0
+ (_, _, height, width) = img1.size()
+ if window is None:
+ real_size = min(window_size, height, width)
+ window = create_window_3d(real_size, channel=1).to(img1.device)
+
+ img1 = img1.unsqueeze(1)
+ img2 = img2.unsqueeze(1)
+
+ mu1 = F.conv3d(F.pad(img1, (5, 5, 5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=1)
+ mu2 = F.conv3d(F.pad(img2, (5, 5, 5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=1)
+
+ mu1_sq = mu1.pow(2)
+ mu2_sq = mu2.pow(2)
+ mu1_mu2 = mu1 * mu2
+
+ sigma1_sq = F.conv3d(F.pad(img1 * img1, (5, 5, 5, 5, 5, 5), 'replicate'), window, padding=padd, groups=1) - mu1_sq
+ sigma2_sq = F.conv3d(F.pad(img2 * img2, (5, 5, 5, 5, 5, 5), 'replicate'), window, padding=padd, groups=1) - mu2_sq
+ sigma12 = F.conv3d(F.pad(img1 * img2, (5, 5, 5, 5, 5, 5), 'replicate'), window, padding=padd, groups=1) - mu1_mu2
+
+ C1 = (0.01 * L) ** 2
+ C2 = (0.03 * L) ** 2
+
+ v1 = 2.0 * sigma12 + C2
+ v2 = sigma1_sq + sigma2_sq + C2
+ cs = torch.mean(v1 / v2)
+
+ ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
+
+ if size_average:
+ ret = ssim_map.mean()
+ else:
+ ret = ssim_map.mean(1).mean(1).mean(1)
+
+ if full:
+ return ret, cs
+ return ret.detach().cpu().numpy()
+
+
+
+def calculate_psnr(img1, img2):
+ psnr = -10 * torch.log10(((img1 - img2) * (img1 - img2)).mean())
+ return psnr.detach().cpu().numpy()
+
+
+def calculate_ie(img1, img2):
+ ie = torch.abs(torch.round(img1 * 255.0) - torch.round(img2 * 255.0)).mean()
+ return ie.detach().cpu().numpy()
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-G.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-G.py
new file mode 100644
index 0000000000000000000000000000000000000000..911c88a1a462a5bc952f298d6b0a00b92b31df98
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-G.py
@@ -0,0 +1,172 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from quality.amt.networks.blocks.raft import (
+ coords_grid,
+ BasicUpdateBlock, BidirCorrBlock
+)
+from quality.amt.networks.blocks.feat_enc import (
+ LargeEncoder
+)
+from quality.amt.networks.blocks.ifrnet import (
+ resize,
+ Encoder,
+ InitDecoder,
+ IntermediateDecoder
+)
+from quality.amt.networks.blocks.multi_flow import (
+ multi_flow_combine,
+ MultiFlowDecoder
+)
+
+
+class Model(nn.Module):
+ def __init__(self,
+ corr_radius=3,
+ corr_lvls=4,
+ num_flows=5,
+ channels=[84, 96, 112, 128],
+ skip_channels=84):
+ super(Model, self).__init__()
+ self.radius = corr_radius
+ self.corr_levels = corr_lvls
+ self.num_flows = num_flows
+
+ self.feat_encoder = LargeEncoder(output_dim=128, norm_fn='instance', dropout=0.)
+ self.encoder = Encoder(channels, large=True)
+ self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels)
+ self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels)
+ self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels)
+ self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
+
+ self.update4 = self._get_updateblock(112, None)
+ self.update3_low = self._get_updateblock(96, 2.0)
+ self.update2_low = self._get_updateblock(84, 4.0)
+
+ self.update3_high = self._get_updateblock(96, None)
+ self.update2_high = self._get_updateblock(84, None)
+
+ self.comb_block = nn.Sequential(
+ nn.Conv2d(3*self.num_flows, 6*self.num_flows, 7, 1, 3),
+ nn.PReLU(6*self.num_flows),
+ nn.Conv2d(6*self.num_flows, 3, 7, 1, 3),
+ )
+
+ def _get_updateblock(self, cdim, scale_factor=None):
+ return BasicUpdateBlock(cdim=cdim, hidden_dim=192, flow_dim=64,
+ corr_dim=256, corr_dim2=192, fc_dim=188,
+ scale_factor=scale_factor, corr_levels=self.corr_levels,
+ radius=self.radius)
+
+ def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1):
+ # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0
+ # based on linear assumption
+ t1_scale = 1. / embt
+ t0_scale = 1. / (1. - embt)
+ if downsample != 1:
+ inv = 1 / downsample
+ flow0 = inv * resize(flow0, scale_factor=inv)
+ flow1 = inv * resize(flow1, scale_factor=inv)
+
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
+ corr = torch.cat([corr0, corr1], dim=1)
+ flow = torch.cat([flow0, flow1], dim=1)
+ return corr, flow
+
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
+ img0 = img0 - mean_
+ img1 = img1 - mean_
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
+ b, _, h, w = img0_.shape
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
+
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8]
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
+
+ # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4]
+ # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16]
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
+
+ ######################################### the 4th decoder #########################################
+ up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt)
+ corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord,
+ up_flow0_4, up_flow1_4,
+ embt, downsample=1)
+
+ # residue update with lookup corr
+ delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4)
+ delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1)
+ up_flow0_4 = up_flow0_4 + delta_flow0_4
+ up_flow1_4 = up_flow1_4 + delta_flow1_4
+ ft_3_ = ft_3_ + delta_ft_3_
+
+ ######################################### the 3rd decoder #########################################
+ up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
+ corr_3, flow_3 = self._corr_scale_lookup(corr_fn,
+ coord, up_flow0_3, up_flow1_3,
+ embt, downsample=2)
+
+ # residue update with lookup corr
+ delta_ft_2_, delta_flow_3 = self.update3_low(ft_2_, flow_3, corr_3)
+ delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1)
+ up_flow0_3 = up_flow0_3 + delta_flow0_3
+ up_flow1_3 = up_flow1_3 + delta_flow1_3
+ ft_2_ = ft_2_ + delta_ft_2_
+
+ # residue update with lookup corr (hr)
+ corr_3 = resize(corr_3, scale_factor=2.0)
+ up_flow_3 = torch.cat([up_flow0_3, up_flow1_3], dim=1)
+ delta_ft_2_, delta_up_flow_3 = self.update3_high(ft_2_, up_flow_3, corr_3)
+ ft_2_ += delta_ft_2_
+ up_flow0_3 += delta_up_flow_3[:, 0:2]
+ up_flow1_3 += delta_up_flow_3[:, 2:4]
+
+ ######################################### the 2nd decoder #########################################
+ up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
+ corr_2, flow_2 = self._corr_scale_lookup(corr_fn,
+ coord, up_flow0_2, up_flow1_2,
+ embt, downsample=4)
+
+ # residue update with lookup corr
+ delta_ft_1_, delta_flow_2 = self.update2_low(ft_1_, flow_2, corr_2)
+ delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1)
+ up_flow0_2 = up_flow0_2 + delta_flow0_2
+ up_flow1_2 = up_flow1_2 + delta_flow1_2
+ ft_1_ = ft_1_ + delta_ft_1_
+
+ # residue update with lookup corr (hr)
+ corr_2 = resize(corr_2, scale_factor=4.0)
+ up_flow_2 = torch.cat([up_flow0_2, up_flow1_2], dim=1)
+ delta_ft_1_, delta_up_flow_2 = self.update2_high(ft_1_, up_flow_2, corr_2)
+ ft_1_ += delta_ft_1_
+ up_flow0_2 += delta_up_flow_2[:, 0:2]
+ up_flow1_2 += delta_up_flow_2[:, 2:4]
+
+ ######################################### the 1st decoder #########################################
+ up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
+
+ if scale_factor != 1.0:
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ mask = resize(mask, scale_factor=(1.0/scale_factor))
+ img_res = resize(img_res, scale_factor=(1.0/scale_factor))
+
+ # Merge multiple predictions
+ imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1,
+ mask, img_res, mean_)
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
+
+ if eval:
+ return { 'imgt_pred': imgt_pred, }
+ else:
+ up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w)
+ up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w)
+ return {
+ 'imgt_pred': imgt_pred,
+ 'flow0_pred': [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
+ 'flow1_pred': [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
+ 'ft_pred': [ft_1_, ft_2_, ft_3_],
+ }
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-L.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-L.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d1f56740bc4d3060ed79d3cfa9d5d19c9010032
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-L.py
@@ -0,0 +1,154 @@
+import torch
+import torch.nn as nn
+from quality.amt.networks.blocks.raft import (
+ coords_grid,
+ BasicUpdateBlock, BidirCorrBlock
+)
+from quality.amt.networks.blocks.feat_enc import (
+ BasicEncoder,
+)
+from quality.amt.networks.blocks.ifrnet import (
+ resize,
+ Encoder,
+ InitDecoder,
+ IntermediateDecoder
+)
+from quality.amt.networks.blocks.multi_flow import (
+ multi_flow_combine,
+ MultiFlowDecoder
+)
+
+class Model(nn.Module):
+ def __init__(self,
+ corr_radius=3,
+ corr_lvls=4,
+ num_flows=5,
+ channels=[48, 64, 72, 128],
+ skip_channels=48
+ ):
+ super(Model, self).__init__()
+ self.radius = corr_radius
+ self.corr_levels = corr_lvls
+ self.num_flows = num_flows
+
+ self.feat_encoder = BasicEncoder(output_dim=128, norm_fn='instance', dropout=0.)
+ self.encoder = Encoder([48, 64, 72, 128], large=True)
+
+ self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels)
+ self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels)
+ self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels)
+ self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
+
+ self.update4 = self._get_updateblock(72, None)
+ self.update3 = self._get_updateblock(64, 2.0)
+ self.update2 = self._get_updateblock(48, 4.0)
+
+ self.comb_block = nn.Sequential(
+ nn.Conv2d(3*self.num_flows, 6*self.num_flows, 7, 1, 3),
+ nn.PReLU(6*self.num_flows),
+ nn.Conv2d(6*self.num_flows, 3, 7, 1, 3),
+ )
+
+ def _get_updateblock(self, cdim, scale_factor=None):
+ return BasicUpdateBlock(cdim=cdim, hidden_dim=128, flow_dim=48,
+ corr_dim=256, corr_dim2=160, fc_dim=124,
+ scale_factor=scale_factor, corr_levels=self.corr_levels,
+ radius=self.radius)
+
+ def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1):
+ # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0
+ # based on linear assumption
+ t1_scale = 1. / embt
+ t0_scale = 1. / (1. - embt)
+ if downsample != 1:
+ inv = 1 / downsample
+ flow0 = inv * resize(flow0, scale_factor=inv)
+ flow1 = inv * resize(flow1, scale_factor=inv)
+
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
+ corr = torch.cat([corr0, corr1], dim=1)
+ flow = torch.cat([flow0, flow1], dim=1)
+ return corr, flow
+
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
+ img0 = img0 - mean_
+ img1 = img1 - mean_
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
+ b, _, h, w = img0_.shape
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
+
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8]
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
+
+ # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4]
+ # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16]
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
+
+ ######################################### the 4th decoder #########################################
+ up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt)
+ corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord,
+ up_flow0_4, up_flow1_4,
+ embt, downsample=1)
+
+ # residue update with lookup corr
+ delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4)
+ delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1)
+ up_flow0_4 = up_flow0_4 + delta_flow0_4
+ up_flow1_4 = up_flow1_4 + delta_flow1_4
+ ft_3_ = ft_3_ + delta_ft_3_
+
+ ######################################### the 3rd decoder #########################################
+ up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
+ corr_3, flow_3 = self._corr_scale_lookup(corr_fn,
+ coord, up_flow0_3, up_flow1_3,
+ embt, downsample=2)
+
+ # residue update with lookup corr
+ delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3)
+ delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1)
+ up_flow0_3 = up_flow0_3 + delta_flow0_3
+ up_flow1_3 = up_flow1_3 + delta_flow1_3
+ ft_2_ = ft_2_ + delta_ft_2_
+
+ ######################################### the 2nd decoder #########################################
+ up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
+ corr_2, flow_2 = self._corr_scale_lookup(corr_fn,
+ coord, up_flow0_2, up_flow1_2,
+ embt, downsample=4)
+
+ # residue update with lookup corr
+ delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2)
+ delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1)
+ up_flow0_2 = up_flow0_2 + delta_flow0_2
+ up_flow1_2 = up_flow1_2 + delta_flow1_2
+ ft_1_ = ft_1_ + delta_ft_1_
+
+ ######################################### the 1st decoder #########################################
+ up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
+
+ if scale_factor != 1.0:
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ mask = resize(mask, scale_factor=(1.0/scale_factor))
+ img_res = resize(img_res, scale_factor=(1.0/scale_factor))
+
+ # Merge multiple predictions
+ imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1,
+ mask, img_res, mean_)
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
+
+ if eval:
+ return { 'imgt_pred': imgt_pred, }
+ else:
+ up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w)
+ up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w)
+ return {
+ 'imgt_pred': imgt_pred,
+ 'flow0_pred': [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
+ 'flow1_pred': [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
+ 'ft_pred': [ft_1_, ft_2_, ft_3_],
+ }
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-S.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-S.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc30d9dace5fef20312357ec803cdacb57e81aa7
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-S.py
@@ -0,0 +1,154 @@
+import torch
+import torch.nn as nn
+from quality.amt.networks.blocks.raft import (
+ SmallUpdateBlock,
+ coords_grid,
+ BidirCorrBlock
+)
+from quality.amt.networks.blocks.feat_enc import (
+ SmallEncoder
+)
+from quality.amt.networks.blocks.ifrnet import (
+ resize,
+ Encoder,
+ InitDecoder,
+ IntermediateDecoder
+)
+from quality.amt.networks.blocks.multi_flow import (
+ multi_flow_combine,
+ MultiFlowDecoder
+)
+
+class Model(nn.Module):
+ def __init__(self,
+ corr_radius=3,
+ corr_lvls=4,
+ num_flows=3,
+ channels=[20, 32, 44, 56],
+ skip_channels=20):
+ super(Model, self).__init__()
+ self.radius = corr_radius
+ self.corr_levels = corr_lvls
+ self.num_flows = num_flows
+ self.channels = channels
+ self.skip_channels = skip_channels
+
+ self.feat_encoder = SmallEncoder(output_dim=84, norm_fn='instance', dropout=0.)
+ self.encoder = Encoder(channels)
+
+ self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels)
+ self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels)
+ self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels)
+ self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
+
+ self.update4 = self._get_updateblock(44)
+ self.update3 = self._get_updateblock(32, 2)
+ self.update2 = self._get_updateblock(20, 4)
+
+ self.comb_block = nn.Sequential(
+ nn.Conv2d(3*num_flows, 6*num_flows, 3, 1, 1),
+ nn.PReLU(6*num_flows),
+ nn.Conv2d(6*num_flows, 3, 3, 1, 1),
+ )
+
+ def _get_updateblock(self, cdim, scale_factor=None):
+ return SmallUpdateBlock(cdim=cdim, hidden_dim=76, flow_dim=20, corr_dim=64,
+ fc_dim=68, scale_factor=scale_factor,
+ corr_levels=self.corr_levels, radius=self.radius)
+
+ def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1):
+ # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0
+ # based on linear assumption
+ t1_scale = 1. / embt
+ t0_scale = 1. / (1. - embt)
+ if downsample != 1:
+ inv = 1 / downsample
+ flow0 = inv * resize(flow0, scale_factor=inv)
+ flow1 = inv * resize(flow1, scale_factor=inv)
+
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
+ corr = torch.cat([corr0, corr1], dim=1)
+ flow = torch.cat([flow0, flow1], dim=1)
+ return corr, flow
+
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
+ img0 = img0 - mean_
+ img1 = img1 - mean_
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
+ b, _, h, w = img0_.shape
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
+
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8]
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
+
+ # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4]
+ # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16]
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
+
+ ######################################### the 4th decoder #########################################
+ up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt)
+ corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord,
+ up_flow0_4, up_flow1_4,
+ embt, downsample=1)
+
+ # residue update with lookup corr
+ delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4)
+ delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1)
+ up_flow0_4 = up_flow0_4 + delta_flow0_4
+ up_flow1_4 = up_flow1_4 + delta_flow1_4
+ ft_3_ = ft_3_ + delta_ft_3_
+
+ ######################################### the 3rd decoder #########################################
+ up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
+ corr_3, flow_3 = self._corr_scale_lookup(corr_fn,
+ coord, up_flow0_3, up_flow1_3,
+ embt, downsample=2)
+
+ # residue update with lookup corr
+ delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3)
+ delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1)
+ up_flow0_3 = up_flow0_3 + delta_flow0_3
+ up_flow1_3 = up_flow1_3 + delta_flow1_3
+ ft_2_ = ft_2_ + delta_ft_2_
+
+ ######################################### the 2nd decoder #########################################
+ up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
+ corr_2, flow_2 = self._corr_scale_lookup(corr_fn,
+ coord, up_flow0_2, up_flow1_2,
+ embt, downsample=4)
+
+ # residue update with lookup corr
+ delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2)
+ delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1)
+ up_flow0_2 = up_flow0_2 + delta_flow0_2
+ up_flow1_2 = up_flow1_2 + delta_flow1_2
+ ft_1_ = ft_1_ + delta_ft_1_
+
+ ######################################### the 1st decoder #########################################
+ up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
+
+ if scale_factor != 1.0:
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ mask = resize(mask, scale_factor=(1.0/scale_factor))
+ img_res = resize(img_res, scale_factor=(1.0/scale_factor))
+
+ # Merge multiple predictions
+ imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1,
+ mask, img_res, mean_)
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
+
+ if eval:
+ return { 'imgt_pred': imgt_pred, }
+ else:
+ up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w)
+ up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w)
+ return {
+ 'imgt_pred': imgt_pred,
+ 'flow0_pred': [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
+ 'flow1_pred': [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
+ 'ft_pred': [ft_1_, ft_2_, ft_3_],
+ }
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-S.py_d46cf0d5aa964f5085ce7c9717159d96 b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/AMT-S.py_d46cf0d5aa964f5085ce7c9717159d96
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/IFRNet.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/IFRNet.py
new file mode 100644
index 0000000000000000000000000000000000000000..70d1212d52eb71da273070c26ee328cdcd973bf7
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/IFRNet.py
@@ -0,0 +1,169 @@
+import torch
+import torch.nn as nn
+from quality.amt.utils.flow_utils import warp
+from quality.amt.networks.blocks.ifrnet import (
+ convrelu, resize,
+ ResBlock,
+)
+
+
+class Encoder(nn.Module):
+ def __init__(self):
+ super(Encoder, self).__init__()
+ self.pyramid1 = nn.Sequential(
+ convrelu(3, 32, 3, 2, 1),
+ convrelu(32, 32, 3, 1, 1)
+ )
+ self.pyramid2 = nn.Sequential(
+ convrelu(32, 48, 3, 2, 1),
+ convrelu(48, 48, 3, 1, 1)
+ )
+ self.pyramid3 = nn.Sequential(
+ convrelu(48, 72, 3, 2, 1),
+ convrelu(72, 72, 3, 1, 1)
+ )
+ self.pyramid4 = nn.Sequential(
+ convrelu(72, 96, 3, 2, 1),
+ convrelu(96, 96, 3, 1, 1)
+ )
+
+ def forward(self, img):
+ f1 = self.pyramid1(img)
+ f2 = self.pyramid2(f1)
+ f3 = self.pyramid3(f2)
+ f4 = self.pyramid4(f3)
+ return f1, f2, f3, f4
+
+
+class Decoder4(nn.Module):
+ def __init__(self):
+ super(Decoder4, self).__init__()
+ self.convblock = nn.Sequential(
+ convrelu(192+1, 192),
+ ResBlock(192, 32),
+ nn.ConvTranspose2d(192, 76, 4, 2, 1, bias=True)
+ )
+
+ def forward(self, f0, f1, embt):
+ b, c, h, w = f0.shape
+ embt = embt.repeat(1, 1, h, w)
+ f_in = torch.cat([f0, f1, embt], 1)
+ f_out = self.convblock(f_in)
+ return f_out
+
+
+class Decoder3(nn.Module):
+ def __init__(self):
+ super(Decoder3, self).__init__()
+ self.convblock = nn.Sequential(
+ convrelu(220, 216),
+ ResBlock(216, 32),
+ nn.ConvTranspose2d(216, 52, 4, 2, 1, bias=True)
+ )
+
+ def forward(self, ft_, f0, f1, up_flow0, up_flow1):
+ f0_warp = warp(f0, up_flow0)
+ f1_warp = warp(f1, up_flow1)
+ f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1)
+ f_out = self.convblock(f_in)
+ return f_out
+
+
+class Decoder2(nn.Module):
+ def __init__(self):
+ super(Decoder2, self).__init__()
+ self.convblock = nn.Sequential(
+ convrelu(148, 144),
+ ResBlock(144, 32),
+ nn.ConvTranspose2d(144, 36, 4, 2, 1, bias=True)
+ )
+
+ def forward(self, ft_, f0, f1, up_flow0, up_flow1):
+ f0_warp = warp(f0, up_flow0)
+ f1_warp = warp(f1, up_flow1)
+ f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1)
+ f_out = self.convblock(f_in)
+ return f_out
+
+
+class Decoder1(nn.Module):
+ def __init__(self):
+ super(Decoder1, self).__init__()
+ self.convblock = nn.Sequential(
+ convrelu(100, 96),
+ ResBlock(96, 32),
+ nn.ConvTranspose2d(96, 8, 4, 2, 1, bias=True)
+ )
+
+ def forward(self, ft_, f0, f1, up_flow0, up_flow1):
+ f0_warp = warp(f0, up_flow0)
+ f1_warp = warp(f1, up_flow1)
+ f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1)
+ f_out = self.convblock(f_in)
+ return f_out
+
+
+class Model(nn.Module):
+ def __init__(self):
+ super(Model, self).__init__()
+ self.encoder = Encoder()
+ self.decoder4 = Decoder4()
+ self.decoder3 = Decoder3()
+ self.decoder2 = Decoder2()
+ self.decoder1 = Decoder1()
+
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
+ img0 = img0 - mean_
+ img1 = img1 - mean_
+
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
+
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
+
+ out4 = self.decoder4(f0_4, f1_4, embt)
+ up_flow0_4 = out4[:, 0:2]
+ up_flow1_4 = out4[:, 2:4]
+ ft_3_ = out4[:, 4:]
+
+ out3 = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
+ up_flow0_3 = out3[:, 0:2] + 2.0 * resize(up_flow0_4, scale_factor=2.0)
+ up_flow1_3 = out3[:, 2:4] + 2.0 * resize(up_flow1_4, scale_factor=2.0)
+ ft_2_ = out3[:, 4:]
+
+ out2 = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
+ up_flow0_2 = out2[:, 0:2] + 2.0 * resize(up_flow0_3, scale_factor=2.0)
+ up_flow1_2 = out2[:, 2:4] + 2.0 * resize(up_flow1_3, scale_factor=2.0)
+ ft_1_ = out2[:, 4:]
+
+ out1 = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
+ up_flow0_1 = out1[:, 0:2] + 2.0 * resize(up_flow0_2, scale_factor=2.0)
+ up_flow1_1 = out1[:, 2:4] + 2.0 * resize(up_flow1_2, scale_factor=2.0)
+ up_mask_1 = torch.sigmoid(out1[:, 4:5])
+ up_res_1 = out1[:, 5:]
+
+ if scale_factor != 1.0:
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0/scale_factor)) * (1.0/scale_factor)
+ up_mask_1 = resize(up_mask_1, scale_factor=(1.0/scale_factor))
+ up_res_1 = resize(up_res_1, scale_factor=(1.0/scale_factor))
+
+ img0_warp = warp(img0, up_flow0_1)
+ img1_warp = warp(img1, up_flow1_1)
+ imgt_merge = up_mask_1 * img0_warp + (1 - up_mask_1) * img1_warp + mean_
+ imgt_pred = imgt_merge + up_res_1
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
+
+ if eval:
+ return { 'imgt_pred': imgt_pred, }
+ else:
+ return {
+ 'imgt_pred': imgt_pred,
+ 'flow0_pred': [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
+ 'flow1_pred': [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
+ 'ft_pred': [ft_1_, ft_2_, ft_3_],
+ 'img0_warp': img0_warp,
+ 'img1_warp': img1_warp
+ }
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/feat_enc.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/feat_enc.py
new file mode 100644
index 0000000000000000000000000000000000000000..3805bd315422703c19bf6a4d0962ee75002d92aa
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/feat_enc.py
@@ -0,0 +1,343 @@
+import torch
+import torch.nn as nn
+
+
+class BottleneckBlock(nn.Module):
+ def __init__(self, in_planes, planes, norm_fn='group', stride=1):
+ super(BottleneckBlock, self).__init__()
+
+ self.conv1 = nn.Conv2d(in_planes, planes//4, kernel_size=1, padding=0)
+ self.conv2 = nn.Conv2d(planes//4, planes//4, kernel_size=3, padding=1, stride=stride)
+ self.conv3 = nn.Conv2d(planes//4, planes, kernel_size=1, padding=0)
+ self.relu = nn.ReLU(inplace=True)
+
+ num_groups = planes // 8
+
+ if norm_fn == 'group':
+ self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4)
+ self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4)
+ self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+ if not stride == 1:
+ self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+
+ elif norm_fn == 'batch':
+ self.norm1 = nn.BatchNorm2d(planes//4)
+ self.norm2 = nn.BatchNorm2d(planes//4)
+ self.norm3 = nn.BatchNorm2d(planes)
+ if not stride == 1:
+ self.norm4 = nn.BatchNorm2d(planes)
+
+ elif norm_fn == 'instance':
+ self.norm1 = nn.InstanceNorm2d(planes//4)
+ self.norm2 = nn.InstanceNorm2d(planes//4)
+ self.norm3 = nn.InstanceNorm2d(planes)
+ if not stride == 1:
+ self.norm4 = nn.InstanceNorm2d(planes)
+
+ elif norm_fn == 'none':
+ self.norm1 = nn.Sequential()
+ self.norm2 = nn.Sequential()
+ self.norm3 = nn.Sequential()
+ if not stride == 1:
+ self.norm4 = nn.Sequential()
+
+ if stride == 1:
+ self.downsample = None
+
+ else:
+ self.downsample = nn.Sequential(
+ nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4)
+
+
+ def forward(self, x):
+ y = x
+ y = self.relu(self.norm1(self.conv1(y)))
+ y = self.relu(self.norm2(self.conv2(y)))
+ y = self.relu(self.norm3(self.conv3(y)))
+
+ if self.downsample is not None:
+ x = self.downsample(x)
+
+ return self.relu(x+y)
+
+
+class ResidualBlock(nn.Module):
+ def __init__(self, in_planes, planes, norm_fn='group', stride=1):
+ super(ResidualBlock, self).__init__()
+
+ self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride)
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)
+ self.relu = nn.ReLU(inplace=True)
+
+ num_groups = planes // 8
+
+ if norm_fn == 'group':
+ self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+ self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+ if not stride == 1:
+ self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
+
+ elif norm_fn == 'batch':
+ self.norm1 = nn.BatchNorm2d(planes)
+ self.norm2 = nn.BatchNorm2d(planes)
+ if not stride == 1:
+ self.norm3 = nn.BatchNorm2d(planes)
+
+ elif norm_fn == 'instance':
+ self.norm1 = nn.InstanceNorm2d(planes)
+ self.norm2 = nn.InstanceNorm2d(planes)
+ if not stride == 1:
+ self.norm3 = nn.InstanceNorm2d(planes)
+
+ elif norm_fn == 'none':
+ self.norm1 = nn.Sequential()
+ self.norm2 = nn.Sequential()
+ if not stride == 1:
+ self.norm3 = nn.Sequential()
+
+ if stride == 1:
+ self.downsample = None
+
+ else:
+ self.downsample = nn.Sequential(
+ nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3)
+
+
+ def forward(self, x):
+ y = x
+ y = self.relu(self.norm1(self.conv1(y)))
+ y = self.relu(self.norm2(self.conv2(y)))
+
+ if self.downsample is not None:
+ x = self.downsample(x)
+
+ return self.relu(x+y)
+
+
+class SmallEncoder(nn.Module):
+ def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0):
+ super(SmallEncoder, self).__init__()
+ self.norm_fn = norm_fn
+
+ if self.norm_fn == 'group':
+ self.norm1 = nn.GroupNorm(num_groups=8, num_channels=32)
+
+ elif self.norm_fn == 'batch':
+ self.norm1 = nn.BatchNorm2d(32)
+
+ elif self.norm_fn == 'instance':
+ self.norm1 = nn.InstanceNorm2d(32)
+
+ elif self.norm_fn == 'none':
+ self.norm1 = nn.Sequential()
+
+ self.conv1 = nn.Conv2d(3, 32, kernel_size=7, stride=2, padding=3)
+ self.relu1 = nn.ReLU(inplace=True)
+
+ self.in_planes = 32
+ self.layer1 = self._make_layer(32, stride=1)
+ self.layer2 = self._make_layer(64, stride=2)
+ self.layer3 = self._make_layer(96, stride=2)
+
+ self.dropout = None
+ if dropout > 0:
+ self.dropout = nn.Dropout2d(p=dropout)
+
+ self.conv2 = nn.Conv2d(96, output_dim, kernel_size=1)
+
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
+ if m.weight is not None:
+ nn.init.constant_(m.weight, 1)
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ def _make_layer(self, dim, stride=1):
+ layer1 = BottleneckBlock(self.in_planes, dim, self.norm_fn, stride=stride)
+ layer2 = BottleneckBlock(dim, dim, self.norm_fn, stride=1)
+ layers = (layer1, layer2)
+
+ self.in_planes = dim
+ return nn.Sequential(*layers)
+
+
+ def forward(self, x):
+
+ # if input is list, combine batch dimension
+ is_list = isinstance(x, tuple) or isinstance(x, list)
+ if is_list:
+ batch_dim = x[0].shape[0]
+ x = torch.cat(x, dim=0)
+
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu1(x)
+
+ x = self.layer1(x)
+ x = self.layer2(x)
+ x = self.layer3(x)
+ x = self.conv2(x)
+
+ if self.training and self.dropout is not None:
+ x = self.dropout(x)
+
+ if is_list:
+ x = torch.split(x, [batch_dim, batch_dim], dim=0)
+
+ return x
+
+class BasicEncoder(nn.Module):
+ def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0):
+ super(BasicEncoder, self).__init__()
+ self.norm_fn = norm_fn
+
+ if self.norm_fn == 'group':
+ self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64)
+
+ elif self.norm_fn == 'batch':
+ self.norm1 = nn.BatchNorm2d(64)
+
+ elif self.norm_fn == 'instance':
+ self.norm1 = nn.InstanceNorm2d(64)
+
+ elif self.norm_fn == 'none':
+ self.norm1 = nn.Sequential()
+
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
+ self.relu1 = nn.ReLU(inplace=True)
+
+ self.in_planes = 64
+ self.layer1 = self._make_layer(64, stride=1)
+ self.layer2 = self._make_layer(72, stride=2)
+ self.layer3 = self._make_layer(128, stride=2)
+
+ # output convolution
+ self.conv2 = nn.Conv2d(128, output_dim, kernel_size=1)
+
+ self.dropout = None
+ if dropout > 0:
+ self.dropout = nn.Dropout2d(p=dropout)
+
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
+ if m.weight is not None:
+ nn.init.constant_(m.weight, 1)
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ def _make_layer(self, dim, stride=1):
+ layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride)
+ layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1)
+ layers = (layer1, layer2)
+
+ self.in_planes = dim
+ return nn.Sequential(*layers)
+
+
+ def forward(self, x):
+
+ # if input is list, combine batch dimension
+ is_list = isinstance(x, tuple) or isinstance(x, list)
+ if is_list:
+ batch_dim = x[0].shape[0]
+ x = torch.cat(x, dim=0)
+
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu1(x)
+
+ x = self.layer1(x)
+ x = self.layer2(x)
+ x = self.layer3(x)
+
+ x = self.conv2(x)
+
+ if self.training and self.dropout is not None:
+ x = self.dropout(x)
+
+ if is_list:
+ x = torch.split(x, [batch_dim, batch_dim], dim=0)
+
+ return x
+
+class LargeEncoder(nn.Module):
+ def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0):
+ super(LargeEncoder, self).__init__()
+ self.norm_fn = norm_fn
+
+ if self.norm_fn == 'group':
+ self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64)
+
+ elif self.norm_fn == 'batch':
+ self.norm1 = nn.BatchNorm2d(64)
+
+ elif self.norm_fn == 'instance':
+ self.norm1 = nn.InstanceNorm2d(64)
+
+ elif self.norm_fn == 'none':
+ self.norm1 = nn.Sequential()
+
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
+ self.relu1 = nn.ReLU(inplace=True)
+
+ self.in_planes = 64
+ self.layer1 = self._make_layer(64, stride=1)
+ self.layer2 = self._make_layer(112, stride=2)
+ self.layer3 = self._make_layer(160, stride=2)
+ self.layer3_2 = self._make_layer(160, stride=1)
+
+ # output convolution
+ self.conv2 = nn.Conv2d(self.in_planes, output_dim, kernel_size=1)
+
+ self.dropout = None
+ if dropout > 0:
+ self.dropout = nn.Dropout2d(p=dropout)
+
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
+ elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
+ if m.weight is not None:
+ nn.init.constant_(m.weight, 1)
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ def _make_layer(self, dim, stride=1):
+ layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride)
+ layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1)
+ layers = (layer1, layer2)
+
+ self.in_planes = dim
+ return nn.Sequential(*layers)
+
+
+ def forward(self, x):
+
+ # if input is list, combine batch dimension
+ is_list = isinstance(x, tuple) or isinstance(x, list)
+ if is_list:
+ batch_dim = x[0].shape[0]
+ x = torch.cat(x, dim=0)
+
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu1(x)
+
+ x = self.layer1(x)
+ x = self.layer2(x)
+ x = self.layer3(x)
+ x = self.layer3_2(x)
+
+ x = self.conv2(x)
+
+ if self.training and self.dropout is not None:
+ x = self.dropout(x)
+
+ if is_list:
+ x = torch.split(x, [batch_dim, batch_dim], dim=0)
+
+ return x
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/ifrnet.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/ifrnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..219d6fc5725f5b332660f1bbf52c7510fca14e56
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/ifrnet.py
@@ -0,0 +1,111 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from quality.amt.utils.flow_utils import warp
+
+
+def resize(x, scale_factor):
+ return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
+
+def convrelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True):
+ return nn.Sequential(
+ nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias=bias),
+ nn.PReLU(out_channels)
+ )
+
+class ResBlock(nn.Module):
+ def __init__(self, in_channels, side_channels, bias=True):
+ super(ResBlock, self).__init__()
+ self.side_channels = side_channels
+ self.conv1 = nn.Sequential(
+ nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias),
+ nn.PReLU(in_channels)
+ )
+ self.conv2 = nn.Sequential(
+ nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias),
+ nn.PReLU(side_channels)
+ )
+ self.conv3 = nn.Sequential(
+ nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias),
+ nn.PReLU(in_channels)
+ )
+ self.conv4 = nn.Sequential(
+ nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias),
+ nn.PReLU(side_channels)
+ )
+ self.conv5 = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias)
+ self.prelu = nn.PReLU(in_channels)
+
+ def forward(self, x):
+ out = self.conv1(x)
+
+ res_feat = out[:, :-self.side_channels, ...]
+ side_feat = out[:, -self.side_channels:, :, :]
+ side_feat = self.conv2(side_feat)
+ out = self.conv3(torch.cat([res_feat, side_feat], 1))
+
+ res_feat = out[:, :-self.side_channels, ...]
+ side_feat = out[:, -self.side_channels:, :, :]
+ side_feat = self.conv4(side_feat)
+ out = self.conv5(torch.cat([res_feat, side_feat], 1))
+
+ out = self.prelu(x + out)
+ return out
+
+class Encoder(nn.Module):
+ def __init__(self, channels, large=False):
+ super(Encoder, self).__init__()
+ self.channels = channels
+ prev_ch = 3
+ for idx, ch in enumerate(channels, 1):
+ k = 7 if large and idx == 1 else 3
+ p = 3 if k ==7 else 1
+ self.register_module(f'pyramid{idx}',
+ nn.Sequential(
+ convrelu(prev_ch, ch, k, 2, p),
+ convrelu(ch, ch, 3, 1, 1)
+ ))
+ prev_ch = ch
+
+ def forward(self, in_x):
+ fs = []
+ for idx in range(len(self.channels)):
+ out_x = getattr(self, f'pyramid{idx+1}')(in_x)
+ fs.append(out_x)
+ in_x = out_x
+ return fs
+
+class InitDecoder(nn.Module):
+ def __init__(self, in_ch, out_ch, skip_ch) -> None:
+ super().__init__()
+ self.convblock = nn.Sequential(
+ convrelu(in_ch*2+1, in_ch*2),
+ ResBlock(in_ch*2, skip_ch),
+ nn.ConvTranspose2d(in_ch*2, out_ch+4, 4, 2, 1, bias=True)
+ )
+ def forward(self, f0, f1, embt):
+ h, w = f0.shape[2:]
+ embt = embt.repeat(1, 1, h, w)
+ out = self.convblock(torch.cat([f0, f1, embt], 1))
+ flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1)
+ ft_ = out[:, 4:, ...]
+ return flow0, flow1, ft_
+
+class IntermediateDecoder(nn.Module):
+ def __init__(self, in_ch, out_ch, skip_ch) -> None:
+ super().__init__()
+ self.convblock = nn.Sequential(
+ convrelu(in_ch*3+4, in_ch*3),
+ ResBlock(in_ch*3, skip_ch),
+ nn.ConvTranspose2d(in_ch*3, out_ch+4, 4, 2, 1, bias=True)
+ )
+ def forward(self, ft_, f0, f1, flow0_in, flow1_in):
+ f0_warp = warp(f0, flow0_in)
+ f1_warp = warp(f1, flow1_in)
+ f_in = torch.cat([ft_, f0_warp, f1_warp, flow0_in, flow1_in], 1)
+ out = self.convblock(f_in)
+ flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1)
+ ft_ = out[:, 4:, ...]
+ flow0 = flow0 + 2.0 * resize(flow0_in, scale_factor=2.0)
+ flow1 = flow1 + 2.0 * resize(flow1_in, scale_factor=2.0)
+ return flow0, flow1, ft_
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/multi_flow.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/multi_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e2c5dabd5251a77bec5f2960b996c4bc4a617fc
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/multi_flow.py
@@ -0,0 +1,69 @@
+import torch
+import torch.nn as nn
+from quality.amt.utils.flow_utils import warp
+from quality.amt.networks.blocks.ifrnet import (
+ convrelu, resize,
+ ResBlock,
+)
+
+
+def multi_flow_combine(comb_block, img0, img1, flow0, flow1,
+ mask=None, img_res=None, mean=None):
+ '''
+ A parallel implementation of multiple flow field warping
+ comb_block: An nn.Seqential object.
+ img shape: [b, c, h, w]
+ flow shape: [b, 2*num_flows, h, w]
+ mask (opt):
+ If 'mask' is None, the function conduct a simple average.
+ img_res (opt):
+ If 'img_res' is None, the function adds zero instead.
+ mean (opt):
+ If 'mean' is None, the function adds zero instead.
+ '''
+ b, c, h, w = flow0.shape
+ num_flows = c // 2
+ flow0 = flow0.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w)
+ flow1 = flow1.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w)
+
+ mask = mask.reshape(b, num_flows, 1, h, w
+ ).reshape(-1, 1, h, w) if mask is not None else None
+ img_res = img_res.reshape(b, num_flows, 3, h, w
+ ).reshape(-1, 3, h, w) if img_res is not None else 0
+ img0 = torch.stack([img0] * num_flows, 1).reshape(-1, 3, h, w)
+ img1 = torch.stack([img1] * num_flows, 1).reshape(-1, 3, h, w)
+ mean = torch.stack([mean] * num_flows, 1).reshape(-1, 1, 1, 1
+ ) if mean is not None else 0
+
+ img0_warp = warp(img0, flow0)
+ img1_warp = warp(img1, flow1)
+ img_warps = mask * img0_warp + (1 - mask) * img1_warp + mean + img_res
+ img_warps = img_warps.reshape(b, num_flows, 3, h, w)
+ imgt_pred = img_warps.mean(1) + comb_block(img_warps.view(b, -1, h, w))
+ return imgt_pred
+
+
+class MultiFlowDecoder(nn.Module):
+ def __init__(self, in_ch, skip_ch, num_flows=3):
+ super(MultiFlowDecoder, self).__init__()
+ self.num_flows = num_flows
+ self.convblock = nn.Sequential(
+ convrelu(in_ch*3+4, in_ch*3),
+ ResBlock(in_ch*3, skip_ch),
+ nn.ConvTranspose2d(in_ch*3, 8*num_flows, 4, 2, 1, bias=True)
+ )
+
+ def forward(self, ft_, f0, f1, flow0, flow1):
+ n = self.num_flows
+ f0_warp = warp(f0, flow0)
+ f1_warp = warp(f1, flow1)
+ out = self.convblock(torch.cat([ft_, f0_warp, f1_warp, flow0, flow1], 1))
+ delta_flow0, delta_flow1, mask, img_res = torch.split(out, [2*n, 2*n, n, 3*n], 1)
+ mask = torch.sigmoid(mask)
+
+ flow0 = delta_flow0 + 2.0 * resize(flow0, scale_factor=2.0
+ ).repeat(1, self.num_flows, 1, 1)
+ flow1 = delta_flow1 + 2.0 * resize(flow1, scale_factor=2.0
+ ).repeat(1, self.num_flows, 1, 1)
+
+ return flow0, flow1, mask, img_res
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/raft.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/raft.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fb85ad6556a28f5b80034c595be539fd700ad48
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/networks/blocks/raft.py
@@ -0,0 +1,207 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+def resize(x, scale_factor):
+ return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
+
+
+def bilinear_sampler(img, coords, mask=False):
+ """ Wrapper for grid_sample, uses pixel coordinates """
+ H, W = img.shape[-2:]
+ xgrid, ygrid = coords.split([1,1], dim=-1)
+ xgrid = 2*xgrid/(W-1) - 1
+ ygrid = 2*ygrid/(H-1) - 1
+
+ grid = torch.cat([xgrid, ygrid], dim=-1)
+ img = F.grid_sample(img, grid, align_corners=True)
+
+ if mask:
+ mask = (xgrid > -1) & (ygrid > -1) & (xgrid < 1) & (ygrid < 1)
+ return img, mask.float()
+
+ return img
+
+
+def coords_grid(batch, ht, wd, device):
+ coords = torch.meshgrid(torch.arange(ht, device=device),
+ torch.arange(wd, device=device),
+ indexing='ij')
+ coords = torch.stack(coords[::-1], dim=0).float()
+ return coords[None].repeat(batch, 1, 1, 1)
+
+
+class SmallUpdateBlock(nn.Module):
+ def __init__(self, cdim, hidden_dim, flow_dim, corr_dim, fc_dim,
+ corr_levels=4, radius=3, scale_factor=None):
+ super(SmallUpdateBlock, self).__init__()
+ cor_planes = corr_levels * (2 * radius + 1) **2
+ self.scale_factor = scale_factor
+
+ self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0)
+ self.convf1 = nn.Conv2d(4, flow_dim*2, 7, padding=3)
+ self.convf2 = nn.Conv2d(flow_dim*2, flow_dim, 3, padding=1)
+ self.conv = nn.Conv2d(corr_dim+flow_dim, fc_dim, 3, padding=1)
+
+ self.gru = nn.Sequential(
+ nn.Conv2d(fc_dim+4+cdim, hidden_dim, 3, padding=1),
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
+ )
+
+ self.feat_head = nn.Sequential(
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
+ nn.Conv2d(hidden_dim, cdim, 3, padding=1),
+ )
+
+ self.flow_head = nn.Sequential(
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
+ nn.Conv2d(hidden_dim, 4, 3, padding=1),
+ )
+
+ self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
+
+ def forward(self, net, flow, corr):
+ net = resize(net, 1 / self.scale_factor
+ ) if self.scale_factor is not None else net
+ cor = self.lrelu(self.convc1(corr))
+ flo = self.lrelu(self.convf1(flow))
+ flo = self.lrelu(self.convf2(flo))
+ cor_flo = torch.cat([cor, flo], dim=1)
+ inp = self.lrelu(self.conv(cor_flo))
+ inp = torch.cat([inp, flow, net], dim=1)
+
+ out = self.gru(inp)
+ delta_net = self.feat_head(out)
+ delta_flow = self.flow_head(out)
+
+ if self.scale_factor is not None:
+ delta_net = resize(delta_net, scale_factor=self.scale_factor)
+ delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor)
+
+ return delta_net, delta_flow
+
+
+class BasicUpdateBlock(nn.Module):
+ def __init__(self, cdim, hidden_dim, flow_dim, corr_dim, corr_dim2,
+ fc_dim, corr_levels=4, radius=3, scale_factor=None, out_num=1):
+ super(BasicUpdateBlock, self).__init__()
+ cor_planes = corr_levels * (2 * radius + 1) **2
+
+ self.scale_factor = scale_factor
+ self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0)
+ self.convc2 = nn.Conv2d(corr_dim, corr_dim2, 3, padding=1)
+ self.convf1 = nn.Conv2d(4, flow_dim*2, 7, padding=3)
+ self.convf2 = nn.Conv2d(flow_dim*2, flow_dim, 3, padding=1)
+ self.conv = nn.Conv2d(flow_dim+corr_dim2, fc_dim, 3, padding=1)
+
+ self.gru = nn.Sequential(
+ nn.Conv2d(fc_dim+4+cdim, hidden_dim, 3, padding=1),
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
+ )
+
+ self.feat_head = nn.Sequential(
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
+ nn.Conv2d(hidden_dim, cdim, 3, padding=1),
+ )
+
+ self.flow_head = nn.Sequential(
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
+ nn.Conv2d(hidden_dim, 4*out_num, 3, padding=1),
+ )
+
+ self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
+
+ def forward(self, net, flow, corr):
+ net = resize(net, 1 / self.scale_factor
+ ) if self.scale_factor is not None else net
+ cor = self.lrelu(self.convc1(corr))
+ cor = self.lrelu(self.convc2(cor))
+ flo = self.lrelu(self.convf1(flow))
+ flo = self.lrelu(self.convf2(flo))
+ cor_flo = torch.cat([cor, flo], dim=1)
+ inp = self.lrelu(self.conv(cor_flo))
+ inp = torch.cat([inp, flow, net], dim=1)
+
+ out = self.gru(inp)
+ delta_net = self.feat_head(out)
+ delta_flow = self.flow_head(out)
+
+ if self.scale_factor is not None:
+ delta_net = resize(delta_net, scale_factor=self.scale_factor)
+ delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor)
+ return delta_net, delta_flow
+
+
+class BidirCorrBlock:
+ def __init__(self, fmap1, fmap2, num_levels=4, radius=4):
+ self.num_levels = num_levels
+ self.radius = radius
+ self.corr_pyramid = []
+ self.corr_pyramid_T = []
+
+ corr = BidirCorrBlock.corr(fmap1, fmap2)
+ batch, h1, w1, dim, h2, w2 = corr.shape
+ corr_T = corr.clone().permute(0, 4, 5, 3, 1, 2)
+
+ corr = corr.reshape(batch*h1*w1, dim, h2, w2)
+ corr_T = corr_T.reshape(batch*h2*w2, dim, h1, w1)
+
+ self.corr_pyramid.append(corr)
+ self.corr_pyramid_T.append(corr_T)
+
+ for _ in range(self.num_levels-1):
+ corr = F.avg_pool2d(corr, 2, stride=2)
+ corr_T = F.avg_pool2d(corr_T, 2, stride=2)
+ self.corr_pyramid.append(corr)
+ self.corr_pyramid_T.append(corr_T)
+
+ def __call__(self, coords0, coords1):
+ r = self.radius
+ coords0 = coords0.permute(0, 2, 3, 1)
+ coords1 = coords1.permute(0, 2, 3, 1)
+ assert coords0.shape == coords1.shape, f"coords0 shape: [{coords0.shape}] is not equal to [{coords1.shape}]"
+ batch, h1, w1, _ = coords0.shape
+
+ out_pyramid = []
+ out_pyramid_T = []
+ for i in range(self.num_levels):
+ corr = self.corr_pyramid[i]
+ corr_T = self.corr_pyramid_T[i]
+
+ dx = torch.linspace(-r, r, 2*r+1, device=coords0.device)
+ dy = torch.linspace(-r, r, 2*r+1, device=coords0.device)
+ delta = torch.stack(torch.meshgrid(dy, dx, indexing='ij'), axis=-1)
+ delta_lvl = delta.view(1, 2*r+1, 2*r+1, 2)
+
+ centroid_lvl_0 = coords0.reshape(batch*h1*w1, 1, 1, 2) / 2**i
+ centroid_lvl_1 = coords1.reshape(batch*h1*w1, 1, 1, 2) / 2**i
+ coords_lvl_0 = centroid_lvl_0 + delta_lvl
+ coords_lvl_1 = centroid_lvl_1 + delta_lvl
+
+ corr = bilinear_sampler(corr, coords_lvl_0)
+ corr_T = bilinear_sampler(corr_T, coords_lvl_1)
+ corr = corr.view(batch, h1, w1, -1)
+ corr_T = corr_T.view(batch, h1, w1, -1)
+ out_pyramid.append(corr)
+ out_pyramid_T.append(corr_T)
+
+ out = torch.cat(out_pyramid, dim=-1)
+ out_T = torch.cat(out_pyramid_T, dim=-1)
+ return out.permute(0, 3, 1, 2).contiguous().float(), out_T.permute(0, 3, 1, 2).contiguous().float()
+
+ @staticmethod
+ def corr(fmap1, fmap2):
+ batch, dim, ht, wd = fmap1.shape
+ fmap1 = fmap1.view(batch, dim, ht*wd)
+ fmap2 = fmap2.view(batch, dim, ht*wd)
+
+ corr = torch.matmul(fmap1.transpose(1,2), fmap2)
+ corr = corr.view(batch, ht, wd, 1, ht, wd)
+ return corr / torch.sqrt(torch.tensor(dim).float())
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/benchmark_arbitrary.sh b/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/benchmark_arbitrary.sh
new file mode 100644
index 0000000000000000000000000000000000000000..108daea15e6548e276a386e34698d10d0f58981c
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/benchmark_arbitrary.sh
@@ -0,0 +1,5 @@
+CFG=$1
+CKPT=$2
+
+python benchmarks/gopro.py -c $CFG -p $CKPT
+python benchmarks/adobe240.py -c $CFG -p $CKPT
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/benchmark_fixed.sh b/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/benchmark_fixed.sh
new file mode 100644
index 0000000000000000000000000000000000000000..55d06b04a28a8e8456e3721c7f8731ae2e432579
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/benchmark_fixed.sh
@@ -0,0 +1,7 @@
+CFG=$1
+CKPT=$2
+
+python benchmarks/vimeo90k.py -c $CFG -p $CKPT
+python benchmarks/ucf101.py -c $CFG -p $CKPT
+python benchmarks/snu_film.py -c $CFG -p $CKPT
+python benchmarks/xiph.py -c $CFG -p $CKPT
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/train.sh b/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/train.sh
new file mode 100644
index 0000000000000000000000000000000000000000..92afb6465c444bdbd49fc6073337f96e80ae05d1
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/scripts/train.sh
@@ -0,0 +1,6 @@
+NUM_GPU=$1
+CFG=$2
+PORT=$3
+python -m torch.distributed.launch \
+--nproc_per_node $NUM_GPU \
+--master_port $PORT train.py -c $CFG
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/train.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0591e906dddd6f3cab096f6bb345b7bc6a70e8b
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/train.py
@@ -0,0 +1,68 @@
+import os
+import argparse
+from shutil import copyfile
+import torch.distributed as dist
+import torch
+import importlib
+import datetime
+from utils.dist_utils import (
+ get_world_size,
+)
+from omegaconf import OmegaConf
+from utils.utils import seed_all
+parser = argparse.ArgumentParser(description='VFI')
+parser.add_argument('-c', '--config', type=str)
+parser.add_argument('-p', '--port', default='23455', type=str)
+parser.add_argument('--local_rank', default='0')
+
+args = parser.parse_args()
+
+
+def main_worker(rank, config):
+ if 'local_rank' not in config:
+ config['local_rank'] = config['global_rank'] = rank
+ if torch.cuda.is_available():
+ print(f'Rank {rank} is available')
+ config['device'] = f"cuda:{rank}"
+ if config['distributed']:
+ dist.init_process_group(backend='nccl',
+ timeout=datetime.timedelta(seconds=5400))
+ else:
+ config['device'] = 'cpu'
+
+ cfg_name = os.path.basename(args.config).split('.')[0]
+ config['exp_name'] = cfg_name + '_' + config['exp_name']
+ config['save_dir'] = os.path.join(config['save_dir'], config['exp_name'])
+
+ if (not config['distributed']) or rank == 0:
+ os.makedirs(config['save_dir'], exist_ok=True)
+ os.makedirs(f'{config["save_dir"]}/ckpts', exist_ok=True)
+ config_path = os.path.join(config['save_dir'],
+ args.config.split('/')[-1])
+ if not os.path.isfile(config_path):
+ copyfile(args.config, config_path)
+ print('[**] create folder {}'.format(config['save_dir']))
+
+ trainer_name = config.get('trainer_type', 'base_trainer')
+ print(f'using GPU {rank} for training')
+ if rank == 0:
+ print(trainer_name)
+ trainer_pack = importlib.import_module('trainers.' + trainer_name)
+ trainer = trainer_pack.Trainer(config)
+
+ trainer.train()
+
+
+if __name__ == "__main__":
+ torch.backends.cudnn.benchmark = True
+ cfg = OmegaConf.load(args.config)
+ seed_all(cfg.seed)
+ rank = int(args.local_rank)
+ torch.cuda.set_device(torch.device(f'cuda:{rank}'))
+ # setting distributed cfgurations
+ cfg['world_size'] = get_world_size()
+ cfg['local_rank'] = rank
+ if rank == 0:
+ print('world_size: ', cfg['world_size'])
+ main_worker(rank, cfg)
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/train.py_bccd93d831f94150941714abd0f34048 b/benchmarks/edit/code/IVEBench/metrics/quality/amt/train.py_bccd93d831f94150941714abd0f34048
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/base_trainer.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/base_trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec747a9211ddc984b9da291acb961aaad358cde8
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/base_trainer.py
@@ -0,0 +1,243 @@
+import time
+import wandb
+import logging
+import numpy as np
+import os.path as osp
+from collections import OrderedDict
+
+import torch
+from torch.optim import AdamW
+from torch.utils.data import DataLoader
+from torch.utils.data.distributed import DistributedSampler
+from torch.nn.parallel import DistributedDataParallel as DDP
+
+from .logger import CustomLogger
+from utils.utils import AverageMeterGroups
+from metrics.psnr_ssim import calculate_psnr
+from utils.build_utils import build_from_cfg
+
+
+class Trainer:
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.rank = self.config['local_rank']
+ init_log = self._init_logger()
+ self._init_dataset()
+ self._init_loss()
+ self.model_name = config['exp_name']
+ self.model = build_from_cfg(config.network).to(self.config.device)
+
+ if config['distributed']:
+ self.model = DDP(self.model,
+ device_ids=[self.rank],
+ output_device=self.rank,
+ broadcast_buffers=True,
+ find_unused_parameters=False)
+
+ init_log += str(self.model)
+ self.optimizer = AdamW(self.model.parameters(),
+ lr=config.lr, weight_decay=config.weight_decay)
+ if self.rank == 0:
+ print(init_log)
+ self.logger(init_log)
+ self.resume_training()
+
+ def resume_training(self):
+ ckpt_path = self.config.get('resume_state')
+ if ckpt_path is not None:
+ ckpt = torch.load(self.config['resume_state'])
+ if self.config['distributed']:
+ self.model.module.load_state_dict(ckpt['state_dict'])
+ else:
+ self.model.load_state_dict(ckpt['state_dict'])
+ self.optimizer.load_state_dict(ckpt['optim'])
+ self.resume_epoch = ckpt.get('epoch')
+ self.logger(
+ f'load model from {ckpt_path} and training resumes from epoch {self.resume_epoch}')
+ else:
+ self.resume_epoch = 0
+
+ def _init_logger(self):
+ init_log = ''
+ console_cfg = dict(
+ level=logging.INFO,
+ format="%(asctime)s %(filename)s[line:%(lineno)d]"
+ "%(levelname)s %(message)s",
+ datefmt="%a, %d %b %Y %H:%M:%S",
+ filename=f"{self.config['save_dir']}/log",
+ filemode='w')
+ tb_cfg = dict(log_dir=osp.join(self.config['save_dir'], 'tb_logger'))
+ wandb_cfg = None
+ use_wandb = self.config['logger'].get('use_wandb', False)
+ if use_wandb:
+ resume_id = self.config['logger'].get('resume_id', None)
+ if resume_id:
+ wandb_id = resume_id
+ resume = 'allow'
+ init_log += f'Resume wandb logger with id={wandb_id}.'
+ else:
+ wandb_id = wandb.util.generate_id()
+ resume = 'never'
+
+ wandb_cfg = dict(id=wandb_id,
+ resume=resume,
+ name=osp.basename(self.config['save_dir']),
+ config=self.config,
+ project="YOUR PROJECT",
+ entity="YOUR ENTITY",
+ sync_tensorboard=True)
+ init_log += f'Use wandb logger with id={wandb_id}; project=[YOUR PROJECT].'
+ self.logger = CustomLogger(console_cfg, tb_cfg, wandb_cfg, self.rank)
+ return init_log
+
+ def _init_dataset(self):
+ dataset_train = build_from_cfg(self.config.data.train)
+ dataset_val = build_from_cfg(self.config.data.val)
+
+ self.sampler = DistributedSampler(
+ dataset_train, num_replicas=self.config['world_size'], rank=self.config['local_rank'])
+ self.config.data.train_loader.batch_size //= self.config['world_size']
+ self.loader_train = DataLoader(dataset_train,
+ **self.config.data.train_loader,
+ pin_memory=True, drop_last=True, sampler=self.sampler)
+
+ self.loader_val = DataLoader(dataset_val, **self.config.data.val_loader,
+ pin_memory=True, shuffle=False, drop_last=False)
+
+ def _init_loss(self):
+ self.loss_dict = dict()
+ for loss_cfg in self.config.losses:
+ loss = build_from_cfg(loss_cfg)
+ self.loss_dict[loss_cfg['nickname']] = loss
+
+ def set_lr(self, optimizer, lr):
+ for param_group in optimizer.param_groups:
+ param_group['lr'] = lr
+
+ def get_lr(self, iters):
+ ratio = 0.5 * (1.0 + np.cos(iters /
+ (self.config['epochs'] * self.loader_train.__len__()) * np.pi))
+ lr = (self.config['lr'] - self.config['lr_min']
+ ) * ratio + self.config['lr_min']
+ return lr
+
+ def train(self):
+ local_rank = self.config['local_rank']
+ best_psnr = 0.0
+ loss_group = AverageMeterGroups()
+ time_group = AverageMeterGroups()
+ iters_per_epoch = self.loader_train.__len__()
+ iters = self.resume_epoch * iters_per_epoch
+ total_iters = self.config['epochs'] * iters_per_epoch
+
+ start_t = time.time()
+ total_t = 0
+ for epoch in range(self.resume_epoch, self.config['epochs']):
+ self.sampler.set_epoch(epoch)
+ for data in self.loader_train:
+ for k, v in data.items():
+ data[k] = v.to(self.config['device'])
+ data_t = time.time() - start_t
+
+ lr = self.get_lr(iters)
+ self.set_lr(self.optimizer, lr)
+
+ self.optimizer.zero_grad()
+ results = self.model(**data)
+ total_loss = torch.tensor(0., device=self.config['device'])
+ for name, loss in self.loss_dict.items():
+ l = loss(**results, **data)
+ loss_group.update({name: l.cpu().data})
+ total_loss += l
+ total_loss.backward()
+ self.optimizer.step()
+
+ iters += 1
+
+ iter_t = time.time() - start_t
+ total_t += iter_t
+ time_group.update({'data_t': data_t, 'iter_t': iter_t})
+
+ if (iters+1) % 100 == 0 and local_rank == 0:
+ tpi = total_t / (iters - self.resume_epoch * iters_per_epoch)
+ eta = total_iters * tpi
+ remainder = (total_iters - iters) * tpi
+ eta = self.eta_format(eta)
+
+ remainder = self.eta_format(remainder)
+ log_str = f"[{self.model_name}]epoch:{epoch +1}/{self.config['epochs']} "
+ log_str += f"iter:{iters + 1}/{self.config['epochs'] * iters_per_epoch} "
+ log_str += f"time:{time_group.avg('iter_t'):.3f}({time_group.avg('data_t'):.3f}) "
+ log_str += f"lr:{lr:.3e} eta:{remainder}({eta})\n"
+ for name in self.loss_dict.keys():
+ avg_l = loss_group.avg(name)
+ log_str += f"{name}:{avg_l:.3e} "
+ self.logger(tb_msg=[f'loss/{name}', avg_l, iters])
+ log_str += f'best:{best_psnr:.2f}dB\n\n'
+ self.logger(log_str)
+ loss_group.reset()
+ time_group.reset()
+ start_t = time.time()
+
+ if (epoch+1) % self.config['eval_interval'] == 0 and local_rank == 0:
+ psnr, eval_t = self.evaluate(epoch)
+ total_t += eval_t
+ self.logger(tb_msg=['eval/psnr', psnr, epoch])
+ if psnr > best_psnr:
+ best_psnr = psnr
+ self.save('psnr_best.pth', epoch)
+ if self.logger.enable_wandb:
+ wandb.run.summary["best_psnr"] = best_psnr
+ if (epoch+1) % 50 == 0:
+ self.save(f'epoch_{epoch+1}.pth', epoch)
+ self.save('latest.pth', epoch)
+
+ self.logger.close()
+
+ def evaluate(self, epoch):
+ psnr_list = []
+ time_stamp = time.time()
+ for i, data in enumerate(self.loader_val):
+ for k, v in data.items():
+ data[k] = v.to(self.config['device'])
+
+ with torch.no_grad():
+ results = self.model(**data, eval=True)
+ imgt_pred = results['imgt_pred']
+ for j in range(data['img0'].shape[0]):
+ psnr = calculate_psnr(imgt_pred[j].detach().unsqueeze(
+ 0), data['imgt'][j].unsqueeze(0)).cpu().data
+ psnr_list.append(psnr)
+
+ eval_time = time.time() - time_stamp
+
+ self.logger('eval epoch:{}/{} time:{:.2f} psnr:{:.3f}'.format(
+ epoch+1, self.config["epochs"], eval_time, np.array(psnr_list).mean()))
+ return np.array(psnr_list).mean(), eval_time
+
+ def save(self, name, epoch):
+ save_path = '{}/{}/{}'.format(self.config['save_dir'], 'ckpts', name)
+ ckpt = OrderedDict(epoch=epoch)
+ if self.config['distributed']:
+ ckpt['state_dict'] = self.model.module.state_dict()
+ else:
+ ckpt['state_dict'] = self.model.state_dict()
+ ckpt['optim'] = self.optimizer.state_dict()
+ torch.save(ckpt, save_path)
+
+ def eta_format(self, eta):
+ time_str = ''
+ if eta >= 3600:
+ hours = int(eta // 3600)
+ eta -= hours * 3600
+ time_str = f'{hours}'
+
+ if eta >= 60:
+ mins = int(eta // 60)
+ eta -= mins * 60
+ time_str = f'{time_str}:{mins:02}'
+
+ eta = int(eta)
+ time_str = f'{time_str}:{eta:02}'
+ return time_str
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/logger.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..2683f3bb09173f8bfdc73ead72996f327d71dea3
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/trainers/logger.py
@@ -0,0 +1,62 @@
+import time
+import wandb
+import shutil
+import logging
+import os.path as osp
+from torch.utils.tensorboard import SummaryWriter
+
+
+def mv_archived_logger(name):
+ timestamp = time.strftime("%Y-%m-%d_%H:%M:%S_", time.localtime())
+ basename = 'archived_' + timestamp + osp.basename(name)
+ archived_name = osp.join(osp.dirname(name), basename)
+ shutil.move(name, archived_name)
+
+
+class CustomLogger:
+ def __init__(self, common_cfg, tb_cfg=None, wandb_cfg=None, rank=0):
+ global global_logger
+ self.rank = rank
+
+ if self.rank == 0:
+ self.logger = logging.getLogger('VFI')
+ self.logger.setLevel(logging.INFO)
+ format_str = logging.Formatter(common_cfg['format'])
+
+ console_handler = logging.StreamHandler()
+ console_handler.setFormatter(format_str)
+
+ if osp.exists(common_cfg['filename']):
+ mv_archived_logger(common_cfg['filename'])
+
+ file_handler = logging.FileHandler(common_cfg['filename'],
+ common_cfg['filemode'])
+ file_handler.setFormatter(format_str)
+
+ self.logger.addHandler(console_handler)
+ self.logger.addHandler(file_handler)
+ self.tb_logger = None
+
+ self.enable_wandb = False
+
+ if wandb_cfg is not None:
+ self.enable_wandb = True
+ wandb.init(**wandb_cfg)
+
+ if tb_cfg is not None:
+ self.tb_logger = SummaryWriter(**tb_cfg)
+
+ global_logger = self
+
+ def __call__(self, msg=None, level=logging.INFO, tb_msg=None):
+ if self.rank != 0:
+ return
+ if msg is not None:
+ self.logger.log(level, msg)
+
+ if self.tb_logger is not None and tb_msg is not None:
+ self.tb_logger.add_scalar(*tb_msg)
+
+ def close(self):
+ if self.rank == 0 and self.enable_wandb:
+ wandb.finish()
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/build_utils.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/build_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e0c5f58aa1060f2e72267a6121d72514ebcaffb
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/build_utils.py
@@ -0,0 +1,16 @@
+import importlib
+import os
+import sys
+CUR_DIR = os.path.dirname(os.path.abspath(__file__))
+sys.path.append(os.path.join(CUR_DIR, "../"))
+
+
+def base_build_fn(module, cls, params):
+ return getattr(importlib.import_module(
+ module, package=None), cls)(**params)
+
+
+def build_from_cfg(config):
+ module, cls = config['name'].rsplit(".", 1)
+ params = config.get('params', {})
+ return base_build_fn(module, cls, params)
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/dist_utils.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/dist_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6337f9991fc510cfb6cbc7da18574eb443ec1dac
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/dist_utils.py
@@ -0,0 +1,48 @@
+import os
+import torch
+
+
+def get_world_size():
+ """Find OMPI world size without calling mpi functions
+ :rtype: int
+ """
+ if os.environ.get('PMI_SIZE') is not None:
+ return int(os.environ.get('PMI_SIZE') or 1)
+ elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None:
+ return int(os.environ.get('OMPI_COMM_WORLD_SIZE') or 1)
+ else:
+ return torch.cuda.device_count()
+
+
+def get_global_rank():
+ """Find OMPI world rank without calling mpi functions
+ :rtype: int
+ """
+ if os.environ.get('PMI_RANK') is not None:
+ return int(os.environ.get('PMI_RANK') or 0)
+ elif os.environ.get('OMPI_COMM_WORLD_RANK') is not None:
+ return int(os.environ.get('OMPI_COMM_WORLD_RANK') or 0)
+ else:
+ return 0
+
+
+def get_local_rank():
+ """Find OMPI local rank without calling mpi functions
+ :rtype: int
+ """
+ if os.environ.get('MPI_LOCALRANKID') is not None:
+ return int(os.environ.get('MPI_LOCALRANKID') or 0)
+ elif os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') is not None:
+ return int(os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') or 0)
+ else:
+ return 0
+
+
+def get_master_ip():
+ if os.environ.get('AZ_BATCH_MASTER_NODE') is not None:
+ return os.environ.get('AZ_BATCH_MASTER_NODE').split(':')[0]
+ elif os.environ.get('AZ_BATCHAI_MPI_MASTER_NODE') is not None:
+ return os.environ.get('AZ_BATCHAI_MPI_MASTER_NODE')
+ else:
+ return "127.0.0.1"
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/flow_utils.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/flow_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..84fca2049783b22175e0d1e024a19a5f9a79906e
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/flow_utils.py
@@ -0,0 +1,122 @@
+import numpy as np
+import torch
+from PIL import ImageFile
+import torch.nn.functional as F
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+
+
+def warp(img, flow):
+ B, _, H, W = flow.shape
+ xx = torch.linspace(-1.0, 1.0, W).view(1, 1, 1, W).expand(B, -1, H, -1)
+ yy = torch.linspace(-1.0, 1.0, H).view(1, 1, H, 1).expand(B, -1, -1, W)
+ grid = torch.cat([xx, yy], 1).to(img)
+ flow_ = torch.cat([flow[:, 0:1, :, :] / ((W - 1.0) / 2.0), flow[:, 1:2, :, :] / ((H - 1.0) / 2.0)], 1)
+ grid_ = (grid + flow_).permute(0, 2, 3, 1)
+ output = F.grid_sample(input=img, grid=grid_, mode='bilinear', padding_mode='border', align_corners=True)
+ return output
+
+
+def make_colorwheel():
+ """
+ Generates a color wheel for optical flow visualization as presented in:
+ Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007)
+ URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf
+ Code follows the original C++ source code of Daniel Scharstein.
+ Code follows the the Matlab source code of Deqing Sun.
+ Returns:
+ np.ndarray: Color wheel
+ """
+
+ RY = 15
+ YG = 6
+ GC = 4
+ CB = 11
+ BM = 13
+ MR = 6
+
+ ncols = RY + YG + GC + CB + BM + MR
+ colorwheel = np.zeros((ncols, 3))
+ col = 0
+
+ # RY
+ colorwheel[0:RY, 0] = 255
+ colorwheel[0:RY, 1] = np.floor(255*np.arange(0,RY)/RY)
+ col = col+RY
+ # YG
+ colorwheel[col:col+YG, 0] = 255 - np.floor(255*np.arange(0,YG)/YG)
+ colorwheel[col:col+YG, 1] = 255
+ col = col+YG
+ # GC
+ colorwheel[col:col+GC, 1] = 255
+ colorwheel[col:col+GC, 2] = np.floor(255*np.arange(0,GC)/GC)
+ col = col+GC
+ # CB
+ colorwheel[col:col+CB, 1] = 255 - np.floor(255*np.arange(CB)/CB)
+ colorwheel[col:col+CB, 2] = 255
+ col = col+CB
+ # BM
+ colorwheel[col:col+BM, 2] = 255
+ colorwheel[col:col+BM, 0] = np.floor(255*np.arange(0,BM)/BM)
+ col = col+BM
+ # MR
+ colorwheel[col:col+MR, 2] = 255 - np.floor(255*np.arange(MR)/MR)
+ colorwheel[col:col+MR, 0] = 255
+ return colorwheel
+
+def flow_uv_to_colors(u, v, convert_to_bgr=False):
+ """
+ Applies the flow color wheel to (possibly clipped) flow components u and v.
+ According to the C++ source code of Daniel Scharstein
+ According to the Matlab source code of Deqing Sun
+ Args:
+ u (np.ndarray): Input horizontal flow of shape [H,W]
+ v (np.ndarray): Input vertical flow of shape [H,W]
+ convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False.
+ Returns:
+ np.ndarray: Flow visualization image of shape [H,W,3]
+ """
+ flow_image = np.zeros((u.shape[0], u.shape[1], 3), np.uint8)
+ colorwheel = make_colorwheel() # shape [55x3]
+ ncols = colorwheel.shape[0]
+ rad = np.sqrt(np.square(u) + np.square(v))
+ a = np.arctan2(-v, -u)/np.pi
+ fk = (a+1) / 2*(ncols-1)
+ k0 = np.floor(fk).astype(np.int32)
+ k1 = k0 + 1
+ k1[k1 == ncols] = 0
+ f = fk - k0
+ for i in range(colorwheel.shape[1]):
+ tmp = colorwheel[:,i]
+ col0 = tmp[k0] / 255.0
+ col1 = tmp[k1] / 255.0
+ col = (1-f)*col0 + f*col1
+ idx = (rad <= 1)
+ col[idx] = 1 - rad[idx] * (1-col[idx])
+ col[~idx] = col[~idx] * 0.75 # out of range
+ # Note the 2-i => BGR instead of RGB
+ ch_idx = 2-i if convert_to_bgr else i
+ flow_image[:,:,ch_idx] = np.floor(255 * col)
+ return flow_image
+
+def flow_to_image(flow_uv, clip_flow=None, convert_to_bgr=False):
+ """
+ Expects a two dimensional flow image of shape.
+ Args:
+ flow_uv (np.ndarray): Flow UV image of shape [H,W,2]
+ clip_flow (float, optional): Clip maximum of flow values. Defaults to None.
+ convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False.
+ Returns:
+ np.ndarray: Flow visualization image of shape [H,W,3]
+ """
+ assert flow_uv.ndim == 3, 'input flow must have three dimensions'
+ assert flow_uv.shape[2] == 2, 'input flow must have shape [H,W,2]'
+ if clip_flow is not None:
+ flow_uv = np.clip(flow_uv, 0, clip_flow)
+ u = flow_uv[:,:,0]
+ v = flow_uv[:,:,1]
+ rad = np.sqrt(np.square(u) + np.square(v))
+ rad_max = np.max(rad)
+ epsilon = 1e-5
+ u = u / (rad_max + epsilon)
+ v = v / (rad_max + epsilon)
+ return flow_uv_to_colors(u, v, convert_to_bgr)
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/utils.py b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0473226d4eaf98e41e7ae3ee81b722308765e96c
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/amt/utils/utils.py
@@ -0,0 +1,297 @@
+import re
+import sys
+import torch
+import random
+import numpy as np
+from PIL import ImageFile
+import torch.nn.functional as F
+from imageio import imread, imwrite
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+
+
+class AverageMeter():
+ def __init__(self):
+ self.reset()
+
+ def reset(self):
+ self.val = 0.
+ self.avg = 0.
+ self.sum = 0.
+ self.count = 0
+
+ def update(self, val, n=1):
+ self.val = val
+ self.sum += val * n
+ self.count += n
+ self.avg = self.sum / self.count
+
+
+class AverageMeterGroups:
+ def __init__(self) -> None:
+ self.meter_dict = dict()
+
+ def update(self, dict, n=1):
+ for name, val in dict.items():
+ if self.meter_dict.get(name) is None:
+ self.meter_dict[name] = AverageMeter()
+ self.meter_dict[name].update(val, n)
+
+ def reset(self, name=None):
+ if name is None:
+ for v in self.meter_dict.values():
+ v.reset()
+ else:
+ meter = self.meter_dict.get(name)
+ if meter is not None:
+ meter.reset()
+
+ def avg(self, name):
+ meter = self.meter_dict.get(name)
+ if meter is not None:
+ return meter.avg
+
+
+class InputPadder:
+ """ Pads images such that dimensions are divisible by divisor """
+ def __init__(self, dims, divisor=16):
+ self.ht, self.wd = dims[-2:]
+ pad_ht = (((self.ht // divisor) + 1) * divisor - self.ht) % divisor
+ pad_wd = (((self.wd // divisor) + 1) * divisor - self.wd) % divisor
+ self._pad = [pad_wd//2, pad_wd - pad_wd//2, pad_ht//2, pad_ht - pad_ht//2]
+
+ def pad(self, *inputs):
+ if len(inputs) == 1:
+ return F.pad(inputs[0], self._pad, mode='replicate')
+ else:
+ return [F.pad(x, self._pad, mode='replicate') for x in inputs]
+
+ def unpad(self, *inputs):
+ if len(inputs) == 1:
+ return self._unpad(inputs[0])
+ else:
+ return [self._unpad(x) for x in inputs]
+
+ def _unpad(self, x):
+ ht, wd = x.shape[-2:]
+ c = [self._pad[2], ht-self._pad[3], self._pad[0], wd-self._pad[1]]
+ return x[..., c[0]:c[1], c[2]:c[3]]
+
+
+def img2tensor(img):
+ if img.shape[-1] > 3:
+ img = img[:,:,:3]
+ return torch.tensor(img).permute(2, 0, 1).unsqueeze(0) / 255.0
+
+
+def tensor2img(img_t):
+ return (img_t * 255.).detach(
+ ).squeeze(0).permute(1, 2, 0).cpu().numpy(
+ ).clip(0, 255).astype(np.uint8)
+
+def seed_all(seed):
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+
+
+def read(file):
+ if file.endswith('.float3'): return readFloat(file)
+ elif file.endswith('.flo'): return readFlow(file)
+ elif file.endswith('.ppm'): return readImage(file)
+ elif file.endswith('.pgm'): return readImage(file)
+ elif file.endswith('.png'): return readImage(file)
+ elif file.endswith('.jpg'): return readImage(file)
+ elif file.endswith('.pfm'): return readPFM(file)[0]
+ else: raise Exception('don\'t know how to read %s' % file)
+
+
+def write(file, data):
+ if file.endswith('.float3'): return writeFloat(file, data)
+ elif file.endswith('.flo'): return writeFlow(file, data)
+ elif file.endswith('.ppm'): return writeImage(file, data)
+ elif file.endswith('.pgm'): return writeImage(file, data)
+ elif file.endswith('.png'): return writeImage(file, data)
+ elif file.endswith('.jpg'): return writeImage(file, data)
+ elif file.endswith('.pfm'): return writePFM(file, data)
+ else: raise Exception('don\'t know how to write %s' % file)
+
+
+def readPFM(file):
+ file = open(file, 'rb')
+
+ color = None
+ width = None
+ height = None
+ scale = None
+ endian = None
+
+ header = file.readline().rstrip()
+ if header.decode("ascii") == 'PF':
+ color = True
+ elif header.decode("ascii") == 'Pf':
+ color = False
+ else:
+ raise Exception('Not a PFM file.')
+
+ dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode("ascii"))
+ if dim_match:
+ width, height = list(map(int, dim_match.groups()))
+ else:
+ raise Exception('Malformed PFM header.')
+
+ scale = float(file.readline().decode("ascii").rstrip())
+ if scale < 0:
+ endian = '<'
+ scale = -scale
+ else:
+ endian = '>'
+
+ data = np.fromfile(file, endian + 'f')
+ shape = (height, width, 3) if color else (height, width)
+
+ data = np.reshape(data, shape)
+ data = np.flipud(data)
+ return data, scale
+
+
+def writePFM(file, image, scale=1):
+ file = open(file, 'wb')
+
+ color = None
+
+ if image.dtype.name != 'float32':
+ raise Exception('Image dtype must be float32.')
+
+ image = np.flipud(image)
+
+ if len(image.shape) == 3 and image.shape[2] == 3:
+ color = True
+ elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1:
+ color = False
+ else:
+ raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')
+
+ file.write('PF\n' if color else 'Pf\n'.encode())
+ file.write('%d %d\n'.encode() % (image.shape[1], image.shape[0]))
+
+ endian = image.dtype.byteorder
+
+ if endian == '<' or endian == '=' and sys.byteorder == 'little':
+ scale = -scale
+
+ file.write('%f\n'.encode() % scale)
+
+ image.tofile(file)
+
+
+def readFlow(name):
+ if name.endswith('.pfm') or name.endswith('.PFM'):
+ return readPFM(name)[0][:,:,0:2]
+
+ f = open(name, 'rb')
+
+ header = f.read(4)
+ if header.decode("utf-8") != 'PIEH':
+ raise Exception('Flow file header does not contain PIEH')
+
+ width = np.fromfile(f, np.int32, 1).squeeze()
+ height = np.fromfile(f, np.int32, 1).squeeze()
+
+ flow = np.fromfile(f, np.float32, width * height * 2).reshape((height, width, 2))
+
+ return flow.astype(np.float32)
+
+
+def readImage(name):
+ if name.endswith('.pfm') or name.endswith('.PFM'):
+ data = readPFM(name)[0]
+ if len(data.shape)==3:
+ return data[:,:,0:3]
+ else:
+ return data
+ return imread(name)
+
+
+def writeImage(name, data):
+ if name.endswith('.pfm') or name.endswith('.PFM'):
+ return writePFM(name, data, 1)
+ return imwrite(name, data)
+
+
+def writeFlow(name, flow):
+ f = open(name, 'wb')
+ f.write('PIEH'.encode('utf-8'))
+ np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f)
+ flow = flow.astype(np.float32)
+ flow.tofile(f)
+
+
+def readFloat(name):
+ f = open(name, 'rb')
+
+ if(f.readline().decode("utf-8")) != 'float\n':
+ raise Exception('float file %s did not contain keyword' % name)
+
+ dim = int(f.readline())
+
+ dims = []
+ count = 1
+ for i in range(0, dim):
+ d = int(f.readline())
+ dims.append(d)
+ count *= d
+
+ dims = list(reversed(dims))
+
+ data = np.fromfile(f, np.float32, count).reshape(dims)
+ if dim > 2:
+ data = np.transpose(data, (2, 1, 0))
+ data = np.transpose(data, (1, 0, 2))
+
+ return data
+
+
+def writeFloat(name, data):
+ f = open(name, 'wb')
+
+ dim=len(data.shape)
+ if dim>3:
+ raise Exception('bad float file dimension: %d' % dim)
+
+ f.write(('float\n').encode('ascii'))
+ f.write(('%d\n' % dim).encode('ascii'))
+
+ if dim == 1:
+ f.write(('%d\n' % data.shape[0]).encode('ascii'))
+ else:
+ f.write(('%d\n' % data.shape[1]).encode('ascii'))
+ f.write(('%d\n' % data.shape[0]).encode('ascii'))
+ for i in range(2, dim):
+ f.write(('%d\n' % data.shape[i]).encode('ascii'))
+
+ data = data.astype(np.float32)
+ if dim==2:
+ data.tofile(f)
+
+ else:
+ np.transpose(data, (2, 0, 1)).tofile(f)
+
+
+def check_dim_and_resize(tensor_list):
+ shape_list = []
+ for t in tensor_list:
+ shape_list.append(t.shape[2:])
+
+ if len(set(shape_list)) > 1:
+ desired_shape = shape_list[0]
+ print(f'Inconsistent size of input video frames. All frames will be resized to {desired_shape}')
+
+ resize_tensor_list = []
+ for t in tensor_list:
+ resize_tensor_list.append(torch.nn.functional.interpolate(t, size=tuple(desired_shape), mode='bilinear'))
+
+ tensor_list = resize_tensor_list
+
+ return tensor_list
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/__init__.py b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/conv_backbone.py b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/conv_backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..b746d9564da310639ea251d287111085e405c6ac
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/conv_backbone.py
@@ -0,0 +1,336 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from timm.models.layers import trunc_normal_, DropPath
+from timm.models.registry import register_model
+# from .clipiqa_arch import CLIPIQA
+class Block(nn.Module):
+ r""" ConvNeXt Block. There are two equivalent implementations:
+ (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
+ (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
+ We use (2) as we find it slightly faster in PyTorch
+
+ Args:
+ dim (int): Number of input channels.
+ drop_path (float): Stochastic depth rate. Default: 0.0
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
+ """
+ def __init__(self, dim, drop_path=0., layer_scale_init_value=1e-6):
+ super().__init__()
+ self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
+ self.norm = LayerNorm(dim, eps=1e-6)
+ self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
+ self.act = nn.GELU()
+ self.pwconv2 = nn.Linear(4 * dim, dim)
+ self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)),
+ requires_grad=True) if layer_scale_init_value > 0 else None
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
+
+ def forward(self, x):
+ input = x
+ x = self.dwconv(x)
+ x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
+ x = self.norm(x)
+ x = self.pwconv1(x)
+ x = self.act(x)
+ x = self.pwconv2(x)
+ if self.gamma is not None:
+ x = self.gamma * x
+ x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
+
+ x = input + self.drop_path(x)
+ return x
+
+class ConvNeXt(nn.Module):
+ r""" ConvNeXt
+ A PyTorch impl of : `A ConvNet for the 2020s` -
+ https://arxiv.org/pdf/2201.03545.pdf
+ Args:
+ in_chans (int): Number of input image channels. Default: 3
+ num_classes (int): Number of classes for classification head. Default: 1000
+ depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
+ dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
+ drop_path_rate (float): Stochastic depth rate. Default: 0.
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
+ head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1.
+ """
+ def __init__(self, in_chans=3, num_classes=1000,
+ depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], drop_path_rate=0.,
+ layer_scale_init_value=1e-6, head_init_scale=1.,
+ ):
+ super().__init__()
+
+ self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers
+ stem = nn.Sequential(
+ nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
+ LayerNorm(dims[0], eps=1e-6, data_format="channels_first")
+ )
+ self.downsample_layers.append(stem)
+ for i in range(3):
+ downsample_layer = nn.Sequential(
+ LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
+ nn.Conv2d(dims[i], dims[i+1], kernel_size=2, stride=2),
+ )
+ self.downsample_layers.append(downsample_layer)
+
+ self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks
+ dp_rates=[x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
+ cur = 0
+ for i in range(4):
+ stage = nn.Sequential(
+ *[Block(dim=dims[i], drop_path=dp_rates[cur + j],
+ layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])]
+ )
+ self.stages.append(stage)
+ cur += depths[i]
+
+ self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer
+ self.head = nn.Linear(dims[-1], num_classes)
+
+ self.apply(self._init_weights)
+ self.head.weight.data.mul_(head_init_scale)
+ self.head.bias.data.mul_(head_init_scale)
+
+ def _init_weights(self, m):
+ if isinstance(m, (nn.Conv2d, nn.Linear)):
+ trunc_normal_(m.weight, std=.02)
+ nn.init.constant_(m.bias, 0)
+
+ def forward_features(self, x):
+ for i in range(4):
+ x = self.downsample_layers[i](x)
+ x = self.stages[i](x)
+ return self.norm(x.mean([-2, -1])) # global average pooling, (N, C, H, W) -> (N, C)
+
+ def forward(self, x):
+ x = self.forward_features(x)
+ x = self.head(x)
+ return x
+
+class LayerNorm(nn.Module):
+ r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
+ The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
+ shape (batch_size, height, width, channels) while channels_first corresponds to inputs
+ with shape (batch_size, channels, height, width).
+ """
+ def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(normalized_shape))
+ self.bias = nn.Parameter(torch.zeros(normalized_shape))
+ self.eps = eps
+ self.data_format = data_format
+ if self.data_format not in ["channels_last", "channels_first"]:
+ raise NotImplementedError
+ self.normalized_shape = (normalized_shape, )
+
+ def forward(self, x):
+ if self.data_format == "channels_last":
+ return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
+ elif self.data_format == "channels_first":
+ u = x.mean(1, keepdim=True)
+ s = (x - u).pow(2).mean(1, keepdim=True)
+ x = (x - u) / torch.sqrt(s + self.eps)
+ if len(x.shape) == 4:
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
+ elif len(x.shape) == 5:
+ x = self.weight[:, None, None, None] * x + self.bias[:, None, None, None]
+ return x
+
+
+class Block3D(nn.Module):
+ r""" ConvNeXt Block. There are two equivalent implementations:
+ (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
+ (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
+ We use (2) as we find it slightly faster in PyTorch
+
+ Args:
+ dim (int): Number of input channels.
+ drop_path (float): Stochastic depth rate. Default: 0.0
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
+ """
+ def __init__(self, dim, drop_path=0., inflate_len=3, layer_scale_init_value=1e-6):
+ super().__init__()
+ self.dwconv = nn.Conv3d(dim, dim, kernel_size=(inflate_len,7,7), padding=(inflate_len // 2,3,3), groups=dim) # depthwise conv
+ self.norm = LayerNorm(dim, eps=1e-6)
+ self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
+ self.act = nn.GELU()
+ self.pwconv2 = nn.Linear(4 * dim, dim)
+ self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)),
+ requires_grad=True) if layer_scale_init_value > 0 else None
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
+
+ def forward(self, x):
+ input = x
+ x = self.dwconv(x)
+ x = x.permute(0, 2, 3, 4, 1) # (N, C, H, W) -> (N, H, W, C)
+ x = self.norm(x)
+ x = self.pwconv1(x)
+ x = self.act(x)
+ x = self.pwconv2(x)
+ if self.gamma is not None:
+ x = self.gamma * x
+ x = x.permute(0, 4, 1, 2, 3) # (N, H, W, C) -> (N, C, H, W)
+
+ x = input + self.drop_path(x)
+ return x
+
+class ConvNeXt3D(nn.Module):
+ r""" ConvNeXt
+ A PyTorch impl of : `A ConvNet for the 2020s` -
+ https://arxiv.org/pdf/2201.03545.pdf
+ Args:
+ in_chans (int): Number of input image channels. Default: 3
+ num_classes (int): Number of classes for classification head. Default: 1000
+ depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
+ dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
+ drop_path_rate (float): Stochastic depth rate. Default: 0.
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
+ head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1.
+ """
+ def __init__(self, in_chans=3, num_classes=1000,
+ inflate_strategy='131',
+ depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], drop_path_rate=0.,
+ layer_scale_init_value=1e-6, head_init_scale=1.,
+ ):
+ super().__init__()
+
+ self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers
+ stem = nn.Sequential(
+ nn.Conv3d(in_chans, dims[0], kernel_size=(2,4,4), stride=(2,4,4)),
+ LayerNorm(dims[0], eps=1e-6, data_format="channels_first")
+ )
+ self.downsample_layers.append(stem)
+ for i in range(3):
+ downsample_layer = nn.Sequential(
+ LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
+ nn.Conv3d(dims[i], dims[i+1], kernel_size=(1,2,2), stride=(1,2,2)),
+ )
+ self.downsample_layers.append(downsample_layer)
+
+ self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks
+ dp_rates=[x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
+ cur = 0
+ for i in range(4):
+ stage = nn.Sequential(
+ *[Block3D(dim=dims[i], inflate_len=int(inflate_strategy[j%len(inflate_strategy)]),
+ drop_path=dp_rates[cur + j],
+ layer_scale_init_value=layer_scale_init_value) for j in range(depths[i])]
+ )
+ self.stages.append(stage)
+ cur += depths[i]
+
+ self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer
+
+ self.apply(self._init_weights)
+
+ def inflate_weights(self, s_state_dict):
+ t_state_dict = self.state_dict()
+ from collections import OrderedDict
+ for key in t_state_dict.keys():
+ if key not in s_state_dict:
+ print(key)
+ continue
+ if t_state_dict[key].shape != s_state_dict[key].shape:
+ t = t_state_dict[key].shape[2]
+ s_state_dict[key] = s_state_dict[key].unsqueeze(2).repeat(1,1,t,1,1) / t
+ self.load_state_dict(s_state_dict, strict=False)
+
+ def _init_weights(self, m):
+ if isinstance(m, (nn.Conv3d, nn.Linear)):
+ trunc_normal_(m.weight, std=.02)
+ nn.init.constant_(m.bias, 0)
+
+ def forward_features(self, x, return_spatial=False, multi=False, layer=-1):
+ if multi:
+ xs = []
+ for i in range(4):
+ x = self.downsample_layers[i](x)
+ x = self.stages[i](x)
+ if multi:
+ xs.append(x)
+ if return_spatial:
+ if multi:
+ shape = xs[-1].shape[2:]
+ return torch.cat([F.interpolate(x,size=shape, mode="trilinear") for x in xs[:-1]], 1) #+ [self.norm(x.permute(0, 2, 3, 4, 1)).permute(0, 4, 1, 2, 3)], 1)
+ elif layer > -1:
+ return xs[layer]
+ else:
+ return self.norm(x.permute(0, 2, 3, 4, 1)).permute(0, 4, 1, 2, 3)
+ return self.norm(x.mean([-3, -2, -1])) # global average pooling, (N, C, T, H, W) -> (N, C)
+
+ def forward(self, x, multi=False, layer=-1):
+ x = self.forward_features(x, True, multi=multi, layer=layer)
+ return x
+
+
+model_urls = {
+ "convnext_tiny_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth",
+ "convnext_small_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth",
+ "convnext_base_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth",
+ "convnext_large_1k": "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth",
+ "convnext_tiny_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_22k_224.pth",
+ "convnext_small_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_small_22k_224.pth",
+ "convnext_base_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth",
+ "convnext_large_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth",
+ "convnext_xlarge_22k": "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth",
+}
+
+def convnext_tiny(pretrained=False,in_22k=False, **kwargs):
+ model = ConvNeXt(depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], **kwargs)
+ if pretrained:
+ url = model_urls['convnext_tiny_22k'] if in_22k else model_urls['convnext_tiny_1k']
+ checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu", check_hash=True)
+ model.load_state_dict(checkpoint["model"])
+ return model
+
+def convnext_small(pretrained=False,in_22k=False, **kwargs):
+ model = ConvNeXt(depths=[3, 3, 27, 3], dims=[96, 192, 384, 768], **kwargs)
+ if pretrained:
+ url = model_urls['convnext_small_22k'] if in_22k else model_urls['convnext_small_1k']
+ checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu")
+ model.load_state_dict(checkpoint["model"])
+ return model
+
+def convnext_base(pretrained=False, in_22k=False, **kwargs):
+ model = ConvNeXt(depths=[3, 3, 27, 3], dims=[128, 256, 512, 1024], **kwargs)
+ if pretrained:
+ url = model_urls['convnext_base_22k'] if in_22k else model_urls['convnext_base_1k']
+ checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu")
+ model.load_state_dict(checkpoint["model"])
+ return model
+
+
+def convnext_large(pretrained=False, in_22k=False, **kwargs):
+ model = ConvNeXt(depths=[3, 3, 27, 3], dims=[192, 384, 768, 1536], **kwargs)
+ if pretrained:
+ url = model_urls['convnext_large_22k'] if in_22k else model_urls['convnext_large_1k']
+ checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu")
+ model.load_state_dict(checkpoint["model"])
+ return model
+
+def convnext_xlarge(pretrained=False, in_22k=False, **kwargs):
+ model = ConvNeXt(depths=[3, 3, 27, 3], dims=[256, 512, 1024, 2048], **kwargs)
+ if pretrained:
+ assert in_22k, "only ImageNet-22K pre-trained ConvNeXt-XL is available; please set in_22k=True"
+ url = model_urls['convnext_xlarge_22k']
+ checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu")
+ model.load_state_dict(checkpoint["model"])
+ return model
+
+def convnext_3d_tiny(pretrained=False, in_22k=False, **kwargs):
+ print("Using Imagenet 22K pretrain", in_22k)
+ model = ConvNeXt3D(depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], **kwargs)
+ if pretrained:
+ url = model_urls['convnext_tiny_22k'] if in_22k else model_urls['convnext_tiny_1k']
+ checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu", check_hash=True)
+ model.inflate_weights(checkpoint["model"])
+ return model
+
+def convnext_3d_small(pretrained=False, in_22k=False, **kwargs):
+ model = ConvNeXt3D(depths=[3, 3, 27, 3], dims=[96, 192, 384, 768], **kwargs)
+ if pretrained:
+ url = model_urls['convnext_small_22k'] if in_22k else model_urls['convnext_small_1k']
+ checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu", check_hash=True)
+ model.inflate_weights(checkpoint["model"])
+ return model
+
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/datasets.py b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1784c041f71792b4a5ca7cb2c6f710bfa8b38b4
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/datasets.py
@@ -0,0 +1,818 @@
+import decord
+from decord import VideoReader
+from decord import cpu, gpu
+import glob
+import os.path as osp
+import numpy as np
+import torch, torchvision
+from tqdm import tqdm
+import cv2
+
+import numpy as np
+import random
+from functools import lru_cache
+
+import random
+import copy
+
+import skvideo.io
+
+random.seed(42)
+
+decord.bridge.set_bridge("torch")
+
+class UnifiedFrameSampler:
+ def __init__(
+ self, fsize_t, fragments_t, frame_interval=1, num_clips=1, drop_rate=0.0,
+ ):
+
+ self.fragments_t = fragments_t
+ self.fsize_t = fsize_t
+ self.size_t = fragments_t * fsize_t
+ self.frame_interval = frame_interval
+ self.num_clips = num_clips
+ self.drop_rate = drop_rate
+
+ def get_frame_indices(self, num_frames, train=False):
+
+ tgrids = np.array(
+ [num_frames // self.fragments_t * i for i in range(self.fragments_t)],
+ dtype=np.int32,
+ )
+ tlength = num_frames // self.fragments_t
+
+ if tlength > self.fsize_t * self.frame_interval:
+ rnd_t = np.random.randint(
+ 0, tlength - self.fsize_t * self.frame_interval, size=len(tgrids)
+ )
+ else:
+ rnd_t = np.zeros(len(tgrids), dtype=np.int32)
+
+ ranges_t = (
+ np.arange(self.fsize_t)[None, :] * self.frame_interval
+ + rnd_t[:, None]
+ + tgrids[:, None]
+ )
+
+ drop = random.sample(
+ list(range(self.fragments_t)), int(self.fragments_t * self.drop_rate)
+ )
+ dropped_ranges_t = []
+ for i, rt in enumerate(ranges_t):
+ if i not in drop:
+ dropped_ranges_t.append(rt)
+ return np.concatenate(dropped_ranges_t)
+ def __call__(self, total_frames, train=False, start_index=0):
+ frame_inds = []
+
+ for i in range(self.num_clips):
+ frame_inds += [self.get_frame_indices(total_frames)]
+
+ frame_inds = np.concatenate(frame_inds)
+ frame_inds = np.mod(frame_inds + start_index, total_frames)
+ return frame_inds.astype(np.int32)
+
+
+class SimpleFrameSampler:
+ # 简单采样第一帧、最后帧
+ def __init__(
+ self, fsize_t
+ ):
+
+ self.fsize_t = fsize_t
+
+ def __call__(self, total_frames, train=False, start_index=0):
+ if self.fsize_t == 1:
+ frame_inds = [total_frames//2]
+ elif self.fsize_t == 2:
+ frame_inds = [0, total_frames//2]
+ else:
+ frame_inds = []
+ frame_inds.append(0)
+ for i in range(self.fsize_t-2):
+ frame_inds.append(total_frames//(self.fsize_t-1)*(i+1))
+ frame_inds.append(total_frames-1)
+
+ frame_inds = np.array(frame_inds)
+
+ return frame_inds.astype(np.int32)
+
+
+def get_spatial_fragments(
+ video,
+ fragments_h=7,
+ fragments_w=7,
+ fsize_h=32,
+ fsize_w=32,
+ aligned=32,
+ nfrags=1,
+ random=False,
+ random_upsample=False,
+ fallback_type="upsample",
+ **kwargs,
+):
+ size_h = fragments_h * fsize_h # 224
+ size_w = fragments_w * fsize_w # 224
+ ## video: [C,T,H,W]
+ ## situation for images
+ if video.shape[1] == 1:
+ aligned = 1
+
+ dur_t, res_h, res_w = video.shape[-3:]
+ ratio = min(res_h / size_h, res_w / size_w)
+ if fallback_type == "upsample" and ratio < 1:
+
+ ovideo = video
+ video = torch.nn.functional.interpolate(
+ video / 255.0, scale_factor=1 / ratio, mode="bilinear"
+ )
+ video = (video * 255.0).type_as(ovideo)
+
+ if random_upsample:
+
+ randratio = random.random() * 0.5 + 1
+ video = torch.nn.functional.interpolate(
+ video / 255.0, scale_factor=randratio, mode="bilinear"
+ )
+ video = (video * 255.0).type_as(ovideo)
+
+
+
+ assert dur_t % aligned == 0, "Please provide match vclip and align index"
+ size = size_h, size_w
+
+ ## make sure that sampling will not run out of the picture
+ # grid split
+ hgrids = torch.LongTensor(
+ [min(res_h // fragments_h * i, res_h - fsize_h) for i in range(fragments_h)]
+ )
+ wgrids = torch.LongTensor(
+ [min(res_w // fragments_w * i, res_w - fsize_w) for i in range(fragments_w)]
+ )
+ hlength, wlength = res_h // fragments_h, res_w // fragments_w
+
+ if random:
+ print("This part is deprecated. Please remind that.")
+ if res_h > fsize_h:
+ rnd_h = torch.randint(
+ res_h - fsize_h, (len(hgrids), len(wgrids), dur_t // aligned)
+ )
+ else:
+ rnd_h = torch.zeros((len(hgrids), len(wgrids), dur_t // aligned)).int()
+ if res_w > fsize_w:
+ rnd_w = torch.randint(
+ res_w - fsize_w, (len(hgrids), len(wgrids), dur_t // aligned)
+ )
+ else:
+ rnd_w = torch.zeros((len(hgrids), len(wgrids), dur_t // aligned)).int()
+ else:
+ if hlength > fsize_h:
+ rnd_h = torch.randint(
+ hlength - fsize_h, (len(hgrids), len(wgrids), dur_t // aligned)
+ )
+ else:
+ rnd_h = torch.zeros((len(hgrids), len(wgrids), dur_t // aligned)).int()
+ if wlength > fsize_w:
+ rnd_w = torch.randint(
+ wlength - fsize_w, (len(hgrids), len(wgrids), dur_t // aligned)
+ )
+ else:
+ rnd_w = torch.zeros((len(hgrids), len(wgrids), dur_t // aligned)).int()
+
+ target_video = torch.zeros(video.shape[:-2] + size).to(video.device)
+ # target_videos = []
+
+ for i, hs in enumerate(hgrids):
+ for j, ws in enumerate(wgrids):
+ for t in range(dur_t // aligned):
+ t_s, t_e = t * aligned, (t + 1) * aligned
+ h_s, h_e = i * fsize_h, (i + 1) * fsize_h
+ w_s, w_e = j * fsize_w, (j + 1) * fsize_w
+ if random:
+ h_so, h_eo = rnd_h[i][j][t], rnd_h[i][j][t] + fsize_h
+ w_so, w_eo = rnd_w[i][j][t], rnd_w[i][j][t] + fsize_w
+ else:
+ h_so, h_eo = hs + rnd_h[i][j][t], hs + rnd_h[i][j][t] + fsize_h
+ w_so, w_eo = ws + rnd_w[i][j][t], ws + rnd_w[i][j][t] + fsize_w
+ target_video[:, t_s:t_e, h_s:h_e, w_s:w_e] = video[
+ :, t_s:t_e, h_so:h_eo, w_so:w_eo
+ ]
+ # target_videos.append(video[:,t_s:t_e,h_so:h_eo,w_so:w_eo])
+ # target_video = torch.stack(target_videos, 0).reshape((dur_t // aligned, fragments, fragments,) + target_videos[0].shape).permute(3,0,4,1,5,2,6)
+ # target_video = target_video.reshape((-1, dur_t,) + size) ## Splicing Fragments
+ return target_video
+
+
+@lru_cache
+def get_resize_function(size_h, size_w, target_ratio=1, random_crop=False):
+ if random_crop:
+ return torchvision.transforms.RandomResizedCrop((size_h, size_w), scale=(0.40,1.0))
+ if target_ratio > 1:
+ size_h = int(target_ratio * size_w)
+ assert size_h > size_w
+ elif target_ratio < 1:
+ size_w = int(size_h / target_ratio)
+ assert size_w > size_h
+ return torchvision.transforms.Resize((size_h, size_w))
+
+def get_resized_video(
+ video,
+ size_h=224,
+ size_w=224,
+ random_crop=False,
+ arp=False,
+ **kwargs,
+):
+ video = video.permute(1,0,2,3)
+ resize_opt = get_resize_function(size_h, size_w,
+ video.shape[-2] / video.shape[-1] if arp else 1,
+ random_crop)
+ video = resize_opt(video).permute(1,0,2,3)
+ return video
+
+def get_arp_resized_video(
+ video,
+ short_edge=224,
+ train=False,
+ **kwargs,
+):
+ if train: ## if during training, will random crop into square and then resize
+ res_h, res_w = video.shape[-2:]
+ ori_short_edge = min(video.shape[-2:])
+ if res_h > ori_short_edge:
+ rnd_h = random.randrange(res_h - ori_short_edge)
+ video = video[...,rnd_h:rnd_h+ori_short_edge,:]
+ elif res_w > ori_short_edge:
+ rnd_w = random.randrange(res_w - ori_short_edge)
+ video = video[...,:,rnd_h:rnd_h+ori_short_edge]
+ ori_short_edge = min(video.shape[-2:])
+ scale_factor = short_edge / ori_short_edge
+ ovideo = video
+ video = torch.nn.functional.interpolate(
+ video / 255.0, scale_factors=scale_factor, mode="bilinear"
+ )
+ video = (video * 255.0).type_as(ovideo)
+ return video
+
+def get_arp_fragment_video(
+ video,
+ short_fragments=7,
+ fsize=32,
+ train=False,
+ **kwargs,
+):
+ if train: ## if during training, will random crop into square and then get fragments
+ res_h, res_w = video.shape[-2:]
+ ori_short_edge = min(video.shape[-2:])
+ if res_h > ori_short_edge:
+ rnd_h = random.randrange(res_h - ori_short_edge)
+ video = video[...,rnd_h:rnd_h+ori_short_edge,:]
+ elif res_w > ori_short_edge:
+ rnd_w = random.randrange(res_w - ori_short_edge)
+ video = video[...,:,rnd_h:rnd_h+ori_short_edge]
+ kwargs["fsize_h"], kwargs["fsize_w"] = fsize, fsize
+ res_h, res_w = video.shape[-2:]
+ if res_h > res_w:
+ kwargs["fragments_w"] = short_fragments
+ kwargs["fragments_h"] = int(short_fragments * res_h / res_w)
+ else:
+ kwargs["fragments_h"] = short_fragments
+ kwargs["fragments_w"] = int(short_fragments * res_w / res_h)
+ return get_spatial_fragments(video, **kwargs)
+
+def get_cropped_video(
+ video,
+ size_h=224,
+ size_w=224,
+ **kwargs,
+):
+ kwargs["fragments_h"], kwargs["fragments_w"] = 1, 1
+ kwargs["fsize_h"], kwargs["fsize_w"] = size_h, size_w
+ return get_spatial_fragments(video, **kwargs)
+
+
+def get_single_sample(
+ video,
+ sample_type="resize",
+ **kwargs,
+):
+ if sample_type.startswith("resize"):
+ video = get_resized_video(video, **kwargs)
+ elif sample_type.startswith("image"):
+ video = get_resized_video(video, **kwargs)
+ elif sample_type.startswith("semantic"):
+ video = get_resized_video(video, **kwargs)
+ elif sample_type.startswith("arp_resize"):
+ video = get_arp_resized_video(video, **kwargs)
+ elif sample_type.startswith("fragments"):
+ video = get_spatial_fragments(video, **kwargs)
+ elif sample_type.startswith("arp_fragments"):
+ video = get_arp_fragment_video(video, **kwargs)
+ elif sample_type.startswith("crop"):
+ video = get_cropped_video(video, **kwargs)
+ elif sample_type == "original":
+ return video
+
+ return video
+
+def get_spatial_samples(
+ video,
+ random_crop=0, ## 1: ARP-kept Crop; 2: Square-like Crop
+ sample_types={"resize": {}, "fragments": {}}, ## resize | arp_resize | crop | fragments
+):
+ if random_crop == 1:
+ print("Alert!")
+ ## Random Crop but keep the ARP
+ res_h, res_w = video.shape[-2:]
+ rnd_ratio = random.random() * 0.2 + 0.8
+ new_h, new_w = int(rnd_ratio * res_h), int(rnd_ratio * res_w)
+ rnd_h = random.randrange(res_h - new_h)
+ rnd_w = random.randrange(res_w - new_w)
+ video = video[..., rnd_h:rnd_hn+new_h, rnd_w:rnd_w+new_w]
+ ovideo = video
+ video = torch.nn.functional.interpolate(
+ video / 255.0, scale_factor=random.random() * 0.3 + 1.0, mode="bilinear"
+ )
+ video = (video * 255.0).type_as(ovideo)
+
+ if random_crop == 2:
+ ## Random Crop into a Size similar to Square
+ rnd_ratio = random.random() * 0.2 + 0.8
+ res_h, res_w = video.shape[-2:]
+ new_h = new_w = int(rnd_ratio * min(res_h, res_w))
+ rnd_h = random.randrange(res_h - new_h)
+ rnd_w = random.randrange(res_w - new_w)
+ video = video[..., rnd_h:rnd_h+new_h, rnd_w:rnd_w+new_w]
+ sampled_video = {}
+ for sample_type, arg in sample_types.items():
+ sampled_video[sample_type] = get_single_sample(video, sample_type,
+ **arg)
+ return sampled_video
+
+
+def get_spatial_and_temporal_samples(
+ video_path,
+ sample_types,
+ samplers,
+ is_train=False,
+ augment=False,
+):
+ video = {}
+ if video_path.endswith(".yuv"):
+ print("This part will be deprecated due to large memory cost.")
+ ## This is only an adaptation to LIVE-Qualcomm
+ ovideo = skvideo.io.vread(video_path, 1080, 1920, inputdict={'-pix_fmt':'yuvj420p'})
+ for stype in samplers:
+ frame_inds = samplers[stype](ovideo.shape[0], is_train)
+ imgs = [torch.from_numpy(ovideo[idx]) for idx in frame_inds]
+ video[stype] = torch.stack(imgs, 0).permute(3, 0, 1, 2)
+ del ovideo
+ else:
+ vreader = VideoReader(video_path)
+ ### Avoid duplicated video decoding!!! Important!!!!
+ all_frame_inds = []
+ frame_inds = {}
+ for stype in samplers:
+ frame_inds[stype] = samplers[stype](len(vreader), is_train)
+ all_frame_inds.append(frame_inds[stype])
+
+ ### Each frame is only decoded one time!!!
+ all_frame_inds = np.concatenate(all_frame_inds,0)
+ frame_dict = {idx: vreader[idx] for idx in np.unique(all_frame_inds)}
+
+ for stype in samplers:
+ imgs = [frame_dict[idx] for idx in frame_inds[stype]]
+ video[stype] = torch.stack(imgs, 0).permute(3, 0, 1, 2)
+
+ sampled_video = {}
+ for stype, sopt in sample_types.items():
+ sampled_video[stype] = get_single_sample(video[stype], stype,
+ **sopt)
+ return sampled_video, frame_inds
+
+
+class SampleFrames:
+ def __init__(self, clip_len, frame_interval=1, num_clips=1):
+
+ self.clip_len = clip_len
+ self.frame_interval = frame_interval
+ self.num_clips = num_clips
+
+ def _get_train_clips(self, num_frames):
+ """Get clip offsets in train mode.
+
+ It will calculate the average interval for selected frames,
+ and randomly shift them within offsets between [0, avg_interval].
+ If the total number of frames is smaller than clips num or origin
+ frames length, it will return all zero indices.
+
+ Args:
+ num_frames (int): Total number of frame in the video.
+
+ Returns:
+ np.ndarray: Sampled frame indices in train mode.
+ """
+ ori_clip_len = self.clip_len * self.frame_interval
+ avg_interval = (num_frames - ori_clip_len + 1) // self.num_clips
+
+ if avg_interval > 0:
+ base_offsets = np.arange(self.num_clips) * avg_interval
+ clip_offsets = base_offsets + np.random.randint(
+ avg_interval, size=self.num_clips
+ )
+ elif num_frames > max(self.num_clips, ori_clip_len):
+ clip_offsets = np.sort(
+ np.random.randint(num_frames - ori_clip_len + 1, size=self.num_clips)
+ )
+ elif avg_interval == 0:
+ ratio = (num_frames - ori_clip_len + 1.0) / self.num_clips
+ clip_offsets = np.around(np.arange(self.num_clips) * ratio)
+ else:
+ clip_offsets = np.zeros((self.num_clips,), dtype=np.int)
+ return clip_offsets
+
+ def _get_test_clips(self, num_frames, start_index=0):
+ """Get clip offsets in test mode.
+
+ Calculate the average interval for selected frames, and shift them
+ fixedly by avg_interval/2.
+
+ Args:
+ num_frames (int): Total number of frame in the video.
+
+ Returns:
+ np.ndarray: Sampled frame indices in test mode.
+ """
+ ori_clip_len = self.clip_len * self.frame_interval
+ avg_interval = (num_frames - ori_clip_len + 1) / float(self.num_clips)
+ if num_frames > ori_clip_len - 1:
+ base_offsets = np.arange(self.num_clips) * avg_interval
+ clip_offsets = (base_offsets + avg_interval / 2.0).astype(np.int32)
+ else:
+ clip_offsets = np.zeros((self.num_clips,), dtype=np.int32)
+ return clip_offsets
+
+ def __call__(self, total_frames, train=False, start_index=0):
+ """Perform the SampleFrames loading.
+
+ Args:
+ results (dict): The resulting dict to be modified and passed
+ to the next transform in pipeline.
+ """
+ if train:
+ clip_offsets = self._get_train_clips(total_frames)
+ else:
+ clip_offsets = self._get_test_clips(total_frames)
+ frame_inds = (
+ clip_offsets[:, None]
+ + np.arange(self.clip_len)[None, :] * self.frame_interval
+ )
+ frame_inds = np.concatenate(frame_inds)
+
+ frame_inds = frame_inds.reshape((-1, self.clip_len))
+ frame_inds = np.mod(frame_inds, total_frames)
+ frame_inds = np.concatenate(frame_inds) + start_index
+ return frame_inds.astype(np.int32)
+
+
+class FragmentSampleFrames:
+ def __init__(self, fsize_t, fragments_t, frame_interval=1, num_clips=1, drop_rate=0., ):
+
+ self.fragments_t = fragments_t
+ self.fsize_t = fsize_t
+ self.size_t = fragments_t * fsize_t
+ self.frame_interval = frame_interval
+ self.num_clips = num_clips
+ self.drop_rate = drop_rate
+
+ def get_frame_indices(self, num_frames, train=False):
+
+ tgrids = np.array(
+ [num_frames // self.fragments_t * i for i in range(self.fragments_t)],
+ dtype=np.int32,
+ )
+ tlength = num_frames // self.fragments_t
+
+ if tlength > self.fsize_t * self.frame_interval:
+ rnd_t = np.random.randint(
+ 0, tlength - self.fsize_t * self.frame_interval, size=len(tgrids)
+ )
+ else:
+ rnd_t = np.zeros(len(tgrids), dtype=np.int32)
+
+ ranges_t = (
+ np.arange(self.fsize_t)[None, :] * self.frame_interval
+ + rnd_t[:, None]
+ + tgrids[:, None]
+ )
+
+
+ drop = random.sample(list(range(self.fragments_t)), int(self.fragments_t * self.drop_rate))
+ dropped_ranges_t = []
+ for i, rt in enumerate(ranges_t):
+ if i not in drop:
+ dropped_ranges_t.append(rt)
+ return np.concatenate(dropped_ranges_t)
+
+ def __call__(self, total_frames, train=False, start_index=0):
+ frame_inds = []
+
+ for i in range(self.num_clips):
+ frame_inds += [self.get_frame_indices(total_frames)]
+
+ frame_inds = np.concatenate(frame_inds)
+ frame_inds = np.mod(frame_inds + start_index, total_frames)
+ return frame_inds.astype(np.int32)
+
+class SimpleDataset(torch.utils.data.Dataset):
+ def __init__(self, opt):
+ ## opt is a dictionary that includes options for video sampling
+
+ super().__init__()
+
+ self.video_infos = []
+ self.ann_file = opt["anno_file"]
+ self.data_prefix = opt["data_prefix"]
+ self.opt = opt
+ self.sample_type = opt["sample_type"]
+
+ self.phase = opt["phase"]
+ self.mean = torch.FloatTensor([123.675, 116.28, 103.53])
+ self.std = torch.FloatTensor([58.395, 57.12, 57.375])
+ self.sampler = SampleFrames(opt["clip_len"], opt["frame_interval"], opt["num_clips"])
+
+ if isinstance(self.ann_file, list):
+ self.video_infos = self.ann_file
+ else:
+ with open(self.ann_file, "r") as fin:
+ for line in fin:
+ line_split = line.strip().split(",")
+ filename, _, _, label = line_split
+ label = float(label)
+ filename = osp.join(self.data_prefix, filename)
+ self.video_infos.append(dict(filename=filename, label=label))
+
+ def __getitem__(self, index):
+ video_info = self.video_infos[index]
+ filename = video_info["filename"]
+ label = video_info["label"]
+ vreader = VideoReader(filename)
+ ## Read Original Frames
+ frame_inds = self.sampler(len(vreader), self.phase == "train")
+ frame_dict = {idx: vreader[idx] for idx in np.unique(frame_inds)}
+ imgs = [frame_dict[idx] for idx in frame_inds]
+ img_shape = imgs[0].shape
+ video = torch.stack(imgs, 0)
+ video = video.permute(3, 0, 1, 2)
+ ## Process Frames
+ sampled_video = get_single_sample(video,
+ self.sample_type,
+ **self.opt["sampling_args"],
+ )
+ sampled_video = ((sampled_video.permute(1, 2, 3, 0) - self.mean) / self.std).permute(3, 0, 1, 2)
+ return {
+ "video": sampled_video,
+ "num_clips": self.opt["num_clips"],
+ "frame_inds": frame_inds,
+ "gt_label": label,
+ "name": osp.basename(video_info["filename"]),
+ }
+
+ def __len__(self):
+ return len(self.video_infos)
+
+
+class FusionDataset(torch.utils.data.Dataset):
+ def __init__(self, opt):
+ ## opt is a dictionary that includes options for video sampling
+
+ super().__init__()
+
+
+ self.video_infos = []
+ self.ann_file = opt["anno_file"]
+ self.data_prefix = opt["data_prefix"]
+ self.opt = opt
+ self.sample_types = opt["sample_types"]
+ self.data_backend = opt.get("data_backend", "disk")
+ self.augment = opt.get("augment", False)
+ if self.data_backend == "petrel":
+ from petrel_client import client
+ self.client = client.Client(enable_mc=True)
+
+ self.phase = opt["phase"]
+ self.crop = opt.get("random_crop", False)
+ self.mean = torch.FloatTensor([123.675, 116.28, 103.53])
+ self.std = torch.FloatTensor([58.395, 57.12, 57.375])
+ self.samplers = {}
+ for stype, sopt in opt["sample_types"].items():
+ if "t_frag" not in sopt:
+ # revised legacy temporal sampling
+ self.samplers[stype] = FragmentSampleFrames(sopt["clip_len"], sopt["num_clips"], sopt["frame_interval"])
+ else:
+ self.samplers[stype] = FragmentSampleFrames(sopt["clip_len"] // sopt["t_frag"], sopt["t_frag"], sopt["frame_interval"], sopt["num_clips"])
+ print(stype+" branch sampled frames:", self.samplers[stype](240, self.phase == "train"))
+
+ if isinstance(self.ann_file, list):
+ self.video_infos = self.ann_file
+ else:
+ try:
+ with open(self.ann_file, "r") as fin:
+ for line in fin:
+ line_split = line.strip().split(",")
+ filename, label = line_split
+ label = float(label)
+ filename = osp.join(self.data_prefix, filename)
+ self.video_infos.append(dict(filename=filename, label=label))
+
+ except:
+ #### No Label Testing
+ video_filenames = sorted(glob.glob(self.data_prefix+"/*.mp4"))
+ print(video_filenames)
+ for filename in video_filenames:
+ self.video_infos.append(dict(filename=filename, label=-1))
+
+
+ def prepare_video(self, video_path):
+ # 用 self.sample_types, self.samplers 和 get_spatial_and_temporal_samples 处理单个视频
+ # 这里只需要像 __getitem__ 那样,只不过 filename=video_path,label=-1
+ data, frame_inds = get_spatial_and_temporal_samples(
+ video_path,
+ self.sample_types,
+ self.samplers,
+ self.phase == "train",
+ self.augment and (self.phase == "train"),
+ )
+ for k, v in data.items():
+ data[k] = ((v.permute(1, 2, 3, 0) - self.mean) / self.std).permute(3, 0, 1, 2)
+ data["num_clips"] = {}
+ for stype, sopt in self.sample_types.items():
+ data["num_clips"][stype] = sopt["num_clips"]
+ data["frame_inds"] = frame_inds
+ data["gt_label"] = -1
+ data["name"] = osp.basename(video_path)
+ return data
+ def refresh_hypers(self):
+ if not hasattr(self, "initial_sample_types"):
+ self.initial_sample_types = copy.deepcopy(self.sample_types)
+
+ types = self.sample_types
+
+ if "fragments_up" in types:
+ ubh, ubw = self.initial_sample_types["fragments_up"]["fragments_h"] + 1, self.initial_sample_types["fragments_up"]["fragments_w"] + 1
+ lbh, lbw = self.initial_sample_types["fragments"]["fragments_h"] + 1, self.initial_sample_types["fragments"]["fragments_w"] + 1
+ dh, dw = types["fragments_up"]["fragments_h"], types["fragments_up"]["fragments_w"]
+
+ types["fragments_up"]["fragments_h"] = random.randrange(max(lbh, dh-1), min(ubh, dh+2))
+ types["fragments_up"]["fragments_w"] = random.randrange(max(lbw, dw-1), min(ubw, dw+2))
+
+ if "resize_up" in types:
+
+ types["resize_up"]["size_h"] = types["fragments_up"]["fragments_h"] * types["fragments_up"]["fsize_h"]
+ types["resize_up"]["size_w"] = types["fragments_up"]["fragments_w"] * types["fragments_up"]["fsize_w"]
+
+ self.sample_types.update(types)
+
+
+
+ def __getitem__(self, index):
+ video_info = self.video_infos[index]
+ filename = video_info["filename"]
+ label = video_info["label"]
+
+
+ ## Read Original Frames
+ ## Process Frames
+ data, frame_inds = get_spatial_and_temporal_samples(filename, self.sample_types, self.samplers,
+ self.phase == "train", self.augment and (self.phase == "train"),
+ )
+
+ for k, v in data.items():
+ data[k] = ((v.permute(1, 2, 3, 0) - self.mean) / self.std).permute(3, 0, 1, 2)
+
+ data["num_clips"] = {}
+ for stype, sopt in self.sample_types.items():
+ data["num_clips"][stype] = sopt["num_clips"]
+ data["frame_inds"] = frame_inds
+ data["gt_label"] = label
+ data["name"] = osp.basename(video_info["filename"])
+
+ return data
+
+ def __len__(self):
+ return len(self.video_infos)
+
+class VTSS_Dataset(torch.utils.data.Dataset):
+ def __init__(self, opt):
+ ## opt is a dictionary that includes options for video sampling
+
+ super().__init__()
+
+
+ self.video_infos = []
+ self.ann_file = opt["anno_file"]
+ self.data_prefix = opt["data_prefix"]
+ self.opt = opt
+ self.sample_types = opt["sample_types"]
+ self.data_backend = opt.get("data_backend", "disk")
+ self.augment = opt.get("augment", False)
+ if self.data_backend == "petrel":
+ from petrel_client import client
+ self.client = client.Client(enable_mc=True)
+
+ self.phase = opt["phase"]
+ self.crop = opt.get("random_crop", False)
+ self.mean = torch.FloatTensor([123.675, 116.28, 103.53])
+ self.std = torch.FloatTensor([58.395, 57.12, 57.375])
+ self.samplers = {}
+ for stype, sopt in opt["sample_types"].items():
+ if stype == "fragments":
+ if "t_frag" not in sopt:
+ # revised legacy temporal sampling
+ self.samplers[stype] = FragmentSampleFrames(sopt["clip_len"], sopt["num_clips"], sopt["frame_interval"])
+ else:
+ self.samplers[stype] = FragmentSampleFrames(sopt["clip_len"] // sopt["t_frag"], sopt["t_frag"], sopt["frame_interval"], sopt["num_clips"])
+
+ print(stype+" branch sampled frames:", self.samplers[stype](240, self.phase == "train"))
+ if stype == "image":
+ self.samplers[stype] = SimpleFrameSampler(
+ sopt["clip_len"]
+ )
+ if stype == "semantic":
+ self.samplers[stype] = SimpleFrameSampler(
+ sopt["clip_len"]
+ )
+ if isinstance(self.ann_file, list):
+ self.video_infos = self.ann_file
+ else:
+ # try:
+ if opt["add_feature"] == True: # 添加刷库的特征
+ with open(self.ann_file, "r") as fin:
+ for line in fin:
+ line_split = line.strip().split(",")
+ filename, _, _, label = line_split[:4]
+ feature = [float(d) for d in line_split[4:]]
+ label = float(label)
+ filename = osp.join(self.data_prefix, filename)
+ self.video_infos.append(dict(filename=filename, label=label, feature=feature))
+ else:
+ with open(self.ann_file, "r") as fin:
+ for line in fin:
+ line_split = line.strip().split(",")
+ filename, _, _, label = line_split
+ label = float(label)
+ filename = osp.join(self.data_prefix, filename)
+ self.video_infos.append(dict(filename=filename, label=label))
+
+ def refresh_hypers(self):
+ if not hasattr(self, "initial_sample_types"):
+ self.initial_sample_types = copy.deepcopy(self.sample_types)
+
+ types = self.sample_types
+
+ if "fragments_up" in types:
+ ubh, ubw = self.initial_sample_types["fragments_up"]["fragments_h"] + 1, self.initial_sample_types["fragments_up"]["fragments_w"] + 1
+ lbh, lbw = self.initial_sample_types["fragments"]["fragments_h"] + 1, self.initial_sample_types["fragments"]["fragments_w"] + 1
+ dh, dw = types["fragments_up"]["fragments_h"], types["fragments_up"]["fragments_w"]
+
+ types["fragments_up"]["fragments_h"] = random.randrange(max(lbh, dh-1), min(ubh, dh+2))
+ types["fragments_up"]["fragments_w"] = random.randrange(max(lbw, dw-1), min(ubw, dw+2))
+
+ if "resize_up" in types:
+
+ types["resize_up"]["size_h"] = types["fragments_up"]["fragments_h"] * types["fragments_up"]["fsize_h"]
+ types["resize_up"]["size_w"] = types["fragments_up"]["fragments_w"] * types["fragments_up"]["fsize_w"]
+
+ self.sample_types.update(types)
+
+
+ def __getitem__(self, index):
+ video_info = self.video_infos[index]
+ filename = video_info["filename"]
+ label = video_info["label"]
+ if "feature" in video_info:
+ feature = video_info["feature"]
+
+
+ ## Read Original Frames
+ ## Process Frames
+ data, frame_inds = get_spatial_and_temporal_samples(filename, self.sample_types, self.samplers,
+ self.phase == "train", self.augment and (self.phase == "train"),
+ )
+
+ for k, v in data.items():
+ data[k] = ((v.permute(1, 2, 3, 0) - self.mean) / self.std).permute(3, 0, 1, 2)
+
+ data["num_clips"] = {}
+ for stype, sopt in self.sample_types.items():
+ data["num_clips"][stype] = sopt["num_clips"]
+ data["frame_inds"] = frame_inds
+ data["gt_label"] = label
+ data["name"] = video_info["filename"]
+ if "feature" in video_info:
+ data["feature"] = torch.tensor(feature)
+
+ return data
+
+ def __len__(self):
+ return len(self.video_infos)
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/head.py b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/head.py
new file mode 100644
index 0000000000000000000000000000000000000000..79e45e3309dd1f717525cfa7bb3f5f59da369417
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/head.py
@@ -0,0 +1,233 @@
+import torch.nn as nn
+import torch
+from torchvision.ops import roi_pool, roi_align
+from torch.nn import functional as F
+import numpy as np
+import math
+
+
+class VQAHead(nn.Module):
+ """MLP Regression Head for VQA.
+ Args:
+ in_channels: input channels for MLP
+ hidden_channels: hidden channels for MLP
+ dropout_ratio: the dropout ratio for features before the MLP (default 0.5)
+ """
+
+ def __init__(
+ self, in_channels=768, hidden_channels=64, dropout_ratio=0.5, **kwargs
+ ):
+ super().__init__()
+ self.dropout_ratio = dropout_ratio
+ self.in_channels = in_channels
+ self.hidden_channels = hidden_channels
+ if self.dropout_ratio != 0:
+ self.dropout = nn.Dropout(p=self.dropout_ratio)
+ else:
+ self.dropout = None
+ self.fc_hid = nn.Conv3d(self.in_channels, self.hidden_channels, (1, 1, 1))
+ self.fc_last = nn.Conv3d(self.hidden_channels, 1, (1, 1, 1))
+ self.gelu = nn.GELU()
+
+ self.avg_pool = nn.AdaptiveAvgPool3d((1, 1, 1))
+
+ def forward(self, x, rois=None):
+ x = self.dropout(x)
+ qlt_score = self.fc_last(self.dropout(self.gelu(self.fc_hid(x))))
+ return qlt_score
+
+
+class VARHead(nn.Module):
+ """MLP Regression Head for Video Action Recognition.
+ Args:
+ in_channels: input channels for MLP
+ hidden_channels: hidden channels for MLP
+ dropout_ratio: the dropout ratio for features before the MLP (default 0.5)
+ """
+
+ def __init__(
+ self, in_channels=768, out_channels=400, dropout_ratio=0.5, **kwargs
+ ):
+ super().__init__()
+ self.dropout_ratio = dropout_ratio
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ if self.dropout_ratio != 0:
+ self.dropout = nn.Dropout(p=self.dropout_ratio)
+ else:
+ self.dropout = None
+ self.fc = nn.Conv3d(self.in_channels, self.out_channels, (1, 1, 1))
+ self.avg_pool = nn.AdaptiveAvgPool3d((1, 1, 1))
+
+ def forward(self, x, rois=None):
+ x = self.dropout(x)
+ x = self.avg_pool(x)
+ out = self.fc(x)
+ return out
+
+class MLPhead(nn.Module):
+ def __init__(self, need_feature = True):
+ super(MLPhead, self).__init__()
+ self.fc1 = nn.Linear(15, 64)
+ self.fc2 = nn.Linear(64, 128)
+ self.fc3 = nn.Linear(128, 256)
+ self.fc4 = nn.Linear(256, 400)
+ self.fc_final = nn.Linear(400, 1)
+ self.relu = nn.GELU()
+ self.drop = nn.Dropout(0.1)
+ self.need_feature = need_feature
+
+ def forward(self, x):
+ x = self.relu(self.fc1(x))
+ x = self.drop(x)
+ x = self.relu(self.fc2(x))
+ x = self.drop(x)
+ x = self.relu(self.fc3(x))
+ x = self.drop(x)
+ x = self.relu(self.fc4(x))
+
+ feature = x
+ x = self.drop(x)
+ score = self.fc_final(x)
+ if self.need_feature :
+ return feature, score
+ else:
+ return score
+
+class MLPhead_sem(nn.Module):
+ def __init__(self, need_feature = True):
+ super(MLPhead_sem, self).__init__()
+ self.fc1 = nn.Linear(768, 512)
+ self.fc2 = nn.Linear(512, 400)
+ self.fc3 = nn.Linear(400, 1)
+ self.relu = nn.GELU()
+ self.drop = nn.Dropout(0.1)
+ self.need_feature = need_feature
+
+ def forward(self, x):
+ x = self.relu(self.fc1(x))
+ x = self.drop(x)
+ x = self.relu(self.fc2(x))
+ feature = x
+ x = self.drop(x)
+ score = self.fc3(x)
+ if self.need_feature :
+ return feature, score
+ else:
+ return score
+
+class MLPhead_image(nn.Module):
+ def __init__(self, need_feature = True):
+ super(MLPhead_image, self).__init__()
+ self.fc1 = nn.Linear(1000, 512)
+ self.fc2 = nn.Linear(512, 400)
+ self.fc3 = nn.Linear(400, 1)
+ self.relu = nn.GELU()
+ self.drop = nn.Dropout(0.1)
+ self.need_feature = need_feature
+
+ def forward(self, x):
+ x = self.relu(self.fc1(x))
+ x = self.drop(x)
+ x = self.relu(self.fc2(x))
+ feature = x
+ x = self.drop(x)
+ score = self.fc3(x)
+ if self.need_feature :
+ return feature, score
+ else:
+ return score
+
+
+class Final_MLP(nn.Module):
+ def __init__(self, in_channel = 1264):
+ super(Final_MLP, self).__init__()
+ self.fc0 = nn.Linear(in_channel, 512)
+ self.fc1 = nn.Linear(512, 256)
+ self.fc2 = nn.Linear(256, 64)
+ self.fc3 = nn.Linear(64, 1)
+ self.relu = nn.GELU()
+ self.drop = nn.Dropout(0.1)
+
+ def forward(self, x):
+ x = self.relu(self.fc0(x))
+ x = self.drop(x)
+ x = self.relu(self.fc1(x))
+ x = self.drop(x)
+ x = self.relu(self.fc2(x))
+ x = self.drop(x)
+ x = self.relu(self.fc3(x))
+ return x
+
+class IQAHead(nn.Module):
+ """MLP Regression Head for IQA.
+ Args:
+ in_channels: input channels for MLP
+ hidden_channels: hidden channels for MLP
+ dropout_ratio: the dropout ratio for features before the MLP (default 0.5)
+ """
+
+ def __init__(
+ self, in_channels=768, hidden_channels=64, dropout_ratio=0.5, **kwargs
+ ):
+ super().__init__()
+ self.dropout_ratio = dropout_ratio
+ self.in_channels = in_channels
+ self.hidden_channels = hidden_channels
+ if self.dropout_ratio != 0:
+ self.dropout = nn.Dropout(p=self.dropout_ratio)
+ else:
+ self.dropout = None
+ self.fc_hid = nn.Linear(self.in_channels, self.hidden_channels)
+ self.fc_last = nn.Linear(self.hidden_channels, 1)
+ self.gelu = nn.GELU()
+
+ def forward(self, x):
+ x = self.dropout(x)
+ qlt_score = self.fc_last(self.dropout(self.gelu(self.fc_hid(x))))
+ return qlt_score
+
+
+class WeightFeatureFusion(nn.Module):
+ def __init__(self):
+ super(WeightFeatureFusion, self).__init__()
+ self.fc = nn.Linear(400 * 2, 2)
+
+ def forward(self, x1, x2):
+ x = torch.cat([x1, x2], dim=1)
+ weights = self.fc(x)
+ fused_feature = weights[:, 0].unsqueeze(dim=1) * x1 + weights[:, 1].unsqueeze(dim=1) * x2
+
+ return fused_feature
+
+class CrossGatingBlock(nn.Module):
+ def __init__(self, x_features=400, num_channels=400, use_bias=True, use_global_mlp=True, dropout_rate=0):
+ super().__init__()
+ self.x_features = x_features
+ self.num_channels = num_channels
+ self.use_bias = use_bias
+ self.use_global_mlp = use_global_mlp
+ self.drop = dropout_rate
+
+ self.Conv_0 = nn.Linear(self.x_features, self.num_channels)
+ self.Conv_1 = nn.Linear(self.num_channels, self.num_channels)
+ self.in_project_x = nn.Linear(self.num_channels, self.num_channels, bias=self.use_bias)
+ self.gelu1 = nn.GELU(approximate='tanh')
+ self.out_project_y = nn.Linear(self.num_channels, self.num_channels, bias=self.use_bias)
+ self.dropout1 = nn.Dropout(self.drop)
+
+ def forward(self, x, y):
+
+ x = self.Conv_0(x)
+ y = self.Conv_1(y)
+
+ shortcut_y = y
+
+ x = self.in_project_x(x)
+ gx = self.gelu1(x)
+ y = y * gx
+ y = self.out_project_y(y)
+ y = self.dropout1(y)
+
+ y = y + shortcut_y
+ return y
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/infer.yml b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/infer.yml
new file mode 100644
index 0000000000000000000000000000000000000000..dd2af3710b6a3b114a8d84d8278c23b0c6aeaae3
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/infer.yml
@@ -0,0 +1,51 @@
+name: FAST-VQA-B-Refactor-1*4
+num_epochs: 30
+l_num_epochs: 0
+warmup_epochs: 2.5
+ema: true
+save_model: true
+batch_size: 16
+num_workers: 6
+
+wandb:
+ project_name: VQA_Experiments_2024
+
+data:
+ test-data:
+ type: FusionDataset
+ args:
+ phase: test
+ anno_file: ./training_suitability_assessment/sample/video_name.txt
+ data_prefix: ./training_suitability_assessment/sample/video/
+ sample_types:
+ #resize:
+ # size_h: 224
+ # size_w: 224
+ fragments:
+ fragments_h: 7
+ fragments_w: 7
+ fsize_h: 32
+ fsize_w: 32
+ aligned: 32
+ clip_len: 32
+ frame_interval: 2
+ num_clips: 4
+model:
+ type: DiViDeAddEvaluator
+ args:
+ backbone:
+ fragments:
+ checkpoint: false
+ pretrained:
+ backbone_size: swin_tiny_grpb
+ backbone_preserve_keys: fragments
+ divide_head: false
+ vqa_head:
+ in_channels: 768
+ hidden_channels: 64
+
+optimizer:
+ lr: !!float 1e-3
+ backbone_lr_mult: !!float 1e-1
+ wd: 0.05
+
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/inference.py b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..04d2a25fc032c4c3a0608c983f045097ac443119
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/inference.py
@@ -0,0 +1,169 @@
+import torch
+import cv2
+import random
+import os.path as osp
+from model import DiViDeAddEvaluator
+from datasets import FusionDataset
+
+import argparse
+
+from scipy.stats import spearmanr, pearsonr
+from scipy.stats.stats import kendalltau as kendallr
+import numpy as np
+
+from time import time
+from tqdm import tqdm
+import pickle
+import math
+
+import wandb
+import yaml
+import csv
+from thop import profile
+
+
+def rescale(pr, gt=None):
+ if gt is None:
+ pr = (pr - np.mean(pr)) / np.std(pr)
+ else:
+ pr = ((pr - np.mean(pr)) / np.std(pr)) * np.std(gt) + np.mean(gt)
+ return pr
+
+sample_types=["resize", "fragments", "crop", "arp_resize", "arp_fragments"]
+
+
+def profile_inference(inf_set, model, device):
+ video = {}
+ data = inf_set[0]
+ for key in sample_types:
+ if key in data:
+ video[key] = data[key].to(device)
+ c, t, h, w = video[key].shape
+ video[key] = video[key].reshape(1, c, data["num_clips"][key], t // data["num_clips"][key], h, w).permute(0,2,1,3,4,5).reshape( data["num_clips"][key], c, t // data["num_clips"][key], h, w)
+ with torch.no_grad():
+ flops, params = profile(model, (video, ))
+ print(f"The FLOps of the Variant is {flops/1e9:.1f}G, with Params {params/1e6:.2f}M.")
+
+def inference_set(inf_loader, model, device, output_file, save_model=False, set_name="na"):
+ print(f"Validating for {set_name}.")
+ results = []
+ video_paths = []
+ keys = []
+
+ for i, data in enumerate(tqdm(inf_loader, desc="Validating")):
+ result = dict()
+ video = {}
+ for key in sample_types:
+ if key not in keys:
+ keys.append(key)
+ if key in data:
+ video[key] = data[key].to(device)
+ b, c, t, h, w = video[key].shape
+ video[key] = video[key].reshape(b, c, data["num_clips"][key], t // data["num_clips"][key], h, w).permute(0,2,1,3,4,5).reshape(b * data["num_clips"][key], c, t // data["num_clips"][key], h, w)
+ with torch.no_grad():
+ labels = model(video,reduce_scores=False)
+ labels = [np.mean(l.cpu().numpy()) for l in labels]
+ result["pr_labels"] = labels
+ video_path = data["name"][0]
+ video_paths.append(video_path)
+ result["gt_label"] = data["gt_label"].item()
+ result["name"] = data["name"]
+ results.append(result)
+
+
+ ## generate the demo video for video quality localization
+ gt_labels = [r["gt_label"] for r in results]
+ pr_labels = 0
+ pr_dict = {}
+ for i, key in zip(range(len(results[0]["pr_labels"])), keys):
+ key_pr_labels = np.array([np.mean(r["pr_labels"][i]) for r in results])
+ pr_dict[key] = key_pr_labels
+ pr_labels += rescale(key_pr_labels)
+
+ pr_labels = rescale(pr_labels, gt_labels) #resize pr_labels to the same scale as gt_labels
+
+ s = spearmanr(gt_labels, pr_labels)[0]
+ p = pearsonr(gt_labels, pr_labels)[0]
+ k = kendallr(gt_labels, pr_labels)[0]
+ r = np.sqrt(((gt_labels - pr_labels) ** 2).mean())
+ print(
+ f"For {len(inf_loader)} videos, \nthe accuracy of the model is as follows:\n SROCC: {s:.4f} \n PLCC: {p:.4f} \n KROCC: {k:.4f} \n RMSE: {r:.4f}."
+ )
+ with open(output_file, 'w', newline='') as csvfile:
+ writer = csv.writer(csvfile)
+ writer.writerow(["video_path", "gt_label", "pr_label"])
+ for i in range(len(video_paths)):
+ writer.writerow([video_paths[i],gt_labels[i], pr_labels[i]])
+
+
+def main():
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "-o", "--opt", type=str, default="test.yml", help="the option file"
+ )
+ parser.add_argument(
+ "-t", "--output", type=str, default=f"out_file.csv", help="the output file"
+ )
+
+
+ args = parser.parse_args()
+ with open(args.opt, "r") as f:
+ opt = yaml.safe_load(f)
+
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+
+ model = DiViDeAddEvaluator(**opt["model"]["args"]).to(device)
+
+ state_dict = torch.load(opt["test_load_path"], map_location=device)["state_dict"]
+
+ if "test_load_path_aux" in opt:
+ aux_state_dict = torch.load(opt["test_load_path_aux"], map_location=device)["state_dict"]
+
+ from collections import OrderedDict
+
+ fusion_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k.startswith("vqa_head"):
+ ki = k.replace("vqa", "fragments")
+ else:
+ ki = k
+ fusion_state_dict[ki] = v
+
+ for k, v in aux_state_dict.items():
+ if k.startswith("frag"):
+ continue
+ if k.startswith("vqa_head"):
+ ki = k.replace("vqa", "resize")
+ else:
+ ki = k
+ fusion_state_dict[ki] = v
+
+ state_dict = fusion_state_dict
+
+ model.load_state_dict(state_dict, strict=True)
+
+ for key in opt["data"].keys(): # different datasets
+
+ if "val" not in key and "test" not in key:
+ continue
+
+ val_dataset = FusionDataset(opt["data"][key]["args"])
+
+
+ val_loader = torch.utils.data.DataLoader(
+ val_dataset, batch_size=1, num_workers=opt["num_workers"], pin_memory=True,
+ )
+
+ inference_set(
+ val_loader,
+ model,
+ device,
+ args.output,
+ set_name=key,
+ )
+
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/model.py b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..d30de343506a9060b7796edc533dabe3da2405c7
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/model.py
@@ -0,0 +1,274 @@
+import torch
+import torch.nn as nn
+import time
+from torch.nn.functional import adaptive_avg_pool3d
+from functools import partial, reduce
+from .swin_backbone import SwinTransformer3D as VideoBackbone
+from .swin_backbone import swin_3d_tiny, swin_3d_small
+from .conv_backbone import convnext_3d_tiny, convnext_3d_small, convnext_tiny
+from .head import VQAHead, IQAHead, VARHead, MLPhead, Final_MLP, MLPhead_sem, MLPhead_image, WeightFeatureFusion, CrossGatingBlock
+
+
+
+
+class TSAN(nn.Module):
+ def __init__(
+ self,
+ backbone_size="divided",
+ backbone_preserve_keys = 'fragments,resize',
+ multi=False,
+ layer=-1,
+ backbone=dict(resize={"window_size": (4,4,4)}, fragments={"window_size": (4,4,4)}),
+ divide_head=False,
+ vqa_head=dict(in_channels=768, out_channels=400),
+ var=False,
+ add_feature = True,
+ fusion_type = "cat"
+ ):
+ self.backbone_preserve_keys = backbone_preserve_keys.split(",")
+ self.multi = multi
+ self.layer = layer
+ self.add_feature = add_feature
+ self.fusion_type = fusion_type
+ super().__init__()
+ for key, hypers in backbone.items():
+ print(backbone_size)
+ if key not in self.backbone_preserve_keys:
+ continue
+ if backbone_size=="divided":
+ t_backbone_size = hypers["type"]
+ else:
+ t_backbone_size = backbone_size
+ if t_backbone_size == 'swin_tiny':
+ b = swin_3d_tiny(**backbone[key])
+ elif t_backbone_size == 'swin_tiny_grpb':
+ b = VideoBackbone()
+ elif t_backbone_size == 'conv_2d_tiny':
+ b = convnext_tiny(pretrained=True)
+ elif t_backbone_size == "feature_mlp":
+ b = MLPhead()
+ else:
+ raise NotImplementedError
+ print("Setting backbone:", key+"_backbone")
+ setattr(self, key+"_backbone", b)
+ if divide_head:
+ for key in backbone:
+ if key not in self.backbone_preserve_keys or key == "feature":
+ continue
+ elif key == "semantic":
+ b = MLPhead_sem()
+ elif key == "image":
+ b = MLPhead_image()
+ else:
+ b = VARHead(**vqa_head)
+ print("Setting head:", key+"_head")
+ setattr(self, key+"_head", b)
+
+ else:
+ if var:
+ self.vqa_head = VARHead(**vqa_head)
+ print(b)
+ else:
+ self.vqa_head = VQAHead(**vqa_head)
+ if self.fusion_type == "cat":
+ final_mlp_channel = 0
+ for key in backbone:
+ if key == "semantic" or key == "image" or key == "fragments":
+ final_mlp_channel += 400
+ elif key == "feature":
+ final_mlp_channel += 400
+ self.mlp_head = MLPhead()
+ self.final_mlp = Final_MLP(in_channel=final_mlp_channel)
+
+ elif self.fusion_type == "gate+weight":
+ self.weight_feature_fusion = WeightFeatureFusion()
+ self.gate_feature_fusion_static = CrossGatingBlock()
+ self.gate_feature_fusion_dynamic = CrossGatingBlock()
+ self.final_mlp = Final_MLP(in_channel=400)
+ def forward(self, vclips, inference=True, return_pooled_feats=False, reduce_scores=True, pooled=False, **kwargs):
+ if inference:
+ self.eval()
+ with torch.no_grad():
+
+ feats = []
+ for key in vclips:
+
+ if key == "feature":
+ feat, _ = getattr(self, key.split("_")[0]+"_backbone")(vclips[key])
+ elif key == "semantic":
+ feat,_ = getattr(self, key.split("_")[0]+"_backbone")(torch.squeeze(vclips[key],dim=2), multi=self.multi, layer=self.layer, **kwargs)
+ elif key == "image":
+ feat = getattr(self, key.split("_")[0]+"_backbone")(torch.squeeze(vclips[key], dim=2))
+
+ else:
+ feat= getattr(self, key.split("_")[0]+"_backbone")(vclips[key], multi=self.multi, layer=self.layer, **kwargs)
+
+ if hasattr(self, key.split("_")[0]+"_head"):
+ if key == "semantic" or key == "image":
+ feat, _ = getattr(self, key.split("_")[0]+"_head")(feat)
+ else:
+ feat = getattr(self, key.split("_")[0]+"_head")(feat)
+ feat = feat.squeeze(2).squeeze(2).squeeze(2)
+ feats.append(feat)
+ if self.fusion_type == "cat":
+ fusion_feat = torch.cat(feats, dim=1)
+ elif self.fusion_type == "weight":
+ fusion_feat = self.weight_feature_fusion(feats[0], feats[1], feats[2])
+ elif self.fusion_type == "gate+weight":
+ feat_dynamic = feats[0]
+ feat_static = feats[1]
+ feat_feature = feats[2]
+ feat_dynamic = self.gate_feature_fusion_dynamic(feat_feature, feat_dynamic)
+ feat_static = self.gate_feature_fusion_static(feat_feature, feat_static)
+ fusion_feat = self.weight_feature_fusion(feat_dynamic, feat_static)
+ score = self.final_mlp(fusion_feat)
+ return score
+
+ else:
+ self.train()
+
+ feats = []
+ for key in vclips: # fragments、image、feature
+ if key == "feature":
+ feat, _ = getattr(self, key.split("_")[0]+"_backbone")(vclips[key])
+ elif key == "semantic":
+ feat,_ = getattr(self, key.split("_")[0]+"_backbone")(torch.squeeze(vclips[key]), multi=self.multi, layer=self.layer, **kwargs)
+ elif key == "image":
+ feat = getattr(self, key.split("_")[0]+"_backbone")(torch.squeeze(vclips[key]))
+ else:
+ feat= getattr(self, key.split("_")[0]+"_backbone")(vclips[key], multi=self.multi, layer=self.layer, **kwargs)
+ if hasattr(self, key.split("_")[0]+"_head"):
+ if key == "semantic" or key == "image":
+ feat, _ = getattr(self, key.split("_")[0]+"_head")(feat)
+ else:
+ feat = getattr(self, key.split("_")[0]+"_head")(feat)
+ feat = torch.squeeze(feat)
+ feats.append(feat)
+ if self.fusion_type == "cat":
+ fusion_feat = torch.cat(feats, dim=1)
+ elif self.fusion_type == "gate+weight":
+ feat_dynamic = feats[0]
+ feat_static = feats[1]
+ feat_feature = feats[2]
+ feat_dynamic = self.gate_feature_fusion_dynamic(feat_feature, feat_dynamic)
+ feat_static = self.gate_feature_fusion_static(feat_feature, feat_static)
+ fusion_feat = self.weight_feature_fusion(feat_dynamic, feat_static)
+ score = self.final_mlp(fusion_feat)
+ return score
+
+
+class DiViDeAddEvaluator(nn.Module):
+ def __init__(
+ self,
+ backbone_size="divided",
+ backbone_preserve_keys = 'fragments,resize',
+ multi=False,
+ layer=-1,
+ backbone=dict(resize={"window_size": (4,4,4)}, fragments={"window_size": (4,4,4)}),
+ divide_head=False,
+ vqa_head=dict(in_channels=768),
+ var=False,
+
+ ):
+ self.backbone_preserve_keys = backbone_preserve_keys.split(",")
+ self.multi = multi
+ self.layer = layer
+ super().__init__()
+ for key, hypers in backbone.items():
+ print(backbone_size)
+ if key not in self.backbone_preserve_keys:
+ continue
+ if backbone_size=="divided":
+ t_backbone_size = hypers["type"]
+ else:
+ t_backbone_size = backbone_size
+ if t_backbone_size == 'swin_tiny':
+ b = swin_3d_tiny(**backbone[key])
+ elif t_backbone_size == 'swin_tiny_grpb':
+ # to reproduce fast-vqa
+ b = VideoBackbone()
+ elif t_backbone_size == 'swin_tiny_grpb_m':
+ # to reproduce fast-vqa-m
+ b = VideoBackbone(window_size=(4,4,4), frag_biases=[0,0,0,0])
+ elif t_backbone_size == 'swin_small':
+ b = swin_3d_small(**backbone[key])
+ elif t_backbone_size == 'conv_tiny':
+ b = convnext_3d_tiny(pretrained=True)
+ elif t_backbone_size == 'conv_small':
+ b = convnext_3d_small(pretrained=True)
+ elif t_backbone_size == 'xclip':
+ b = build_x_clip_model(**backbone[key])
+ else:
+ raise NotImplementedError
+ print("Setting backbone:", key+"_backbone")
+ setattr(self, key+"_backbone", b)
+ if divide_head:
+ print(divide_head)
+ for key in backbone:
+ if key not in self.backbone_preserve_keys:
+ continue
+ if var:
+ b = VARHead(**vqa_head)
+ print(b)
+ else:
+ b = VQAHead(**vqa_head)
+ print("Setting head:", key+"_head")
+ setattr(self, key+"_head", b)
+ else:
+ if var:
+ self.vqa_head = VARHead(**vqa_head)
+ print(b)
+ else:
+ self.vqa_head = VQAHead(**vqa_head)
+
+ def forward(self, vclips, inference=True, return_pooled_feats=False, reduce_scores=True, pooled=False, **kwargs):
+ if inference:
+ self.eval()
+ with torch.no_grad():
+
+ scores = []
+ feats = {}
+ for key in vclips:
+ feat = getattr(self, key.split("_")[0]+"_backbone")(vclips[key], multi=self.multi, layer=self.layer, **kwargs)
+ if hasattr(self, key.split("_")[0]+"_head"):
+ scores += [getattr(self, key.split("_")[0]+"_head")(feat)]
+ else:
+ scores += [getattr(self, "vqa_head")(feat)]
+ if return_pooled_feats:
+ feats[key] = feat.mean((-3,-2,-1))
+ if reduce_scores:
+ if len(scores) > 1:
+ scores = reduce(lambda x,y:x+y, scores)
+ else:
+ scores = scores[0]
+ if pooled:
+ scores = torch.mean(scores, (1,2,3,4))
+ self.train()
+ if return_pooled_feats:
+ return scores, feats
+ return scores
+ else:
+ self.train()
+ scores = []
+ feats = {}
+ for key in vclips:
+ feat = getattr(self, key.split("_")[0]+"_backbone")(vclips[key], multi=self.multi, layer=self.layer, **kwargs)
+ if hasattr(self, key.split("_")[0]+"_head"):
+ scores += [getattr(self, key.split("_")[0]+"_head")(feat)]
+ else:
+ scores += [getattr(self, "vqa_head")(feat)]
+ if return_pooled_feats:
+ feats[key] = feat.mean((-3,-2,-1))
+ if reduce_scores:
+ if len(scores) > 1:
+ scores = reduce(lambda x,y:x+y, scores)
+ else:
+ scores = scores[0]
+ if pooled:
+ print(scores.shape)
+ scores = torch.mean(scores, (1,2,3,4))
+ print(scores.shape)
+
+ if return_pooled_feats:
+ return scores, feats
+ return scores
\ No newline at end of file
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/requirements.txt b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..120c5e1380beea0929bda23c232d897b6a8f51e3
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/requirements.txt
@@ -0,0 +1,12 @@
+torch
+torchvision
+opencv-python
+decord
+matplotlib
+scipy
+numpy
+tqdm
+timm
+einops
+clip
+sk-video
diff --git a/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/swin_backbone.py b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/swin_backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f4bb5683295c39dd448d02a68cdcb3d9c26ca8d
--- /dev/null
+++ b/benchmarks/edit/code/IVEBench/metrics/quality/training_suitability_assessment/swin_backbone.py
@@ -0,0 +1,1089 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as checkpoint
+import numpy as np
+from timm.models.layers import DropPath, trunc_normal_
+import math
+
+from functools import reduce, lru_cache
+from operator import mul
+from einops import rearrange
+
+
+def fragment_infos(D, H, W, fragments=7, device="cuda"):
+ m = torch.arange(fragments).unsqueeze(-1).float()
+ m = (m + m.t() * fragments).reshape(1, 1, 1, fragments, fragments)
+ m = F.interpolate(m.to(device), size=(D, H, W)).permute(0, 2, 3, 4, 1)
+ return m.long()
+
+
+@lru_cache
+def global_position_index(
+ D,
+ H,
+ W,
+ fragments=(1, 7, 7),
+ window_size=(8, 7, 7),
+ shift_size=(0, 0, 0),
+ device="cuda",
+):
+ frags_d = torch.arange(fragments[0])
+ frags_h = torch.arange(fragments[1])
+ frags_w = torch.arange(fragments[2])
+ frags = torch.stack(
+ torch.meshgrid(frags_d, frags_h, frags_w)
+ ).float() # 3, Fd, Fh, Fw
+ coords = (
+ torch.nn.functional.interpolate(frags[None].to(device), size=(D, H, W))
+ .long()
+ .permute(0, 2, 3, 4, 1)
+ )
+ coords = torch.roll(
+ coords, shifts=(-shift_size[0], -shift_size[1], -shift_size[2]), dims=(1, 2, 3)
+ )
+ window_coords = window_partition(coords, window_size)
+ relative_coords = (
+ window_coords[:, None, :] - window_coords[:, :, None]
+ ) # Wd*Wh*Ww, Wd*Wh*Ww, 3
+ return relative_coords # relative_coords
+
+@lru_cache
+def get_adaptive_window_size(
+ base_window_size,
+ input_x_size,
+ base_x_size,
+):
+ tw, hw, ww = base_window_size
+ tx_, hx_, wx_ = input_x_size
+ tx, hx, wx = base_x_size
+ print((tw * tx_) // tx, (hw * hx_) // hx, (ww * wx_) // wx)
+ return (tw * tx_) // tx, (hw * hx_) // hx, (ww * wx_) // wx
+
+
+
+class Mlp(nn.Module):
+ """Multilayer perceptron."""
+
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ drop=0.0,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, D, H, W, C)
+ window_size (tuple[int]): window size
+
+ Returns:
+ windows: (B*num_windows, window_size*window_size, C)
+ """
+ B, D, H, W, C = x.shape
+ x = x.view(
+ B,
+ D // window_size[0],
+ window_size[0],
+ H // window_size[1],
+ window_size[1],
+ W // window_size[2],
+ window_size[2],
+ C,
+ )
+ windows = (
+ x.permute(0, 1, 3, 5, 2, 4, 6, 7)
+ .contiguous()
+ .view(-1, reduce(mul, window_size), C)
+ )
+ return windows
+
+
+def window_reverse(windows, window_size, B, D, H, W):
+ """
+ Args:
+ windows: (B*num_windows, window_size, window_size, C)
+ window_size (tuple[int]): Window size
+ H (int): Height of image
+ W (int): Width of image
+
+ Returns:
+ x: (B, D, H, W, C)
+ """
+ x = windows.view(
+ B,
+ D // window_size[0],
+ H // window_size[1],
+ W // window_size[2],
+ window_size[0],
+ window_size[1],
+ window_size[2],
+ -1,
+ )
+ x = x.permute(0, 1, 4, 2, 5, 3, 6, 7).contiguous().view(B, D, H, W, -1)
+ return x
+
+
+def get_window_size(x_size, window_size, shift_size=None):
+ use_window_size = list(window_size)
+ if shift_size is not None:
+ use_shift_size = list(shift_size)
+ for i in range(len(x_size)):
+ if x_size[i] <= window_size[i]:
+ use_window_size[i] = x_size[i]
+ if shift_size is not None:
+ use_shift_size[i] = 0
+
+ if shift_size is None:
+ return tuple(use_window_size)
+ else:
+ return tuple(use_window_size), tuple(use_shift_size)
+
+
+class WindowAttention3D(nn.Module):
+ """Window based multi-head self attention (W-MSA) module with relative position bias.
+ It supports both of shifted and non-shifted window.
+ Args:
+ dim (int): Number of input channels.
+ window_size (tuple[int]): The temporal length, height and width of the window.
+ num_heads (int): Number of attention heads.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
+ """
+
+ def __init__(
+ self,
+ dim,
+ window_size,
+ num_heads,
+ qkv_bias=False,
+ qk_scale=None,
+ attn_drop=0.0,
+ proj_drop=0.0,
+ frag_bias=False,
+ ):
+
+ super().__init__()
+ self.dim = dim
+ self.window_size = window_size # Wd, Wh, Ww
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # define a parameter table of relative position bias
+ self.relative_position_bias_table = nn.Parameter(
+ torch.zeros(
+ (2 * window_size[0] - 1)
+ * (2 * window_size[1] - 1)
+ * (2 * window_size[2] - 1),
+ num_heads,
+ )
+ ) # 2*Wd-1 * 2*Wh-1 * 2*Ww-1, nH
+ if frag_bias:
+ self.fragment_position_bias_table = nn.Parameter(
+ torch.zeros(
+ (2 * window_size[0] - 1)
+ * (2 * window_size[1] - 1)
+ * (2 * window_size[2] - 1),
+ num_heads,
+ )
+ )
+
+ # get pair-wise relative position index for each token inside the window
+ coords_d = torch.arange(self.window_size[0])
+ coords_h = torch.arange(self.window_size[1])
+ coords_w = torch.arange(self.window_size[2])
+ coords = torch.stack(
+ torch.meshgrid(coords_d, coords_h, coords_w)
+ ) # 3, Wd, Wh, Ww
+ coords_flatten = torch.flatten(coords, 1) # 3, Wd*Wh*Ww
+ relative_coords = (
+ coords_flatten[:, :, None] - coords_flatten[:, None, :]
+ ) # 3, Wd*Wh*Ww, Wd*Wh*Ww
+ relative_coords = relative_coords.permute(
+ 1, 2, 0
+ ).contiguous() # Wd*Wh*Ww, Wd*Wh*Ww, 3
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
+ relative_coords[:, :, 1] += self.window_size[1] - 1
+ relative_coords[:, :, 2] += self.window_size[2] - 1
+
+ relative_coords[:, :, 0] *= (2 * self.window_size[1] - 1) * (
+ 2 * self.window_size[2] - 1
+ )
+ relative_coords[:, :, 1] *= 2 * self.window_size[2] - 1
+ relative_position_index = relative_coords.sum(-1) # Wd*Wh*Ww, Wd*Wh*Ww
+ self.register_buffer("relative_position_index", relative_position_index)
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ trunc_normal_(self.relative_position_bias_table, std=0.02)
+ self.softmax = nn.Softmax(dim=-1)
+
+ def forward(self, x, mask=None, fmask=None, resized_window_size=None):
+ """Forward function.
+ Args:
+ x: input features with shape of (num_windows*B, N, C)
+ mask: (0/-inf) mask with shape of (num_windows, N, N) or None
+ """
+ B_, N, C = x.shape
+ qkv = (
+ self.qkv(x)
+ .reshape(B_, N, 3, self.num_heads, C // self.num_heads)
+ .permute(2, 0, 3, 1, 4)
+ )
+ q, k, v = qkv[0], qkv[1], qkv[2] # B_, nH, N, C
+
+ q = q * self.scale
+ attn = q @ k.transpose(-2, -1)
+
+ if resized_window_size is None:
+ rpi = self.relative_position_index[:N, :N]
+ else:
+ relative_position_index = self.relative_position_index.reshape(*self.window_size, *self.window_size)
+ d, h, w = resized_window_size
+
+ rpi = relative_position_index[:d,:h,:w,:d,:h,:w]
+ relative_position_bias = self.relative_position_bias_table[
+ rpi.reshape(-1)
+ ].reshape(
+ N, N, -1
+ ) # Wd*Wh*Ww,Wd*Wh*Ww,nH
+ relative_position_bias = relative_position_bias.permute(
+ 2, 0, 1
+ ).contiguous() # nH, Wd*Wh*Ww, Wd*Wh*Ww
+ if hasattr(self, "fragment_position_bias_table"):
+ fragment_position_bias = self.fragment_position_bias_table[
+ rpi.reshape(-1)
+ ].reshape(
+ N, N, -1
+ ) # Wd*Wh*Ww,Wd*Wh*Ww,nH
+ fragment_position_bias = fragment_position_bias.permute(
+ 2, 0, 1
+ ).contiguous() # nH, Wd*Wh*Ww, Wd*Wh*Ww
+
+ ### Mask Position Bias
+ if fmask is not None:
+ # fgate = torch.where(fmask - fmask.transpose(-1, -2) == 0, 1, 0).float()
+ fgate = fmask.abs().sum(-1)
+ nW = fmask.shape[0]
+ relative_position_bias = relative_position_bias.unsqueeze(0)
+ fgate = fgate.unsqueeze(1)
+ if hasattr(self, "fragment_position_bias_table"):
+ relative_position_bias = (
+ relative_position_bias * fgate
+ + fragment_position_bias * (1 - fgate)
+ )
+
+ attn = attn.view(
+ B_ // nW, nW, self.num_heads, N, N
+ ) + relative_position_bias.unsqueeze(0)
+ attn = attn.view(-1, self.num_heads, N, N)
+ else:
+ attn = attn + relative_position_bias.unsqueeze(0) # B_, nH, N, N
+
+ if mask is not None:
+ nW = mask.shape[0]
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(
+ 1
+ ).unsqueeze(0)
+ attn = attn.view(-1, self.num_heads, N, N)
+ attn = self.softmax(attn)
+ else:
+ attn = self.softmax(attn)
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+
+ return x
+
+
+class SwinTransformerBlock3D(nn.Module):
+ """Swin Transformer Block.
+
+ Args:
+ dim (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ window_size (tuple[int]): Window size.
+ shift_size (tuple[int]): Shift size for SW-MSA.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(
+ self,
+ dim,
+ num_heads,
+ window_size=(2, 7, 7),
+ shift_size=(0, 0, 0),
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop=0.0,
+ attn_drop=0.0,
+ drop_path=0.0,
+ act_layer=nn.GELU,
+ norm_layer=nn.LayerNorm,
+ use_checkpoint=False,
+ jump_attention=False,
+ frag_bias=False,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.shift_size = shift_size
+ self.mlp_ratio = mlp_ratio
+ self.use_checkpoint = use_checkpoint
+ self.jump_attention = jump_attention
+ self.frag_bias = frag_bias
+
+ assert (
+ 0 <= self.shift_size[0] < self.window_size[0]
+ ), "shift_size must in 0-window_size"
+ assert (
+ 0 <= self.shift_size[1] < self.window_size[1]
+ ), "shift_size must in 0-window_size"
+ assert (
+ 0 <= self.shift_size[2] < self.window_size[2]
+ ), "shift_size must in 0-window_size"
+
+ self.norm1 = norm_layer(dim)
+ self.attn = WindowAttention3D(
+ dim,
+ window_size=self.window_size,
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop=attn_drop,
+ proj_drop=drop,
+ frag_bias=frag_bias,
+ )
+
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.norm2 = norm_layer(dim)
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = Mlp(
+ in_features=dim,
+ hidden_features=mlp_hidden_dim,
+ act_layer=act_layer,
+ drop=drop,
+ )
+
+ def forward_part1(self, x, mask_matrix, resized_window_size=None):
+ B, D, H, W, C = x.shape
+ window_size, shift_size = get_window_size(
+ (D, H, W),
+ self.window_size if resized_window_size is None else resized_window_size,
+ self.shift_size
+ )
+
+ x = self.norm1(x)
+ # pad feature maps to multiples of window size
+ pad_l = pad_t = pad_d0 = 0
+ pad_d1 = (window_size[0] - D % window_size[0]) % window_size[0]
+ pad_b = (window_size[1] - H % window_size[1]) % window_size[1]
+ pad_r = (window_size[2] - W % window_size[2]) % window_size[2]
+
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b, pad_d0, pad_d1))
+ _, Dp, Hp, Wp, _ = x.shape
+ if False: # not hasattr(self, 'finfo_windows'):
+ finfo = fragment_infos(Dp, Hp, Wp)
+
+ # cyclic shift
+ if any(i > 0 for i in shift_size):
+ shifted_x = torch.roll(
+ x,
+ shifts=(-shift_size[0], -shift_size[1], -shift_size[2]),
+ dims=(1, 2, 3),
+ )
+ if False: # not hasattr(self, 'finfo_windows'):
+ shifted_finfo = torch.roll(
+ finfo,
+ shifts=(-shift_size[0], -shift_size[1], -shift_size[2]),
+ dims=(1, 2, 3),
+ )
+ attn_mask = mask_matrix
+ else:
+ shifted_x = x
+ if False: # not hasattr(self, 'finfo_windows'):
+ shifted_finfo = finfo
+ attn_mask = None
+ # partition windows
+ x_windows = window_partition(shifted_x, window_size) # B*nW, Wd*Wh*Ww, C
+ if False: # not hasattr(self, 'finfo_windows'):
+ self.finfo_windows = window_partition(shifted_finfo, window_size)
+ # W-MSA/SW-MSA
+ # print(shift_size)
+ gpi = global_position_index(
+ Dp, Hp, Wp, fragments=(1,) + window_size[1:], window_size=window_size, shift_size=shift_size, device=x.device,
+ )
+ attn_windows = self.attn(
+ x_windows, mask=attn_mask, fmask=gpi, resized_window_size=window_size if resized_window_size is not None else None,
+ ) # self.finfo_windows) # B*nW, Wd*Wh*Ww, C
+ # merge windows
+ attn_windows = attn_windows.view(-1, *(window_size + (C,)))
+ shifted_x = window_reverse(
+ attn_windows, window_size, B, Dp, Hp, Wp
+ ) # B D' H' W' C
+ # reverse cyclic shift
+ if any(i > 0 for i in shift_size):
+ x = torch.roll(
+ shifted_x,
+ shifts=(shift_size[0], shift_size[1], shift_size[2]),
+ dims=(1, 2, 3),
+ )
+ else:
+ x = shifted_x
+
+ if pad_d1 > 0 or pad_r > 0 or pad_b > 0:
+ x = x[:, :D, :H, :W, :].contiguous()
+ return x
+
+ def forward_part2(self, x):
+ return self.drop_path(self.mlp(self.norm2(x)))
+
+ def forward(self, x, mask_matrix, resized_window_size=None):
+ """Forward function.
+
+ Args:
+ x: Input feature, tensor size (B, D, H, W, C).
+ mask_matrix: Attention mask for cyclic shift.
+ """
+
+ shortcut = x
+ if not self.jump_attention:
+ if self.use_checkpoint:
+ x = checkpoint.checkpoint(self.forward_part1, x, mask_matrix, resized_window_size)
+ else:
+ x = self.forward_part1(x, mask_matrix, resized_window_size)
+ x = shortcut + self.drop_path(x)
+
+ if self.use_checkpoint:
+ x = x + checkpoint.checkpoint(self.forward_part2, x)
+ else:
+ x = x + self.forward_part2(x)
+
+ return x
+
+
+class PatchMerging(nn.Module):
+ """Patch Merging Layer
+
+ Args:
+ dim (int): Number of input channels.
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
+ super().__init__()
+ self.dim = dim
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
+ self.norm = norm_layer(4 * dim)
+
+ def forward(self, x):
+ """Forward function.
+
+ Args:
+ x: Input feature, tensor size (B, D, H, W, C).
+ """
+ B, D, H, W, C = x.shape
+
+ # padding
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
+ if pad_input:
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
+
+ x0 = x[:, :, 0::2, 0::2, :] # B D H/2 W/2 C
+ x1 = x[:, :, 1::2, 0::2, :] # B D H/2 W/2 C
+ x2 = x[:, :, 0::2, 1::2, :] # B D H/2 W/2 C
+ x3 = x[:, :, 1::2, 1::2, :] # B D H/2 W/2 C
+ x = torch.cat([x0, x1, x2, x3], -1) # B D H/2 W/2 4*C
+
+ x = self.norm(x)
+ x = self.reduction(x)
+
+ return x
+
+
+# cache each stage results
+@lru_cache()
+def compute_mask(D, H, W, window_size, shift_size, device):
+ img_mask = torch.zeros((1, D, H, W, 1), device=device) # 1 Dp Hp Wp 1
+ cnt = 0
+ for d in (
+ slice(-window_size[0]),
+ slice(-window_size[0], -shift_size[0]),
+ slice(-shift_size[0], None),
+ ):
+ for h in (
+ slice(-window_size[1]),
+ slice(-window_size[1], -shift_size[1]),
+ slice(-shift_size[1], None),
+ ):
+ for w in (
+ slice(-window_size[2]),
+ slice(-window_size[2], -shift_size[2]),
+ slice(-shift_size[2], None),
+ ):
+ img_mask[:, d, h, w, :] = cnt
+ cnt += 1
+ mask_windows = window_partition(img_mask, window_size) # nW, ws[0]*ws[1]*ws[2], 1
+ mask_windows = mask_windows.squeeze(-1) # nW, ws[0]*ws[1]*ws[2]
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
+ attn_mask == 0, float(0.0)
+ )
+ return attn_mask
+
+
+class BasicLayer(nn.Module):
+ """A basic Swin Transformer layer for one stage.
+
+ Args:
+ dim (int): Number of feature channels
+ depth (int): Depths of this stage.
+ num_heads (int): Number of attention head.
+ window_size (tuple[int]): Local window size. Default: (1,7,7).
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
+ """
+
+ def __init__(
+ self,
+ dim,
+ depth,
+ num_heads,
+ window_size=(1, 7, 7),
+ mlp_ratio=4.0,
+ qkv_bias=False,
+ qk_scale=None,
+ drop=0.0,
+ attn_drop=0.0,
+ drop_path=0.0,
+ norm_layer=nn.LayerNorm,
+ downsample=None,
+ use_checkpoint=False,
+ jump_attention=False,
+ frag_bias=False,
+ ):
+ super().__init__()
+ self.window_size = window_size
+ self.shift_size = tuple(i // 2 for i in window_size)
+ self.depth = depth
+ self.use_checkpoint = use_checkpoint
+ # build blocks
+ self.blocks = nn.ModuleList(
+ [
+ SwinTransformerBlock3D(
+ dim=dim,
+ num_heads=num_heads,
+ window_size=window_size,
+ shift_size=(0, 0, 0) if (i % 2 == 0) else self.shift_size,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop,
+ attn_drop=attn_drop,
+ drop_path=drop_path[i]
+ if isinstance(drop_path, list)
+ else drop_path,
+ norm_layer=norm_layer,
+ use_checkpoint=use_checkpoint,
+ jump_attention=jump_attention,
+ frag_bias=frag_bias,
+ )
+ for i in range(depth)
+ ]
+ )
+
+ self.downsample = downsample
+ if self.downsample is not None:
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
+
+ def forward(self, x, resized_window_size=None):
+ """Forward function.
+
+ Args:
+ x: Input feature, tensor size (B, C, D, H, W).
+ """
+ # calculate attention mask for SW-MSA
+ B, C, D, H, W = x.shape
+
+ window_size, shift_size = get_window_size(
+ (D, H, W),
+ self.window_size if resized_window_size is None else resized_window_size,
+ self.shift_size,
+ )
+
+ x = rearrange(x, "b c d h w -> b d h w c")
+ Dp = int(np.ceil(D / window_size[0])) * window_size[0]
+ Hp = int(np.ceil(H / window_size[1])) * window_size[1]
+ Wp = int(np.ceil(W / window_size[2])) * window_size[2]
+ attn_mask = compute_mask(Dp, Hp, Wp, window_size, shift_size, x.device)
+ for blk in self.blocks:
+ x = blk(x, attn_mask, resized_window_size=resized_window_size)
+ x = x.view(B, D, H, W, -1)
+
+ if self.downsample is not None:
+ x = self.downsample(x)
+ x = rearrange(x, "b d h w c -> b c d h w")
+ return x
+
+
+class PatchEmbed3D(nn.Module):
+ """Video to Patch Embedding.
+
+ Args:
+ patch_size (int): Patch token size. Default: (2,4,4).
+ in_chans (int): Number of input video channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
+ """
+
+ def __init__(self, patch_size=(2, 4, 4), in_chans=3, embed_dim=96, norm_layer=None):
+ super().__init__()
+ self.patch_size = patch_size
+
+ self.in_chans = in_chans
+ self.embed_dim = embed_dim
+
+ self.proj = nn.Conv3d(
+ in_chans, embed_dim, kernel_size=patch_size, stride=patch_size
+ )
+ if norm_layer is not None:
+ self.norm = norm_layer(embed_dim)
+ else:
+ self.norm = None
+
+ def forward(self, x):
+ """Forward function."""
+ # padding
+ # x.shape:torch.Size([1, 3, 32, 224, 224])
+ _, _, D, H, W = x.size() # (2, 4, 4)
+ if W % self.patch_size[2] != 0:
+ x = F.pad(x, (0, self.patch_size[2] - W % self.patch_size[2]))
+ if H % self.patch_size[1] != 0:
+ x = F.pad(x, (0, 0, 0, self.patch_size[1] - H % self.patch_size[1]))
+ if D % self.patch_size[0] != 0:
+ x = F.pad(x, (0, 0, 0, 0, 0, self.patch_size[0] - D % self.patch_size[0]))
+
+ x = self.proj(x) # B C D Wh Ww # x.shape : torch.Size([1, 96, 16, 56, 56]
+ if self.norm is not None:
+ D, Wh, Ww = x.size(2), x.size(3), x.size(4)
+ x = x.flatten(2).transpose(1, 2)
+ x = self.norm(x)
+ x = x.transpose(1, 2).view(-1, self.embed_dim, D, Wh, Ww)
+
+ return x
+
+
+class SwinTransformer3D(nn.Module):
+ """Swin Transformer backbone.
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
+ https://arxiv.org/pdf/2103.14030
+
+ Args:
+ patch_size (int | tuple(int)): Patch size. Default: (4,4,4).
+ in_chans (int): Number of input image channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ depths (tuple[int]): Depths of each Swin Transformer stage.
+ num_heads (tuple[int]): Number of attention head of each stage.
+ window_size (int): Window size. Default: 7.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: Truee
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
+ drop_rate (float): Dropout rate.
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
+ norm_layer: Normalization layer. Default: nn.LayerNorm.
+ patch_norm (bool): If True, add normalization after patch embedding. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters.
+ """
+
+ def __init__(
+ self,
+ pretrained=None,
+ pretrained2d=False,
+ patch_size=(2, 4, 4),
+ in_chans=3,
+ embed_dim=96,
+ depths=[2, 2, 6, 2],
+ num_heads=[3, 6, 12, 24],
+ window_size=(8, 7, 7),
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop_rate=0.0,
+ attn_drop_rate=0.0,
+ drop_path_rate=0.1,
+ norm_layer=nn.LayerNorm,
+ patch_norm=True,
+ frozen_stages=-1,
+ use_checkpoint=True,
+ jump_attention=[False, False, False, False],
+ frag_biases=[True, True, True, False],
+ base_x_size=(32, 224, 224),
+ ):
+ super().__init__()
+
+ self.pretrained = pretrained
+ self.pretrained2d = pretrained2d
+ self.num_layers = len(depths)
+ self.embed_dim = embed_dim
+ self.patch_norm = patch_norm
+ self.frozen_stages = frozen_stages
+ self.window_size = window_size
+ self.patch_size = patch_size
+ self.base_x_size = base_x_size
+
+ # split image into non-overlapping patches
+ self.patch_embed = PatchEmbed3D(
+ patch_size=patch_size,
+ in_chans=in_chans,
+ embed_dim=embed_dim,
+ norm_layer=norm_layer if self.patch_norm else None,
+ )
+
+ self.pos_drop = nn.Dropout(p=drop_rate)
+
+ # stochastic depth
+ dpr = [
+ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
+ ] # stochastic depth decay rule
+
+ # build layers
+ self.layers = nn.ModuleList()
+ for i_layer in range(self.num_layers):
+ layer = BasicLayer(
+ dim=int(embed_dim * 2 ** i_layer),
+ depth=depths[i_layer], # [2, 2, 6, 2]
+ num_heads=num_heads[i_layer], # [3, 6, 12, 24]
+ window_size=window_size[i_layer] # (8, 7, 7)
+ if isinstance(window_size, list)
+ else window_size,
+ mlp_ratio=mlp_ratio, # 4.0
+ qkv_bias=qkv_bias, # True
+ qk_scale=qk_scale, # False
+ drop=drop_rate, # 0.0
+ attn_drop=attn_drop_rate, # 0.0
+ drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], # [0, ......, 0.1]
+ norm_layer=norm_layer,
+ downsample=PatchMerging if i_layer < self.num_layers - 1 else None,
+ use_checkpoint=use_checkpoint,
+ jump_attention=jump_attention[i_layer], # [False, False, False, False]
+ frag_bias=frag_biases[i_layer], # [True, True, True, False]
+ )
+ self.layers.append(layer)
+
+ self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
+
+ # add a norm layer for each output
+ self.norm = norm_layer(self.num_features)
+
+ self._freeze_stages()
+
+ self.init_weights()
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+
+ if self.frozen_stages >= 1:
+ self.pos_drop.eval()
+ for i in range(0, self.frozen_stages):
+ m = self.layers[i]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ def inflate_weights(self):
+ """Inflate the swin2d parameters to swin3d.
+
+ The differences between swin3d and swin2d mainly lie in an extra
+ axis. To utilize the pretrained parameters in 2d model,
+ the weight of swin2d models should be inflated to fit in the shapes of
+ the 3d counterpart.
+
+ Args:
+ logger (logging.Logger): The logger used to print
+ debugging infomation.
+ """
+ checkpoint = torch.load(self.pretrained, map_location="cpu")
+ state_dict = checkpoint["model"]
+
+
+ # delete relative_position_index since we always re-init it
+ relative_position_index_keys = [
+ k for k in state_dict.keys() if "relative_position_index" in k
+ ]
+ for k in relative_position_index_keys:
+ del state_dict[k]
+
+ # delete attn_mask since we always re-init it
+ attn_mask_keys = [k for k in state_dict.keys() if "attn_mask" in k]
+ for k in attn_mask_keys:
+ del state_dict[k]
+
+
+ state_dict["patch_embed.proj.weight"] = (
+ state_dict["patch_embed.proj.weight"]
+ .unsqueeze(2)
+ .repeat(1, 1, self.patch_size[0], 1, 1)
+ / self.patch_size[0]
+ )
+
+ # bicubic interpolate relative_position_bias_table if not match
+ relative_position_bias_table_keys = [
+ k for k in state_dict.keys() if "relative_position_bias_table" in k
+ ]
+ for k in relative_position_bias_table_keys:
+ relative_position_bias_table_pretrained = state_dict[k]
+ relative_position_bias_table_current = self.state_dict()[k]
+ L1, nH1 = relative_position_bias_table_pretrained.size()
+ L2, nH2 = relative_position_bias_table_current.size()
+ L2 = (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1)
+ wd = self.window_size[0]
+ if nH1 != nH2:
+ print(f"Error in loading {k}, passing")
+ else:
+ if L1 != L2:
+ S1 = int(L1 ** 0.5)
+ relative_position_bias_table_pretrained_resized = (
+ torch.nn.functional.interpolate(
+ relative_position_bias_table_pretrained.permute(1, 0).view(
+ 1, nH1, S1, S1
+ ),
+ size=(
+ 2 * self.window_size[1] - 1,
+ 2 * self.window_size[2] - 1,
+ ),
+ mode="bicubic",
+ )
+ )
+ relative_position_bias_table_pretrained = (
+ relative_position_bias_table_pretrained_resized.view(
+ nH2, L2
+ ).permute(1, 0)
+ )
+ state_dict[k] = relative_position_bias_table_pretrained.repeat(
+ 2 * wd - 1, 1
+ )
+
+ msg = self.load_state_dict(state_dict, strict=False)
+ print(msg)
+ print(f"=> loaded successfully '{self.pretrained}'")
+ del checkpoint
+ torch.cuda.empty_cache()
+
+ def load_swin(self, load_path, strict=False):
+ print("loading swin lah")
+ from collections import OrderedDict
+
+ model_state_dict = self.state_dict()
+ state_dict = torch.load(load_path)["state_dict"]
+
+ clean_dict = OrderedDict()
+ for key, value in state_dict.items():
+ if "backbone" in key:
+ clean_key = key[9:]
+ clean_dict[clean_key] = value
+ if "relative_position_bias_table" in clean_key:
+ forked_key = clean_key.replace(
+ "relative_position_bias_table", "fragment_position_bias_table"
+ )
+ if forked_key in clean_dict:
+ print("load_swin_error?")
+ else:
+ clean_dict[forked_key] = value
+
+ # bicubic interpolate relative_position_bias_table if not match
+ relative_position_bias_table_keys = [
+ k for k in clean_dict.keys() if "relative_position_bias_table" in k
+ ]
+ for k in relative_position_bias_table_keys:
+ print(k)
+ relative_position_bias_table_pretrained = clean_dict[k]
+ relative_position_bias_table_current = model_state_dict[k]
+ L1, nH1 = relative_position_bias_table_pretrained.size()
+ L2, nH2 = relative_position_bias_table_current.size()
+ if isinstance(self.window_size, list):
+ i_layer = int(k.split(".")[1])
+ L2 = (2 * self.window_size[i_layer][1] - 1) * (
+ 2 * self.window_size[i_layer][2] - 1
+ )
+ wd = self.window_size[i_layer][0]
+ else:
+ L2 = (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1)
+ wd = self.window_size[0]
+ if nH1 != nH2:
+ print(f"Error in loading {k}, passing")
+ else:
+ if L1 != L2:
+ S1 = int((L1 / 15) ** 0.5)
+ print(
+ relative_position_bias_table_pretrained.shape, 15, nH1, S1, S1
+ )
+ relative_position_bias_table_pretrained_resized = (
+ torch.nn.functional.interpolate(
+ relative_position_bias_table_pretrained.permute(1, 0)
+ .view(nH1, 15, S1, S1)
+ .transpose(0, 1),
+ size=(
+ 2 * self.window_size[i_layer][1] - 1,
+ 2 * self.window_size[i_layer][2] - 1,
+ ),
+ mode="bicubic",
+ )
+ )
+ relative_position_bias_table_pretrained = (
+ relative_position_bias_table_pretrained_resized.transpose(
+ 0, 1
+ ).view(nH2, 15, L2)
+ )
+ clean_dict[k] = relative_position_bias_table_pretrained # .repeat(2*wd-1,1)
+
+ ## Clean Mismatched Keys
+ for key, value in model_state_dict.items():
+ if key in clean_dict:
+ if value.shape != clean_dict[key].shape:
+ print(key)
+ clean_dict.pop(key)
+
+ self.load_state_dict(clean_dict, strict=strict)
+
+ def init_weights(self, pretrained=None):
+ print(self.pretrained, self.pretrained2d)
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+
+ def _init_weights(m):
+ if isinstance(m, nn.Linear):
+ trunc_normal_(m.weight, std=0.02)
+ if isinstance(m, nn.Linear) and m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+
+ if pretrained:
+ self.pretrained = pretrained
+ if isinstance(self.pretrained, str):
+ self.apply(_init_weights)
+ #logger = get_root_logger()
+ #logger.info(f"load model from: {self.pretrained}")
+
+ if self.pretrained2d:
+ # Inflate 2D model into 3D model.
+ self.inflate_weights()
+ else:
+ # Directly load 3D model.
+ self.load_swin(self.pretrained, strict=False) # , logger=logger)
+ elif self.pretrained is None:
+ self.apply(_init_weights)
+ else:
+ raise TypeError("pretrained must be a str or None")
+
+
+
+ def forward(self, x, multi=False, layer=-1, adaptive_window_size=True):
+ # x.shape : torch.Size([1, 3, 32, 224, 224])
+ """Forward function."""
+ if adaptive_window_size:
+ resized_window_size = get_adaptive_window_size(self.window_size, x.shape[2:], self.base_x_size)
+ else:
+ resized_window_size = None
+ # resized_window_size : (8, 7, 7)
+ x = self.patch_embed(x) # x.shape : torch.Size([1, 96, 16, 56, 56])
+
+ x = self.pos_drop(x)
+ feats = [x]
+
+
+ for l, mlayer in enumerate(self.layers):
+ x = mlayer(x.contiguous(), resized_window_size)
+ feats += [x]
+
+ x = rearrange(x, "n c d h w -> n d h w c")
+ x = self.norm(x)
+ x = rearrange(x, "n d h w c -> n c d h w")
+
+ if multi:
+ shape = x.shape[2:]
+ return torch.cat([F.interpolate(xi,size=shape, mode="trilinear") for xi in feats[:-1]], 1)
+ elif layer > -1:
+ print("something", len(feats))
+ return feats[layer]
+ else:
+ return x
+
+ def train(self, mode=True):
+ """Convert the model into training mode while keep layers freezed."""
+ super(SwinTransformer3D, self).train(mode)
+ self._freeze_stages()
+
+
+def swin_3d_tiny(**kwargs):
+ ## Original Swin-3D Tiny with reduced windows
+ return SwinTransformer3D(depths=[2, 2, 6, 2],
+ frag_biases=[0,0,0,0],
+ **kwargs)
+
+def swin_3d_small(**kwargs):
+ # Original Swin-3D Small with reduced windows
+ return SwinTransformer3D(depths=[2, 2, 18, 2],
+ frag_biases=[0,0,0,0],
+ **kwargs)
+
+
+
+class SwinTransformer2D(nn.Sequential):
+ def __init__(self):
+ ## Only backbone for Swin Transformer 2D
+ from timm.models import swin_tiny_patch4_window7_224
+
+ super().__init__(*list(swin_tiny_patch4_window7_224().children())[:-2])
diff --git a/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/README.md b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..77e2c592d871dfef0845696885a7659a97b0282b
--- /dev/null
+++ b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/README.md
@@ -0,0 +1,55 @@
+## OpenVE-Bench
+
+[OpenVE-Bench](https://huggingface.co/datasets/Lewandofski/OpenVE-Bench) is a new Instruction-Guided Video Editing benchmark contained 431 video-edit pairs that cover a diverse range of editing tasks with three key metrics highly aligned with human judgment.
+
+A folder containing original videos:
+
+```folder
+├── OpenVE-Bench
+│ ├── videos
+| |── 0000_global_style_Apply_the_Impression.mp4
+| |── 0001_global_style_Apply_the_Ukiyoe_ani.mp4
+| |── ...
+│ ├── benchmark_videos.csv
+```
+
+`benchmark_videos.csv` contains following fields:
+
+```
+edited_type,prompt,original_video
+```
+
+## Generate and Organize Your Videos
+
+Following the editing `prompt` in the `benchmark_videos.csv` file and the `original_video`, generate the video results for your model, and record the video paths in a new CSV `new_result.csv` file, adding a `edited_result_path` column at the end.
+
+`new_result.csv` should contains following fields:
+
+```
+edited_type,prompt,original_video,edited_result_path
+```
+
+## Evaluate using Seed1.6VL/Gemini 2.5 Pro/InternVL3.5-38B/Qwen3VL-32B
+For Seed1.6VL and Gemini 2.5 Pro, you should set your correct API key.
+
+Seed 1.6 VL
+```python
+python seed_benchmark.py --input_csv new_result.csv --root_path yours_OpenVE-Bench_path --output_csv new_result_gemini_score.csv
+```
+
+Gemini 2.5 Pro
+```python
+python gemini_benchmark.py --input_csv new_result.csv --root_path yours_OpenVE-Bench_path --output_csv new_result_gemini_score.csv
+```
+
+[InternVL3.5-38B](https://huggingface.co/OpenGVLab/InternVL3_5-38B)
+```python
+python internvl_benchmark.py --input_csv new_result.csv --root_path yours_OpenVE-Bench_path --output_csv new_result_gemini_score.csv --model_path /yours_model_path/InternVL3.5-38B
+```
+
+[Qwen3VL-32B](https://huggingface.co/Qwen/Qwen3-VL-32B-Instruct)
+```python
+python qwen3vl_benchmark.py --input_csv new_result.csv --root_path yours_OpenVE-Bench_path --output_csv new_result_gemini_score.csv --model_path /yours_model_path/Qwen3VL-32B
+```
+
+*The final average metric results are in a JSON file.*
\ No newline at end of file
diff --git a/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/gemini_benchmark.py b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/gemini_benchmark.py
new file mode 100644
index 0000000000000000000000000000000000000000..862dbae0e01d8f49f91c34acd3d6474497c25a91
--- /dev/null
+++ b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/gemini_benchmark.py
@@ -0,0 +1,278 @@
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
+ # SPDX-License-Identifier: Apache-2.0
+import argparse
+import csv
+import os
+import torch
+import torchvision.transforms as T
+from PIL import Image
+from tqdm import tqdm
+import math
+import numpy as np
+import time
+import argparse
+import re
+import json
+import base64
+import requests
+import time
+
+ak = ""
+gemini_url = "" + ak
+gemini_headers = {
+ "Content-Type": "application/json",
+ "X-TT-LOGID": ""
+}
+
+Global_Style = """\nYou are a data rater specializing in grading video style transfer edits. You will be given an input video, a reference style (image or video), and the styled result video. Your task is to evaluate the style transfer on a 5-point scale from three perspectives:\n\nStyle Fidelity\n1. Target style absent or clearly wrong.\n2. Style shows in a few areas/frames only, or mixed with unrelated styles.\n3. Key traits (palette, brushwork, texture) present but patchy or inconsistent across frames.\n4. Style reproduced well across almost the whole video; only small local or brief temporal mismatches.\n5. Full, faithful transfer: colour, texture, brushwork, and lighting all match the exemplar consistently over the entire duration and space of the video.\n\nContent Preservation\n1. Major objects, layout, or overall motion lost/distorted; original scene barely recognisable.\n2. Main subject recognisable, but its size, perspective, motion, or key parts are clearly wrong/missing.\n3. Overall structure and motion correct; some local warping, minor omissions, or slight motion jerkiness.\n4. Nearly all geometry and motion intact; only slight, non-distracting deformation.\n5. All objects, spatial relations, and motion are perfectly kept; only stylistic, harmless distortion.\n\nTemporal Stability\n1. Extreme flickering or "boiling" effects; the style is completely unstable frame-to-frame, making the video unwatchable.\n2. Significant and distracting flickering or temporal inconsistency in style application.\n3. Noticeable but tolerable flicker or texture "boiling", especially during motion.\n4. Largely stable with only minor, subtle flickering visible in areas of complex motion or fine texture.\n5. Perfectly stable and temporally coherent; the style appears "stuck" to the scene with no flickering.\n\nThe scores for Content Preservation and Temporal Stability should not be higher than the Style Fidelity score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the scores based on the criteria above, no more than 30 words.\nStyle Fidelity: A number from 1 to 5.\nContent Preservation: A number from 1 to 5.\nTemporal Stability: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Creative_Edit = """\nYou are a data rater specializing in grading instruction-following creative video edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the creative edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The instruction is completely ignored or the edit is irrelevant to the prompt.\n2 The edit attempts the instruction but fundamentally fails; the core subject, style, or action is wrong or only applied for a brief moment.\n3 The edit generally follows the instruction, but with major deviations in style, motion, or concept; the effect is highly inconsistent over time.\n4 The edit successfully executes the instruction with only minor inaccuracies in style, motion, or detail; the result is temporally consistent.\n5 The edit perfectly and creatively interprets and executes the instruction throughout the video's duration, fully achieving the intended creative goal.\n\nTemporal & Visual Coherence\n1 Massive flickering, strobing, or artifacts that make the video unwatchable; edited elements are completely disjointed from the scene.\n2 Obvious temporal inconsistency (e.g., style flickers on/off), clear visual boundaries or seams; mismatched color/lighting between frames.\n3 The edit is mostly stable, but with noticeable "boiling" or "shimmering" in textures/styles; minor jitter or softness on edges.\n4 The edit is very stable and well-integrated; only slight, hard-to-spot artifacts or flickering are present, motion is smooth.\n5 Perfectly stable and seamless integration; the edit feels like part of the original footage with no detectable flickering, jitter, or discontinuities.\n\nPhysical Plausibility & Detail Preservation\n1 Complete break from physical laws; added objects have no correct lighting/shadows, move unnaturally; original video details are heavily degraded.\n2 Major physical inconsistencies; shadows/reflections are static or move incorrectly; motion of edits doesn't match camera movement; original background is warped.\n3 Physics and lighting are generally believable but with minor flaws (e.g., a shadow is slightly off); unedited parts of the video are mostly preserved.\n4 Edited elements interact realistically with the scene's lighting, motion, and perspective; original video details are well-preserved.\n5 High degree of physical realism and integration; motion, lighting, and physics of the edits are indistinguishable from a real recording; original details are perfectly maintained.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nTemporal & Visual Coherence: A number from 1 to 5.\nPhysical Plausibility & Detail Preservation: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Camera_Edit = """\nYou are a data rater specializing in grading camera shot type alteration edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the camera shot change on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The shot type is not changed, or changed to a completely wrong type (e.g., requested close-up, but got a long shot).\n2 The direction of the shot change is correct (e.g., zoomed in for a close-up), but the degree is wrong (e.g., a medium shot instead of a close-up).\n3 The shot type is generally correct, but the framing is poor, cutting off important parts of the subject or being poorly centered.\n4 The shot type and framing are correct, with only minor inaccuracies in composition.\n5 The video is perfectly transformed into the requested shot type (long, medium, or close-up) with ideal framing of the subject.\n\nVisual Quality & Stability\n1 Massive distortion, glitches, warping, or heavy noise; the edited video is unusable.\n2 Significant and distracting jitter, shimmering, or warping is visible throughout the video, making the shot feel unstable.\n3 Minor but noticeable visual flaws, such as slight edge distortion or a subtle "breathing" effect in the frame.\n4 The video is stable and clear, with only very slight, almost unnoticeable artifacts upon close inspection.\n5 The resulting shot is perfectly stable and clear, with no digital artifacts, distortion, or jitter. It looks as if it were originally filmed with that shot type.\n\nConsistency & Detail Fidelity\n1 The subject, background, or action in the edited video is completely different from the original video; a total failure of consistency.\n2 The main subject is the same, but their action, the background, or the lighting is drastically and illogically changed compared to the original video.\n3 The scene is generally consistent, but there are noticeable continuity errors (e.g., an object disappears, the subject's pose changes unnaturally).\n4 The subject, action, and environment are highly consistent with the original video. Original details are well-preserved with only minor, hard-to-spot discrepancies.\n5 Perfect consistency; the edited video perfectly preserves the subject, lighting, background, and continuity of action from the original video, creating the illusion of the same scene captured from a different camera position.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Quality & Stability: A number from 1 to 5.\nConsistency & Detail Fidelity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Change = """\nYou are a data rater specializing in grading video replacement edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the replacement editing effect on a 5-point scale from three perspectives, paying close attention to temporal consistency (how the edit holds up over time and with motion).\n\nPrompt Compliance\n1 Target not replaced, or an unrelated object/part of the video edited.\n2 Only part of the target replaced (e.g., in only a few frames), or wrong class/description used.\n3 Target largely replaced but other objects altered, remnants visible across frames, or count/position clearly wrong.\n4 Correct object fully replaced for the entire duration; only minor attribute errors (colour, size, etc.).\n5 Perfect replacement: all and only the specified objects replaced for the entire duration; new objects’ class, number, position, scale, pose, motion and detail exactly match the prompt.\n\nVisual Naturalness & Temporal Stability\n1 Video heavily broken or new object deformed / flickers uncontrollably / jitters erratically.\n2 Obvious seams/edges that flicker or move unnaturally; strong mismatch in resolution or colour that is inconsistent across frames; background not restored or is unstable.\n3 Basic style similar, but lighting or palette clashes are inconsistent as the video plays; fuzzy edges, noise or minor flickering/jittering are noticeable.\n4 Style almost uniform and stable; tiny temporal artefacts (e.g., edge shimmer) visible only on close, frame-by-frame inspection; casual viewers see no edit.\n5 Completely seamless and temporally stable; new objects blend fully with the scene in every frame, edit area undetectable.\n\nPhysical & Motion Integrity\n1 Floating or sliding unnaturally (poor motion tracking), severe perspective/light errors inconsistent with camera/object movement; background heavily warped or unstable.\n2 Missing or static shadows/reflections that do not move with the object/light; poor occlusion; new object’s motion clearly mismatches scene motion.\n3 Lighting, perspective and interactions mostly correct but with minor inconsistencies over time; motion tracking has small, tolerable drifts.\n4 New object's motion is well-tracked and it interacts realistically with the scene (shadows, reflections) and preserves existing details throughout the video.\n5 Physically and dynamically flawless: motion, perspective, shadows, and reflections are perfectly integrated and move correctly with the scene and camera in every frame; background untouched and stable.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Naturalness & Temporal Stability: A number from 1 to 5.\nPhysical & Motion Integrity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Background_Change = """\nYou are a data rater specializing in grading video background editing. You will be given two videos (before and after editing) and the editing instruction. Your task is to evaluate the background change on a 5-point scale from three perspectives:\n\nInstruction Compliance\n1 No change, or background unrelated to prompt, or foreground also replaced/distorted.\n2 Background partly replaced or wrong style/content; foreground noticeably altered.\n3 Main background replaced but elements missing/extra, or faint spill onto subject edges.\n4 Requested background fully present; foreground intact except minute artefacts or small prompt mismatch (e.g. colour tone).\n5 Background exactly matches prompt (content, style, placement); all foreground pixels untouched.\n\nVisual & Temporal Seamlessness (Edge, Blend & Stability)\n1 Large tearing, posterisation, or significant temporal artifacts like flickering, jittering edges; edit area obvious at a glance.\n2 Clear cut-out halos, colour-resolution gap, or obvious edge 'boiling' (instability) over time.\n3 Blend acceptable but visible on closer look: slight edge blur, or minor temporal instability (e.g., shimmer).\n4 Nearly invisible seams; edges are stable across motion, textures aligned, only minor issues when zoomed in.\n5 Indistinguishable composite: edges, textures, resolution and colour grading are perfectly continuous and stable throughout the video's duration.\n\nPhysical Consistency (Lighting, Perspective, Motion & Depth)\n1 Severe mismatch: wrong horizon, conflicting light, floating subject, or background remains static during camera movement (no parallax).\n2 Noticeable inconsistencies in light or scale; incorrect perspective shifts during motion.\n3 Overall believable; small errors in shadow, perspective, or minor motion tracking flaws.\n4 Lighting, scale, and depth well matched; background perspective and scale track convincingly with camera motion.\n5 Physically flawless: foreground and new background share coherent light, shadows, perspective, and atmospheric depth throughout all subject and camera motion, enhancing overall realism.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nInstruction Compliance: A number from 1 to 5.\nVisual & Temporal Seamlessness: A number from 1 to 5.\nPhysical Consistency: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Remove = """\nYou are a data rater specializing in grading video object removal editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class removed, or target only partially removed, or an unrelated object is also removed.\n3 Correct object removed, but with significant errors: unintended objects are also removed, OR significant fragments/ghosting of the target remain.\n4 The correct object is removed; only minor issues like a few tiny fragments remaining or tiny, unintended background items being affected.\n5 Perfect: All and only the requested objects are removed as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious erase marks or "smudges"; the inpainted background's style, resolution, or palette strongly mismatches; the edited region jitters or appears static against a moving background.\n3 General style is similar, but the inpainted background's lighting/colours clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the removed area or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the removal is temporally stable and visually indistinguishable from a clean background.\n\nPhysical & Detail Coherence\n1 Key original elements are blocked by poor inpainting; the background is heavily distorted or hallucinates incorrect structures; motion is completely wrong (e.g., a static patch in a moving scene).\n2 The inpainted background visibly shifts, jitters, or is poorly reconstructed over time, failing to match the original scene's motion.\n3 Background reconstruction is mostly correct and consistent; remaining flaws are small and acceptable; background changes are localized and stable.\n4 No loss of original detail around the removed area; background reconstruction is clean, stable, and respects the scene's geometry and motion.\n5 The background is essentially untouched and stable; the inpainted area perfectly matches the surrounding content's motion, texture, and detail over time.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Local_Add = """\nYou are a data rater specializing in grading video object addition editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class added, or target only partially added, or an unrelated object is also added.\n3 Correct object added, but with significant errors: key attributes (e.g., position, colour, count, size) are wrong.\n4 The correct object is added with main attributes correct; only minor details are off (e.g., slight colour mismatch, minor position error).\n5 Perfect: All and only the requested objects are added as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious paste marks; style, resolution, or palette of the added object strongly mismatches; the added region jitters or appears static against a moving background.\n3 General style is similar, but lighting/colours on the added object clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the added object or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the edit is temporally stable and visually indistinguishable from the original video's content and motion.\n\nPhysical & Detail Coherence\n1 Severe physical errors (e.g., the added object floats, has wrong perspective/lighting); key original elements are blocked; motion of the added object is completely wrong.\n2 Contact with surfaces, occlusion by other objects, or motion of the added object is handled poorly.\n3 Lighting, perspective, and motion of the added object are mostly correct and consistent with the scene; remaining flaws are small and acceptable.\n4 Shadows, reflections, and material response from the added object are believable and move correctly with the scene; no loss of original detail.\n5 Edit enhances overall realism: the added object has precise highlights, shadows, and motion effects that are temporally coherent and perfectly integrated.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Subtitle_Edit = """"\nYou are a data rater specializing in grading instruction-following subtitle edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the subtitle edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 Target subtitle not added/removed/replaced, or wrong subtitle affected.\n2 Right action (add/remove/replace) but with incorrect content; only part of the edit is done; other subtitles are also altered.\n3 Mainly correct action and content, yet with significant spelling/grammar errors, or minor unintended edits to other subtitles.\n4 Correct action performed on the right subtitle; content is correct with only minor inaccuracies (e.g., small typos, punctuation errors).\n5 Exactly and only the requested subtitle(s) are added/removed/replaced; content matches the prompt perfectly; zero unintended edits.\n\nSubtitle Attribute Fidelity\n1 Completely fails to follow specified attributes (e.g., wrong position, wrong color). If attributes are not specified, the chosen ones make the subtitle unreadable or are extremely disruptive.\n2 Major deviation from specified attributes (e.g., requested bottom, placed on top). If not specified, chosen attributes are clearly wrong and distracting (e.g., obscures key visuals).\n3 Follows the general direction of specified attributes but with significant errors (e.g., correct side but wrong exact position). If not specified, chosen attributes are acceptable but noticeably inconsistent.\n4 Follows specified attributes with only minor inaccuracies (e.g., slightly off-center, minor deviation in font/color). If not specified, chosen attributes are highly appropriate with only minor flaws.\n5 All specified attributes (position, font, color, etc.) are matched perfectly. If attributes are not specified, the chosen ones are perfectly consistent with existing subtitles or professional standards.\n\nIntegrity of Unedited Content\n1 Massive collateral damage: background video is heavily corrupted/glitched, or other non-target subtitles are wrongly deleted/altered.\n2 Noticeable collateral damage: visible artifacts, distortion, or color shifts in the background video; other subtitles are visibly affected.\n3 Minor unintended effects: slight and localized visual artifacts in the background, or minor, non-critical changes to adjacent subtitles' appearance/timing.\n4 Almost perfect preservation: only extremely subtle artifacts in the video frame, visible only upon close inspection; all other subtitles are untouched.\n5 Perfect preservation: the edit is perfectly isolated; the background video and all other subtitles remain 100% identical to the original, with zero unintended changes.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nSubtitle Attribute Fidelity: A number from 1 to 5.\nIntegrity of Unedited Content: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+
+
+def extract_scores_and_average(entry: str) -> float:
+ import re
+
+ pattern = r':\s*(\d+\.?\d*)'
+ matches = re.findall(pattern, entry)
+
+ scores = []
+ for match in matches:
+ try:
+ scores.append(float(match))
+ except ValueError:
+ continue
+
+ if scores:
+ return round(sum(scores) / len(scores), 2)
+ return None
+
+
+def call_gemini_model(original_video_path, edited_video_path, prompt):
+ global gemini_headers, gemini_url
+
+ max_retries = 5
+ retry_count = 0
+
+ while retry_count < max_retries:
+ try:
+ user_content = [{"type": "text", "text": prompt.strip()}]
+
+ # Process Original Video
+ if os.path.exists(original_video_path):
+ with open(original_video_path, "rb") as video_file:
+ base64_video = base64.b64encode(video_file.read()).decode('utf-8')
+ user_content.append(
+ {"type": "image_url", "image_url": {"url": f"data:video/mp4;base64,{base64_video}"}}
+ )
+ else:
+ user_content.append(
+ {"type": "image_url", "image_url": {"url": original_video_path}}
+ )
+
+ # Process Edited Video
+ if os.path.exists(edited_video_path):
+ with open(edited_video_path, "rb") as video_file:
+ base64_video = base64.b64encode(video_file.read()).decode('utf-8')
+ user_content.append(
+ {"type": "image_url", "image_url": {"url": f"data:video/mp4;base64,{base64_video}"}}
+ )
+ else:
+ user_content.append(
+ {"type": "image_url", "image_url": {"url": edited_video_path}}
+ )
+
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": user_content},
+ ]
+
+ payload = {
+ "max_tokens": 8192,
+ "messages": messages,
+ "model": "gemini-2.5-pro-preview-05-06",
+ "temperature": 0.7,
+ "stream": False
+ }
+
+ response = requests.post(gemini_url, headers=gemini_headers, data=json.dumps(payload), timeout=120)
+ result = json.loads(response.text)
+
+ if response.status_code == 200:
+ if "choices" in result and result["choices"]:
+ for message in result["choices"]:
+ try:
+ message = message.get("message", {})
+ content = message.get("content", "")
+ if retry_count > 0:
+ logging.info(f"The Gemini call succeeded, and it was retried {retry_count} times.")
+ return content
+ except Exception as e:
+ logging.error(f"Error extracting content: {e}")
+ continue
+ return f"ERROR: No valid content found in choices - {result}"
+ else:
+ error_msg = f"ERROR: No choices in response - {result}"
+ logging.warning(f"Retry for {retry_count + 1}th time: {error_msg}")
+ retry_count += 1
+ time.sleep(60)
+ continue
+ else:
+ error_msg = f"ERROR: call Gemini failed, status code: {response.status_code}, response: {result}"
+ logging.warning(f"Retry for {retry_count + 1}th time: {error_msg}")
+ retry_count += 1
+ time.sleep(60)
+ continue
+
+ except Exception as e:
+ error_msg = f"An error occurred while calling the Gemini model.: {e}"
+ logging.warning(f"Retry for {retry_count + 1}th time: {error_msg}")
+ retry_count += 1
+ time.sleep(60)
+ continue
+
+
+def process_csv(input_csv_path, output_csv_path, root_path, edited_video_path="edited_result_path"):
+ start = time.time()
+ all_scores_by_type = {}
+ all_scores = []
+
+ with open(input_csv_path, 'r', encoding='utf-8-sig') as infile, \
+ open(output_csv_path, 'w', encoding='utf-8', newline='') as outfile:
+
+ reader = csv.DictReader(infile)
+ writer = csv.writer(outfile, delimiter=',')
+
+ header = reader.fieldnames
+ writer.writerow(header + ['results', 'average'])
+
+ for row_idx, row in enumerate(tqdm(reader, desc=f"Processing {os.path.basename(input_csv_path)}")):
+ try:
+ edited_type = row.get('edited_type', '')
+ prompt = row.get('prompt', '')
+ original_video = row.get('original_video', '')
+ edited_result_path = row.get(edited_video_path, '')
+
+ original_video = os.path.join(root_path, original_video)
+
+ if not os.path.exists(edited_result_path):
+ print(f"Warning: The edited video file does not exist.: {edited_result_path}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {edited_result_path}", "ERROR"])
+ continue
+
+ if not os.path.exists(original_video):
+ print(f"Warning: The original video file does not exist.: {original_video}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {original_video}", "ERROR"])
+ continue
+
+ if edited_type == "global_style":
+ system_prompt = Global_Style
+ elif edited_type == "local_change":
+ system_prompt = Local_Change
+ elif edited_type == "background_change":
+ system_prompt = Background_Change
+ elif edited_type == "subtitle_edit":
+ system_prompt = Subtitle_Edit
+ elif edited_type == "local_remove":
+ system_prompt = Local_Remove
+ elif edited_type == "local_add":
+ system_prompt = Local_Add
+ elif edited_type == "creative_edit":
+ system_prompt = Creative_Edit
+ elif edited_type == "camera_edit":
+ system_prompt = Camera_Edit
+ else:
+ raise ValueError("Invalid edit type")
+
+ full_system_prompt = system_prompt.replace('', prompt)
+
+ print(f"The Gemini model is being used for evaluation.... (行 {row_idx + 1})")
+ response = call_gemini_model(original_video, edited_result_path, full_system_prompt)
+
+ formatted_response = response.replace('\n', '\\n')
+
+ # Calculate the average value
+ average_score = extract_scores_and_average(response)
+
+ # Write the original data, results, and average value onto a new line
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [formatted_response, average_score])
+
+ # Record the scores for subsequent statistics
+ if average_score is not None:
+ all_scores.append(average_score)
+
+ # Grouped by editing type
+ if edited_type not in all_scores_by_type:
+ all_scores_by_type[edited_type] = []
+ all_scores_by_type[edited_type].append(average_score)
+
+ except Exception as e:
+ print(f"\nError: An error occurred while processing row {row}: {e}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: {e}", "ERROR"])
+
+
+ # Calculate the average score for different editing types (only scores in the range of 1-5 are counted).
+ type_averages = {}
+ for edited_type, scores in all_scores_by_type.items():
+ valid_scores = [score for score in scores if 1 <= score <= 5]
+ if valid_scores:
+ type_averages[edited_type] = round(sum(valid_scores) / len(valid_scores), 2)
+ else:
+ type_averages[edited_type] = None
+
+ # Calculate the overall average score (only scores in the range of 1-5 are counted).
+ overall_average = None
+ valid_all_scores = [score for score in all_scores if 1 <= score <= 5]
+ if valid_all_scores:
+ overall_average = round(sum(valid_all_scores) / len(valid_all_scores), 2)
+
+ # Save the statistical results to a JSON file
+ stats_output_path = output_csv_path.replace('.csv', '_stats.json')
+ stats_data = {
+ "overall_average": overall_average,
+ "type_averages": type_averages,
+ "total_processed": len(all_scores),
+ "total_valid_scores": len(valid_all_scores),
+ "breakdown_by_type": {}
+ }
+
+ # Calculate detailed statistics for each type
+ for k, v in all_scores_by_type.items():
+ valid_scores_for_type = [score for score in v if 1 <= score <= 5]
+ stats_data["breakdown_by_type"][k] = {
+ "count": len(valid_scores_for_type),
+ "average": round(sum(valid_scores_for_type) / len(valid_scores_for_type), 2) if valid_scores_for_type else None,
+ "original_count": len(v),
+ "invalid_count": len(v) - len(valid_scores_for_type) # Number of invalid data
+ }
+
+ with open(stats_output_path, 'w', encoding='utf-8') as f:
+ json.dump(stats_data, f, ensure_ascii=False, indent=2)
+
+ print(f"\nProcessing complete! Results saved to: {output_csv_path}")
+ print(f"Statistical results saved to: {stats_output_path}")
+ print(f"Average score for each editing type: {type_averages}")
+ print(f"Overall average score: {overall_average}")
+ print(f'Time for total: {time.time()-start} seconds')
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Use the Gemini 2.5 Pro model to process video and prompt CSV files.")
+ parser.add_argument("--input_csv", type=str, default="benchmark/your_model_out.csv", help="The path to the input CSV file.")
+ parser.add_argument("--root_path", type=str, default="yours_OpenVE-Bench_path", help="The path to the OpenVE-Bench videos.")
+ parser.add_argument("--output_csv", type=str, default="benchmark/your_model_out_gemini.csv", help="The path to the output CSV file.")
+ args = parser.parse_args()
+
+ output_dir = os.path.dirname(args.output_csv)
+ if output_dir:
+ os.makedirs(output_dir, exist_ok=True)
+
+ process_csv(args.input_csv, args.output_csv, args.root_path, edited_video_path="edited_result_path")
diff --git a/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/internvl_benchmark.py b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/internvl_benchmark.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f55a2b08e4f7d3c2d63f58219e36b46b4085dae
--- /dev/null
+++ b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/internvl_benchmark.py
@@ -0,0 +1,323 @@
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
+ # SPDX-License-Identifier: Apache-2.0
+import argparse
+import csv
+import os
+import torch
+from tqdm import tqdm
+import math
+import numpy as np
+import torchvision.transforms as T
+from decord import VideoReader, cpu
+from PIL import Image
+from torchvision.transforms.functional import InterpolationMode
+from transformers import AutoModel, AutoTokenizer, AutoConfig
+import time
+import argparse
+import re
+import json
+
+IMAGENET_MEAN = (0.485, 0.456, 0.406)
+IMAGENET_STD = (0.229, 0.224, 0.225)
+
+def build_transform(input_size):
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
+ transform = T.Compose([
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
+ T.ToTensor(),
+ T.Normalize(mean=MEAN, std=STD)
+ ])
+ return transform
+
+def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
+ best_ratio_diff = float('inf')
+ best_ratio = (1, 1)
+ area = width * height
+ for ratio in target_ratios:
+ target_aspect_ratio = ratio[0] / ratio[1]
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
+ if ratio_diff < best_ratio_diff:
+ best_ratio_diff = ratio_diff
+ best_ratio = ratio
+ elif ratio_diff == best_ratio_diff:
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
+ best_ratio = ratio
+ return best_ratio
+
+
+def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
+ orig_width, orig_height = image.size
+ aspect_ratio = orig_width / orig_height
+
+ # calculate the existing image aspect ratio
+ target_ratios = set(
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
+ i * j <= max_num and i * j >= min_num)
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
+
+ # find the closest aspect ratio to the target
+ target_aspect_ratio = find_closest_aspect_ratio(
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
+
+ # calculate the target width and height
+ target_width = image_size * target_aspect_ratio[0]
+ target_height = image_size * target_aspect_ratio[1]
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
+
+ # resize the image
+ resized_img = image.resize((target_width, target_height))
+ processed_images = []
+ for i in range(blocks):
+ box = (
+ (i % (target_width // image_size)) * image_size,
+ (i // (target_width // image_size)) * image_size,
+ ((i % (target_width // image_size)) + 1) * image_size,
+ ((i // (target_width // image_size)) + 1) * image_size
+ )
+ # split the image
+ split_img = resized_img.crop(box)
+ processed_images.append(split_img)
+ assert len(processed_images) == blocks
+ if use_thumbnail and len(processed_images) != 1:
+ thumbnail_img = image.resize((image_size, image_size))
+ processed_images.append(thumbnail_img)
+ return processed_images
+
+def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
+ if bound:
+ start, end = bound[0], bound[1]
+ else:
+ start, end = -100000, 100000
+ start_idx = max(first_idx, round(start * fps))
+ end_idx = min(round(end * fps), max_frame)
+ seg_size = float(end_idx - start_idx) / num_segments
+ frame_indices = np.array([
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
+ for idx in range(num_segments)
+ ])
+ return frame_indices
+
+def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
+ max_frame = len(vr) - 1
+ fps = float(vr.get_avg_fps())
+
+ pixel_values_list, num_patches_list = [], []
+ transform = build_transform(input_size=input_size)
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
+ for frame_index in frame_indices:
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
+ pixel_values = [transform(tile) for tile in img]
+ pixel_values = torch.stack(pixel_values)
+ num_patches_list.append(pixel_values.shape[0])
+ pixel_values_list.append(pixel_values)
+ pixel_values = torch.cat(pixel_values_list)
+ return pixel_values, num_patches_list
+
+def extract_scores_and_average(entry: str) -> float:
+ import re
+
+ pattern = r':\s*(\d+\.?\d*)'
+ matches = re.findall(pattern, entry)
+
+ scores = []
+ for match in matches:
+ try:
+ scores.append(float(match))
+ except ValueError:
+ continue
+
+ if scores:
+ return round(sum(scores) / len(scores), 2)
+ return None
+
+Global_Style = """\nYou are a data rater specializing in grading video style transfer edits. You will be given an input video, a reference style (image or video), and the styled result video. Your task is to evaluate the style transfer on a 5-point scale from three perspectives:\n\nStyle Fidelity\n1. Target style absent or clearly wrong.\n2. Style shows in a few areas/frames only, or mixed with unrelated styles.\n3. Key traits (palette, brushwork, texture) present but patchy or inconsistent across frames.\n4. Style reproduced well across almost the whole video; only small local or brief temporal mismatches.\n5. Full, faithful transfer: colour, texture, brushwork, and lighting all match the exemplar consistently over the entire duration and space of the video.\n\nContent Preservation\n1. Major objects, layout, or overall motion lost/distorted; original scene barely recognisable.\n2. Main subject recognisable, but its size, perspective, motion, or key parts are clearly wrong/missing.\n3. Overall structure and motion correct; some local warping, minor omissions, or slight motion jerkiness.\n4. Nearly all geometry and motion intact; only slight, non-distracting deformation.\n5. All objects, spatial relations, and motion are perfectly kept; only stylistic, harmless distortion.\n\nTemporal Stability\n1. Extreme flickering or "boiling" effects; the style is completely unstable frame-to-frame, making the video unwatchable.\n2. Significant and distracting flickering or temporal inconsistency in style application.\n3. Noticeable but tolerable flicker or texture "boiling", especially during motion.\n4. Largely stable with only minor, subtle flickering visible in areas of complex motion or fine texture.\n5. Perfectly stable and temporally coherent; the style appears "stuck" to the scene with no flickering.\n\nThe scores for Content Preservation and Temporal Stability should not be higher than the Style Fidelity score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the scores based on the criteria above, no more than 30 words.\nStyle Fidelity: A number from 1 to 5.\nContent Preservation: A number from 1 to 5.\nTemporal Stability: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Creative_Edit = """\nYou are a data rater specializing in grading instruction-following creative video edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the creative edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The instruction is completely ignored or the edit is irrelevant to the prompt.\n2 The edit attempts the instruction but fundamentally fails; the core subject, style, or action is wrong or only applied for a brief moment.\n3 The edit generally follows the instruction, but with major deviations in style, motion, or concept; the effect is highly inconsistent over time.\n4 The edit successfully executes the instruction with only minor inaccuracies in style, motion, or detail; the result is temporally consistent.\n5 The edit perfectly and creatively interprets and executes the instruction throughout the video's duration, fully achieving the intended creative goal.\n\nTemporal & Visual Coherence\n1 Massive flickering, strobing, or artifacts that make the video unwatchable; edited elements are completely disjointed from the scene.\n2 Obvious temporal inconsistency (e.g., style flickers on/off), clear visual boundaries or seams; mismatched color/lighting between frames.\n3 The edit is mostly stable, but with noticeable "boiling" or "shimmering" in textures/styles; minor jitter or softness on edges.\n4 The edit is very stable and well-integrated; only slight, hard-to-spot artifacts or flickering are present, motion is smooth.\n5 Perfectly stable and seamless integration; the edit feels like part of the original footage with no detectable flickering, jitter, or discontinuities.\n\nPhysical Plausibility & Detail Preservation\n1 Complete break from physical laws; added objects have no correct lighting/shadows, move unnaturally; original video details are heavily degraded.\n2 Major physical inconsistencies; shadows/reflections are static or move incorrectly; motion of edits doesn't match camera movement; original background is warped.\n3 Physics and lighting are generally believable but with minor flaws (e.g., a shadow is slightly off); unedited parts of the video are mostly preserved.\n4 Edited elements interact realistically with the scene's lighting, motion, and perspective; original video details are well-preserved.\n5 High degree of physical realism and integration; motion, lighting, and physics of the edits are indistinguishable from a real recording; original details are perfectly maintained.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nTemporal & Visual Coherence: A number from 1 to 5.\nPhysical Plausibility & Detail Preservation: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Camera_Edit = """\nYou are a data rater specializing in grading camera shot type alteration edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the camera shot change on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The shot type is not changed, or changed to a completely wrong type (e.g., requested close-up, but got a long shot).\n2 The direction of the shot change is correct (e.g., zoomed in for a close-up), but the degree is wrong (e.g., a medium shot instead of a close-up).\n3 The shot type is generally correct, but the framing is poor, cutting off important parts of the subject or being poorly centered.\n4 The shot type and framing are correct, with only minor inaccuracies in composition.\n5 The video is perfectly transformed into the requested shot type (long, medium, or close-up) with ideal framing of the subject.\n\nVisual Quality & Stability\n1 Massive distortion, glitches, warping, or heavy noise; the edited video is unusable.\n2 Significant and distracting jitter, shimmering, or warping is visible throughout the video, making the shot feel unstable.\n3 Minor but noticeable visual flaws, such as slight edge distortion or a subtle "breathing" effect in the frame.\n4 The video is stable and clear, with only very slight, almost unnoticeable artifacts upon close inspection.\n5 The resulting shot is perfectly stable and clear, with no digital artifacts, distortion, or jitter. It looks as if it were originally filmed with that shot type.\n\nConsistency & Detail Fidelity\n1 The subject, background, or action in the edited video is completely different from the original video; a total failure of consistency.\n2 The main subject is the same, but their action, the background, or the lighting is drastically and illogically changed compared to the original video.\n3 The scene is generally consistent, but there are noticeable continuity errors (e.g., an object disappears, the subject's pose changes unnaturally).\n4 The subject, action, and environment are highly consistent with the original video. Original details are well-preserved with only minor, hard-to-spot discrepancies.\n5 Perfect consistency; the edited video perfectly preserves the subject, lighting, background, and continuity of action from the original video, creating the illusion of the same scene captured from a different camera position.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Quality & Stability: A number from 1 to 5.\nConsistency & Detail Fidelity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Change = """\nYou are a data rater specializing in grading video replacement edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the replacement editing effect on a 5-point scale from three perspectives, paying close attention to temporal consistency (how the edit holds up over time and with motion).\n\nPrompt Compliance\n1 Target not replaced, or an unrelated object/part of the video edited.\n2 Only part of the target replaced (e.g., in only a few frames), or wrong class/description used.\n3 Target largely replaced but other objects altered, remnants visible across frames, or count/position clearly wrong.\n4 Correct object fully replaced for the entire duration; only minor attribute errors (colour, size, etc.).\n5 Perfect replacement: all and only the specified objects replaced for the entire duration; new objects’ class, number, position, scale, pose, motion and detail exactly match the prompt.\n\nVisual Naturalness & Temporal Stability\n1 Video heavily broken or new object deformed / flickers uncontrollably / jitters erratically.\n2 Obvious seams/edges that flicker or move unnaturally; strong mismatch in resolution or colour that is inconsistent across frames; background not restored or is unstable.\n3 Basic style similar, but lighting or palette clashes are inconsistent as the video plays; fuzzy edges, noise or minor flickering/jittering are noticeable.\n4 Style almost uniform and stable; tiny temporal artefacts (e.g., edge shimmer) visible only on close, frame-by-frame inspection; casual viewers see no edit.\n5 Completely seamless and temporally stable; new objects blend fully with the scene in every frame, edit area undetectable.\n\nPhysical & Motion Integrity\n1 Floating or sliding unnaturally (poor motion tracking), severe perspective/light errors inconsistent with camera/object movement; background heavily warped or unstable.\n2 Missing or static shadows/reflections that do not move with the object/light; poor occlusion; new object’s motion clearly mismatches scene motion.\n3 Lighting, perspective and interactions mostly correct but with minor inconsistencies over time; motion tracking has small, tolerable drifts.\n4 New object's motion is well-tracked and it interacts realistically with the scene (shadows, reflections) and preserves existing details throughout the video.\n5 Physically and dynamically flawless: motion, perspective, shadows, and reflections are perfectly integrated and move correctly with the scene and camera in every frame; background untouched and stable.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Naturalness & Temporal Stability: A number from 1 to 5.\nPhysical & Motion Integrity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Background_Change = """\nYou are a data rater specializing in grading video background editing. You will be given two videos (before and after editing) and the editing instruction. Your task is to evaluate the background change on a 5-point scale from three perspectives:\n\nInstruction Compliance\n1 No change, or background unrelated to prompt, or foreground also replaced/distorted.\n2 Background partly replaced or wrong style/content; foreground noticeably altered.\n3 Main background replaced but elements missing/extra, or faint spill onto subject edges.\n4 Requested background fully present; foreground intact except minute artefacts or small prompt mismatch (e.g. colour tone).\n5 Background exactly matches prompt (content, style, placement); all foreground pixels untouched.\n\nVisual & Temporal Seamlessness (Edge, Blend & Stability)\n1 Large tearing, posterisation, or significant temporal artifacts like flickering, jittering edges; edit area obvious at a glance.\n2 Clear cut-out halos, colour-resolution gap, or obvious edge 'boiling' (instability) over time.\n3 Blend acceptable but visible on closer look: slight edge blur, or minor temporal instability (e.g., shimmer).\n4 Nearly invisible seams; edges are stable across motion, textures aligned, only minor issues when zoomed in.\n5 Indistinguishable composite: edges, textures, resolution and colour grading are perfectly continuous and stable throughout the video's duration.\n\nPhysical Consistency (Lighting, Perspective, Motion & Depth)\n1 Severe mismatch: wrong horizon, conflicting light, floating subject, or background remains static during camera movement (no parallax).\n2 Noticeable inconsistencies in light or scale; incorrect perspective shifts during motion.\n3 Overall believable; small errors in shadow, perspective, or minor motion tracking flaws.\n4 Lighting, scale, and depth well matched; background perspective and scale track convincingly with camera motion.\n5 Physically flawless: foreground and new background share coherent light, shadows, perspective, and atmospheric depth throughout all subject and camera motion, enhancing overall realism.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nInstruction Compliance: A number from 1 to 5.\nVisual & Temporal Seamlessness: A number from 1 to 5.\nPhysical Consistency: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Remove = """\nYou are a data rater specializing in grading video object removal editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class removed, or target only partially removed, or an unrelated object is also removed.\n3 Correct object removed, but with significant errors: unintended objects are also removed, OR significant fragments/ghosting of the target remain.\n4 The correct object is removed; only minor issues like a few tiny fragments remaining or tiny, unintended background items being affected.\n5 Perfect: All and only the requested objects are removed as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious erase marks or "smudges"; the inpainted background's style, resolution, or palette strongly mismatches; the edited region jitters or appears static against a moving background.\n3 General style is similar, but the inpainted background's lighting/colours clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the removed area or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the removal is temporally stable and visually indistinguishable from a clean background.\n\nPhysical & Detail Coherence\n1 Key original elements are blocked by poor inpainting; the background is heavily distorted or hallucinates incorrect structures; motion is completely wrong (e.g., a static patch in a moving scene).\n2 The inpainted background visibly shifts, jitters, or is poorly reconstructed over time, failing to match the original scene's motion.\n3 Background reconstruction is mostly correct and consistent; remaining flaws are small and acceptable; background changes are localized and stable.\n4 No loss of original detail around the removed area; background reconstruction is clean, stable, and respects the scene's geometry and motion.\n5 The background is essentially untouched and stable; the inpainted area perfectly matches the surrounding content's motion, texture, and detail over time.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Local_Add = """\nYou are a data rater specializing in grading video object addition editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class added, or target only partially added, or an unrelated object is also added.\n3 Correct object added, but with significant errors: key attributes (e.g., position, colour, count, size) are wrong.\n4 The correct object is added with main attributes correct; only minor details are off (e.g., slight colour mismatch, minor position error).\n5 Perfect: All and only the requested objects are added as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious paste marks; style, resolution, or palette of the added object strongly mismatches; the added region jitters or appears static against a moving background.\n3 General style is similar, but lighting/colours on the added object clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the added object or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the edit is temporally stable and visually indistinguishable from the original video's content and motion.\n\nPhysical & Detail Coherence\n1 Severe physical errors (e.g., the added object floats, has wrong perspective/lighting); key original elements are blocked; motion of the added object is completely wrong.\n2 Contact with surfaces, occlusion by other objects, or motion of the added object is handled poorly.\n3 Lighting, perspective, and motion of the added object are mostly correct and consistent with the scene; remaining flaws are small and acceptable.\n4 Shadows, reflections, and material response from the added object are believable and move correctly with the scene; no loss of original detail.\n5 Edit enhances overall realism: the added object has precise highlights, shadows, and motion effects that are temporally coherent and perfectly integrated.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Subtitle_Edit = """"\nYou are a data rater specializing in grading instruction-following subtitle edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the subtitle edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 Target subtitle not added/removed/replaced, or wrong subtitle affected.\n2 Right action (add/remove/replace) but with incorrect content; only part of the edit is done; other subtitles are also altered.\n3 Mainly correct action and content, yet with significant spelling/grammar errors, or minor unintended edits to other subtitles.\n4 Correct action performed on the right subtitle; content is correct with only minor inaccuracies (e.g., small typos, punctuation errors).\n5 Exactly and only the requested subtitle(s) are added/removed/replaced; content matches the prompt perfectly; zero unintended edits.\n\nSubtitle Attribute Fidelity\n1 Completely fails to follow specified attributes (e.g., wrong position, wrong color). If attributes are not specified, the chosen ones make the subtitle unreadable or are extremely disruptive.\n2 Major deviation from specified attributes (e.g., requested bottom, placed on top). If not specified, chosen attributes are clearly wrong and distracting (e.g., obscures key visuals).\n3 Follows the general direction of specified attributes but with significant errors (e.g., correct side but wrong exact position). If not specified, chosen attributes are acceptable but noticeably inconsistent.\n4 Follows specified attributes with only minor inaccuracies (e.g., slightly off-center, minor deviation in font/color). If not specified, chosen attributes are highly appropriate with only minor flaws.\n5 All specified attributes (position, font, color, etc.) are matched perfectly. If attributes are not specified, the chosen ones are perfectly consistent with existing subtitles or professional standards.\n\nIntegrity of Unedited Content\n1 Massive collateral damage: background video is heavily corrupted/glitched, or other non-target subtitles are wrongly deleted/altered.\n2 Noticeable collateral damage: visible artifacts, distortion, or color shifts in the background video; other subtitles are visibly affected.\n3 Minor unintended effects: slight and localized visual artifacts in the background, or minor, non-critical changes to adjacent subtitles' appearance/timing.\n4 Almost perfect preservation: only extremely subtle artifacts in the video frame, visible only upon close inspection; all other subtitles are untouched.\n5 Perfect preservation: the edit is perfectly isolated; the background video and all other subtitles remain 100% identical to the original, with zero unintended changes.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nSubtitle Attribute Fidelity: A number from 1 to 5.\nIntegrity of Unedited Content: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+
+
+def process_csv(input_csv_path, output_csv_path, model_path, root_path, edited_video_path="edited_result_path"):
+ model = AutoModel.from_pretrained(
+ model_path,
+ torch_dtype=torch.bfloat16,
+ low_cpu_mem_usage=True,
+ trust_remote_code=True,
+ device_map="cuda"
+ ).eval()
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False)
+ generation_config = dict(max_new_tokens=1024, do_sample=True, temperature=0.6)
+ print("Model initialization complete.")
+
+ start = time.time()
+
+ all_scores_by_type = {}
+ all_scores = []
+
+ with open(input_csv_path, 'r', encoding='utf-8-sig') as infile, \
+ open(output_csv_path, 'w', encoding='utf-8', newline='') as outfile:
+
+ reader = csv.DictReader(infile)
+ writer = csv.writer(outfile, delimiter=',')
+
+ header = reader.fieldnames
+ writer.writerow(header + ['results', 'average'])
+
+ for row in tqdm(reader, desc=f"Processing {os.path.basename(input_csv_path)}"):
+ try:
+ edited_type = row.get('edited_type', '')
+ prompt = row.get('prompt', '')
+ original_video = row.get('original_video', '')
+ edited_result_path = row.get(edited_video_path, '')
+
+ original_video = os.path.join(root_path, original_video)
+
+ if not os.path.exists(edited_result_path):
+ print(f"Warning: The edited video file does not exist.: {edited_result_path}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {edited_result_path}", "ERROR"])
+ continue
+
+ if not os.path.exists(original_video):
+ print(f"Warning: The original video file does not exist.: {original_video}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {original_video}", "ERROR"])
+ continue
+
+ if edited_type == "global_style":
+ system_prompt = Global_Style
+ elif edited_type == "local_change":
+ system_prompt = Local_Change
+ elif edited_type == "background_change":
+ system_prompt = Background_Change
+ elif edited_type == "subtitle_edit":
+ system_prompt = Subtitle_Edit
+ elif edited_type == "local_remove":
+ system_prompt = Local_Remove
+ elif edited_type == "local_add":
+ system_prompt = Local_Add
+ elif edited_type == "creative_edit":
+ system_prompt = Creative_Edit
+ elif edited_type == "camera_edit":
+ system_prompt = Camera_Edit
+ else:
+ raise ValueError("Invalid edit type")
+
+ full_system_prompt = system_prompt.replace('', prompt)
+
+ edited_pixel_values, edited_num_patches_list = load_video(lucy_result_path, num_segments=17, max_num=1)
+ edited_pixel_values = edited_pixel_values.to(torch.bfloat16).cuda()
+
+ original_pixel_values, original_num_patches_list = load_video(original_video, num_segments=17, max_num=1)
+ original_pixel_values = original_pixel_values.to(torch.bfloat16).cuda()
+
+ pixel_values = torch.cat((original_pixel_values, edited_pixel_values), dim=0)
+
+ # 准备输入
+ original_video_prefix = ''.join([f'Before Editing Video: Frame{i+1}: \n' for i in range(len(original_num_patches_list))])
+ edited_video_prefix = ''.join([f'After Editing Video: Frame{i+1}: \n' for i in range(len(edited_num_patches_list))])
+
+ full_system_prompt = system_prompt.replace('', prompt)
+ question = full_system_prompt + original_video_prefix + edited_video_prefix
+
+ num_patches_list = original_num_patches_list + edited_num_patches_list
+
+ response = model.chat(
+ tokenizer=tokenizer,
+ pixel_values=pixel_values,
+ question=question,
+ generation_config=generation_config,
+ num_patches_list=num_patches_list,
+ history=None,
+ return_history=False
+ )
+
+ formatted_response = response.replace('\n', '\\n')
+
+ # Calculate the average value
+ average_score = extract_scores_and_average(response)
+
+ # Write the original data, results, and average value onto a new line
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [formatted_response, average_score])
+
+ # Record the scores for subsequent statistics
+ if average_score is not None:
+ all_scores.append(average_score)
+
+ # Grouped by editing type
+ if edited_type not in all_scores_by_type:
+ all_scores_by_type[edited_type] = []
+ all_scores_by_type[edited_type].append(average_score)
+
+ except Exception as e:
+ print(f"\nError: An error occurred while processing row {row}: {e}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: {e}", "ERROR"])
+
+
+ # Calculate the average score for different editing types (only scores in the range of 1-5 are counted).
+ type_averages = {}
+ for edited_type, scores in all_scores_by_type.items():
+ valid_scores = [score for score in scores if 1 <= score <= 5]
+ if valid_scores:
+ type_averages[edited_type] = round(sum(valid_scores) / len(valid_scores), 2)
+ else:
+ type_averages[edited_type] = None
+
+ # Calculate the overall average score (only scores in the range of 1-5 are counted).
+ overall_average = None
+ valid_all_scores = [score for score in all_scores if 1 <= score <= 5]
+ if valid_all_scores:
+ overall_average = round(sum(valid_all_scores) / len(valid_all_scores), 2)
+
+ # Save the statistical results to a JSON file
+ stats_output_path = output_csv_path.replace('.csv', '_stats.json')
+ stats_data = {
+ "overall_average": overall_average,
+ "type_averages": type_averages,
+ "total_processed": len(all_scores),
+ "total_valid_scores": len(valid_all_scores),
+ "breakdown_by_type": {}
+ }
+
+ # Calculate detailed statistics for each type
+ for k, v in all_scores_by_type.items():
+ valid_scores_for_type = [score for score in v if 1 <= score <= 5]
+ stats_data["breakdown_by_type"][k] = {
+ "count": len(valid_scores_for_type),
+ "average": round(sum(valid_scores_for_type) / len(valid_scores_for_type), 2) if valid_scores_for_type else None,
+ "original_count": len(v),
+ "invalid_count": len(v) - len(valid_scores_for_type) # Number of invalid data
+ }
+
+ with open(stats_output_path, 'w', encoding='utf-8') as f:
+ json.dump(stats_data, f, ensure_ascii=False, indent=2)
+
+ print(f"\nProcessing complete! Results saved to: {output_csv_path}")
+ print(f"Statistical results saved to: {stats_output_path}")
+ print(f"Average score for each editing type: {type_averages}")
+ print(f"Overall average score: {overall_average}")
+ print(f'Time for total: {time.time()-start} seconds')
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Use the InternVL3_5 model to process video and prompt CSV files.")
+ parser.add_argument("--input_csv", type=str, default="benchmark/your_model_out.csv", help="The path to the input CSV file.")
+ parser.add_argument("--root_path", type=str, default="yours_OpenVE-Bench_path", help="The path to the OpenVE-Bench videos.")
+ parser.add_argument("--output_csv", type=str, default="benchmark/your_model_out_internvl.csv", help="The path to the output CSV file.")
+ parser.add_argument("--model_path", type=str, default="/your_path/InternVL3_5-38B", help="Path of InternVL3_5-38B model")
+ args = parser.parse_args()
+
+ output_dir = os.path.dirname(args.output_csv)
+ if output_dir:
+ os.makedirs(output_dir, exist_ok=True)
+
+ process_csv(args.input_csv, args.output_csv, args.model_path, args.root_path, edited_video_path="edited_result_path")
+
diff --git a/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/qwen3vl_benchmark.py b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/qwen3vl_benchmark.py
new file mode 100644
index 0000000000000000000000000000000000000000..baaeccd11638b9e3a998497ae61b237f42f3a06d
--- /dev/null
+++ b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/qwen3vl_benchmark.py
@@ -0,0 +1,244 @@
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
+ # SPDX-License-Identifier: Apache-2.0
+import argparse
+import csv
+import os
+import torch
+import torchvision.transforms as T
+from decord import VideoReader, cpu
+from PIL import Image
+from tqdm import tqdm
+import math
+import numpy as np
+import time
+import argparse
+import re
+from transformers import Qwen3VLMoeForConditionalGeneration, AutoProcessor, Qwen3VLForConditionalGeneration
+import json
+
+def extract_scores_and_average(entry: str) -> float:
+ import re
+ pattern = r':\s*(\d+\.?\d*)'
+ matches = re.findall(pattern, entry)
+
+ scores = []
+ for match in matches:
+ try:
+ scores.append(float(match))
+ except ValueError:
+ continue
+
+ if scores:
+ return round(sum(scores) / len(scores), 2)
+ return None
+
+
+Global_Style = """\nYou are a data rater specializing in grading video style transfer edits. You will be given an input video, a reference style (image or video), and the styled result video. Your task is to evaluate the style transfer on a 5-point scale from three perspectives:\n\nStyle Fidelity\n1. Target style absent or clearly wrong.\n2. Style shows in a few areas/frames only, or mixed with unrelated styles.\n3. Key traits (palette, brushwork, texture) present but patchy or inconsistent across frames.\n4. Style reproduced well across almost the whole video; only small local or brief temporal mismatches.\n5. Full, faithful transfer: colour, texture, brushwork, and lighting all match the exemplar consistently over the entire duration and space of the video.\n\nContent Preservation\n1. Major objects, layout, or overall motion lost/distorted; original scene barely recognisable.\n2. Main subject recognisable, but its size, perspective, motion, or key parts are clearly wrong/missing.\n3. Overall structure and motion correct; some local warping, minor omissions, or slight motion jerkiness.\n4. Nearly all geometry and motion intact; only slight, non-distracting deformation.\n5. All objects, spatial relations, and motion are perfectly kept; only stylistic, harmless distortion.\n\nTemporal Stability\n1. Extreme flickering or "boiling" effects; the style is completely unstable frame-to-frame, making the video unwatchable.\n2. Significant and distracting flickering or temporal inconsistency in style application.\n3. Noticeable but tolerable flicker or texture "boiling", especially during motion.\n4. Largely stable with only minor, subtle flickering visible in areas of complex motion or fine texture.\n5. Perfectly stable and temporally coherent; the style appears "stuck" to the scene with no flickering.\n\nThe scores for Content Preservation and Temporal Stability should not be higher than the Style Fidelity score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the scores based on the criteria above, no more than 30 words.\nStyle Fidelity: A number from 1 to 5.\nContent Preservation: A number from 1 to 5.\nTemporal Stability: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Creative_Edit = """\nYou are a data rater specializing in grading instruction-following creative video edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the creative edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The instruction is completely ignored or the edit is irrelevant to the prompt.\n2 The edit attempts the instruction but fundamentally fails; the core subject, style, or action is wrong or only applied for a brief moment.\n3 The edit generally follows the instruction, but with major deviations in style, motion, or concept; the effect is highly inconsistent over time.\n4 The edit successfully executes the instruction with only minor inaccuracies in style, motion, or detail; the result is temporally consistent.\n5 The edit perfectly and creatively interprets and executes the instruction throughout the video's duration, fully achieving the intended creative goal.\n\nTemporal & Visual Coherence\n1 Massive flickering, strobing, or artifacts that make the video unwatchable; edited elements are completely disjointed from the scene.\n2 Obvious temporal inconsistency (e.g., style flickers on/off), clear visual boundaries or seams; mismatched color/lighting between frames.\n3 The edit is mostly stable, but with noticeable "boiling" or "shimmering" in textures/styles; minor jitter or softness on edges.\n4 The edit is very stable and well-integrated; only slight, hard-to-spot artifacts or flickering are present, motion is smooth.\n5 Perfectly stable and seamless integration; the edit feels like part of the original footage with no detectable flickering, jitter, or discontinuities.\n\nPhysical Plausibility & Detail Preservation\n1 Complete break from physical laws; added objects have no correct lighting/shadows, move unnaturally; original video details are heavily degraded.\n2 Major physical inconsistencies; shadows/reflections are static or move incorrectly; motion of edits doesn't match camera movement; original background is warped.\n3 Physics and lighting are generally believable but with minor flaws (e.g., a shadow is slightly off); unedited parts of the video are mostly preserved.\n4 Edited elements interact realistically with the scene's lighting, motion, and perspective; original video details are well-preserved.\n5 High degree of physical realism and integration; motion, lighting, and physics of the edits are indistinguishable from a real recording; original details are perfectly maintained.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nTemporal & Visual Coherence: A number from 1 to 5.\nPhysical Plausibility & Detail Preservation: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Camera_Edit = """\nYou are a data rater specializing in grading camera shot type alteration edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the camera shot change on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The shot type is not changed, or changed to a completely wrong type (e.g., requested close-up, but got a long shot).\n2 The direction of the shot change is correct (e.g., zoomed in for a close-up), but the degree is wrong (e.g., a medium shot instead of a close-up).\n3 The shot type is generally correct, but the framing is poor, cutting off important parts of the subject or being poorly centered.\n4 The shot type and framing are correct, with only minor inaccuracies in composition.\n5 The video is perfectly transformed into the requested shot type (long, medium, or close-up) with ideal framing of the subject.\n\nVisual Quality & Stability\n1 Massive distortion, glitches, warping, or heavy noise; the edited video is unusable.\n2 Significant and distracting jitter, shimmering, or warping is visible throughout the video, making the shot feel unstable.\n3 Minor but noticeable visual flaws, such as slight edge distortion or a subtle "breathing" effect in the frame.\n4 The video is stable and clear, with only very slight, almost unnoticeable artifacts upon close inspection.\n5 The resulting shot is perfectly stable and clear, with no digital artifacts, distortion, or jitter. It looks as if it were originally filmed with that shot type.\n\nConsistency & Detail Fidelity\n1 The subject, background, or action in the edited video is completely different from the original video; a total failure of consistency.\n2 The main subject is the same, but their action, the background, or the lighting is drastically and illogically changed compared to the original video.\n3 The scene is generally consistent, but there are noticeable continuity errors (e.g., an object disappears, the subject's pose changes unnaturally).\n4 The subject, action, and environment are highly consistent with the original video. Original details are well-preserved with only minor, hard-to-spot discrepancies.\n5 Perfect consistency; the edited video perfectly preserves the subject, lighting, background, and continuity of action from the original video, creating the illusion of the same scene captured from a different camera position.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Quality & Stability: A number from 1 to 5.\nConsistency & Detail Fidelity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Change = """\nYou are a data rater specializing in grading video replacement edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the replacement editing effect on a 5-point scale from three perspectives, paying close attention to temporal consistency (how the edit holds up over time and with motion).\n\nPrompt Compliance\n1 Target not replaced, or an unrelated object/part of the video edited.\n2 Only part of the target replaced (e.g., in only a few frames), or wrong class/description used.\n3 Target largely replaced but other objects altered, remnants visible across frames, or count/position clearly wrong.\n4 Correct object fully replaced for the entire duration; only minor attribute errors (colour, size, etc.).\n5 Perfect replacement: all and only the specified objects replaced for the entire duration; new objects’ class, number, position, scale, pose, motion and detail exactly match the prompt.\n\nVisual Naturalness & Temporal Stability\n1 Video heavily broken or new object deformed / flickers uncontrollably / jitters erratically.\n2 Obvious seams/edges that flicker or move unnaturally; strong mismatch in resolution or colour that is inconsistent across frames; background not restored or is unstable.\n3 Basic style similar, but lighting or palette clashes are inconsistent as the video plays; fuzzy edges, noise or minor flickering/jittering are noticeable.\n4 Style almost uniform and stable; tiny temporal artefacts (e.g., edge shimmer) visible only on close, frame-by-frame inspection; casual viewers see no edit.\n5 Completely seamless and temporally stable; new objects blend fully with the scene in every frame, edit area undetectable.\n\nPhysical & Motion Integrity\n1 Floating or sliding unnaturally (poor motion tracking), severe perspective/light errors inconsistent with camera/object movement; background heavily warped or unstable.\n2 Missing or static shadows/reflections that do not move with the object/light; poor occlusion; new object’s motion clearly mismatches scene motion.\n3 Lighting, perspective and interactions mostly correct but with minor inconsistencies over time; motion tracking has small, tolerable drifts.\n4 New object's motion is well-tracked and it interacts realistically with the scene (shadows, reflections) and preserves existing details throughout the video.\n5 Physically and dynamically flawless: motion, perspective, shadows, and reflections are perfectly integrated and move correctly with the scene and camera in every frame; background untouched and stable.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Naturalness & Temporal Stability: A number from 1 to 5.\nPhysical & Motion Integrity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Background_Change = """\nYou are a data rater specializing in grading video background editing. You will be given two videos (before and after editing) and the editing instruction. Your task is to evaluate the background change on a 5-point scale from three perspectives:\n\nInstruction Compliance\n1 No change, or background unrelated to prompt, or foreground also replaced/distorted.\n2 Background partly replaced or wrong style/content; foreground noticeably altered.\n3 Main background replaced but elements missing/extra, or faint spill onto subject edges.\n4 Requested background fully present; foreground intact except minute artefacts or small prompt mismatch (e.g. colour tone).\n5 Background exactly matches prompt (content, style, placement); all foreground pixels untouched.\n\nVisual & Temporal Seamlessness (Edge, Blend & Stability)\n1 Large tearing, posterisation, or significant temporal artifacts like flickering, jittering edges; edit area obvious at a glance.\n2 Clear cut-out halos, colour-resolution gap, or obvious edge 'boiling' (instability) over time.\n3 Blend acceptable but visible on closer look: slight edge blur, or minor temporal instability (e.g., shimmer).\n4 Nearly invisible seams; edges are stable across motion, textures aligned, only minor issues when zoomed in.\n5 Indistinguishable composite: edges, textures, resolution and colour grading are perfectly continuous and stable throughout the video's duration.\n\nPhysical Consistency (Lighting, Perspective, Motion & Depth)\n1 Severe mismatch: wrong horizon, conflicting light, floating subject, or background remains static during camera movement (no parallax).\n2 Noticeable inconsistencies in light or scale; incorrect perspective shifts during motion.\n3 Overall believable; small errors in shadow, perspective, or minor motion tracking flaws.\n4 Lighting, scale, and depth well matched; background perspective and scale track convincingly with camera motion.\n5 Physically flawless: foreground and new background share coherent light, shadows, perspective, and atmospheric depth throughout all subject and camera motion, enhancing overall realism.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nInstruction Compliance: A number from 1 to 5.\nVisual & Temporal Seamlessness: A number from 1 to 5.\nPhysical Consistency: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Remove = """\nYou are a data rater specializing in grading video object removal editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class removed, or target only partially removed, or an unrelated object is also removed.\n3 Correct object removed, but with significant errors: unintended objects are also removed, OR significant fragments/ghosting of the target remain.\n4 The correct object is removed; only minor issues like a few tiny fragments remaining or tiny, unintended background items being affected.\n5 Perfect: All and only the requested objects are removed as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious erase marks or "smudges"; the inpainted background's style, resolution, or palette strongly mismatches; the edited region jitters or appears static against a moving background.\n3 General style is similar, but the inpainted background's lighting/colours clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the removed area or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the removal is temporally stable and visually indistinguishable from a clean background.\n\nPhysical & Detail Coherence\n1 Key original elements are blocked by poor inpainting; the background is heavily distorted or hallucinates incorrect structures; motion is completely wrong (e.g., a static patch in a moving scene).\n2 The inpainted background visibly shifts, jitters, or is poorly reconstructed over time, failing to match the original scene's motion.\n3 Background reconstruction is mostly correct and consistent; remaining flaws are small and acceptable; background changes are localized and stable.\n4 No loss of original detail around the removed area; background reconstruction is clean, stable, and respects the scene's geometry and motion.\n5 The background is essentially untouched and stable; the inpainted area perfectly matches the surrounding content's motion, texture, and detail over time.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Local_Add = """\nYou are a data rater specializing in grading video object addition editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class added, or target only partially added, or an unrelated object is also added.\n3 Correct object added, but with significant errors: key attributes (e.g., position, colour, count, size) are wrong.\n4 The correct object is added with main attributes correct; only minor details are off (e.g., slight colour mismatch, minor position error).\n5 Perfect: All and only the requested objects are added as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious paste marks; style, resolution, or palette of the added object strongly mismatches; the added region jitters or appears static against a moving background.\n3 General style is similar, but lighting/colours on the added object clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the added object or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the edit is temporally stable and visually indistinguishable from the original video's content and motion.\n\nPhysical & Detail Coherence\n1 Severe physical errors (e.g., the added object floats, has wrong perspective/lighting); key original elements are blocked; motion of the added object is completely wrong.\n2 Contact with surfaces, occlusion by other objects, or motion of the added object is handled poorly.\n3 Lighting, perspective, and motion of the added object are mostly correct and consistent with the scene; remaining flaws are small and acceptable.\n4 Shadows, reflections, and material response from the added object are believable and move correctly with the scene; no loss of original detail.\n5 Edit enhances overall realism: the added object has precise highlights, shadows, and motion effects that are temporally coherent and perfectly integrated.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Subtitle_Edit = """"\nYou are a data rater specializing in grading instruction-following subtitle edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the subtitle edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 Target subtitle not added/removed/replaced, or wrong subtitle affected.\n2 Right action (add/remove/replace) but with incorrect content; only part of the edit is done; other subtitles are also altered.\n3 Mainly correct action and content, yet with significant spelling/grammar errors, or minor unintended edits to other subtitles.\n4 Correct action performed on the right subtitle; content is correct with only minor inaccuracies (e.g., small typos, punctuation errors).\n5 Exactly and only the requested subtitle(s) are added/removed/replaced; content matches the prompt perfectly; zero unintended edits.\n\nSubtitle Attribute Fidelity\n1 Completely fails to follow specified attributes (e.g., wrong position, wrong color). If attributes are not specified, the chosen ones make the subtitle unreadable or are extremely disruptive.\n2 Major deviation from specified attributes (e.g., requested bottom, placed on top). If not specified, chosen attributes are clearly wrong and distracting (e.g., obscures key visuals).\n3 Follows the general direction of specified attributes but with significant errors (e.g., correct side but wrong exact position). If not specified, chosen attributes are acceptable but noticeably inconsistent.\n4 Follows specified attributes with only minor inaccuracies (e.g., slightly off-center, minor deviation in font/color). If not specified, chosen attributes are highly appropriate with only minor flaws.\n5 All specified attributes (position, font, color, etc.) are matched perfectly. If attributes are not specified, the chosen ones are perfectly consistent with existing subtitles or professional standards.\n\nIntegrity of Unedited Content\n1 Massive collateral damage: background video is heavily corrupted/glitched, or other non-target subtitles are wrongly deleted/altered.\n2 Noticeable collateral damage: visible artifacts, distortion, or color shifts in the background video; other subtitles are visibly affected.\n3 Minor unintended effects: slight and localized visual artifacts in the background, or minor, non-critical changes to adjacent subtitles' appearance/timing.\n4 Almost perfect preservation: only extremely subtle artifacts in the video frame, visible only upon close inspection; all other subtitles are untouched.\n5 Perfect preservation: the edit is perfectly isolated; the background video and all other subtitles remain 100% identical to the original, with zero unintended changes.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nSubtitle Attribute Fidelity: A number from 1 to 5.\nIntegrity of Unedited Content: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+
+
+def process_csv(input_csv_path, output_csv_path, model_path, root_path, edited_video_path="edited_result_path"):
+
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
+ model_path,
+ torch_dtype=torch.bfloat16,
+ attn_implementation="flash_attention_2",
+ device_map="auto"
+ ).eval()
+
+ processor = AutoProcessor.from_pretrained(model_path)
+ print("Model initialization complete.")
+
+ start = time.time()
+
+ all_scores_by_type = {}
+ all_scores = []
+
+ with open(input_csv_path, 'r', encoding='utf-8-sig') as infile, \
+ open(output_csv_path, 'w', encoding='utf-8', newline='') as outfile:
+
+ reader = csv.DictReader(infile)
+ writer = csv.writer(outfile, delimiter=',')
+
+ header = reader.fieldnames
+ writer.writerow(header + ['results', 'average'])
+
+ for row in tqdm(reader, desc=f"Processing {os.path.basename(input_csv_path)}"):
+ try:
+ edited_type = row.get('edited_type', '')
+ prompt = row.get('prompt', '')
+ original_video = row.get('original_video', '')
+ edited_result_path = row.get(edited_video_path, '')
+
+ original_video = os.path.join(root_path, original_video)
+
+ if not os.path.exists(edited_result_path):
+ print(f"Warning: The edited video file does not exist.: {edited_result_path}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {edited_result_path}", "ERROR"])
+ continue
+
+ if not os.path.exists(original_video):
+ print(f"Warning: The original video file does not exist.: {original_video}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {original_video}", "ERROR"])
+ continue
+
+ if edited_type == "global_style":
+ system_prompt = Global_Style
+ elif edited_type == "local_change":
+ system_prompt = Local_Change
+ elif edited_type == "background_change":
+ system_prompt = Background_Change
+ elif edited_type == "subtitle_edit":
+ system_prompt = Subtitle_Edit
+ elif edited_type == "local_remove":
+ system_prompt = Local_Remove
+ elif edited_type == "local_add":
+ system_prompt = Local_Add
+ elif edited_type == "creative_edit":
+ system_prompt = Creative_Edit
+ elif edited_type == "camera_edit":
+ system_prompt = Camera_Edit
+ else:
+ raise ValueError("Invalid edit type")
+
+ full_system_prompt = system_prompt.replace('', prompt)
+
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": full_system_prompt},
+ {
+ "type": "video",
+ "video": original_video,
+ "min_pixels": 4 * 32 * 32,
+ "max_pixels": 32 * 32 * 32,
+ "total_pixels": 128 * 32 * 32,
+ },
+ {
+ "type": "video",
+ "video": edited_result_path,
+ "min_pixels": 4 * 32 * 32,
+ "max_pixels": 32 * 32 * 32,
+ "total_pixels": 128 * 32 * 32,
+ },
+ ],
+ }
+ ]
+
+ inputs = processor.apply_chat_template(
+ messages,
+ tokenize=True,
+ add_generation_prompt=True,
+ return_dict=True,
+ return_tensors="pt"
+ )
+
+ inputs = {k: v.cuda() if torch.is_tensor(v) else v for k, v in inputs.items()}
+
+ generated_ids = model.generate(
+ **inputs,
+ max_new_tokens=256,
+ do_sample=True,
+ temperature=0.6
+ )
+
+ generated_ids_trimmed = [
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs['input_ids'], generated_ids)
+ ]
+ response = processor.batch_decode(
+ generated_ids_trimmed,
+ skip_special_tokens=True,
+ clean_up_tokenization_spaces=False
+ )[0]
+
+ formatted_response = response.replace('\n', '\\n')
+
+ # Calculate the average value
+ average_score = extract_scores_and_average(response)
+
+ # Write the original data, results, and average value onto a new line
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [formatted_response, average_score])
+
+ # Record the scores for subsequent statistics
+ if average_score is not None:
+ all_scores.append(average_score)
+
+ # Grouped by editing type
+ if edited_type not in all_scores_by_type:
+ all_scores_by_type[edited_type] = []
+ all_scores_by_type[edited_type].append(average_score)
+
+ except Exception as e:
+ print(f"\nError: An error occurred while processing row {row}: {e}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: {e}", "ERROR"])
+
+
+ # Calculate the average score for different editing types (only scores in the range of 1-5 are counted).
+ type_averages = {}
+ for edited_type, scores in all_scores_by_type.items():
+ valid_scores = [score for score in scores if 1 <= score <= 5]
+ if valid_scores:
+ type_averages[edited_type] = round(sum(valid_scores) / len(valid_scores), 2)
+ else:
+ type_averages[edited_type] = None
+
+ # Calculate the overall average score (only scores in the range of 1-5 are counted).
+ overall_average = None
+ valid_all_scores = [score for score in all_scores if 1 <= score <= 5]
+ if valid_all_scores:
+ overall_average = round(sum(valid_all_scores) / len(valid_all_scores), 2)
+
+ # Save the statistical results to a JSON file
+ stats_output_path = output_csv_path.replace('.csv', '_stats.json')
+ stats_data = {
+ "overall_average": overall_average,
+ "type_averages": type_averages,
+ "total_processed": len(all_scores),
+ "total_valid_scores": len(valid_all_scores),
+ "breakdown_by_type": {}
+ }
+
+ # Calculate detailed statistics for each type
+ for k, v in all_scores_by_type.items():
+ valid_scores_for_type = [score for score in v if 1 <= score <= 5]
+ stats_data["breakdown_by_type"][k] = {
+ "count": len(valid_scores_for_type),
+ "average": round(sum(valid_scores_for_type) / len(valid_scores_for_type), 2) if valid_scores_for_type else None,
+ "original_count": len(v),
+ "invalid_count": len(v) - len(valid_scores_for_type) # Number of invalid data
+ }
+
+ with open(stats_output_path, 'w', encoding='utf-8') as f:
+ json.dump(stats_data, f, ensure_ascii=False, indent=2)
+
+ print(f"\nProcessing complete! Results saved to: {output_csv_path}")
+ print(f"Statistical results saved to: {stats_output_path}")
+ print(f"Average score for each editing type: {type_averages}")
+ print(f"Overall average score: {overall_average}")
+ print(f'Time for total: {time.time()-start} seconds')
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Use the Qwen3-VL model to process video and prompt CSV files.")
+ parser.add_argument("--input_csv", type=str, default="benchmark/your_model_out.csv", help="The path to the input CSV file.")
+ parser.add_argument("--root_path", type=str, default="yours_OpenVE-Bench_path", help="The path to the OpenVE-Bench videos.")
+ parser.add_argument("--output_csv", type=str, default="benchmark/your_model_out_qwen3vl.csv", help="The path to the output CSV file.")
+ parser.add_argument("--model_path", type=str, default="/your_path/Qwen3-VL-32B-Instruct", help="Path of Qwen3-VL model")
+ args = parser.parse_args()
+
+ output_dir = os.path.dirname(args.output_csv)
+ if output_dir:
+ os.makedirs(output_dir, exist_ok=True)
+
+ process_csv(args.input_csv, args.output_csv, args.model_path, args.root_path, edited_video_path="edited_result_path")
\ No newline at end of file
diff --git a/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/seed_benchmark.py b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/seed_benchmark.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a75eec2b2f47d35e28eeaf4e5ecb772ab17c660
--- /dev/null
+++ b/benchmarks/edit/code/OpenVE-3M/OpenVE-Bench/seed_benchmark.py
@@ -0,0 +1,279 @@
+ # Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
+ # SPDX-License-Identifier: Apache-2.0
+import argparse
+import csv
+import os
+import torch
+import torchvision.transforms as T
+from PIL import Image
+from tqdm import tqdm
+import math
+import numpy as np
+import time
+import csv
+import argparse
+import re
+import json
+
+# from byteplussdkarkruntime import Ark
+import bytedtos
+import requests
+from volcenginesdkarkruntime import Ark as VolcArk
+import traceback
+
+# TOS Settings
+bucket = ""
+accessKey = ""
+url_prefix = "" + bucket + "/"
+tos_client = bytedtos.Client(bucket, accessKey)
+
+
+def extract_scores_and_average(entry: str) -> float:
+ import re
+
+ pattern = r':\s*(\d+\.?\d*)'
+ matches = re.findall(pattern, entry)
+
+ scores = []
+ for match in matches:
+ try:
+ scores.append(float(match))
+ except ValueError:
+ continue
+
+ if scores:
+ return round(sum(scores) / len(scores), 2)
+ return None
+
+
+Global_Style = """\nYou are a data rater specializing in grading video style transfer edits. You will be given an input video, a reference style (image or video), and the styled result video. Your task is to evaluate the style transfer on a 5-point scale from three perspectives:\n\nStyle Fidelity\n1. Target style absent or clearly wrong.\n2. Style shows in a few areas/frames only, or mixed with unrelated styles.\n3. Key traits (palette, brushwork, texture) present but patchy or inconsistent across frames.\n4. Style reproduced well across almost the whole video; only small local or brief temporal mismatches.\n5. Full, faithful transfer: colour, texture, brushwork, and lighting all match the exemplar consistently over the entire duration and space of the video.\n\nContent Preservation\n1. Major objects, layout, or overall motion lost/distorted; original scene barely recognisable.\n2. Main subject recognisable, but its size, perspective, motion, or key parts are clearly wrong/missing.\n3. Overall structure and motion correct; some local warping, minor omissions, or slight motion jerkiness.\n4. Nearly all geometry and motion intact; only slight, non-distracting deformation.\n5. All objects, spatial relations, and motion are perfectly kept; only stylistic, harmless distortion.\n\nTemporal Stability\n1. Extreme flickering or "boiling" effects; the style is completely unstable frame-to-frame, making the video unwatchable.\n2. Significant and distracting flickering or temporal inconsistency in style application.\n3. Noticeable but tolerable flicker or texture "boiling", especially during motion.\n4. Largely stable with only minor, subtle flickering visible in areas of complex motion or fine texture.\n5. Perfectly stable and temporally coherent; the style appears "stuck" to the scene with no flickering.\n\nThe scores for Content Preservation and Temporal Stability should not be higher than the Style Fidelity score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the scores based on the criteria above, no more than 30 words.\nStyle Fidelity: A number from 1 to 5.\nContent Preservation: A number from 1 to 5.\nTemporal Stability: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Creative_Edit = """\nYou are a data rater specializing in grading instruction-following creative video edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the creative edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The instruction is completely ignored or the edit is irrelevant to the prompt.\n2 The edit attempts the instruction but fundamentally fails; the core subject, style, or action is wrong or only applied for a brief moment.\n3 The edit generally follows the instruction, but with major deviations in style, motion, or concept; the effect is highly inconsistent over time.\n4 The edit successfully executes the instruction with only minor inaccuracies in style, motion, or detail; the result is temporally consistent.\n5 The edit perfectly and creatively interprets and executes the instruction throughout the video's duration, fully achieving the intended creative goal.\n\nTemporal & Visual Coherence\n1 Massive flickering, strobing, or artifacts that make the video unwatchable; edited elements are completely disjointed from the scene.\n2 Obvious temporal inconsistency (e.g., style flickers on/off), clear visual boundaries or seams; mismatched color/lighting between frames.\n3 The edit is mostly stable, but with noticeable "boiling" or "shimmering" in textures/styles; minor jitter or softness on edges.\n4 The edit is very stable and well-integrated; only slight, hard-to-spot artifacts or flickering are present, motion is smooth.\n5 Perfectly stable and seamless integration; the edit feels like part of the original footage with no detectable flickering, jitter, or discontinuities.\n\nPhysical Plausibility & Detail Preservation\n1 Complete break from physical laws; added objects have no correct lighting/shadows, move unnaturally; original video details are heavily degraded.\n2 Major physical inconsistencies; shadows/reflections are static or move incorrectly; motion of edits doesn't match camera movement; original background is warped.\n3 Physics and lighting are generally believable but with minor flaws (e.g., a shadow is slightly off); unedited parts of the video are mostly preserved.\n4 Edited elements interact realistically with the scene's lighting, motion, and perspective; original video details are well-preserved.\n5 High degree of physical realism and integration; motion, lighting, and physics of the edits are indistinguishable from a real recording; original details are perfectly maintained.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nTemporal & Visual Coherence: A number from 1 to 5.\nPhysical Plausibility & Detail Preservation: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Camera_Edit = """\nYou are a data rater specializing in grading camera shot type alteration edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the camera shot change on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 The shot type is not changed, or changed to a completely wrong type (e.g., requested close-up, but got a long shot).\n2 The direction of the shot change is correct (e.g., zoomed in for a close-up), but the degree is wrong (e.g., a medium shot instead of a close-up).\n3 The shot type is generally correct, but the framing is poor, cutting off important parts of the subject or being poorly centered.\n4 The shot type and framing are correct, with only minor inaccuracies in composition.\n5 The video is perfectly transformed into the requested shot type (long, medium, or close-up) with ideal framing of the subject.\n\nVisual Quality & Stability\n1 Massive distortion, glitches, warping, or heavy noise; the edited video is unusable.\n2 Significant and distracting jitter, shimmering, or warping is visible throughout the video, making the shot feel unstable.\n3 Minor but noticeable visual flaws, such as slight edge distortion or a subtle "breathing" effect in the frame.\n4 The video is stable and clear, with only very slight, almost unnoticeable artifacts upon close inspection.\n5 The resulting shot is perfectly stable and clear, with no digital artifacts, distortion, or jitter. It looks as if it were originally filmed with that shot type.\n\nConsistency & Detail Fidelity\n1 The subject, background, or action in the edited video is completely different from the original video; a total failure of consistency.\n2 The main subject is the same, but their action, the background, or the lighting is drastically and illogically changed compared to the original video.\n3 The scene is generally consistent, but there are noticeable continuity errors (e.g., an object disappears, the subject's pose changes unnaturally).\n4 The subject, action, and environment are highly consistent with the original video. Original details are well-preserved with only minor, hard-to-spot discrepancies.\n5 Perfect consistency; the edited video perfectly preserves the subject, lighting, background, and continuity of action from the original video, creating the illusion of the same scene captured from a different camera position.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Quality & Stability: A number from 1 to 5.\nConsistency & Detail Fidelity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Change = """\nYou are a data rater specializing in grading video replacement edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the replacement editing effect on a 5-point scale from three perspectives, paying close attention to temporal consistency (how the edit holds up over time and with motion).\n\nPrompt Compliance\n1 Target not replaced, or an unrelated object/part of the video edited.\n2 Only part of the target replaced (e.g., in only a few frames), or wrong class/description used.\n3 Target largely replaced but other objects altered, remnants visible across frames, or count/position clearly wrong.\n4 Correct object fully replaced for the entire duration; only minor attribute errors (colour, size, etc.).\n5 Perfect replacement: all and only the specified objects replaced for the entire duration; new objects’ class, number, position, scale, pose, motion and detail exactly match the prompt.\n\nVisual Naturalness & Temporal Stability\n1 Video heavily broken or new object deformed / flickers uncontrollably / jitters erratically.\n2 Obvious seams/edges that flicker or move unnaturally; strong mismatch in resolution or colour that is inconsistent across frames; background not restored or is unstable.\n3 Basic style similar, but lighting or palette clashes are inconsistent as the video plays; fuzzy edges, noise or minor flickering/jittering are noticeable.\n4 Style almost uniform and stable; tiny temporal artefacts (e.g., edge shimmer) visible only on close, frame-by-frame inspection; casual viewers see no edit.\n5 Completely seamless and temporally stable; new objects blend fully with the scene in every frame, edit area undetectable.\n\nPhysical & Motion Integrity\n1 Floating or sliding unnaturally (poor motion tracking), severe perspective/light errors inconsistent with camera/object movement; background heavily warped or unstable.\n2 Missing or static shadows/reflections that do not move with the object/light; poor occlusion; new object’s motion clearly mismatches scene motion.\n3 Lighting, perspective and interactions mostly correct but with minor inconsistencies over time; motion tracking has small, tolerable drifts.\n4 New object's motion is well-tracked and it interacts realistically with the scene (shadows, reflections) and preserves existing details throughout the video.\n5 Physically and dynamically flawless: motion, perspective, shadows, and reflections are perfectly integrated and move correctly with the scene and camera in every frame; background untouched and stable.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual Naturalness & Temporal Stability: A number from 1 to 5.\nPhysical & Motion Integrity: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Background_Change = """\nYou are a data rater specializing in grading video background editing. You will be given two videos (before and after editing) and the editing instruction. Your task is to evaluate the background change on a 5-point scale from three perspectives:\n\nInstruction Compliance\n1 No change, or background unrelated to prompt, or foreground also replaced/distorted.\n2 Background partly replaced or wrong style/content; foreground noticeably altered.\n3 Main background replaced but elements missing/extra, or faint spill onto subject edges.\n4 Requested background fully present; foreground intact except minute artefacts or small prompt mismatch (e.g. colour tone).\n5 Background exactly matches prompt (content, style, placement); all foreground pixels untouched.\n\nVisual & Temporal Seamlessness (Edge, Blend & Stability)\n1 Large tearing, posterisation, or significant temporal artifacts like flickering, jittering edges; edit area obvious at a glance.\n2 Clear cut-out halos, colour-resolution gap, or obvious edge 'boiling' (instability) over time.\n3 Blend acceptable but visible on closer look: slight edge blur, or minor temporal instability (e.g., shimmer).\n4 Nearly invisible seams; edges are stable across motion, textures aligned, only minor issues when zoomed in.\n5 Indistinguishable composite: edges, textures, resolution and colour grading are perfectly continuous and stable throughout the video's duration.\n\nPhysical Consistency (Lighting, Perspective, Motion & Depth)\n1 Severe mismatch: wrong horizon, conflicting light, floating subject, or background remains static during camera movement (no parallax).\n2 Noticeable inconsistencies in light or scale; incorrect perspective shifts during motion.\n3 Overall believable; small errors in shadow, perspective, or minor motion tracking flaws.\n4 Lighting, scale, and depth well matched; background perspective and scale track convincingly with camera motion.\n5 Physically flawless: foreground and new background share coherent light, shadows, perspective, and atmospheric depth throughout all subject and camera motion, enhancing overall realism.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nInstruction Compliance: A number from 1 to 5.\nVisual & Temporal Seamlessness: A number from 1 to 5.\nPhysical Consistency: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+Local_Remove = """\nYou are a data rater specializing in grading video object removal editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class removed, or target only partially removed, or an unrelated object is also removed.\n3 Correct object removed, but with significant errors: unintended objects are also removed, OR significant fragments/ghosting of the target remain.\n4 The correct object is removed; only minor issues like a few tiny fragments remaining or tiny, unintended background items being affected.\n5 Perfect: All and only the requested objects are removed as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious erase marks or "smudges"; the inpainted background's style, resolution, or palette strongly mismatches; the edited region jitters or appears static against a moving background.\n3 General style is similar, but the inpainted background's lighting/colours clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the removed area or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the removal is temporally stable and visually indistinguishable from a clean background.\n\nPhysical & Detail Coherence\n1 Key original elements are blocked by poor inpainting; the background is heavily distorted or hallucinates incorrect structures; motion is completely wrong (e.g., a static patch in a moving scene).\n2 The inpainted background visibly shifts, jitters, or is poorly reconstructed over time, failing to match the original scene's motion.\n3 Background reconstruction is mostly correct and consistent; remaining flaws are small and acceptable; background changes are localized and stable.\n4 No loss of original detail around the removed area; background reconstruction is clean, stable, and respects the scene's geometry and motion.\n5 The background is essentially untouched and stable; the inpainted area perfectly matches the surrounding content's motion, texture, and detail over time.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Local_Add = """\nYou are a data rater specializing in grading video object addition editing. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the edit quality on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 No edit performed, the video is corrupted, or the edit is completely wrong.\n2 Wrong object/class added, or target only partially added, or an unrelated object is also added.\n3 Correct object added, but with significant errors: key attributes (e.g., position, colour, count, size) are wrong.\n4 The correct object is added with main attributes correct; only minor details are off (e.g., slight colour mismatch, minor position error).\n5 Perfect: All and only the requested objects are added as instructed; every other element is untouched.\n\nVisual & Temporal Naturalness\n1 Video is badly broken, full of artefacts, or shows severe flickering/jittering throughout.\n2 Obvious paste marks; style, resolution, or palette of the added object strongly mismatches; the added region jitters or appears static against a moving background.\n3 General style is similar, but lighting/colours on the added object clearly clash or are inconsistent across frames; noticeable temporal disharmony.\n4 Style is almost uniform; minor edge issues around the added object or slight temporal instability (e.g., minor flicker) visible only on close inspection.\n5 Perfectly seamless; the edit is temporally stable and visually indistinguishable from the original video's content and motion.\n\nPhysical & Detail Coherence\n1 Severe physical errors (e.g., the added object floats, has wrong perspective/lighting); key original elements are blocked; motion of the added object is completely wrong.\n2 Contact with surfaces, occlusion by other objects, or motion of the added object is handled poorly.\n3 Lighting, perspective, and motion of the added object are mostly correct and consistent with the scene; remaining flaws are small and acceptable.\n4 Shadows, reflections, and material response from the added object are believable and move correctly with the scene; no loss of original detail.\n5 Edit enhances overall realism: the added object has precise highlights, shadows, and motion effects that are temporally coherent and perfectly integrated.\n\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nVisual & Temporal Naturalness: A number from 1 to 5.\nPhysical & Detail Coherence: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:"""
+Subtitle_Edit = """"\nYou are a data rater specializing in grading instruction-following subtitle edits. You will be given two videos (before and after editing) and the corresponding editing instructions. Your task is to evaluate the subtitle edit on a 5-point scale from three perspectives:\n\nPrompt Compliance\n1 Target subtitle not added/removed/replaced, or wrong subtitle affected.\n2 Right action (add/remove/replace) but with incorrect content; only part of the edit is done; other subtitles are also altered.\n3 Mainly correct action and content, yet with significant spelling/grammar errors, or minor unintended edits to other subtitles.\n4 Correct action performed on the right subtitle; content is correct with only minor inaccuracies (e.g., small typos, punctuation errors).\n5 Exactly and only the requested subtitle(s) are added/removed/replaced; content matches the prompt perfectly; zero unintended edits.\n\nSubtitle Attribute Fidelity\n1 Completely fails to follow specified attributes (e.g., wrong position, wrong color). If attributes are not specified, the chosen ones make the subtitle unreadable or are extremely disruptive.\n2 Major deviation from specified attributes (e.g., requested bottom, placed on top). If not specified, chosen attributes are clearly wrong and distracting (e.g., obscures key visuals).\n3 Follows the general direction of specified attributes but with significant errors (e.g., correct side but wrong exact position). If not specified, chosen attributes are acceptable but noticeably inconsistent.\n4 Follows specified attributes with only minor inaccuracies (e.g., slightly off-center, minor deviation in font/color). If not specified, chosen attributes are highly appropriate with only minor flaws.\n5 All specified attributes (position, font, color, etc.) are matched perfectly. If attributes are not specified, the chosen ones are perfectly consistent with existing subtitles or professional standards.\n\nIntegrity of Unedited Content\n1 Massive collateral damage: background video is heavily corrupted/glitched, or other non-target subtitles are wrongly deleted/altered.\n2 Noticeable collateral damage: visible artifacts, distortion, or color shifts in the background video; other subtitles are visibly affected.\n3 Minor unintended effects: slight and localized visual artifacts in the background, or minor, non-critical changes to adjacent subtitles' appearance/timing.\n4 Almost perfect preservation: only extremely subtle artifacts in the video frame, visible only upon close inspection; all other subtitles are untouched.\n5 Perfect preservation: the edit is perfectly isolated; the background video and all other subtitles remain 100% identical to the original, with zero unintended changes.\nThe second and third score should no higher than first score!!!\n\nExample Response Format:\nBrief reasoning: A short explanation of the score based on the criteria above, no more than 20 words.\nPrompt Compliance: A number from 1 to 5.\nSubtitle Attribute Fidelity: A number from 1 to 5.\nIntegrity of Unedited Content: A number from 1 to 5.\nediting instruction is : .\n\nBelow are the videos before and after editing:\n"""
+
+
+def save_tos(content, object_name, overwrite=True):
+ try:
+ tos_client.put_object(object_name, content)
+ url = url_prefix + object_name
+ except Exception as e:
+ raise RuntimeError("Upload obj to tos error")
+ return url
+
+def save_video_url_to_tos(fpath, output_name, overwrite=True):
+ with open(fpath, 'rb') as f:
+ video_content = f.read()
+ final_video_url = save_tos(video_content, output_name, overwrite=overwrite)
+ return final_video_url
+
+
+def call_doubao_model(original_video_url, edited_video_url, prompt):
+ client = VolcArk(
+ base_url="",
+ api_key="",
+ )
+
+ max_retries = 5
+ retry_count = 0
+
+ while retry_count < max_retries:
+ try:
+ response = client.chat.completions.create(
+ model="ep-20250730194856-r7z7s",
+ messages=[
+ {
+ "role": "system",
+ "content": prompt.strip()
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "video_url",
+ "video_url": {
+ "url": original_video_url,
+ "fps": 2,
+ }
+ },
+ {
+ "type": "video_url",
+ "video_url": {
+ "url": edited_video_url,
+ "fps": 2,
+ }
+ },
+ ]
+ }
+ ],
+ )
+
+ result = response.choices[0].message.content
+ if retry_count > 0:
+ print(f"Doubao call succeeded, retried {retry_count} times.")
+ return result
+
+ except Exception as e:
+ error_msg = f"An error occurred while calling the Doubao model.: {e}"
+ print(f"Full traceback: {traceback.format_exc()}")
+ print(f"Retry for {retry_count + 1}th time: {error_msg}")
+ retry_count += 1
+ if retry_count >= max_retries:
+ print(error_msg)
+ return f"ERROR: {e}"
+ time.sleep(60)
+
+
+def process_csv(input_csv_path, output_csv_path, root_path, edited_video_path="edited_result_path",):
+ start = time.time()
+
+ all_scores_by_type = {}
+ all_scores = []
+
+ with open(input_csv_path, 'r', encoding='utf-8-sig') as infile, \
+ open(output_csv_path, 'w', encoding='utf-8', newline='') as outfile:
+
+ reader = csv.DictReader(infile)
+ writer = csv.writer(outfile, delimiter=',')
+
+ header = reader.fieldnames
+ writer.writerow(header + ['results', 'average'])
+
+
+ for row_idx, row in enumerate(tqdm(reader, desc=f"Processing {os.path.basename(input_csv_path)}")):
+ try:
+
+ edited_type = row.get('edited_type', '')
+ prompt = row.get('prompt', '')
+ original_video = row.get('original_video', '')
+ edited_result_path = row.get(edited_video_path, '')
+
+ original_video = os.path.join(root_path, original_video)
+
+ if not os.path.exists(edited_result_path):
+ print(f"Warning: The edited video file does not exist. {edited_result_path}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {edited_result_path}", "ERROR"])
+ continue
+
+ if not os.path.exists(original_video):
+ print(f"Warning: The original_video file does not exist.: {original_video}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: Video file not found: {original_video}", "ERROR"])
+ continue
+
+ if edited_type == "global_style":
+ system_prompt = Global_Style
+ elif edited_type == "local_change":
+ system_prompt = Local_Change
+ elif edited_type == "background_change":
+ system_prompt = Background_Change
+ elif edited_type == "subtitle_edit":
+ system_prompt = Subtitle_Edit
+ elif edited_type == "local_remove":
+ system_prompt = Local_Remove
+ elif edited_type == "local_add":
+ system_prompt = Local_Add
+ elif edited_type == "creative_edit":
+ system_prompt = Creative_Edit
+ elif edited_type == "camera_edit":
+ system_prompt = Camera_Edit
+ else:
+ raise ValueError("Invalid edit type")
+
+ full_system_prompt = system_prompt.replace('', prompt)
+
+ original_video_name = f"original_video_{int(time.time())}_{row_idx}.mp4"
+ edited_video_name = f"edited_video_{int(time.time())}_{row_idx}.mp4"
+
+ original_video_url = save_video_url_to_tos(original_video, original_video_name)
+ edited_video_url = save_video_url_to_tos(edited_result_path, edited_video_name)
+
+ print(f"Video upload complete: {original_video_name}, {edited_video_name}")
+
+ print(f"The Seed1.6VL model is being used for evaluation.... (row {row_idx + 1})")
+ response = call_doubao_model(original_video_url, edited_video_url, full_system_prompt)
+
+ formatted_response = response.replace('\n', '\\n')
+
+ # Calculate the average value
+ average_score = extract_scores_and_average(response)
+
+ # Write the original data, results, and average value onto a new line
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [formatted_response, average_score])
+
+ # Record the scores for subsequent statistics
+ if average_score is not None:
+ all_scores.append(average_score)
+
+ # Grouped by editing type
+ if edited_type not in all_scores_by_type:
+ all_scores_by_type[edited_type] = []
+ all_scores_by_type[edited_type].append(average_score)
+
+ except Exception as e:
+ print(f"\nError: An error occurred while processing row {row}: {e}")
+ original_row = [row.get(col, '') for col in header]
+ writer.writerow(original_row + [f"ERROR: {e}", "ERROR"])
+
+ # Calculate the average score for different editing types (only scores in the range of 1-5 are counted).
+ type_averages = {}
+ for edited_type, scores in all_scores_by_type.items():
+ valid_scores = [score for score in scores if 1 <= score <= 5]
+ if valid_scores:
+ type_averages[edited_type] = round(sum(valid_scores) / len(valid_scores), 2)
+ else:
+ type_averages[edited_type] = None
+
+ # Calculate the overall average score (only scores in the range of 1-5 are counted).
+ overall_average = None
+ valid_all_scores = [score for score in all_scores if 1 <= score <= 5]
+ if valid_all_scores:
+ overall_average = round(sum(valid_all_scores) / len(valid_all_scores), 2)
+
+ # Save the statistical results to a JSON file
+ stats_output_path = output_csv_path.replace('.csv', '_stats.json')
+ stats_data = {
+ "overall_average": overall_average,
+ "type_averages": type_averages,
+ "total_processed": len(all_scores),
+ "total_valid_scores": len(valid_all_scores),
+ "breakdown_by_type": {}
+ }
+
+ # Calculate detailed statistics for each type
+ for k, v in all_scores_by_type.items():
+ valid_scores_for_type = [score for score in v if 1 <= score <= 5]
+ stats_data["breakdown_by_type"][k] = {
+ "count": len(valid_scores_for_type),
+ "average": round(sum(valid_scores_for_type) / len(valid_scores_for_type), 2) if valid_scores_for_type else None,
+ "original_count": len(v),
+ "invalid_count": len(v) - len(valid_scores_for_type) # Number of invalid data
+ }
+
+ with open(stats_output_path, 'w', encoding='utf-8') as f:
+ json.dump(stats_data, f, ensure_ascii=False, indent=2)
+
+ print(f"\nProcessing complete! Results saved to: {output_csv_path}")
+ print(f"Statistical results saved to: {stats_output_path}")
+ print(f"Average score for each editing type: {type_averages}")
+ print(f"Overall average score: {overall_average}")
+ print(f'Time for total: {time.time()-start} seconds')
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Use the Seed 1.6 VL model to process video and prompt CSV files.")
+ parser.add_argument("--input_csv", type=str, default="benchmark/your_model_out.csv", help="The path to the input CSV file.")
+ parser.add_argument("--root_path", type=str, default="yours_OpenVE-Bench_path", help="The path to the OpenVE-Bench videos.")
+ parser.add_argument("--output_csv", type=str, default="benchmark/your_model_out_seed.csv", help="The path to the output CSV file.")
+ args = parser.parse_args()
+
+ output_dir = os.path.dirname(args.output_csv)
+ if output_dir:
+ os.makedirs(output_dir, exist_ok=True)
+
+ process_csv(args.input_csv, args.output_csv, args.root_path, edited_video_path="edited_result_path")
\ No newline at end of file