Ouzhang commited on
Commit
8a5d8ba
·
verified ·
1 Parent(s): 86dd31e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Helios-main/eval/6_get_drifting_motion_smoothness.py +336 -0
  2. Helios-main/eval/checkpoints/get_checkpoints.sh +1 -0
  3. Helios-main/eval/playground/helios_t2v_prompts.csv +0 -0
  4. Helios-main/eval/utils/convert_json_to_excel.py +136 -0
  5. Helios-main/eval/utils/extract_short_from_long.py +97 -0
  6. Helios-main/eval/utils/third_party/ViCLIP/__init__.py +0 -0
  7. Helios-main/eval/utils/third_party/ViCLIP/simple_tokenizer.py +147 -0
  8. Helios-main/eval/utils/third_party/ViCLIP/viclip.py +216 -0
  9. Helios-main/eval/utils/third_party/ViCLIP/viclip_text.py +260 -0
  10. Helios-main/eval/utils/third_party/ViCLIP/viclip_vision.py +364 -0
  11. Helios-main/eval/utils/third_party/amt/LICENSE +176 -0
  12. Helios-main/eval/utils/third_party/amt/README.md +167 -0
  13. Helios-main/eval/utils/third_party/amt/__init__.py +0 -0
  14. Helios-main/eval/utils/third_party/amt/benchmarks/__init__.py +0 -0
  15. Helios-main/eval/utils/third_party/amt/benchmarks/adobe240.py +65 -0
  16. Helios-main/eval/utils/third_party/amt/benchmarks/gopro.py +65 -0
  17. Helios-main/eval/utils/third_party/amt/benchmarks/snu_film.py +76 -0
  18. Helios-main/eval/utils/third_party/amt/benchmarks/speed_parameters.py +41 -0
  19. Helios-main/eval/utils/third_party/amt/benchmarks/ucf101.py +63 -0
  20. Helios-main/eval/utils/third_party/amt/benchmarks/vimeo90k.py +75 -0
  21. Helios-main/eval/utils/third_party/amt/benchmarks/vimeo90k_tta.py +76 -0
  22. Helios-main/eval/utils/third_party/amt/datasets/__init__.py +0 -0
  23. Helios-main/eval/utils/third_party/amt/datasets/adobe_datasets.py +77 -0
  24. Helios-main/eval/utils/third_party/amt/datasets/gopro_datasets.py +213 -0
  25. Helios-main/eval/utils/third_party/amt/datasets/vimeo_datasets.py +168 -0
  26. Helios-main/eval/utils/third_party/amt/docs/develop.md +239 -0
  27. Helios-main/eval/utils/third_party/amt/docs/method.md +126 -0
  28. Helios-main/eval/utils/third_party/amt/environment.yaml +19 -0
  29. Helios-main/eval/utils/third_party/amt/losses/__init__.py +0 -0
  30. Helios-main/eval/utils/third_party/amt/losses/loss.py +201 -0
  31. Helios-main/eval/utils/third_party/amt/metrics/__init__.py +0 -0
  32. Helios-main/eval/utils/third_party/amt/metrics/psnr_ssim.py +142 -0
  33. Helios-main/eval/utils/third_party/amt/networks/AMT-G.py +156 -0
  34. Helios-main/eval/utils/third_party/amt/networks/AMT-L.py +140 -0
  35. Helios-main/eval/utils/third_party/amt/networks/AMT-S.py +139 -0
  36. Helios-main/eval/utils/third_party/amt/networks/IFRNet.py +153 -0
  37. Helios-main/eval/utils/third_party/amt/networks/__init__.py +0 -0
  38. Helios-main/eval/utils/third_party/amt/scripts/train.sh +6 -0
  39. Helios-main/eval/utils/third_party/amt/train.py +69 -0
  40. Helios-main/eval/utils/third_party/amt/trainers/__init__.py +0 -0
  41. Helios-main/eval/utils/third_party/amt/trainers/base_trainer.py +248 -0
  42. Helios-main/eval/utils/third_party/amt/trainers/logger.py +62 -0
  43. Helios-main/eval/utils/third_party/amt/utils/__init__.py +0 -0
  44. Helios-main/eval/utils/third_party/amt/utils/build_utils.py +17 -0
  45. Helios-main/eval/utils/third_party/amt/utils/dist_utils.py +48 -0
  46. Helios-main/eval/utils/third_party/amt/utils/flow_utils.py +126 -0
  47. Helios-main/eval/utils/third_party/amt/utils/utils.py +315 -0
  48. Helios-main/eval/utils/utils.py +297 -0
  49. Helios-main/helios/diffusers_version/__init__.py +0 -0
  50. Helios-main/helios/diffusers_version/pipeline_helios_diffusers.py +1359 -0
Helios-main/eval/6_get_drifting_motion_smoothness.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import json
4
+ import os
5
+ import re
6
+
7
+ import cv2
8
+ import numpy as np
9
+ import pandas as pd
10
+ import torch
11
+ from omegaconf import OmegaConf
12
+ from tqdm import tqdm
13
+
14
+ from utils.third_party.amt.utils.build_utils import build_from_cfg
15
+ from utils.third_party.amt.utils.utils import InputPadder, check_dim_and_resize, img2tensor, tensor2img
16
+ from utils.utils import align_dimension
17
+
18
+
19
+ # Percentage of frames to use for start/end portions
20
+ DRIFT_RATIO = 0.15
21
+
22
+
23
+ class FrameProcess:
24
+ def __init__(self, height=384, width=640):
25
+ self.height = height
26
+ self.width = width
27
+
28
+ def get_frames(self, video_path):
29
+ """Extract frames from MP4 video"""
30
+ frame_list = []
31
+ video = cv2.VideoCapture(video_path)
32
+
33
+ original_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
34
+ original_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
35
+ original_aspect_ratio = original_width / original_height
36
+
37
+ if self.width > self.height:
38
+ target_width = self.width
39
+ target_height = int(self.width / original_aspect_ratio)
40
+ else:
41
+ target_height = self.height
42
+ target_width = int(self.height * original_aspect_ratio)
43
+
44
+ target_height = align_dimension(target_height, 2)
45
+ target_width = align_dimension(target_width, 2)
46
+
47
+ while video.isOpened():
48
+ success, frame = video.read()
49
+ if success:
50
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
51
+ frame = cv2.resize(frame, (target_width, target_height))
52
+ frame_list.append(frame)
53
+ else:
54
+ break
55
+ video.release()
56
+ assert frame_list != [], "No frames extracted from video"
57
+ return frame_list
58
+
59
+ def extract_frame(self, frame_list, start_from=0):
60
+ extract = []
61
+ for i in range(start_from, len(frame_list), 2):
62
+ extract.append(frame_list[i])
63
+ return extract
64
+
65
+
66
+ class MotionSmoothnessEvaluator:
67
+ def __init__(self, config, ckpt, height=384, width=640, device="cuda"):
68
+ self.device = device
69
+ self.config = config
70
+ self.ckpt = ckpt
71
+ self.niters = 1
72
+ self.height = height
73
+ self.width = width
74
+ self.initialization()
75
+ self.load_model()
76
+
77
+ def load_model(self):
78
+ """Load AMT model"""
79
+ cfg_path = self.config
80
+ ckpt_path = self.ckpt
81
+ network_cfg = OmegaConf.load(cfg_path).network
82
+ network_name = network_cfg.name
83
+ print(f"Loading [{network_name}] from [{ckpt_path}]...")
84
+
85
+ self.model = build_from_cfg(network_cfg)
86
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
87
+ self.model.load_state_dict(ckpt["state_dict"])
88
+ self.model = self.model.to(self.device)
89
+ self.model.eval()
90
+
91
+ def initialization(self):
92
+ """Initialize parameters based on device"""
93
+ if self.device.type == "cuda":
94
+ self.anchor_resolution = 1024 * 512
95
+ self.anchor_memory = 1500 * 1024**2
96
+ self.anchor_memory_bias = 2500 * 1024**2
97
+ self.vram_avail = torch.cuda.get_device_properties(self.device).total_memory
98
+ else:
99
+ self.anchor_resolution = 8192 * 8192
100
+ self.anchor_memory = 1
101
+ self.anchor_memory_bias = 0
102
+ self.vram_avail = 1
103
+
104
+ self.embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(self.device)
105
+ self.fp = FrameProcess(height=self.height, width=self.width)
106
+
107
+ def compute_motion_score_on_frames(self, frames):
108
+ """Calculate motion smoothness score for a list of frames"""
109
+ if len(frames) < 4:
110
+ return 0.0
111
+
112
+ frame_list = self.fp.extract_frame(frames, start_from=0)
113
+ if len(frame_list) < 2:
114
+ return 0.0
115
+
116
+ # Convert to tensors
117
+ inputs = [img2tensor(frame).to(self.device) for frame in frame_list]
118
+
119
+ inputs = check_dim_and_resize(inputs)
120
+ h, w = inputs[0].shape[-2:]
121
+ scale = (
122
+ self.anchor_resolution
123
+ / (h * w)
124
+ * np.sqrt((self.vram_avail - self.anchor_memory_bias) / self.anchor_memory)
125
+ )
126
+ scale = 1 if scale > 1 else scale
127
+ scale = 1 / np.floor(1 / np.sqrt(scale) * 16) * 16
128
+
129
+ padding = int(16 / scale)
130
+ padder = InputPadder(inputs[0].shape, padding)
131
+ inputs = padder.pad(*inputs)
132
+
133
+ # Frame interpolation
134
+ iters = int(self.niters)
135
+ for i in range(iters):
136
+ outputs = [inputs[0]]
137
+ for in_0, in_1 in zip(inputs[:-1], inputs[1:]):
138
+ in_0 = in_0.to(self.device)
139
+ in_1 = in_1.to(self.device)
140
+ with torch.no_grad():
141
+ imgt_pred = self.model(in_0, in_1, self.embt, scale_factor=scale, eval=True)["imgt_pred"]
142
+ outputs += [imgt_pred.cpu(), in_1.cpu()]
143
+ inputs = outputs
144
+
145
+ # Calculate VFI score
146
+ outputs = padder.unpad(*outputs)
147
+ outputs = [tensor2img(out) for out in outputs]
148
+ vfi_score = self.vfi_score(frames, outputs)
149
+ norm = (255.0 - vfi_score) / 255.0
150
+
151
+ return norm
152
+
153
+ def vfi_score(self, ori_frames, interpolate_frames):
154
+ """Calculate video frame interpolation quality score"""
155
+ ori = self.fp.extract_frame(ori_frames, start_from=1)
156
+ interpolate = self.fp.extract_frame(interpolate_frames, start_from=1)
157
+
158
+ scores = []
159
+ min_len = min(len(ori), len(interpolate))
160
+ for i in range(min_len):
161
+ scores.append(self.get_diff(ori[i], interpolate[i]))
162
+
163
+ if len(scores) == 0:
164
+ return 0.0
165
+ return np.mean(np.array(scores))
166
+
167
+ def get_diff(self, img1, img2):
168
+ """Calculate absolute difference between two images"""
169
+ img = cv2.absdiff(img1, img2)
170
+ return np.mean(img)
171
+
172
+ def evaluate_drifting(self, video_path):
173
+ """
174
+ Evaluate drifting motion smoothness for a single video.
175
+ Returns: (drift_score, start_score, end_score)
176
+ """
177
+ frames = self.fp.get_frames(video_path)
178
+ total_frames = len(frames)
179
+ num_drift_frames = max(4, int(total_frames * DRIFT_RATIO)) # Need at least 4 frames for AMT
180
+
181
+ # Extract start and end portions
182
+ start_frames = frames[:num_drift_frames]
183
+ end_frames = frames[-num_drift_frames:]
184
+
185
+ # Calculate scores for each portion
186
+ start_score = self.compute_motion_score_on_frames(start_frames)
187
+ end_score = self.compute_motion_score_on_frames(end_frames)
188
+
189
+ # Calculate drift as absolute difference
190
+ drift_score = abs(start_score - end_score)
191
+
192
+ return drift_score, start_score, end_score
193
+
194
+
195
+ def main(args):
196
+ baseline_name = os.path.basename(args.video_dir)
197
+ output_path = os.path.join(args.output_path, baseline_name)
198
+ output_json_path = os.path.join(output_path, "drifting_motion_smoothness_results.json")
199
+
200
+ # Set device
201
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
202
+ print(f"Using device: {device}")
203
+
204
+ # Load CSV file
205
+ if not os.path.exists(args.input_csv):
206
+ raise FileNotFoundError(f"CSV file not found: {args.input_csv}")
207
+
208
+ df = pd.read_csv(args.input_csv)
209
+ df_dict = df.set_index("id").to_dict("index")
210
+
211
+ # Validate CSV columns
212
+ required_columns = ["id", "duration"]
213
+ for col in required_columns:
214
+ if col not in df.columns:
215
+ raise ValueError(f"CSV must contain '{col}' column. Found columns: {df.columns.tolist()}")
216
+
217
+ # Load existing results if available
218
+ existing_results = {}
219
+ if os.path.exists(output_json_path):
220
+ print(f"Found existing results at {output_json_path}, loading...")
221
+ with open(output_json_path, "r") as f:
222
+ existing_data = json.load(f)
223
+ for item in existing_data.get("per_video_results", []):
224
+ existing_results[item["id"]] = item
225
+ print(f"Loaded {len(existing_results)} existing results")
226
+
227
+ # Get video files
228
+ video_files = glob.glob(os.path.join(args.video_dir, "*_*_ori*.mp4"))
229
+ video_files.sort(key=lambda x: int(re.search(r"(\d+)_", os.path.basename(x)).group(1)))
230
+ print(f"\nFound {len(video_files)} videos in directory")
231
+
232
+ # Check which videos need processing
233
+ results = []
234
+ drift_scores = []
235
+ videos_to_process = []
236
+
237
+ for video_path in video_files:
238
+ video_name = os.path.basename(video_path)
239
+ parts = video_name.replace(".mp4", "").split("_")
240
+ video_id = int(parts[0])
241
+
242
+ if video_id not in df_dict:
243
+ print(f"Warning: Video {video_name} (id={video_id}) not found in CSV, skipping")
244
+ continue
245
+
246
+ # Check if already processed
247
+ if video_id in existing_results:
248
+ # Use existing result
249
+ results.append(existing_results[video_id])
250
+ drift_scores.append(existing_results[video_id]["drift_motion_smoothness_score"])
251
+ else:
252
+ # Need to process
253
+ videos_to_process.append((video_path, video_id, video_name))
254
+
255
+ print(f"Already processed: {len(existing_results)} videos")
256
+ print(f"Need to process: {len(videos_to_process)} videos")
257
+
258
+ # Process remaining videos
259
+ if videos_to_process:
260
+ # Load model
261
+ print("Loading AMT model...")
262
+ evaluator = MotionSmoothnessEvaluator(
263
+ args.config, args.smoothness_model_path, height=args.height, width=args.width, device=device
264
+ )
265
+
266
+ print("\nEvaluating remaining videos...")
267
+ for video_path, video_id, video_name in tqdm(videos_to_process):
268
+ try:
269
+ drift_score, start_score, end_score = evaluator.evaluate_drifting(video_path)
270
+
271
+ result_item = {
272
+ "id": video_id,
273
+ "video_name": video_name,
274
+ "drift_motion_smoothness_score": float(drift_score),
275
+ "start_motion_smoothness_score": float(start_score),
276
+ "end_motion_smoothness_score": float(end_score),
277
+ }
278
+ results.append(result_item)
279
+ drift_scores.append(drift_score)
280
+
281
+ except Exception as e:
282
+ print(f"Error processing {video_name}: {str(e)}")
283
+ continue
284
+ else:
285
+ print("No videos to process. Skipping evaluation.")
286
+ return
287
+
288
+ # Sort all results by video_id
289
+ results_sorted = sorted(results, key=lambda x: x["id"])
290
+
291
+ # Calculate overall metrics
292
+ if drift_scores:
293
+ avg_drift = sum(drift_scores) / len(drift_scores)
294
+
295
+ output = {
296
+ "metric": "drifting_motion_smoothness",
297
+ "description": f"Start-end contrast of motion smoothness (first/last {DRIFT_RATIO * 100:.0f}% frames)",
298
+ "average_drift_score": avg_drift,
299
+ "num_videos": len(drift_scores),
300
+ "per_video_results": results_sorted,
301
+ }
302
+
303
+ # Save results
304
+ os.makedirs(output_path, exist_ok=True)
305
+ with open(output_json_path, "w") as f:
306
+ json.dump(output, f, indent=2)
307
+
308
+ print(f"\n{'=' * 60}")
309
+ print("Results Summary:")
310
+ print(f"{'=' * 60}")
311
+ print(f"Average Drifting Motion Smoothness Score: {avg_drift:.4f}")
312
+ print("(Lower is better - indicates less motion quality drift)")
313
+ print(f"Number of videos evaluated: {len(drift_scores)}")
314
+ print(f"Results saved to: {output_json_path}")
315
+ print(f"{'=' * 60}\n")
316
+ else:
317
+ print("No videos were successfully evaluated!")
318
+
319
+
320
+ if __name__ == "__main__":
321
+ parser = argparse.ArgumentParser(description="Evaluate drifting motion smoothness using AMT model")
322
+
323
+ # Input/Output arguments
324
+ parser.add_argument("--height", type=str, default=384)
325
+ parser.add_argument("--width", type=str, default=640)
326
+ parser.add_argument("--input_csv", type=str, default="playground/helios_t2v_prompts.csv")
327
+ parser.add_argument("--video_dir", type=str, default="playground/toy-video")
328
+ parser.add_argument("--output_path", type=str, default="playground/results")
329
+
330
+ # Model arguments
331
+ parser.add_argument("--config", type=str, default="checkpoints/AMT-S.yaml")
332
+ parser.add_argument("--smoothness_model_path", type=str, default="checkpoints/amt_model/amt-s.pth")
333
+
334
+ args = parser.parse_args()
335
+
336
+ main(args)
Helios-main/eval/checkpoints/get_checkpoints.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ hf download BestWishYsh/HeliosBench-Weights --local-dir ./
Helios-main/eval/playground/helios_t2v_prompts.csv ADDED
The diff for this file is too large to render. See raw diff
 
Helios-main/eval/utils/convert_json_to_excel.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+ import pandas as pd
5
+
6
+
7
+ CUSTOM_ORDER = [
8
+ "total_weighted_rating",
9
+ "aesthetic",
10
+ "motion_amplitude",
11
+ "motion_smoothness",
12
+ "semantic",
13
+ "naturalness",
14
+ "drifting_aesthetic",
15
+ "drifting_motion_smoothness",
16
+ "drifting_semantic",
17
+ "drifting_naturalness",
18
+ ]
19
+
20
+ SELECTED_METRICS = [
21
+ "total_weighted_rating",
22
+ "aesthetic",
23
+ "motion_amplitude",
24
+ "motion_smoothness",
25
+ "semantic",
26
+ "naturalness",
27
+ ]
28
+
29
+
30
+ def json_to_excel(json_path, excel_path=None, use_selected_metrics=False, show_raw_values=False, score_type=""):
31
+ with open(json_path, "r") as f:
32
+ data = json.load(f)
33
+
34
+ models_data = data["models"]
35
+ df = pd.DataFrame.from_dict(models_data, orient="index")
36
+
37
+ df.reset_index(inplace=True)
38
+ df.rename(columns={"index": "model_name"}, inplace=True)
39
+
40
+ if use_selected_metrics:
41
+ available_cols = ["model_name"] + [col for col in SELECTED_METRICS if col in df.columns]
42
+ df = df[available_cols]
43
+ print(f"Selected {len(available_cols) - 1} metrics from available metrics")
44
+
45
+ valid_order = ["model_name"] + [col for col in CUSTOM_ORDER if col in df.columns]
46
+ df = df[valid_order]
47
+ print(f"Kept {len(valid_order) - 1} metrics as specified in CUSTOM_ORDER")
48
+
49
+ if excel_path is None:
50
+ excel_path = json_path.rsplit(".", 1)[0] + f"_{score_type}" + ".xlsx"
51
+
52
+ with pd.ExcelWriter(excel_path, engine="openpyxl") as writer:
53
+ df.to_excel(writer, sheet_name="Models", index=False)
54
+
55
+ metadata = pd.DataFrame(
56
+ {
57
+ "Property": ["timestamp", "num_models", "num_metrics", "filtered", "format"],
58
+ "Value": [
59
+ data.get("timestamp", "N/A"),
60
+ data.get("num_models", len(models_data)),
61
+ len(df.columns) - 1,
62
+ "Yes" if use_selected_metrics else "No",
63
+ "Raw Values" if show_raw_values else "Percentage",
64
+ ],
65
+ }
66
+ )
67
+ metadata.to_excel(writer, sheet_name="Metadata", index=False)
68
+
69
+ worksheet = writer.sheets["Models"]
70
+ for idx, col in enumerate(df.columns):
71
+ max_length = max(df[col].astype(str).apply(len).max(), len(col))
72
+ if idx < 26:
73
+ col_letter = chr(65 + idx)
74
+ else:
75
+ col_letter = chr(65 + idx // 26 - 1) + chr(65 + idx % 26)
76
+ worksheet.column_dimensions[col_letter].width = min(max_length + 2, 50)
77
+
78
+ if col != "model_name" and pd.api.types.is_numeric_dtype(df[col]):
79
+ for row in range(2, len(df) + 2): # Start from row 2 (after header)
80
+ cell = worksheet[f"{col_letter}{row}"]
81
+ if cell.value is not None:
82
+ if col == "total_weighted_rating":
83
+ cell.number_format = "0.00"
84
+ elif show_raw_values:
85
+ cell.number_format = "0"
86
+ else:
87
+ cell.value = cell.value * 100
88
+ cell.number_format = '0.00"%"'
89
+
90
+ print(f"Conversion successful! Output file: {excel_path}")
91
+ print(f"Processed {len(df)} models with {len(df.columns) - 1} metrics")
92
+ print(f"Format: {'Raw values' if show_raw_values else 'Percentage'}")
93
+
94
+ return excel_path
95
+
96
+
97
+ if __name__ == "__main__":
98
+ parser = argparse.ArgumentParser()
99
+
100
+ parser.add_argument("--json_file", type=str, required=True, help="Input JSON file path")
101
+ parser.add_argument(
102
+ "--excel_file",
103
+ type=str,
104
+ required=True,
105
+ help="Output Excel file path (optional, defaults to input filename.xlsx)",
106
+ )
107
+ parser.add_argument("--filter", action="store_true", help="Use only metrics defined in SELECTED_METRICS list")
108
+ parser.add_argument(
109
+ "--score_type",
110
+ type=str,
111
+ choices=["raw", "normalized", "rating"],
112
+ default="rating",
113
+ help="Type of scores to use: 'raw', 'normalized', or 'rating'",
114
+ )
115
+
116
+ args = parser.parse_args()
117
+
118
+ if args.score_type == "rating":
119
+ raw_value = True
120
+ else:
121
+ raw_value = False
122
+
123
+ try:
124
+ json_to_excel(
125
+ args.json_file,
126
+ args.excel_file,
127
+ use_selected_metrics=args.filter,
128
+ show_raw_values=raw_value,
129
+ score_type=args.score_type,
130
+ )
131
+ except FileNotFoundError:
132
+ print(f"Error: File not found {args.json_file}")
133
+ except json.JSONDecodeError:
134
+ print(f"Error: {args.json_file} is not a valid JSON file")
135
+ except Exception as e:
136
+ print(f"Error: {e}")
Helios-main/eval/utils/extract_short_from_long.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+
7
+ def extract_first_n_frames(input_root, output_root, num_frames=81):
8
+ input_path = Path(input_root)
9
+ output_path = Path(output_root)
10
+
11
+ for subfolder in input_path.iterdir():
12
+ if not subfolder.is_dir():
13
+ continue
14
+
15
+ print(f"Processing folder: {subfolder.name}")
16
+
17
+ output_subfolder = output_path / subfolder.name
18
+ output_subfolder.mkdir(parents=True, exist_ok=True)
19
+
20
+ video_files = list(subfolder.glob("*.mp4"))
21
+
22
+ for i, video_file in enumerate(video_files, 1):
23
+ original_name = video_file.stem
24
+ if "_ori" in original_name:
25
+ new_name = original_name.rsplit("_ori", 1)[0] + f"_ori{num_frames}.mp4"
26
+ else:
27
+ new_name = video_file.name
28
+
29
+ output_file = output_subfolder / new_name
30
+ if os.path.exists(output_file):
31
+ print(f"Skipping existing file: {output_file}")
32
+ continue
33
+
34
+ cmd = [
35
+ "ffmpeg",
36
+ "-i",
37
+ str(video_file),
38
+ "-vframes",
39
+ str(num_frames), # Extract only first N frames
40
+ "-map",
41
+ "0", # Copy all streams (video + audio)
42
+ "-c",
43
+ "copy", # Try direct copy (fastest, preserves all parameters)
44
+ "-y",
45
+ str(output_file),
46
+ ]
47
+
48
+ try:
49
+ result = subprocess.run(cmd, capture_output=True)
50
+
51
+ if result.returncode != 0:
52
+ print(f" Direct copy failed for {video_file.name}, re-encoding...")
53
+ cmd = [
54
+ "ffmpeg",
55
+ "-i",
56
+ str(video_file),
57
+ "-vframes",
58
+ str(num_frames),
59
+ "-c:v",
60
+ "libx264", # Re-encode video
61
+ "-qp",
62
+ "0", # Lossless quality
63
+ "-c:a",
64
+ "copy", # Copy audio directly
65
+ "-map",
66
+ "0", # Copy all streams
67
+ "-y",
68
+ str(output_file),
69
+ ]
70
+ subprocess.run(cmd, check=True, capture_output=True)
71
+
72
+ print(f" [{i}/{len(video_files)}] {video_file.name} -> {new_name}")
73
+ except subprocess.CalledProcessError as e:
74
+ print(f" Error processing {video_file.name}: {e}")
75
+ continue
76
+
77
+
78
+ if __name__ == "__main__":
79
+ parser = argparse.ArgumentParser(description="Extract first N frames from videos")
80
+ parser.add_argument(
81
+ "--input",
82
+ type=str,
83
+ default="long",
84
+ help="Input root directory (default: current directory)",
85
+ )
86
+ parser.add_argument(
87
+ "--output",
88
+ type=str,
89
+ default="short/0_from_long",
90
+ help="Output root directory (default: ./output_frames)",
91
+ )
92
+ parser.add_argument("--frames", type=int, default=81, help="Number of frames to extract (default: 81)")
93
+
94
+ args = parser.parse_args()
95
+
96
+ extract_first_n_frames(args.input, args.output, args.frames)
97
+ print("\nDone!")
Helios-main/eval/utils/third_party/ViCLIP/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/ViCLIP/simple_tokenizer.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ import subprocess
5
+ from functools import lru_cache
6
+
7
+ import ftfy
8
+ import regex as re
9
+
10
+
11
+ def default_bpe():
12
+ tokenizer_file = os.path.join("checkpoints", "ViCLIP/bpe_simple_vocab_16e6.txt.gz")
13
+ if not os.path.exists(tokenizer_file):
14
+ print(f"Downloading ViCLIP tokenizer to {tokenizer_file}")
15
+ wget_command = [
16
+ "wget",
17
+ "https://raw.githubusercontent.com/openai/CLIP/main/clip/bpe_simple_vocab_16e6.txt.gz",
18
+ "-P",
19
+ os.path.dirname(tokenizer_file),
20
+ ]
21
+ subprocess.run(wget_command)
22
+ return tokenizer_file
23
+
24
+
25
+ @lru_cache()
26
+ def bytes_to_unicode():
27
+ """
28
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
29
+ The reversible bpe codes work on unicode strings.
30
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
31
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
32
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
33
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
34
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
35
+ """
36
+ bs = (
37
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
38
+ )
39
+ cs = bs[:]
40
+ n = 0
41
+ for b in range(2**8):
42
+ if b not in bs:
43
+ bs.append(b)
44
+ cs.append(2**8 + n)
45
+ n += 1
46
+ cs = [chr(n) for n in cs]
47
+ return dict(zip(bs, cs))
48
+
49
+
50
+ def get_pairs(word):
51
+ """Return set of symbol pairs in a word.
52
+ Word is represented as tuple of symbols (symbols being variable-length strings).
53
+ """
54
+ pairs = set()
55
+ prev_char = word[0]
56
+ for char in word[1:]:
57
+ pairs.add((prev_char, char))
58
+ prev_char = char
59
+ return pairs
60
+
61
+
62
+ def basic_clean(text):
63
+ text = ftfy.fix_text(text)
64
+ text = html.unescape(html.unescape(text))
65
+ return text.strip()
66
+
67
+
68
+ def whitespace_clean(text):
69
+ text = re.sub(r"\s+", " ", text)
70
+ text = text.strip()
71
+ return text
72
+
73
+
74
+ class SimpleTokenizer(object):
75
+ def __init__(self, bpe_path: str = default_bpe()):
76
+ self.byte_encoder = bytes_to_unicode()
77
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
78
+ merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
79
+ merges = merges[1 : 49152 - 256 - 2 + 1]
80
+ merges = [tuple(merge.split()) for merge in merges]
81
+ vocab = list(bytes_to_unicode().values())
82
+ vocab = vocab + [v + "</w>" for v in vocab]
83
+ for merge in merges:
84
+ vocab.append("".join(merge))
85
+ vocab.extend(["<|startoftext|>", "<|endoftext|>"])
86
+ self.encoder = dict(zip(vocab, range(len(vocab))))
87
+ self.decoder = {v: k for k, v in self.encoder.items()}
88
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
89
+ self.cache = {"<|startoftext|>": "<|startoftext|>", "<|endoftext|>": "<|endoftext|>"}
90
+ self.pat = re.compile(
91
+ r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
92
+ re.IGNORECASE,
93
+ )
94
+
95
+ def bpe(self, token):
96
+ if token in self.cache:
97
+ return self.cache[token]
98
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
99
+ pairs = get_pairs(word)
100
+
101
+ if not pairs:
102
+ return token + "</w>"
103
+
104
+ while True:
105
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
106
+ if bigram not in self.bpe_ranks:
107
+ break
108
+ first, second = bigram
109
+ new_word = []
110
+ i = 0
111
+ while i < len(word):
112
+ try:
113
+ j = word.index(first, i)
114
+ new_word.extend(word[i:j])
115
+ i = j
116
+ except Exception:
117
+ new_word.extend(word[i:])
118
+ break
119
+
120
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
121
+ new_word.append(first + second)
122
+ i += 2
123
+ else:
124
+ new_word.append(word[i])
125
+ i += 1
126
+ new_word = tuple(new_word)
127
+ word = new_word
128
+ if len(word) == 1:
129
+ break
130
+ else:
131
+ pairs = get_pairs(word)
132
+ word = " ".join(word)
133
+ self.cache[token] = word
134
+ return word
135
+
136
+ def encode(self, text):
137
+ bpe_tokens = []
138
+ text = whitespace_clean(basic_clean(text)).lower()
139
+ for token in re.findall(self.pat, text):
140
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
141
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" "))
142
+ return bpe_tokens
143
+
144
+ def decode(self, tokens):
145
+ text = "".join([self.decoder[token] for token in tokens])
146
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="replace").replace("</w>", " ")
147
+ return text
Helios-main/eval/utils/third_party/ViCLIP/viclip.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
8
+ from .viclip_text import clip_text_l14
9
+ from .viclip_vision import clip_joint_l14
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class ViCLIP(nn.Module):
16
+ """docstring for ViCLIP"""
17
+
18
+ def __init__(
19
+ self,
20
+ tokenizer=None,
21
+ pretrain=os.path.join(os.path.dirname(os.path.abspath(__file__)), "ViClip-InternVid-10M-FLT.pth"),
22
+ freeze_text=True,
23
+ ):
24
+ super(ViCLIP, self).__init__()
25
+ if tokenizer:
26
+ self.tokenizer = tokenizer
27
+ else:
28
+ self.tokenizer = _Tokenizer()
29
+ self.max_txt_l = 32
30
+
31
+ self.vision_encoder_name = "vit_l14"
32
+
33
+ self.vision_encoder_pretrained = False
34
+ self.inputs_image_res = 224
35
+ self.vision_encoder_kernel_size = 1
36
+ self.vision_encoder_center = True
37
+ self.video_input_num_frames = 8
38
+ self.vision_encoder_drop_path_rate = 0.1
39
+ self.vision_encoder_checkpoint_num = 24
40
+ self.is_pretrain = pretrain
41
+ self.vision_width = 1024
42
+ self.text_width = 768
43
+ self.embed_dim = 768
44
+ self.masking_prob = 0.9
45
+
46
+ self.text_encoder_name = "vit_l14"
47
+ self.text_encoder_pretrained = False #'bert-base-uncased'
48
+ self.text_encoder_d_model = 768
49
+
50
+ self.text_encoder_vocab_size = 49408
51
+
52
+ # create modules.
53
+ self.vision_encoder = self.build_vision_encoder()
54
+ self.text_encoder = self.build_text_encoder()
55
+
56
+ self.temp = nn.parameter.Parameter(torch.ones([]) * 1 / 100.0)
57
+ self.temp_min = 1 / 100.0
58
+
59
+ if pretrain:
60
+ logger.info(f"Load pretrained weights from {pretrain}")
61
+ state_dict = torch.load(pretrain, map_location="cpu", weights_only=False)["model"]
62
+ self.load_state_dict(state_dict)
63
+
64
+ # Freeze weights
65
+ if freeze_text:
66
+ self.freeze_text()
67
+
68
+ def freeze_text(self):
69
+ """freeze text encoder"""
70
+ for p in self.text_encoder.parameters():
71
+ p.requires_grad = False
72
+
73
+ def no_weight_decay(self):
74
+ ret = {"temp"}
75
+ ret.update({"vision_encoder." + k for k in self.vision_encoder.no_weight_decay()})
76
+ ret.update({"text_encoder." + k for k in self.text_encoder.no_weight_decay()})
77
+
78
+ return ret
79
+
80
+ def forward(self, image, text, raw_text, idx, log_generation=None, return_sims=False):
81
+ """forward and calculate loss.
82
+
83
+ Args:
84
+ image (torch.Tensor): The input images. Shape: [B,T,C,H,W].
85
+ text (dict): TODO
86
+ idx (torch.Tensor): TODO
87
+
88
+ Returns: TODO
89
+
90
+ """
91
+ self.clip_contrastive_temperature()
92
+
93
+ vision_embeds = self.encode_vision(image)
94
+ text_embeds = self.encode_text(raw_text)
95
+ if return_sims:
96
+ sims = torch.nn.functional.normalize(vision_embeds, dim=-1) @ torch.nn.functional.normalize(
97
+ text_embeds, dim=-1
98
+ ).transpose(0, 1)
99
+ return sims
100
+
101
+ # calculate loss
102
+
103
+ ## VTC loss
104
+ loss_vtc = self.clip_loss.vtc_loss(vision_embeds, text_embeds, idx, self.temp, all_gather=True)
105
+
106
+ return {
107
+ "loss_vtc": loss_vtc,
108
+ }
109
+
110
+ def encode_vision(self, image, test=False):
111
+ """encode image / videos as features.
112
+
113
+ Args:
114
+ image (torch.Tensor): The input images.
115
+ test (bool): Whether testing.
116
+
117
+ Returns: tuple.
118
+ - vision_embeds (torch.Tensor): The features of all patches. Shape: [B,T,L,C].
119
+ - pooled_vision_embeds (torch.Tensor): The pooled features. Shape: [B,T,C].
120
+
121
+ """
122
+ if image.ndim == 5:
123
+ image = image.permute(0, 2, 1, 3, 4).contiguous()
124
+ else:
125
+ image = image.unsqueeze(2)
126
+
127
+ if not test and self.masking_prob > 0.0:
128
+ return self.vision_encoder(image, masking_prob=self.masking_prob)
129
+
130
+ return self.vision_encoder(image)
131
+
132
+ def encode_text(self, text):
133
+ """encode text.
134
+ Args:
135
+ text (dict): The output of huggingface's `PreTrainedTokenizer`. contains keys:
136
+ - input_ids (torch.Tensor): Token ids to be fed to a model. Shape: [B,L].
137
+ - attention_mask (torch.Tensor): The mask indicate padded tokens. Shape: [B,L]. 0 is padded token.
138
+ - other keys refer to "https://huggingface.co/docs/transformers/v4.21.2/en/main_classes/tokenizer#transformers.PreTrainedTokenizer.__call__".
139
+ Returns: tuple.
140
+ - text_embeds (torch.Tensor): The features of all tokens. Shape: [B,L,C].
141
+ - pooled_text_embeds (torch.Tensor): The pooled features. Shape: [B,C].
142
+
143
+ """
144
+ device = next(self.text_encoder.parameters()).device
145
+ text = self.text_encoder.tokenize(text, context_length=self.max_txt_l).to(device)
146
+ text_embeds = self.text_encoder(text)
147
+ return text_embeds
148
+
149
+ @torch.no_grad()
150
+ def clip_contrastive_temperature(self, min_val=0.001, max_val=0.5):
151
+ """Seems only used during pre-training"""
152
+ self.temp.clamp_(min=self.temp_min)
153
+
154
+ def build_vision_encoder(self):
155
+ """build vision encoder
156
+ Returns: (vision_encoder, vision_layernorm). Each is a `nn.Module`.
157
+
158
+ """
159
+ encoder_name = self.vision_encoder_name
160
+ if encoder_name != "vit_l14":
161
+ raise ValueError(f"Not implemented: {encoder_name}")
162
+ vision_encoder = clip_joint_l14(
163
+ pretrained=self.vision_encoder_pretrained,
164
+ input_resolution=self.inputs_image_res,
165
+ kernel_size=self.vision_encoder_kernel_size,
166
+ center=self.vision_encoder_center,
167
+ num_frames=self.video_input_num_frames,
168
+ drop_path=self.vision_encoder_drop_path_rate,
169
+ checkpoint_num=self.vision_encoder_checkpoint_num,
170
+ )
171
+ return vision_encoder
172
+
173
+ def build_text_encoder(self):
174
+ """build text_encoder and possiblly video-to-text multimodal fusion encoder.
175
+ Returns: nn.Module. The text encoder
176
+
177
+ """
178
+ encoder_name = self.text_encoder_name
179
+ if encoder_name != "vit_l14":
180
+ raise ValueError(f"Not implemented: {encoder_name}")
181
+ text_encoder = clip_text_l14(
182
+ pretrained=self.text_encoder_pretrained,
183
+ embed_dim=self.text_encoder_d_model,
184
+ context_length=self.max_txt_l,
185
+ vocab_size=self.text_encoder_vocab_size,
186
+ checkpoint_num=0,
187
+ )
188
+
189
+ return text_encoder
190
+
191
+ def get_text_encoder(self):
192
+ """get text encoder, used for text and cross-modal encoding"""
193
+ encoder = self.text_encoder
194
+ return encoder.bert if hasattr(encoder, "bert") else encoder
195
+
196
+ def get_text_features(self, input_text, tokenizer, text_feature_dict={}):
197
+ if input_text in text_feature_dict:
198
+ return text_feature_dict[input_text]
199
+ text_template = f"{input_text}"
200
+ with torch.no_grad():
201
+ # text_token = tokenizer.encode(text_template).cuda()
202
+ text_features = self.encode_text(text_template).float()
203
+ text_features /= text_features.norm(dim=-1, keepdim=True)
204
+ text_feature_dict[input_text] = text_features
205
+ return text_features
206
+
207
+ def get_vid_features(self, input_frames):
208
+ with torch.no_grad():
209
+ clip_feat = self.encode_vision(input_frames, test=True).float()
210
+ clip_feat /= clip_feat.norm(dim=-1, keepdim=True)
211
+ return clip_feat
212
+
213
+ def get_predict_label(self, clip_feature, text_feats_tensor, top=5):
214
+ label_probs = (100.0 * clip_feature @ text_feats_tensor.T).softmax(dim=-1)
215
+ top_probs, top_labels = label_probs.cpu().topk(top, dim=-1)
216
+ return top_probs, top_labels
Helios-main/eval/utils/third_party/ViCLIP/viclip_text.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+ import os
4
+ from collections import OrderedDict
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ import torch.utils.checkpoint as checkpoint
9
+ from pkg_resources import packaging
10
+ from torch import nn
11
+
12
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
13
+
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ MODEL_PATH = "https://huggingface.co/laion/CLIP-ViT-L-14-DataComp.XL-s13B-b90K"
19
+ _MODELS = {
20
+ "ViT-L/14": os.path.join(MODEL_PATH, "vit_l14_text.pth"),
21
+ }
22
+
23
+
24
+ class LayerNorm(nn.LayerNorm):
25
+ """Subclass torch's LayerNorm to handle fp16."""
26
+
27
+ def forward(self, x: torch.Tensor):
28
+ orig_type = x.dtype
29
+ ret = super().forward(x.type(torch.float32))
30
+ return ret.type(orig_type)
31
+
32
+
33
+ class QuickGELU(nn.Module):
34
+ def forward(self, x: torch.Tensor):
35
+ return x * torch.sigmoid(1.702 * x)
36
+
37
+
38
+ class ResidualAttentionBlock(nn.Module):
39
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
40
+ super().__init__()
41
+
42
+ self.attn = nn.MultiheadAttention(d_model, n_head)
43
+ self.ln_1 = LayerNorm(d_model)
44
+ self.mlp = nn.Sequential(
45
+ OrderedDict(
46
+ [
47
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
48
+ ("gelu", QuickGELU()),
49
+ ("c_proj", nn.Linear(d_model * 4, d_model)),
50
+ ]
51
+ )
52
+ )
53
+ self.ln_2 = LayerNorm(d_model)
54
+ self.attn_mask = attn_mask
55
+
56
+ def attention(self, x: torch.Tensor):
57
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
58
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
59
+
60
+ def forward(self, x: torch.Tensor):
61
+ x = x + self.attention(self.ln_1(x))
62
+ x = x + self.mlp(self.ln_2(x))
63
+ return x
64
+
65
+
66
+ class Transformer(nn.Module):
67
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None, checkpoint_num: int = 0):
68
+ super().__init__()
69
+ self.width = width
70
+ self.layers = layers
71
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
72
+
73
+ self.checkpoint_num = checkpoint_num
74
+
75
+ def forward(self, x: torch.Tensor):
76
+ if self.checkpoint_num > 0:
77
+ segments = min(self.checkpoint_num, len(self.resblocks))
78
+ return checkpoint.checkpoint_sequential(self.resblocks, segments, x)
79
+ else:
80
+ return self.resblocks(x)
81
+
82
+
83
+ class CLIP_TEXT(nn.Module):
84
+ def __init__(
85
+ self,
86
+ embed_dim: int,
87
+ context_length: int,
88
+ vocab_size: int,
89
+ transformer_width: int,
90
+ transformer_heads: int,
91
+ transformer_layers: int,
92
+ checkpoint_num: int,
93
+ ):
94
+ super().__init__()
95
+
96
+ self.context_length = context_length
97
+ self._tokenizer = _Tokenizer()
98
+
99
+ self.transformer = Transformer(
100
+ width=transformer_width,
101
+ layers=transformer_layers,
102
+ heads=transformer_heads,
103
+ attn_mask=self.build_attention_mask(),
104
+ checkpoint_num=checkpoint_num,
105
+ )
106
+
107
+ self.vocab_size = vocab_size
108
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
109
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
110
+ self.ln_final = LayerNorm(transformer_width)
111
+
112
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
113
+
114
+ def no_weight_decay(self):
115
+ return {"token_embedding", "positional_embedding"}
116
+
117
+ @functools.lru_cache(maxsize=None)
118
+ def build_attention_mask(self):
119
+ # lazily create causal attention mask, with full attention between the vision tokens
120
+ # pytorch uses additive attention mask; fill with -inf
121
+ mask = torch.empty(self.context_length, self.context_length)
122
+ mask.fill_(float("-inf"))
123
+ mask.triu_(1) # zero out the lower diagonal
124
+ return mask
125
+
126
+ def tokenize(self, texts, context_length=77, truncate=True):
127
+ """
128
+ Returns the tokenized representation of given input string(s)
129
+ Parameters
130
+ ----------
131
+ texts : Union[str, List[str]]
132
+ An input string or a list of input strings to tokenize
133
+ context_length : int
134
+ The context length to use; all CLIP models use 77 as the context length
135
+ truncate: bool
136
+ Whether to truncate the text in case its encoding is longer than the context length
137
+ Returns
138
+ -------
139
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
140
+ We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
141
+ """
142
+ if isinstance(texts, str):
143
+ texts = [texts]
144
+
145
+ sot_token = self._tokenizer.encoder["<|startoftext|>"]
146
+ eot_token = self._tokenizer.encoder["<|endoftext|>"]
147
+ all_tokens = [[sot_token] + self._tokenizer.encode(text) + [eot_token] for text in texts]
148
+ if packaging.version.parse(torch.__version__) < packaging.version.parse("1.8.0"):
149
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
150
+ else:
151
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
152
+
153
+ for i, tokens in enumerate(all_tokens):
154
+ if len(tokens) > context_length:
155
+ if truncate:
156
+ tokens = tokens[:context_length]
157
+ tokens[-1] = eot_token
158
+ else:
159
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
160
+ result[i, : len(tokens)] = torch.tensor(tokens)
161
+
162
+ return result
163
+
164
+ def forward(self, text):
165
+ x = self.token_embedding(text) # [batch_size, n_ctx, d_model]
166
+
167
+ x = x + self.positional_embedding
168
+ x = x.permute(1, 0, 2) # NLD -> LND
169
+ x = self.transformer(x)
170
+ x = x.permute(1, 0, 2) # LND -> NLD
171
+ x = self.ln_final(x)
172
+
173
+ # x.shape = [batch_size, n_ctx, transformer.width]
174
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
175
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
176
+
177
+ return x
178
+
179
+
180
+ def clip_text_b16(
181
+ embed_dim=512,
182
+ context_length=77,
183
+ vocab_size=49408,
184
+ transformer_width=512,
185
+ transformer_heads=8,
186
+ transformer_layers=12,
187
+ ):
188
+ raise NotImplementedError
189
+ model = CLIP_TEXT(embed_dim, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers)
190
+ pretrained = _MODELS["ViT-B/16"]
191
+ logger.info(f"Load pretrained weights from {pretrained}")
192
+ state_dict = torch.load(pretrained, map_location="cpu")
193
+ model.load_state_dict(state_dict, strict=False)
194
+ return model.eval()
195
+
196
+
197
+ def clip_text_l14(
198
+ embed_dim=768,
199
+ context_length=77,
200
+ vocab_size=49408,
201
+ transformer_width=768,
202
+ transformer_heads=12,
203
+ transformer_layers=12,
204
+ checkpoint_num=0,
205
+ pretrained=True,
206
+ ):
207
+ model = CLIP_TEXT(
208
+ embed_dim,
209
+ context_length,
210
+ vocab_size,
211
+ transformer_width,
212
+ transformer_heads,
213
+ transformer_layers,
214
+ checkpoint_num,
215
+ )
216
+ if pretrained:
217
+ if isinstance(pretrained, str) and pretrained != "bert-base-uncased":
218
+ pretrained = _MODELS[pretrained]
219
+ else:
220
+ pretrained = _MODELS["ViT-L/14"]
221
+ logger.info(f"Load pretrained weights from {pretrained}")
222
+ state_dict = torch.load(pretrained, map_location="cpu")
223
+ if context_length != state_dict["positional_embedding"].size(0):
224
+ # assert context_length < state_dict["positional_embedding"].size(0), "Cannot increase context length."
225
+ print(f"Resize positional embedding from {state_dict['positional_embedding'].size(0)} to {context_length}")
226
+ if context_length < state_dict["positional_embedding"].size(0):
227
+ state_dict["positional_embedding"] = state_dict["positional_embedding"][:context_length]
228
+ else:
229
+ state_dict["positional_embedding"] = F.pad(
230
+ state_dict["positional_embedding"],
231
+ (0, 0, 0, context_length - state_dict["positional_embedding"].size(0)),
232
+ value=0,
233
+ )
234
+
235
+ message = model.load_state_dict(state_dict, strict=False)
236
+ print(f"Load pretrained weights from {pretrained}: {message}")
237
+ return model.eval()
238
+
239
+
240
+ def clip_text_l14_336(
241
+ embed_dim=768,
242
+ context_length=77,
243
+ vocab_size=49408,
244
+ transformer_width=768,
245
+ transformer_heads=12,
246
+ transformer_layers=12,
247
+ ):
248
+ raise NotImplementedError
249
+ model = CLIP_TEXT(embed_dim, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers)
250
+ pretrained = _MODELS["ViT-L/14_336"]
251
+ logger.info(f"Load pretrained weights from {pretrained}")
252
+ state_dict = torch.load(pretrained, map_location="cpu")
253
+ model.load_state_dict(state_dict, strict=False)
254
+ return model.eval()
255
+
256
+
257
+ def build_clip(config):
258
+ model_cls = config.text_encoder.clip_teacher
259
+ model = eval(model_cls)()
260
+ return model
Helios-main/eval/utils/third_party/ViCLIP/viclip_vision.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import logging
3
+ import os
4
+ from collections import OrderedDict
5
+
6
+ import torch
7
+ import torch.utils.checkpoint as checkpoint
8
+ from einops import rearrange
9
+ from timm.layers import DropPath
10
+ from timm.models import register_model
11
+ from torch import nn
12
+
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def load_temp_embed_with_mismatch(temp_embed_old, temp_embed_new, add_zero=True):
18
+ """
19
+ Add/Remove extra temporal_embeddings as needed.
20
+ https://arxiv.org/abs/2104.00650 shows adding zero paddings works.
21
+
22
+ temp_embed_old: (1, num_frames_old, 1, d)
23
+ temp_embed_new: (1, num_frames_new, 1, d)
24
+ add_zero: bool, if True, add zero, else, interpolate trained embeddings.
25
+ """
26
+ # TODO zero pad
27
+ num_frms_new = temp_embed_new.shape[1]
28
+ num_frms_old = temp_embed_old.shape[1]
29
+ logger.info(f"Load temporal_embeddings, lengths: {num_frms_old}-->{num_frms_new}")
30
+ if num_frms_new > num_frms_old:
31
+ if add_zero:
32
+ temp_embed_new[:, :num_frms_old] = temp_embed_old # untrained embeddings are zeros.
33
+ else:
34
+ pass
35
+ # temp_embed_new = interpolate_temporal_pos_embed(temp_embed_old, num_frms_new)
36
+ elif num_frms_new < num_frms_old:
37
+ temp_embed_new = temp_embed_old[:, :num_frms_new]
38
+ else: # =
39
+ temp_embed_new = temp_embed_old
40
+ return temp_embed_new
41
+
42
+
43
+ MODEL_PATH = "https://pjlab-gvm-data.oss-cn-shanghai.aliyuncs.com/internvideo/viclip/"
44
+ _MODELS = {
45
+ "ViT-L/14": os.path.join(MODEL_PATH, "ViClip-InternVid-10M-FLT.pth"),
46
+ }
47
+
48
+
49
+ class QuickGELU(nn.Module):
50
+ def forward(self, x):
51
+ return x * torch.sigmoid(1.702 * x)
52
+
53
+
54
+ class ResidualAttentionBlock(nn.Module):
55
+ def __init__(self, d_model, n_head, drop_path=0.0, attn_mask=None, dropout=0.0):
56
+ super().__init__()
57
+
58
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
59
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
60
+ self.attn = nn.MultiheadAttention(d_model, n_head, dropout=dropout)
61
+ self.ln_1 = nn.LayerNorm(d_model)
62
+ self.mlp = nn.Sequential(
63
+ OrderedDict(
64
+ [
65
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
66
+ ("gelu", QuickGELU()),
67
+ ("drop1", nn.Dropout(dropout)),
68
+ ("c_proj", nn.Linear(d_model * 4, d_model)),
69
+ ("drop2", nn.Dropout(dropout)),
70
+ ]
71
+ )
72
+ )
73
+ self.ln_2 = nn.LayerNorm(d_model)
74
+ self.attn_mask = attn_mask
75
+
76
+ def attention(self, x):
77
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
78
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
79
+
80
+ def forward(self, x):
81
+ x = x + self.drop_path1(self.attention(self.ln_1(x)))
82
+ x = x + self.drop_path2(self.mlp(self.ln_2(x)))
83
+ return x
84
+
85
+
86
+ class Transformer(nn.Module):
87
+ def __init__(self, width, layers, heads, drop_path=0.0, checkpoint_num=0, dropout=0.0):
88
+ super().__init__()
89
+ dpr = [x.item() for x in torch.linspace(0, drop_path, layers)]
90
+ self.resblocks = nn.ModuleList()
91
+ for idx in range(layers):
92
+ self.resblocks.append(ResidualAttentionBlock(width, heads, drop_path=dpr[idx], dropout=dropout))
93
+ self.checkpoint_num = checkpoint_num
94
+
95
+ def forward(self, x):
96
+ for idx, blk in enumerate(self.resblocks):
97
+ if idx < self.checkpoint_num:
98
+ x = checkpoint.checkpoint(blk, x, use_reentrant=False)
99
+ else:
100
+ x = blk(x)
101
+ return x
102
+
103
+
104
+ class VisionTransformer(nn.Module):
105
+ def __init__(
106
+ self,
107
+ input_resolution,
108
+ patch_size,
109
+ width,
110
+ layers,
111
+ heads,
112
+ output_dim=None,
113
+ kernel_size=1,
114
+ num_frames=8,
115
+ drop_path=0,
116
+ checkpoint_num=0,
117
+ dropout=0.0,
118
+ temp_embed=True,
119
+ ):
120
+ super().__init__()
121
+ self.output_dim = output_dim
122
+ self.conv1 = nn.Conv3d(
123
+ 3,
124
+ width,
125
+ (kernel_size, patch_size, patch_size),
126
+ (kernel_size, patch_size, patch_size),
127
+ (0, 0, 0),
128
+ bias=False,
129
+ )
130
+
131
+ scale = width**-0.5
132
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
133
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
134
+ self.ln_pre = nn.LayerNorm(width)
135
+ if temp_embed:
136
+ self.temporal_positional_embedding = nn.Parameter(torch.zeros(1, num_frames, width))
137
+
138
+ self.transformer = Transformer(
139
+ width, layers, heads, drop_path=drop_path, checkpoint_num=checkpoint_num, dropout=dropout
140
+ )
141
+
142
+ self.ln_post = nn.LayerNorm(width)
143
+ if output_dim is not None:
144
+ self.proj = nn.Parameter(torch.empty(width, output_dim))
145
+ else:
146
+ self.proj = None
147
+
148
+ self.dropout = nn.Dropout(dropout)
149
+
150
+ def get_num_layers(self):
151
+ return len(self.transformer.resblocks)
152
+
153
+ @torch.jit.ignore
154
+ def no_weight_decay(self):
155
+ return {"positional_embedding", "class_embedding", "temporal_positional_embedding"}
156
+
157
+ def mask_tokens(self, inputs, masking_prob=0.0):
158
+ B, L, _ = inputs.shape
159
+
160
+ # This is different from text as we are masking a fix number of tokens
161
+ Lm = int(masking_prob * L)
162
+ masked_indices = torch.zeros(B, L)
163
+ indices = torch.argsort(torch.rand_like(masked_indices), dim=-1)[:, :Lm]
164
+ batch_indices = torch.arange(masked_indices.shape[0]).unsqueeze(-1).expand_as(indices)
165
+ masked_indices[batch_indices, indices] = 1
166
+
167
+ masked_indices = masked_indices.bool()
168
+
169
+ return inputs[~masked_indices].reshape(B, -1, inputs.shape[-1])
170
+
171
+ def forward(self, x, masking_prob=0.0):
172
+ x = self.conv1(x) # shape = [*, width, grid, grid]
173
+ B, C, T, H, W = x.shape
174
+ x = x.permute(0, 2, 3, 4, 1).reshape(B * T, H * W, C)
175
+
176
+ x = torch.cat(
177
+ [
178
+ self.class_embedding.to(x.dtype)
179
+ + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
180
+ x,
181
+ ],
182
+ dim=1,
183
+ ) # shape = [*, grid ** 2 + 1, width]
184
+ x = x + self.positional_embedding.to(x.dtype)
185
+
186
+ # temporal pos
187
+ cls_tokens = x[:B, :1, :]
188
+ x = x[:, 1:]
189
+ x = rearrange(x, "(b t) n m -> (b n) t m", b=B, t=T)
190
+ if hasattr(self, "temporal_positional_embedding"):
191
+ if x.size(1) == 1:
192
+ # This is a workaround for unused parameter issue
193
+ x = x + self.temporal_positional_embedding.mean(1)
194
+ else:
195
+ x = x + self.temporal_positional_embedding
196
+ x = rearrange(x, "(b n) t m -> b (n t) m", b=B, t=T)
197
+
198
+ if masking_prob > 0.0:
199
+ x = self.mask_tokens(x, masking_prob)
200
+
201
+ x = torch.cat((cls_tokens, x), dim=1)
202
+
203
+ x = self.ln_pre(x)
204
+
205
+ x = x.permute(1, 0, 2) # BND -> NBD
206
+ x = self.transformer(x)
207
+
208
+ x = self.ln_post(x)
209
+
210
+ if self.proj is not None:
211
+ x = self.dropout(x[0]) @ self.proj
212
+ else:
213
+ x = x.permute(1, 0, 2) # NBD -> BND
214
+
215
+ return x
216
+
217
+
218
+ def inflate_weight(weight_2d, time_dim, center=True):
219
+ logger.info(f"Init center: {center}")
220
+ if center:
221
+ weight_3d = torch.zeros(*weight_2d.shape)
222
+ weight_3d = weight_3d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
223
+ middle_idx = time_dim // 2
224
+ weight_3d[:, :, middle_idx, :, :] = weight_2d
225
+ else:
226
+ weight_3d = weight_2d.unsqueeze(2).repeat(1, 1, time_dim, 1, 1)
227
+ weight_3d = weight_3d / time_dim
228
+ return weight_3d
229
+
230
+
231
+ def load_state_dict(model, state_dict, input_resolution=224, patch_size=16, center=True):
232
+ state_dict_3d = model.state_dict()
233
+ for k in state_dict.keys():
234
+ if k in state_dict_3d.keys() and state_dict[k].shape != state_dict_3d[k].shape:
235
+ if len(state_dict_3d[k].shape) <= 2:
236
+ logger.info(f"Ignore: {k}")
237
+ continue
238
+ logger.info(f"Inflate: {k}, {state_dict[k].shape} => {state_dict_3d[k].shape}")
239
+ time_dim = state_dict_3d[k].shape[2]
240
+ state_dict[k] = inflate_weight(state_dict[k], time_dim, center=center)
241
+
242
+ pos_embed_checkpoint = state_dict["positional_embedding"]
243
+ embedding_size = pos_embed_checkpoint.shape[-1]
244
+ num_patches = (input_resolution // patch_size) ** 2
245
+ orig_size = int((pos_embed_checkpoint.shape[-2] - 1) ** 0.5)
246
+ new_size = int(num_patches**0.5)
247
+ if orig_size != new_size:
248
+ logger.info(f"Pos_emb from {orig_size} to {new_size}")
249
+ extra_tokens = pos_embed_checkpoint[:1]
250
+ pos_tokens = pos_embed_checkpoint[1:]
251
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
252
+ pos_tokens = torch.nn.functional.interpolate(
253
+ pos_tokens, size=(new_size, new_size), mode="bicubic", align_corners=False
254
+ )
255
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(0, 2)
256
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=0)
257
+ state_dict["positional_embedding"] = new_pos_embed
258
+
259
+ message = model.load_state_dict(state_dict, strict=False)
260
+ logger.info(f"Load pretrained weights: {message}")
261
+
262
+
263
+ @register_model
264
+ def clip_joint_b16(pretrained=True, input_resolution=224, kernel_size=1, center=True, num_frames=8, drop_path=0.0):
265
+ model = VisionTransformer(
266
+ input_resolution=input_resolution,
267
+ patch_size=16,
268
+ width=768,
269
+ layers=12,
270
+ heads=12,
271
+ output_dim=512,
272
+ kernel_size=kernel_size,
273
+ num_frames=num_frames,
274
+ drop_path=drop_path,
275
+ )
276
+ raise NotImplementedError
277
+ if pretrained:
278
+ logger.info("load pretrained weights")
279
+ state_dict = torch.load(_MODELS["ViT-B/16"], map_location="cpu")
280
+ load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=16, center=center)
281
+ return model.eval()
282
+
283
+
284
+ @register_model
285
+ def clip_joint_l14(
286
+ pretrained=False,
287
+ input_resolution=224,
288
+ kernel_size=1,
289
+ center=True,
290
+ num_frames=8,
291
+ drop_path=0.0,
292
+ checkpoint_num=0,
293
+ dropout=0.0,
294
+ ):
295
+ model = VisionTransformer(
296
+ input_resolution=input_resolution,
297
+ patch_size=14,
298
+ width=1024,
299
+ layers=24,
300
+ heads=16,
301
+ output_dim=768,
302
+ kernel_size=kernel_size,
303
+ num_frames=num_frames,
304
+ drop_path=drop_path,
305
+ checkpoint_num=checkpoint_num,
306
+ dropout=dropout,
307
+ )
308
+ if pretrained:
309
+ if isinstance(pretrained, str):
310
+ model_name = pretrained
311
+ else:
312
+ model_name = "ViT-L/14"
313
+ logger.info("load pretrained weights")
314
+ state_dict = torch.load(_MODELS[model_name], map_location="cpu")
315
+ load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center)
316
+ return model.eval()
317
+
318
+
319
+ @register_model
320
+ def clip_joint_l14_336(pretrained=True, input_resolution=336, kernel_size=1, center=True, num_frames=8, drop_path=0.0):
321
+ raise NotImplementedError
322
+ model = VisionTransformer(
323
+ input_resolution=input_resolution,
324
+ patch_size=14,
325
+ width=1024,
326
+ layers=24,
327
+ heads=16,
328
+ output_dim=768,
329
+ kernel_size=kernel_size,
330
+ num_frames=num_frames,
331
+ drop_path=drop_path,
332
+ )
333
+ if pretrained:
334
+ logger.info("load pretrained weights")
335
+ state_dict = torch.load(_MODELS["ViT-L/14_336"], map_location="cpu")
336
+ load_state_dict(model, state_dict, input_resolution=input_resolution, patch_size=14, center=center)
337
+ return model.eval()
338
+
339
+
340
+ def interpolate_pos_embed_vit(state_dict, new_model):
341
+ key = "vision_encoder.temporal_positional_embedding"
342
+ if key in state_dict:
343
+ vision_temp_embed_new = new_model.state_dict()[key]
344
+ vision_temp_embed_new = vision_temp_embed_new.unsqueeze(2) # [1, n, d] -> [1, n, 1, d]
345
+ vision_temp_embed_old = state_dict[key]
346
+ vision_temp_embed_old = vision_temp_embed_old.unsqueeze(2)
347
+
348
+ state_dict[key] = load_temp_embed_with_mismatch(
349
+ vision_temp_embed_old, vision_temp_embed_new, add_zero=False
350
+ ).squeeze(2)
351
+
352
+ key = "text_encoder.positional_embedding"
353
+ if key in state_dict:
354
+ text_temp_embed_new = new_model.state_dict()[key]
355
+ text_temp_embed_new = text_temp_embed_new.unsqueeze(0).unsqueeze(2) # [n, d] -> [1, n, 1, d]
356
+ text_temp_embed_old = state_dict[key]
357
+ text_temp_embed_old = text_temp_embed_old.unsqueeze(0).unsqueeze(2)
358
+
359
+ state_dict[key] = (
360
+ load_temp_embed_with_mismatch(text_temp_embed_old, text_temp_embed_new, add_zero=False)
361
+ .squeeze(2)
362
+ .squeeze(0)
363
+ )
364
+ return state_dict
Helios-main/eval/utils/third_party/amt/LICENSE ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## creative commons
2
+
3
+ # Attribution-NonCommercial 4.0 International
4
+
5
+ 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.
6
+
7
+ ### Using Creative Commons Public Licenses
8
+
9
+ 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.
10
+
11
+ * __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).
12
+
13
+ * __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).
14
+
15
+ ## Creative Commons Attribution-NonCommercial 4.0 International Public License
16
+
17
+ 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.
18
+
19
+ ### Section 1 – Definitions.
20
+
21
+ 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.
22
+
23
+ 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.
24
+
25
+ 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.
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
32
+
33
+ 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.
34
+
35
+ h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
36
+
37
+ 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.
38
+
39
+ 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.
40
+
41
+ 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.
42
+
43
+ l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
44
+
45
+ ### Section 2 – Scope.
46
+
47
+ a. ___License grant.___
48
+
49
+ 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:
50
+
51
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
52
+
53
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
54
+
55
+ 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.
56
+
57
+ 3. __Term.__ The term of this Public License is specified in Section 6(a).
58
+
59
+ 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.
60
+
61
+ 5. __Downstream recipients.__
62
+
63
+ 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.
64
+
65
+ 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.
66
+
67
+ 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).
68
+
69
+ b. ___Other rights.___
70
+
71
+ 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.
72
+
73
+ 2. Patent and trademark rights are not licensed under this Public License.
74
+
75
+ 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.
76
+
77
+ ### Section 3 – License Conditions.
78
+
79
+ Your exercise of the Licensed Rights is expressly made subject to the following conditions.
80
+
81
+ a. ___Attribution.___
82
+
83
+ 1. If You Share the Licensed Material (including in modified form), You must:
84
+
85
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
86
+
87
+ 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);
88
+
89
+ ii. a copyright notice;
90
+
91
+ iii. a notice that refers to this Public License;
92
+
93
+ iv. a notice that refers to the disclaimer of warranties;
94
+
95
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
96
+
97
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
98
+
99
+ 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.
100
+
101
+ 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.
102
+
103
+ 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.
104
+
105
+ 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.
106
+
107
+ ### Section 4 – Sui Generis Database Rights.
108
+
109
+ Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
110
+
111
+ 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;
112
+
113
+ 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
114
+
115
+ 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.
116
+
117
+ 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.
118
+
119
+ ### Section 5 – Disclaimer of Warranties and Limitation of Liability.
120
+
121
+ 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.__
122
+
123
+ 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.__
124
+
125
+ 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.
126
+
127
+ ### Section 6 – Term and Termination.
128
+
129
+ 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.
130
+
131
+ b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
132
+
133
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
134
+
135
+ 2. upon express reinstatement by the Licensor.
136
+
137
+ 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.
138
+
139
+ 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.
140
+
141
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
142
+
143
+ ### Section 7 – Other Terms and Conditions.
144
+
145
+ a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
146
+
147
+ 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.
148
+
149
+ ### Section 8 – Interpretation.
150
+
151
+ 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.
152
+
153
+ 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.
154
+
155
+ 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.
156
+
157
+ 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.
158
+
159
+ > 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.
160
+ >
161
+ > Creative Commons may be contacted at creativecommons.org
162
+
163
+
164
+ ### Commercial licensing opportunities
165
+ For commercial uses of the Model & Software, please send email to cmm[AT]nankai.edu.cn
166
+
167
+ Citation:
168
+
169
+ @inproceedings{licvpr23amt,
170
+ title = {AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation},
171
+ author = {Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming},
172
+ booktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
173
+ year = {2023}
174
+ }
175
+
176
+ Copyright (c) 2023 MCG-NKU
Helios-main/eval/utils/third_party/amt/README.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation
2
+
3
+
4
+ This repository contains the official implementation of the following paper:
5
+ > **AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation**<br>
6
+ > [Zhen Li](https://paper99.github.io/)<sup>\*</sup>, [Zuo-Liang Zhu](https://nk-cs-zzl.github.io/)<sup>\*</sup>, [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)<br>
7
+ > (\* denotes equal contribution) <br>
8
+ > Nankai University <br>
9
+ > In CVPR 2023<br>
10
+
11
+ [[Paper](https://arxiv.org/abs/2304.09790)]
12
+ [[Project Page](https://nk-cs-zzl.github.io/projects/amt/index.html)]
13
+ [[Web demos](#web-demos)]
14
+ [Video]
15
+
16
+ AMT is a **lightweight, fast, and accurate** algorithm for Frame Interpolation.
17
+ It aims to provide practical solutions for **video generation** from **a few given frames (at least two frames)**.
18
+
19
+ ![Demo gif](assets/amt_demo.gif)
20
+ * More examples can be found in our [project page](https://nk-cs-zzl.github.io/projects/amt/index.html).
21
+
22
+ ## Web demos
23
+ Integrated into [Hugging Face Spaces 🤗](https://huggingface.co/spaces) using [Gradio](https://github.com/gradio-app/gradio). Try out the Web Demo: [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/NKU-AMT/AMT)
24
+
25
+ Try AMT to interpolate between two or more images at [![PyTTI-Tools:FILM](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1IeVO5BmLouhRh6fL2z_y18kgubotoaBq?usp=sharing)
26
+
27
+
28
+ ## Change Log
29
+ - **Apr 20, 2023**: Our code is publicly available.
30
+
31
+
32
+ ## Method Overview
33
+ ![pipeline](https://user-images.githubusercontent.com/21050959/229420451-65951bd0-732c-4f09-9121-f291a3862d6e.png)
34
+
35
+ 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).
36
+
37
+ ## Dependencies and Installation
38
+ 1. Clone Repo
39
+
40
+ ```bash
41
+ git clone https://github.com/MCG-NKU/AMT.git
42
+ ```
43
+
44
+ 2. Create Conda Environment and Install Dependencies
45
+
46
+ ```bash
47
+ conda env create -f environment.yaml
48
+ conda activate amt
49
+ ```
50
+ 3. Download pretrained models for demos from [Pretrained Models](#pretrained-models) and place them to the `pretrained` folder
51
+
52
+ ## Quick Demo
53
+
54
+ **Note that the selected pretrained model (`[CKPT_PATH]`) needs to match the config file (`[CFG]`).**
55
+
56
+ > 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.)
57
+
58
+
59
+ ```bash
60
+ python demos/demo_2x.py -c [CFG] -p [CKPT] -n [N_ITER] -i [INPUT] -o [OUT_PATH] -r [FRAME_RATE]
61
+ # e.g. [INPUT]
62
+ # -i could be a video / a regular expression / a folder contains multiple images
63
+ # -i demo.mp4 (video)/img_*.png (regular expression)/img0.png img1.png (images)/demo_input (folder)
64
+
65
+ # e.g. a simple usage
66
+ 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
67
+
68
+ ```
69
+
70
+ + Note: Please enable `--save_images` for saving the output images (Save speed will be slowed down if there are too many output images)
71
+ + Input type supported: `a video` / `a regular expression` / `multiple images` / `a folder containing input frames`.
72
+ + Results are in the `[OUT_PATH]` (default is `results/2x`) folder.
73
+
74
+ ## Pretrained Models
75
+
76
+ <p id="Pretrained"></p>
77
+
78
+ <table>
79
+ <thead>
80
+ <tr>
81
+ <th> Dataset </th>
82
+ <th> :link: Download Links </th>
83
+ <th> Config file </th>
84
+ <th> Trained on </th>
85
+ <th> Arbitrary/Fixed </th>
86
+ </tr>
87
+ </thead>
88
+ <tbody>
89
+ <tr>
90
+ <td>AMT-S</td>
91
+ <th> [<a href="https://drive.google.com/file/d/1WmOKmQmd6pnLpID8EpUe-TddFpJuavrL/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1yGaNLeb9TG5-81t0skrOUA?pwd=f66n">Baidu Cloud</a>][<a href="https://huggingface.co/lalala125/AMT/resolve/main/amt-s.pth">Hugging Face</a>] </th>
92
+ <th> [<a href="cfgs/AMT-S.yaml">cfgs/AMT-S</a>] </th>
93
+ <th>Vimeo90k</th>
94
+ <th>Fixed</th>
95
+ </tr>
96
+ <tr>
97
+ <td>AMT-L</td>
98
+ <th>[<a href="https://drive.google.com/file/d/1UyhYpAQLXMjFA55rlFZ0kdiSVTL7oU-z/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1qI4fBgS405Bd4Wn1R3Gbeg?pwd=nbne">Baidu Cloud</a>][<a href="https://huggingface.co/lalala125/AMT/resolve/main/amt-l.pth">Hugging Face</a>]</th>
99
+ <th> [<a href="cfgs/AMT-L.yaml">cfgs/AMT-L</a>] </th>
100
+ <th>Vimeo90k</th>
101
+ <th>Fixed</th>
102
+ </tr>
103
+ <tr>
104
+ <td>AMT-G</td>
105
+ <th>[<a href="https://drive.google.com/file/d/1yieLtKh4ei3gOrLN1LhKSP_9157Q-mtP/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1AjmQVziQut1bXgQnDcDKvA?pwd=caf6">Baidu Cloud</a>][<a href="https://huggingface.co/lalala125/AMT/resolve/main/amt-g.pth">Hugging Face</a>] </th>
106
+ <th> [<a href="cfgs/AMT-G.yaml">cfgs/AMT-G</a>] </th>
107
+ <th>Vimeo90k</th>
108
+ <th>Fixed</th>
109
+ </tr>
110
+ <tr>
111
+ <td>AMT-S</td>
112
+ <th>[<a href="https://drive.google.com/file/d/1f1xAF0EDm-rjDdny8_aLyeedfM0QL4-C/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1eZtoULyduQM8AkXeYEBOEw?pwd=8hy3">Baidu Cloud</a>][<a href="https://huggingface.co/lalala125/AMT/resolve/main/gopro_amt-s.pth">Hugging Face</a>] </th>
113
+ <th> [<a href="cfgs/AMT-S_gopro.yaml">cfgs/AMT-S_gopro</a>] </th>
114
+ <th>GoPro</th>
115
+ <th>Arbitrary</th>
116
+ </tr>
117
+ </tbody>
118
+ </table>
119
+
120
+ ## Training and Evaluation
121
+
122
+ 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.
123
+
124
+
125
+ ## Citation
126
+ If you find our repo useful for your research, please consider citing our paper:
127
+
128
+ ```bibtex
129
+ @inproceedings{licvpr23amt,
130
+ title={AMT: All-Pairs Multi-Field Transforms for Efficient Frame Interpolation},
131
+ author={Li, Zhen and Zhu, Zuo-Liang and Han, Ling-Hao and Hou, Qibin and Guo, Chun-Le and Cheng, Ming-Ming},
132
+ booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
133
+ year={2023}
134
+ }
135
+ ```
136
+
137
+
138
+ ## License
139
+ 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.
140
+ Please note that any commercial use of this code requires formal permission prior to use.
141
+
142
+ ## Contact
143
+
144
+ For technical questions, please contact `zhenli1031[AT]gmail.com` and `nkuzhuzl[AT]gmail.com`.
145
+
146
+ For commercial licensing, please contact `cmm[AT]nankai.edu.cn`
147
+
148
+ ## Acknowledgement
149
+
150
+ We thank Jia-Wen Xiao, Zheng-Peng Duan, Rui-Qi Wu, and Xin Jin for proof reading.
151
+ We thank [Zhewei Huang](https://github.com/hzwer) for his suggestions.
152
+
153
+ Here are some great resources we benefit from:
154
+
155
+ - [IFRNet](https://github.com/ltkong218/IFRNet) and [RIFE](https://github.com/megvii-research/ECCV2022-RIFE) for data processing, benchmarking, and loss designs.
156
+ - [RAFT](https://github.com/princeton-vl/RAFT), [M2M-VFI](https://github.com/feinanshan/M2M_VFI), and [GMFlow](https://github.com/haofeixu/gmflow) for inspirations.
157
+ - [FILM](https://github.com/google-research/frame-interpolation) for Web demo reference.
158
+
159
+
160
+ **If you develop/use AMT in your projects, welcome to let us know. We will list your projects in this repository.**
161
+
162
+ We also thank all of our contributors.
163
+
164
+ <a href="https://github.com/MCG-NKU/AMT/graphs/contributors">
165
+ <img src="https://contrib.rocks/image?repo=MCG-NKU/AMT" />
166
+ </a>
167
+
Helios-main/eval/utils/third_party/amt/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/benchmarks/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/benchmarks/adobe240.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+
4
+ import numpy as np
5
+ import torch
6
+ import tqdm
7
+ from omegaconf import OmegaConf
8
+
9
+
10
+ sys.path.append(".")
11
+ from datasets.adobe_datasets import Adobe240_Dataset
12
+ from metrics.psnr_ssim import calculate_psnr, calculate_ssim
13
+
14
+ from utils.build_utils import build_from_cfg
15
+
16
+
17
+ parser = argparse.ArgumentParser(
18
+ prog="AMT",
19
+ description="Adobe240 evaluation",
20
+ )
21
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S_gopro.yaml")
22
+ parser.add_argument(
23
+ "-p",
24
+ "--ckpt",
25
+ default="pretrained/gopro_amt-s.pth",
26
+ )
27
+ parser.add_argument(
28
+ "-r",
29
+ "--root",
30
+ default="data/Adobe240/test_frames",
31
+ )
32
+ args = parser.parse_args()
33
+
34
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35
+ cfg_path = args.config
36
+ ckpt_path = args.ckpt
37
+ root = args.root
38
+
39
+ network_cfg = OmegaConf.load(cfg_path).network
40
+ network_name = network_cfg.name
41
+ model = build_from_cfg(network_cfg)
42
+ ckpt = torch.load(ckpt_path)
43
+ model.load_state_dict(ckpt["state_dict"])
44
+ model = model.to(device)
45
+ model.eval()
46
+
47
+ dataset = Adobe240_Dataset(dataset_dir=root, augment=False)
48
+
49
+ psnr_list = []
50
+ ssim_list = []
51
+ pbar = tqdm.tqdm(dataset, total=len(dataset))
52
+ for data in pbar:
53
+ input_dict = {}
54
+ for k, v in data.items():
55
+ input_dict[k] = v.to(device).unsqueeze(0)
56
+ with torch.no_grad():
57
+ imgt_pred = model(**input_dict)["imgt_pred"]
58
+ psnr = calculate_psnr(imgt_pred, input_dict["imgt"])
59
+ ssim = calculate_ssim(imgt_pred, input_dict["imgt"])
60
+ psnr_list.append(psnr)
61
+ ssim_list.append(ssim)
62
+ avg_psnr = np.mean(psnr_list)
63
+ avg_ssim = np.mean(ssim_list)
64
+ desc_str = f"[{network_name}/Adobe240] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}"
65
+ pbar.set_description_str(desc_str)
Helios-main/eval/utils/third_party/amt/benchmarks/gopro.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+
4
+ import numpy as np
5
+ import torch
6
+ import tqdm
7
+ from omegaconf import OmegaConf
8
+
9
+
10
+ sys.path.append(".")
11
+ from datasets.gopro_datasets import GoPro_Test_Dataset
12
+ from metrics.psnr_ssim import calculate_psnr, calculate_ssim
13
+
14
+ from utils.build_utils import build_from_cfg
15
+
16
+
17
+ parser = argparse.ArgumentParser(
18
+ prog="AMT",
19
+ description="GOPRO evaluation",
20
+ )
21
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S_gopro.yaml")
22
+ parser.add_argument(
23
+ "-p",
24
+ "--ckpt",
25
+ default="pretrained/gopro_amt-s.pth",
26
+ )
27
+ parser.add_argument(
28
+ "-r",
29
+ "--root",
30
+ default="data/GOPRO",
31
+ )
32
+ args = parser.parse_args()
33
+
34
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35
+ cfg_path = args.config
36
+ ckpt_path = args.ckpt
37
+ root = args.root
38
+
39
+ network_cfg = OmegaConf.load(cfg_path).network
40
+ network_name = network_cfg.name
41
+ model = build_from_cfg(network_cfg)
42
+ ckpt = torch.load(ckpt_path)
43
+ model.load_state_dict(ckpt["state_dict"])
44
+ model = model.to(device)
45
+ model.eval()
46
+
47
+ dataset = GoPro_Test_Dataset(dataset_dir=root)
48
+
49
+ psnr_list = []
50
+ ssim_list = []
51
+ pbar = tqdm.tqdm(dataset, total=len(dataset))
52
+ for data in pbar:
53
+ input_dict = {}
54
+ for k, v in data.items():
55
+ input_dict[k] = v.to(device).unsqueeze(0)
56
+ with torch.no_grad():
57
+ imgt_pred = model(**input_dict)["imgt_pred"]
58
+ psnr = calculate_psnr(imgt_pred, input_dict["imgt"])
59
+ ssim = calculate_ssim(imgt_pred, input_dict["imgt"])
60
+ psnr_list.append(psnr)
61
+ ssim_list.append(ssim)
62
+ avg_psnr = np.mean(psnr_list)
63
+ avg_ssim = np.mean(ssim_list)
64
+ desc_str = f"[{network_name}/GOPRO] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}"
65
+ pbar.set_description_str(desc_str)
Helios-main/eval/utils/third_party/amt/benchmarks/snu_film.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import os.path as osp
4
+ import sys
5
+
6
+ import numpy as np
7
+ import torch
8
+ import tqdm
9
+ from omegaconf import OmegaConf
10
+
11
+
12
+ sys.path.append(".")
13
+ from metrics.psnr_ssim import calculate_psnr, calculate_ssim
14
+
15
+ from utils.build_utils import build_from_cfg
16
+ from utils.utils import InputPadder, img2tensor, read
17
+
18
+
19
+ def parse_path(path):
20
+ path_list = path.split("/")
21
+ new_path = osp.join(*path_list[-3:])
22
+ return new_path
23
+
24
+
25
+ parser = argparse.ArgumentParser(
26
+ prog="AMT",
27
+ description="SNU-FILM evaluation",
28
+ )
29
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml")
30
+ parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth")
31
+ parser.add_argument("-r", "--root", default="data/SNU_FILM")
32
+ args = parser.parse_args()
33
+
34
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35
+ cfg_path = args.config
36
+ ckpt_path = args.ckpt
37
+ root = args.root
38
+
39
+ network_cfg = OmegaConf.load(cfg_path).network
40
+ network_name = network_cfg.name
41
+ model = build_from_cfg(network_cfg)
42
+ ckpt = torch.load(ckpt_path)
43
+ model.load_state_dict(ckpt["state_dict"])
44
+ model = model.to(device)
45
+ model.eval()
46
+
47
+ divisor = 20
48
+ scale_factor = 0.8
49
+ splits = ["easy", "medium", "hard", "extreme"]
50
+ for split in splits:
51
+ with open(os.path.join(root, f"test-{split}.txt"), "r") as fr:
52
+ file_list = [l.strip().split(" ") for l in fr.readlines()]
53
+ pbar = tqdm.tqdm(file_list, total=len(file_list))
54
+
55
+ psnr_list = []
56
+ ssim_list = []
57
+ for name in pbar:
58
+ img0 = img2tensor(read(osp.join(root, parse_path(name[0])))).to(device)
59
+ imgt = img2tensor(read(osp.join(root, parse_path(name[1])))).to(device)
60
+ img1 = img2tensor(read(osp.join(root, parse_path(name[2])))).to(device)
61
+ padder = InputPadder(img0.shape, divisor)
62
+ img0, img1 = padder.pad(img0, img1)
63
+
64
+ embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device)
65
+ imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)["imgt_pred"]
66
+ imgt_pred = padder.unpad(imgt_pred)
67
+
68
+ psnr = calculate_psnr(imgt_pred, imgt).detach().cpu().numpy()
69
+ ssim = calculate_ssim(imgt_pred, imgt).detach().cpu().numpy()
70
+
71
+ psnr_list.append(psnr)
72
+ ssim_list.append(ssim)
73
+ avg_psnr = np.mean(psnr_list)
74
+ avg_ssim = np.mean(ssim_list)
75
+ desc_str = f"[{network_name}/SNU-FILM] [{split}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}"
76
+ pbar.set_description_str(desc_str)
Helios-main/eval/utils/third_party/amt/benchmarks/speed_parameters.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+ import time
4
+
5
+ import torch
6
+ from omegaconf import OmegaConf
7
+
8
+
9
+ sys.path.append(".")
10
+ from utils.build_utils import build_from_cfg
11
+
12
+
13
+ parser = argparse.ArgumentParser(
14
+ prog="AMT",
15
+ description="Speed&parameter benchmark",
16
+ )
17
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml")
18
+ args = parser.parse_args()
19
+
20
+ cfg_path = args.config
21
+ network_cfg = OmegaConf.load(cfg_path).network
22
+ model = build_from_cfg(network_cfg)
23
+ model = model.cuda()
24
+ model.eval()
25
+
26
+ img0 = torch.randn(1, 3, 256, 448).cuda()
27
+ img1 = torch.randn(1, 3, 256, 448).cuda()
28
+ embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).cuda()
29
+
30
+ with torch.no_grad():
31
+ for i in range(100):
32
+ out = model(img0, img1, embt, eval=True)
33
+ torch.cuda.synchronize()
34
+ time_stamp = time.time()
35
+ for i in range(1000):
36
+ out = model(img0, img1, embt, eval=True)
37
+ torch.cuda.synchronize()
38
+ print("Time: {:.5f}s".format((time.time() - time_stamp) / 1))
39
+
40
+ total = sum([param.nelement() for param in model.parameters()])
41
+ print("Parameters: {:.2f}M".format(total / 1e6))
Helios-main/eval/utils/third_party/amt/benchmarks/ucf101.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import os.path as osp
4
+ import sys
5
+
6
+ import numpy as np
7
+ import torch
8
+ import tqdm
9
+ from omegaconf import OmegaConf
10
+
11
+
12
+ sys.path.append(".")
13
+ from metrics.psnr_ssim import calculate_psnr, calculate_ssim
14
+
15
+ from utils.build_utils import build_from_cfg
16
+ from utils.utils import img2tensor, read
17
+
18
+
19
+ parser = argparse.ArgumentParser(
20
+ prog="AMT",
21
+ description="UCF101 evaluation",
22
+ )
23
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml")
24
+ parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth")
25
+ parser.add_argument("-r", "--root", default="data/ucf101_interp_ours")
26
+ args = parser.parse_args()
27
+
28
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
29
+ cfg_path = args.config
30
+ ckpt_path = args.ckpt
31
+ root = args.root
32
+
33
+ network_cfg = OmegaConf.load(cfg_path).network
34
+ network_name = network_cfg.name
35
+ model = build_from_cfg(network_cfg)
36
+ ckpt = torch.load(ckpt_path)
37
+ model.load_state_dict(ckpt["state_dict"])
38
+ model = model.to(device)
39
+ model.eval()
40
+
41
+ dirs = sorted(os.listdir(root))
42
+ psnr_list = []
43
+ ssim_list = []
44
+ pbar = tqdm.tqdm(dirs, total=len(dirs))
45
+ for d in pbar:
46
+ dir_path = osp.join(root, d)
47
+ I0 = img2tensor(read(osp.join(dir_path, "frame_00.png"))).to(device)
48
+ I1 = img2tensor(read(osp.join(dir_path, "frame_01_gt.png"))).to(device)
49
+ I2 = img2tensor(read(osp.join(dir_path, "frame_02.png"))).to(device)
50
+ embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device)
51
+
52
+ I1_pred = model(I0, I2, embt, eval=True)["imgt_pred"]
53
+
54
+ psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy()
55
+ ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy()
56
+
57
+ psnr_list.append(psnr)
58
+ ssim_list.append(ssim)
59
+
60
+ avg_psnr = np.mean(psnr_list)
61
+ avg_ssim = np.mean(ssim_list)
62
+ desc_str = f"[{network_name}/UCF101] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}"
63
+ pbar.set_description_str(desc_str)
Helios-main/eval/utils/third_party/amt/benchmarks/vimeo90k.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os.path as osp
3
+ import sys
4
+
5
+ import numpy as np
6
+ import torch
7
+ import tqdm
8
+ from omegaconf import OmegaConf
9
+
10
+
11
+ sys.path.append(".")
12
+ from metrics.psnr_ssim import calculate_psnr, calculate_ssim
13
+
14
+ from utils.build_utils import build_from_cfg
15
+ from utils.utils import img2tensor, read
16
+
17
+
18
+ parser = argparse.ArgumentParser(
19
+ prog="AMT",
20
+ description="Vimeo90K evaluation",
21
+ )
22
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml")
23
+ parser.add_argument(
24
+ "-p",
25
+ "--ckpt",
26
+ default="pretrained/amt-s.pth",
27
+ )
28
+ parser.add_argument(
29
+ "-r",
30
+ "--root",
31
+ default="data/vimeo_triplet",
32
+ )
33
+ args = parser.parse_args()
34
+
35
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
+ cfg_path = args.config
37
+ ckpt_path = args.ckpt
38
+ root = args.root
39
+
40
+ network_cfg = OmegaConf.load(cfg_path).network
41
+ network_name = network_cfg.name
42
+ model = build_from_cfg(network_cfg)
43
+ ckpt = torch.load(ckpt_path)
44
+ model.load_state_dict(ckpt["state_dict"])
45
+ model = model.to(device)
46
+ model.eval()
47
+
48
+ with open(osp.join(root, "tri_testlist.txt"), "r") as fr:
49
+ file_list = fr.readlines()
50
+
51
+ psnr_list = []
52
+ ssim_list = []
53
+
54
+ pbar = tqdm.tqdm(file_list, total=len(file_list))
55
+ for name in pbar:
56
+ name = str(name).strip()
57
+ if len(name) <= 1:
58
+ continue
59
+ dir_path = osp.join(root, "sequences", name)
60
+ I0 = img2tensor(read(osp.join(dir_path, "im1.png"))).to(device)
61
+ I1 = img2tensor(read(osp.join(dir_path, "im2.png"))).to(device)
62
+ I2 = img2tensor(read(osp.join(dir_path, "im3.png"))).to(device)
63
+ embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device)
64
+
65
+ I1_pred = model(I0, I2, embt, scale_factor=1.0, eval=True)["imgt_pred"]
66
+
67
+ psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy()
68
+ ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy()
69
+
70
+ psnr_list.append(psnr)
71
+ ssim_list.append(ssim)
72
+ avg_psnr = np.mean(psnr_list)
73
+ avg_ssim = np.mean(ssim_list)
74
+ desc_str = f"[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}"
75
+ pbar.set_description_str(desc_str)
Helios-main/eval/utils/third_party/amt/benchmarks/vimeo90k_tta.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os.path as osp
3
+ import sys
4
+
5
+ import numpy as np
6
+ import torch
7
+ import tqdm
8
+ from omegaconf import OmegaConf
9
+
10
+
11
+ sys.path.append(".")
12
+ from metrics.psnr_ssim import calculate_psnr, calculate_ssim
13
+
14
+ from utils.build_utils import build_from_cfg
15
+ from utils.utils import img2tensor, read
16
+
17
+
18
+ parser = argparse.ArgumentParser(
19
+ prog="AMT",
20
+ description="Vimeo90K evaluation (with Test-Time Augmentation)",
21
+ )
22
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml")
23
+ parser.add_argument(
24
+ "p",
25
+ "--ckpt",
26
+ default="pretrained/amt-s.pth",
27
+ )
28
+ parser.add_argument(
29
+ "-r",
30
+ "--root",
31
+ default="data/vimeo_triplet",
32
+ )
33
+ args = parser.parse_args()
34
+
35
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
+ cfg_path = args.config
37
+ ckpt_path = args.ckpt
38
+ root = args.root
39
+
40
+ network_cfg = OmegaConf.load(cfg_path).network
41
+ network_name = network_cfg.name
42
+ model = build_from_cfg(network_cfg)
43
+ ckpt = torch.load(ckpt_path)
44
+ model.load_state_dict(ckpt["state_dict"])
45
+ model = model.to(device)
46
+ model.eval()
47
+
48
+ with open(osp.join(root, "tri_testlist.txt"), "r") as fr:
49
+ file_list = fr.readlines()
50
+
51
+ psnr_list = []
52
+ ssim_list = []
53
+
54
+ pbar = tqdm.tqdm(file_list, total=len(file_list))
55
+ for name in pbar:
56
+ name = str(name).strip()
57
+ if len(name) <= 1:
58
+ continue
59
+ dir_path = osp.join(root, "sequences", name)
60
+ I0 = img2tensor(read(osp.join(dir_path, "im1.png"))).to(device)
61
+ I1 = img2tensor(read(osp.join(dir_path, "im2.png"))).to(device)
62
+ I2 = img2tensor(read(osp.join(dir_path, "im3.png"))).to(device)
63
+ embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device)
64
+
65
+ I1_pred1 = model(I0, I2, embt, scale_factor=1.0, eval=True)["imgt_pred"]
66
+ I1_pred2 = model(torch.flip(I0, [2]), torch.flip(I2, [2]), embt, scale_factor=1.0, eval=True)["imgt_pred"]
67
+ I1_pred = I1_pred1 / 2 + torch.flip(I1_pred2, [2]) / 2
68
+ psnr = calculate_psnr(I1_pred, I1).detach().cpu().numpy()
69
+ ssim = calculate_ssim(I1_pred, I1).detach().cpu().numpy()
70
+
71
+ psnr_list.append(psnr)
72
+ ssim_list.append(ssim)
73
+ avg_psnr = np.mean(psnr_list)
74
+ avg_ssim = np.mean(ssim_list)
75
+ desc_str = f"[{network_name}/Vimeo90K] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}"
76
+ pbar.set_description_str(desc_str)
Helios-main/eval/utils/third_party/amt/datasets/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/datasets/adobe_datasets.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ import numpy as np
5
+ import torch
6
+ from torch.utils.data import Dataset
7
+
8
+
9
+ sys.path.append(".")
10
+ from datasets.gopro_datasets import (
11
+ center_crop_woflow,
12
+ random_crop_woflow,
13
+ random_horizontal_flip_woflow,
14
+ random_resize_woflow,
15
+ random_reverse_channel_woflow,
16
+ random_reverse_time_woflow,
17
+ random_rotate_woflow,
18
+ random_vertical_flip_woflow,
19
+ )
20
+
21
+ from utils.utils import img2tensor, read
22
+
23
+
24
+ class Adobe240_Dataset(Dataset):
25
+ def __init__(self, dataset_dir="data/adobe240/test_frames", interFrames=7, augment=True):
26
+ super().__init__()
27
+ self.augment = augment
28
+ self.interFrames = interFrames
29
+ self.setLength = interFrames + 2
30
+ self.dataset_dir = os.path.join(dataset_dir)
31
+ video_list = os.listdir(self.dataset_dir)[9::10]
32
+ self.frames_list = []
33
+ self.file_list = []
34
+ for video in video_list:
35
+ frames = sorted(os.listdir(os.path.join(self.dataset_dir, video)))
36
+ n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1
37
+ videoInputs = [
38
+ frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets)
39
+ ]
40
+ videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs]
41
+ self.file_list.extend(videoInputs)
42
+
43
+ def __getitem__(self, idx):
44
+ clip_idx = idx // self.interFrames
45
+ embt_idx = idx % self.interFrames
46
+ imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]]
47
+ pick_idxs = list(range(0, self.setLength, self.interFrames + 1))
48
+ imgt_beg = self.setLength // 2 - self.interFrames // 2
49
+ imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2
50
+ imgt_idx = list(range(imgt_beg, imgt_end))
51
+ input_paths = [imgpaths[idx] for idx in pick_idxs]
52
+ imgt_paths = [imgpaths[idx] for idx in imgt_idx]
53
+
54
+ img0 = np.array(read(input_paths[0]))
55
+ imgt = np.array(read(imgt_paths[embt_idx]))
56
+ img1 = np.array(read(input_paths[1]))
57
+ embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32))
58
+
59
+ if self.augment:
60
+ img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1)
61
+ img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224))
62
+ img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5)
63
+ img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3)
64
+ img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5)
65
+ img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05)
66
+ img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1, embt=embt, p=0.5)
67
+ else:
68
+ img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512))
69
+
70
+ img0 = img2tensor(img0).squeeze(0)
71
+ imgt = img2tensor(imgt).squeeze(0)
72
+ img1 = img2tensor(img1).squeeze(0)
73
+
74
+ return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt}
75
+
76
+ def __len__(self):
77
+ return len(self.file_list) * self.interFrames
Helios-main/eval/utils/third_party/amt/datasets/gopro_datasets.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+ from torch.utils.data import Dataset
8
+
9
+ from utils.utils import img2tensor, read
10
+
11
+
12
+ def random_resize_woflow(img0, imgt, img1, p=0.1):
13
+ if random.uniform(0, 1) < p:
14
+ img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
15
+ imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
16
+ img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
17
+ return img0, imgt, img1
18
+
19
+
20
+ def random_crop_woflow(img0, imgt, img1, crop_size=(224, 224)):
21
+ h, w = crop_size[0], crop_size[1]
22
+ ih, iw, _ = img0.shape
23
+ x = np.random.randint(0, ih - h + 1)
24
+ y = np.random.randint(0, iw - w + 1)
25
+ img0 = img0[x : x + h, y : y + w, :]
26
+ imgt = imgt[x : x + h, y : y + w, :]
27
+ img1 = img1[x : x + h, y : y + w, :]
28
+ return img0, imgt, img1
29
+
30
+
31
+ def center_crop_woflow(img0, imgt, img1, crop_size=(512, 512)):
32
+ h, w = crop_size[0], crop_size[1]
33
+ ih, iw, _ = img0.shape
34
+ img0 = img0[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :]
35
+ imgt = imgt[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :]
36
+ img1 = img1[ih // 2 - h // 2 : ih // 2 + h // 2, iw // 2 - w // 2 : iw // 2 + w // 2, :]
37
+ return img0, imgt, img1
38
+
39
+
40
+ def random_reverse_channel_woflow(img0, imgt, img1, p=0.5):
41
+ if random.uniform(0, 1) < p:
42
+ img0 = img0[:, :, ::-1]
43
+ imgt = imgt[:, :, ::-1]
44
+ img1 = img1[:, :, ::-1]
45
+ return img0, imgt, img1
46
+
47
+
48
+ def random_vertical_flip_woflow(img0, imgt, img1, p=0.3):
49
+ if random.uniform(0, 1) < p:
50
+ img0 = img0[::-1]
51
+ imgt = imgt[::-1]
52
+ img1 = img1[::-1]
53
+ return img0, imgt, img1
54
+
55
+
56
+ def random_horizontal_flip_woflow(img0, imgt, img1, p=0.5):
57
+ if random.uniform(0, 1) < p:
58
+ img0 = img0[:, ::-1]
59
+ imgt = imgt[:, ::-1]
60
+ img1 = img1[:, ::-1]
61
+ return img0, imgt, img1
62
+
63
+
64
+ def random_rotate_woflow(img0, imgt, img1, p=0.05):
65
+ if random.uniform(0, 1) < p:
66
+ img0 = img0.transpose((1, 0, 2))
67
+ imgt = imgt.transpose((1, 0, 2))
68
+ img1 = img1.transpose((1, 0, 2))
69
+ return img0, imgt, img1
70
+
71
+
72
+ def random_reverse_time_woflow(img0, imgt, img1, embt, p=0.5):
73
+ if random.uniform(0, 1) < p:
74
+ tmp = img1
75
+ img1 = img0
76
+ img0 = tmp
77
+ embt = 1 - embt
78
+ return img0, imgt, img1, embt
79
+
80
+
81
+ class GoPro_Train_Dataset(Dataset):
82
+ def __init__(self, dataset_dir="data/GOPRO", interFrames=7, augment=True):
83
+ self.dataset_dir = dataset_dir + "/train"
84
+ self.interFrames = interFrames
85
+ self.augment = augment
86
+ self.setLength = interFrames + 2
87
+ video_list = [
88
+ "GOPR0372_07_00",
89
+ "GOPR0374_11_01",
90
+ "GOPR0378_13_00",
91
+ "GOPR0384_11_01",
92
+ "GOPR0384_11_04",
93
+ "GOPR0477_11_00",
94
+ "GOPR0868_11_02",
95
+ "GOPR0884_11_00",
96
+ "GOPR0372_07_01",
97
+ "GOPR0374_11_02",
98
+ "GOPR0379_11_00",
99
+ "GOPR0384_11_02",
100
+ "GOPR0385_11_00",
101
+ "GOPR0857_11_00",
102
+ "GOPR0871_11_01",
103
+ "GOPR0374_11_00",
104
+ "GOPR0374_11_03",
105
+ "GOPR0380_11_00",
106
+ "GOPR0384_11_03",
107
+ "GOPR0386_11_00",
108
+ "GOPR0868_11_01",
109
+ "GOPR0881_11_00",
110
+ ]
111
+ self.frames_list = []
112
+ self.file_list = []
113
+ for video in video_list:
114
+ frames = sorted(os.listdir(os.path.join(self.dataset_dir, video)))
115
+ n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1
116
+ videoInputs = [
117
+ frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets)
118
+ ]
119
+ videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs]
120
+ self.file_list.extend(videoInputs)
121
+
122
+ def __len__(self):
123
+ return len(self.file_list) * self.interFrames
124
+
125
+ def __getitem__(self, idx):
126
+ clip_idx = idx // self.interFrames
127
+ embt_idx = idx % self.interFrames
128
+ imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]]
129
+ pick_idxs = list(range(0, self.setLength, self.interFrames + 1))
130
+ imgt_beg = self.setLength // 2 - self.interFrames // 2
131
+ imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2
132
+ imgt_idx = list(range(imgt_beg, imgt_end))
133
+ input_paths = [imgpaths[idx] for idx in pick_idxs]
134
+ imgt_paths = [imgpaths[idx] for idx in imgt_idx]
135
+
136
+ embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32))
137
+ img0 = np.array(read(input_paths[0]))
138
+ imgt = np.array(read(imgt_paths[embt_idx]))
139
+ img1 = np.array(read(input_paths[1]))
140
+
141
+ if self.augment:
142
+ img0, imgt, img1 = random_resize_woflow(img0, imgt, img1, p=0.1)
143
+ img0, imgt, img1 = random_crop_woflow(img0, imgt, img1, crop_size=(224, 224))
144
+ img0, imgt, img1 = random_reverse_channel_woflow(img0, imgt, img1, p=0.5)
145
+ img0, imgt, img1 = random_vertical_flip_woflow(img0, imgt, img1, p=0.3)
146
+ img0, imgt, img1 = random_horizontal_flip_woflow(img0, imgt, img1, p=0.5)
147
+ img0, imgt, img1 = random_rotate_woflow(img0, imgt, img1, p=0.05)
148
+ img0, imgt, img1, embt = random_reverse_time_woflow(img0, imgt, img1, embt=embt, p=0.5)
149
+ else:
150
+ img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512))
151
+
152
+ img0 = img2tensor(img0.copy()).squeeze(0)
153
+ imgt = img2tensor(imgt.copy()).squeeze(0)
154
+ img1 = img2tensor(img1.copy()).squeeze(0)
155
+
156
+ return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt}
157
+
158
+
159
+ class GoPro_Test_Dataset(Dataset):
160
+ def __init__(self, dataset_dir="data/GOPRO", interFrames=7):
161
+ self.dataset_dir = dataset_dir + "/test"
162
+ self.interFrames = interFrames
163
+ self.setLength = interFrames + 2
164
+ video_list = [
165
+ "GOPR0384_11_00",
166
+ "GOPR0385_11_01",
167
+ "GOPR0410_11_00",
168
+ "GOPR0862_11_00",
169
+ "GOPR0869_11_00",
170
+ "GOPR0881_11_01",
171
+ "GOPR0384_11_05",
172
+ "GOPR0396_11_00",
173
+ "GOPR0854_11_00",
174
+ "GOPR0868_11_00",
175
+ "GOPR0871_11_00",
176
+ ]
177
+ self.frames_list = []
178
+ self.file_list = []
179
+ for video in video_list:
180
+ frames = sorted(os.listdir(os.path.join(self.dataset_dir, video)))
181
+ n_sets = (len(frames) - self.setLength) // (interFrames + 1) + 1
182
+ videoInputs = [
183
+ frames[(interFrames + 1) * i : (interFrames + 1) * i + self.setLength] for i in range(n_sets)
184
+ ]
185
+ videoInputs = [[os.path.join(video, f) for f in group] for group in videoInputs]
186
+ self.file_list.extend(videoInputs)
187
+
188
+ def __len__(self):
189
+ return len(self.file_list) * self.interFrames
190
+
191
+ def __getitem__(self, idx):
192
+ clip_idx = idx // self.interFrames
193
+ embt_idx = idx % self.interFrames
194
+ imgpaths = [os.path.join(self.dataset_dir, fp) for fp in self.file_list[clip_idx]]
195
+ pick_idxs = list(range(0, self.setLength, self.interFrames + 1))
196
+ imgt_beg = self.setLength // 2 - self.interFrames // 2
197
+ imgt_end = self.setLength // 2 + self.interFrames // 2 + self.interFrames % 2
198
+ imgt_idx = list(range(imgt_beg, imgt_end))
199
+ input_paths = [imgpaths[idx] for idx in pick_idxs]
200
+ imgt_paths = [imgpaths[idx] for idx in imgt_idx]
201
+
202
+ img0 = np.array(read(input_paths[0]))
203
+ imgt = np.array(read(imgt_paths[embt_idx]))
204
+ img1 = np.array(read(input_paths[1]))
205
+
206
+ img0, imgt, img1 = center_crop_woflow(img0, imgt, img1, crop_size=(512, 512))
207
+
208
+ img0 = img2tensor(img0).squeeze(0)
209
+ imgt = img2tensor(imgt).squeeze(0)
210
+ img1 = img2tensor(img1).squeeze(0)
211
+
212
+ embt = torch.from_numpy(np.array((embt_idx + 1) / (self.interFrames + 1)).reshape(1, 1, 1).astype(np.float32))
213
+ return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "embt": embt}
Helios-main/eval/utils/third_party/amt/datasets/vimeo_datasets.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+ from torch.utils.data import Dataset
8
+
9
+ from utils.utils import read
10
+
11
+
12
+ def random_resize(img0, imgt, img1, flow, p=0.1):
13
+ if random.uniform(0, 1) < p:
14
+ img0 = cv2.resize(img0, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
15
+ imgt = cv2.resize(imgt, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
16
+ img1 = cv2.resize(img1, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR)
17
+ flow = cv2.resize(flow, dsize=None, fx=2.0, fy=2.0, interpolation=cv2.INTER_LINEAR) * 2.0
18
+ return img0, imgt, img1, flow
19
+
20
+
21
+ def random_crop(img0, imgt, img1, flow, crop_size=(224, 224)):
22
+ h, w = crop_size[0], crop_size[1]
23
+ ih, iw, _ = img0.shape
24
+ x = np.random.randint(0, ih - h + 1)
25
+ y = np.random.randint(0, iw - w + 1)
26
+ img0 = img0[x : x + h, y : y + w, :]
27
+ imgt = imgt[x : x + h, y : y + w, :]
28
+ img1 = img1[x : x + h, y : y + w, :]
29
+ flow = flow[x : x + h, y : y + w, :]
30
+ return img0, imgt, img1, flow
31
+
32
+
33
+ def random_reverse_channel(img0, imgt, img1, flow, p=0.5):
34
+ if random.uniform(0, 1) < p:
35
+ img0 = img0[:, :, ::-1]
36
+ imgt = imgt[:, :, ::-1]
37
+ img1 = img1[:, :, ::-1]
38
+ return img0, imgt, img1, flow
39
+
40
+
41
+ def random_vertical_flip(img0, imgt, img1, flow, p=0.3):
42
+ if random.uniform(0, 1) < p:
43
+ img0 = img0[::-1]
44
+ imgt = imgt[::-1]
45
+ img1 = img1[::-1]
46
+ flow = flow[::-1]
47
+ flow = np.concatenate((flow[:, :, 0:1], -flow[:, :, 1:2], flow[:, :, 2:3], -flow[:, :, 3:4]), 2)
48
+ return img0, imgt, img1, flow
49
+
50
+
51
+ def random_horizontal_flip(img0, imgt, img1, flow, p=0.5):
52
+ if random.uniform(0, 1) < p:
53
+ img0 = img0[:, ::-1]
54
+ imgt = imgt[:, ::-1]
55
+ img1 = img1[:, ::-1]
56
+ flow = flow[:, ::-1]
57
+ flow = np.concatenate((-flow[:, :, 0:1], flow[:, :, 1:2], -flow[:, :, 2:3], flow[:, :, 3:4]), 2)
58
+ return img0, imgt, img1, flow
59
+
60
+
61
+ def random_rotate(img0, imgt, img1, flow, p=0.05):
62
+ if random.uniform(0, 1) < p:
63
+ img0 = img0.transpose((1, 0, 2))
64
+ imgt = imgt.transpose((1, 0, 2))
65
+ img1 = img1.transpose((1, 0, 2))
66
+ flow = flow.transpose((1, 0, 2))
67
+ flow = np.concatenate((flow[:, :, 1:2], flow[:, :, 0:1], flow[:, :, 3:4], flow[:, :, 2:3]), 2)
68
+ return img0, imgt, img1, flow
69
+
70
+
71
+ def random_reverse_time(img0, imgt, img1, flow, p=0.5):
72
+ if random.uniform(0, 1) < p:
73
+ tmp = img1
74
+ img1 = img0
75
+ img0 = tmp
76
+ flow = np.concatenate((flow[:, :, 2:4], flow[:, :, 0:2]), 2)
77
+ return img0, imgt, img1, flow
78
+
79
+
80
+ class Vimeo90K_Train_Dataset(Dataset):
81
+ def __init__(self, dataset_dir="data/vimeo_triplet", flow_dir=None, augment=True, crop_size=(224, 224)):
82
+ self.dataset_dir = dataset_dir
83
+ self.augment = augment
84
+ self.crop_size = crop_size
85
+ self.img0_list = []
86
+ self.imgt_list = []
87
+ self.img1_list = []
88
+ self.flow_t0_list = []
89
+ self.flow_t1_list = []
90
+ if flow_dir is None:
91
+ flow_dir = "flow"
92
+ with open(os.path.join(dataset_dir, "tri_trainlist.txt"), "r") as f:
93
+ for i in f:
94
+ name = str(i).strip()
95
+ if len(name) <= 1:
96
+ continue
97
+ self.img0_list.append(os.path.join(dataset_dir, "sequences", name, "im1.png"))
98
+ self.imgt_list.append(os.path.join(dataset_dir, "sequences", name, "im2.png"))
99
+ self.img1_list.append(os.path.join(dataset_dir, "sequences", name, "im3.png"))
100
+ self.flow_t0_list.append(os.path.join(dataset_dir, flow_dir, name, "flow_t0.flo"))
101
+ self.flow_t1_list.append(os.path.join(dataset_dir, flow_dir, name, "flow_t1.flo"))
102
+
103
+ def __len__(self):
104
+ return len(self.imgt_list)
105
+
106
+ def __getitem__(self, idx):
107
+ img0 = read(self.img0_list[idx])
108
+ imgt = read(self.imgt_list[idx])
109
+ img1 = read(self.img1_list[idx])
110
+ flow_t0 = read(self.flow_t0_list[idx])
111
+ flow_t1 = read(self.flow_t1_list[idx])
112
+ flow = np.concatenate((flow_t0, flow_t1), 2).astype(np.float64)
113
+
114
+ if self.augment:
115
+ img0, imgt, img1, flow = random_resize(img0, imgt, img1, flow, p=0.1)
116
+ img0, imgt, img1, flow = random_crop(img0, imgt, img1, flow, crop_size=self.crop_size)
117
+ img0, imgt, img1, flow = random_reverse_channel(img0, imgt, img1, flow, p=0.5)
118
+ img0, imgt, img1, flow = random_vertical_flip(img0, imgt, img1, flow, p=0.3)
119
+ img0, imgt, img1, flow = random_horizontal_flip(img0, imgt, img1, flow, p=0.5)
120
+ img0, imgt, img1, flow = random_rotate(img0, imgt, img1, flow, p=0.05)
121
+ img0, imgt, img1, flow = random_reverse_time(img0, imgt, img1, flow, p=0.5)
122
+
123
+ img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0)
124
+ imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0)
125
+ img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0)
126
+ flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32))
127
+ embt = torch.from_numpy(np.array(1 / 2).reshape(1, 1, 1).astype(np.float32))
128
+
129
+ return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "flow": flow.float(), "embt": embt}
130
+
131
+
132
+ class Vimeo90K_Test_Dataset(Dataset):
133
+ def __init__(self, dataset_dir="data/vimeo_triplet"):
134
+ self.dataset_dir = dataset_dir
135
+ self.img0_list = []
136
+ self.imgt_list = []
137
+ self.img1_list = []
138
+ self.flow_t0_list = []
139
+ self.flow_t1_list = []
140
+ with open(os.path.join(dataset_dir, "tri_testlist.txt"), "r") as f:
141
+ for i in f:
142
+ name = str(i).strip()
143
+ if len(name) <= 1:
144
+ continue
145
+ self.img0_list.append(os.path.join(dataset_dir, "sequences", name, "im1.png"))
146
+ self.imgt_list.append(os.path.join(dataset_dir, "sequences", name, "im2.png"))
147
+ self.img1_list.append(os.path.join(dataset_dir, "sequences", name, "im3.png"))
148
+ self.flow_t0_list.append(os.path.join(dataset_dir, "flow", name, "flow_t0.flo"))
149
+ self.flow_t1_list.append(os.path.join(dataset_dir, "flow", name, "flow_t1.flo"))
150
+
151
+ def __len__(self):
152
+ return len(self.imgt_list)
153
+
154
+ def __getitem__(self, idx):
155
+ img0 = read(self.img0_list[idx])
156
+ imgt = read(self.imgt_list[idx])
157
+ img1 = read(self.img1_list[idx])
158
+ flow_t0 = read(self.flow_t0_list[idx])
159
+ flow_t1 = read(self.flow_t1_list[idx])
160
+ flow = np.concatenate((flow_t0, flow_t1), 2)
161
+
162
+ img0 = torch.from_numpy(img0.transpose((2, 0, 1)).astype(np.float32) / 255.0)
163
+ imgt = torch.from_numpy(imgt.transpose((2, 0, 1)).astype(np.float32) / 255.0)
164
+ img1 = torch.from_numpy(img1.transpose((2, 0, 1)).astype(np.float32) / 255.0)
165
+ flow = torch.from_numpy(flow.transpose((2, 0, 1)).astype(np.float32))
166
+ embt = torch.from_numpy(np.array(1 / 2).reshape(1, 1, 1).astype(np.float32))
167
+
168
+ return {"img0": img0.float(), "imgt": imgt.float(), "img1": img1.float(), "flow": flow.float(), "embt": embt}
Helios-main/eval/utils/third_party/amt/docs/develop.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Development for evaluation and training
2
+
3
+ - [Datasets](#Datasets)
4
+ - [Pretrained Models](#pretrained-models)
5
+ - [Evaluation](#evaluation)
6
+ - [Training](#training)
7
+
8
+ ## Datasets<p id="Datasets"></p>
9
+ First, please prepare standard datasets for evaluation and training.
10
+
11
+ 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.
12
+
13
+ <table>
14
+ <thead>
15
+ <tr>
16
+ <th> Dataset </th>
17
+ <th> :link: Source </th>
18
+ <th> Train/Eval </th>
19
+ <th> Arbitrary/Fixed </th>
20
+ </tr>
21
+ </thead>
22
+ <tbody>
23
+ <tr>
24
+ <td>Vimeo90k</td>
25
+ <th><a href="http://toflow.csail.mit.edu/">ToFlow (IJCV 2019)</a></th>
26
+ <th>Both</th>
27
+ <th>Fixed</th>
28
+ </tr>
29
+ <tr>
30
+ <td>ATD-12K</td>
31
+ <th><a href="https://github.com/lisiyao21/AnimeInterp">AnimeInterp (CVPR 2021)</a></th>
32
+ <th>Both</th>
33
+ <th>Fixed</th>
34
+ </tr>
35
+ <tr>
36
+ <td>SNU-FILM</td>
37
+ <th><a href="https://myungsub.github.io/CAIN/">CAIN (AAAI 2021)</a></th>
38
+ <th>Eval</th>
39
+ <th>Fixed</th>
40
+ </tr>
41
+ <tr>
42
+ <td>UCF101</td>
43
+ <th><a href="https://drive.google.com/file/d/0B7EVK8r0v71pdHBNdXB6TE1wSTQ/view?resourcekey=0-r6ihCy20h3kbgZ3ZdimPiA">Google Driver</a></th>
44
+ <th>Eval</th>
45
+ <th>Fixed</th>
46
+ </tr>
47
+ <tr>
48
+ <td>HD</td>
49
+ <th><a href="https://github.com/baowenbo/MEMC-Net">MEMC-Net (TPAMI 2018)</a>/<a href="https://github.com/baowenbo/MEMC-Net">Google Driver</a></th>
50
+ <th>Eval</th>
51
+ <th>Fixed</th>
52
+ </tr>
53
+ <tr>
54
+ <td>Xiph-2k/-4k</td>
55
+ <th><a href="https://github.com/sniklaus/softmax-splatting/blob/master/benchmark_xiph.py">SoftSplat (CVPR 2020)</a></th>
56
+ <th>Eval</th>
57
+ <th>Fixed</th>
58
+ </tr>
59
+ <tr>
60
+ <td>MiddleBury</td>
61
+ <th><a href="https://vision.middlebury.edu/flow/data/">MiddleBury</a></th>
62
+ <th>Eval</th>
63
+ <th>Fixed</th>
64
+ </tr>
65
+ <tr>
66
+ <td>GoPro</td>
67
+ <th><a href="https://seungjunnah.github.io/Datasets/gopro">GoPro</a></th>
68
+ <th>Both</th>
69
+ <th>Arbitrary</th>
70
+ </tr>
71
+ <tr>
72
+ <td>Adobe240fps</td>
73
+ <th><a href="http://www.cs.ubc.ca/labs/imager/tr/2017/DeepVideoDeblurring">DBN (CVPR 2017)</a></th>
74
+ <th>Both</th>
75
+ <th>Arbitrary</th>
76
+ </tr>
77
+ <tr>
78
+ <td>X4K1000FPS</td>
79
+ <th><a href="https://github.com/JihyongOh/XVFI">XVFI (ICCV 2021)</a></th>
80
+ <th>Both</th>
81
+ <th>Arbitrary</th>
82
+ </tr>
83
+ </tbody>
84
+ </table>
85
+
86
+
87
+ ## Pretrained Models
88
+
89
+ <p id="Pretrained"></p>
90
+
91
+ <table>
92
+ <thead>
93
+ <tr>
94
+ <th> Dataset </th>
95
+ <th> :link: Download Links </th>
96
+ <th> Config file </th>
97
+ <th> Trained on </th>
98
+ <th> Arbitrary/Fixed </th>
99
+ </tr>
100
+ </thead>
101
+ <tbody>
102
+ <tr>
103
+ <td>AMT-S</td>
104
+ <th> [<a href="https://drive.google.com/file/d/1WmOKmQmd6pnLpID8EpUe-TddFpJuavrL/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1yGaNLeb9TG5-81t0skrOUA?pwd=f66n">Baidu Cloud</a>]</th>
105
+ <th> [<a href="../cfgs/AMT-S.yaml">cfgs/AMT-S</a>] </th>
106
+ <th>Vimeo90k</th>
107
+ <th>Fixed</th>
108
+ </tr>
109
+ <tr>
110
+ <td>AMT-L</td>
111
+ <th>[<a href="https://drive.google.com/file/d/1UyhYpAQLXMjFA55rlFZ0kdiSVTL7oU-z/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1qI4fBgS405Bd4Wn1R3Gbeg?pwd=nbne">Baidu Cloud</a>]</th>
112
+ <th> [<a href="../cfgs/AMT-L.yaml">cfgs/AMT-L</a>] </th>
113
+ <th>Vimeo90k</th>
114
+ <th>Fixed</th>
115
+ </tr>
116
+ <tr>
117
+ <td>AMT-G</td>
118
+ <th>[<a href="https://drive.google.com/file/d/1yieLtKh4ei3gOrLN1LhKSP_9157Q-mtP/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1AjmQVziQut1bXgQnDcDKvA?pwd=caf6">Baidu Cloud</a>]</th>
119
+ <th> [<a href="../cfgs/AMT-G.yaml">cfgs/AMT-G</a>] </th>
120
+ <th>Vimeo90k</th>
121
+ <th>Fixed</th>
122
+ </tr>
123
+ <tr>
124
+ <td>AMT-S</td>
125
+ <th>[<a href="https://drive.google.com/file/d/1f1xAF0EDm-rjDdny8_aLyeedfM0QL4-C/view?usp=share_link">Google Driver</a>][<a href="https://pan.baidu.com/s/1eZtoULyduQM8AkXeYEBOEw?pwd=8hy3">Baidu Cloud</a>]</th>
126
+ <th> [<a href="../cfgs/AMT-S_gopro.yaml">cfgs/AMT-S_gopro</a>] </th>
127
+ <th>GoPro</th>
128
+ <th>Arbitrary</th>
129
+ </tr>
130
+ </tbody>
131
+ </table>
132
+
133
+ ## Evaluation
134
+ Before evaluation, you should:
135
+
136
+ 1. Check the dataroot is organized as follows:
137
+
138
+ ```shell
139
+ ./data
140
+ ├── Adobe240
141
+ │ ├── original_high_fps_videos
142
+ │ └── test_frames # using ffmpeg to extract 240 fps frames from `original_high_fps_videos`
143
+ ├── GOPRO
144
+ │ ├── test
145
+ │ └── train
146
+ ├── SNU_FILM
147
+ │ ├── GOPRO_test
148
+ │ ├── test-easy.txt
149
+ │ ├── test-extreme.txt
150
+ │ ├── test-hard.txt
151
+ │ ├── test-medium.txt
152
+ │ └── YouTube_test
153
+ ├── ucf101_interp_ours
154
+ │ ├── 1
155
+ │ ├── 1001
156
+ │ └── ...
157
+ └── vimeo_triplet
158
+ ├── readme.txt
159
+ ├── sequences
160
+ ├── tri_testlist.txt
161
+ └── tri_trainlist.txt
162
+ ```
163
+
164
+ 2. Download the provided [pretrained models](#pretrained-models).
165
+
166
+ Then, you can perform evaluation as follows:
167
+
168
+ + Run all benchmarks for fixed-time models.
169
+
170
+ ```shell
171
+ sh ./scripts/benchmark_fixed.sh [CFG] [CKPT_PATH]
172
+ ## e.g.
173
+ sh ./scripts/benchmark_fixed.sh cfgs/AMT-S.yaml pretrained/amt-s.pth
174
+ ```
175
+
176
+ + Run all benchmarks for arbitrary-time models.
177
+
178
+ ```shell
179
+ sh ./scripts/benchmark_arbitrary.sh [CFG] [CKPT_PATH]
180
+ ## e.g.
181
+ sh ./scripts/benchmark_arbitrary.sh cfgs/AMT-S.yaml pretrained/gopro_amt-s.pth
182
+ ```
183
+
184
+ + Run a single benchmark for fixed-time models. *You can custom data paths in this case*.
185
+
186
+ ```shell
187
+ python [BENCHMARK] -c [CFG] -p [CKPT_PATH] -r [DATAROOT]
188
+ ## e.g.
189
+ python benchmarks/vimeo90k.py -c cfgs/AMT-S.yaml -p pretrained/amt-s.pth -r data/vimeo_triplet
190
+ ```
191
+
192
+ + Run the inference speed & model size comparisons using:
193
+
194
+ ```shell
195
+ python speed_parameters.py -c [CFG]
196
+ ## e.g.
197
+ python speed_parameters.py -c cfgs/AMT-S.yaml
198
+ ```
199
+
200
+
201
+ ## Training
202
+
203
+ Before training, please first prepare the optical flows (which are used for supervision).
204
+
205
+ We need to install `cupy` first before flow generation:
206
+
207
+ ```shell
208
+ conda activate amt # satisfying `requirement.txt`
209
+ conda install -c conda-forge cupy
210
+ ```
211
+
212
+
213
+ After installing `cupy`, we can generate optical flows by the following command:
214
+
215
+ ```shell
216
+ python flow_generation/gen_flow.py -r [DATA_ROOT]
217
+ ## e.g.
218
+ python flow_generation/gen_flow.py -r data/vimeo_triplet
219
+ ```
220
+
221
+ After obtaining the optical flow of the training data,
222
+ run the following commands for training (DDP mode):
223
+
224
+ ```shell
225
+ sh ./scripts/train.sh [NUM_GPU] [CFG] [MASTER_PORT]
226
+ ## e.g.
227
+ sh ./scripts/train.sh 2 cfgs/AMT-S.yaml 14514
228
+ ```
229
+
230
+ Our training configuration files are provided in [`cfgs`](../cfgs). Please carefully check the `dataset_dir` is suitable for you.
231
+
232
+
233
+ Note:
234
+
235
+ - If you intend to turn off DDP training, you can switch the key `distributed` from `true`
236
+ to `false` in the config file.
237
+
238
+ - If you do not use wandb, you can switch the key `logger.use_wandb` from `true`
239
+ to `false` in the config file.
Helios-main/eval/utils/third_party/amt/docs/method.md ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Illustration of AMT
2
+
3
+ <p align="center">
4
+ <img src="https://user-images.githubusercontent.com/21050959/229420451-65951bd0-732c-4f09-9121-f291a3862d6e.png" width="1200">
5
+ </p>
6
+
7
+ ### :rocket: Highlights:
8
+
9
+ + [**Good tradeoff**](#good-tradeoff) between performance and efficiency.
10
+
11
+ + [**All-pairs correlation**](#all-pairs-correlation) for modeling large motions during interpolation.
12
+
13
+ + A [**plug-and-play operator**](#multi-field-refinement) to improve the diversity of predicted task-oriented flows, further **boosting the interpolation performance**.
14
+
15
+
16
+ ## Good Tradeoff
17
+
18
+ <p align="left">
19
+ <img src="https://user-images.githubusercontent.com/21050959/229470703-2f386d62-d26c-46a3-af97-ddfc4270678a.png" width="500">
20
+ </p>
21
+
22
+ 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
23
+ 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.
24
+
25
+ Considering its effectiveness, we hope our AMT could bring a new perspective for the architecture design in efficient frame interpolation.
26
+
27
+ ## All-pairs correlation
28
+
29
+ We build all-pairs correlation to effectively model large motions during interpolation.
30
+
31
+ Here is an example about the update operation at a single scale in AMT:
32
+
33
+ ```python
34
+ # Construct bidirectional correlation volumes
35
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [B, C, H//8, W//8]
36
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
37
+
38
+ # Correlation scaled lookup (bilateral -> bidirectional)
39
+ t1_scale = 1. / embt
40
+ t0_scale = 1. / (1. - embt)
41
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
42
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
43
+ corr = torch.cat([corr0, corr1], dim=1)
44
+ flow = torch.cat([flow0, flow1], dim=1)
45
+
46
+ # Update both intermediate feature and bilateral flows
47
+ delta_feat, delta_flow = self.update(feat, flow, corr)
48
+ delta_flow0, delta_flow1 = torch.chunk(delta_flow, 2, 1)
49
+ flow0 = flow0 + delta_flow0
50
+ flow1= flow1 + delta_flow1
51
+ feat = feat + delta_feat
52
+
53
+ ```
54
+
55
+ Note: we extend above operations to each pyramid scale (except for the last one), which guarantees the consistency of flows on the coarse scale.
56
+
57
+ ### ⏫ performance gain
58
+ | | Vimeo 90k | Hard | Extreme |
59
+ |-------------------------|-----------|-------|---------|
60
+ | Baseline | 35.60 | 30.39 | 25.06 |
61
+ | + All-pairs correlation | 35.97 (**+0.37**) | 30.60 (**+0.21**) | 25.30 (**+0.24**) |
62
+
63
+ More ablations can be found in the [paper](https://arxiv.org/abs/2304.09790).
64
+
65
+ ## Multi-field Refinement
66
+
67
+ For most frame interpolation methods which are based on backward warping, the common formulation for
68
+ interpolating the final intermediate frame $I_{t}$ is:
69
+
70
+ $I_{t} = M \odot \mathcal{W}(I_{0}, F_{t\rightarrow 0}) + (1 - M) \odot \mathcal{W}(I_{1}, F_{t\rightarrow 1}) + R$
71
+
72
+ 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$.
73
+
74
+ Multi-field refinement aims to improve the common formulation of backward warping.
75
+ 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.
76
+ 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.
77
+
78
+ Please refer to [this code snippet](../networks/blocks/multi_flow.py#L46) for the details of the first step.
79
+ Please refer to [this code snippet](../networks/blocks/multi_flow.py#L10) for the details of the last two steps.
80
+
81
+ ### 🌟 easy to use
82
+ The proposed multi-field refinement can be **easily migrated to any frame interpolation model** to improve the performance.
83
+
84
+ Code examples are shown below:
85
+
86
+ ```python
87
+
88
+ # (At the __init__ stage) Initialize a decoder that predicts multiple flow fields (accompanied by the corresponding masks and residuals)
89
+ self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
90
+ ...
91
+
92
+ # (At the forward stage) Predict multiple flow fields (accompanied by the corresponding masks and residuals)
93
+ up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
94
+ # Merge multiple predictions
95
+ imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, # self.comb_block stacks two convolutional layers
96
+ mask, img_res, mean_)
97
+
98
+ ```
99
+
100
+ ### ⏫ performance gain
101
+
102
+ | # Number of flow pairs | Vimeo 90k | Hard | Extreme |
103
+ |------------------------|---------------|---------------|---------------|
104
+ | Baseline (1 pair) | 35.84 | 30.52 | 25.25 |
105
+ | 3 pairs | 35.97 (**+0.13**) | 30.60 (**+0.08**) | 25.30 (**+0.05**) |
106
+ | 5 pairs | 36.00 (**+0.16**) | 30.63 (**+0.11**) | 25.33 (**+0.08**) |
107
+
108
+ ## Comparison with SOTA methods
109
+ <p align="left">
110
+ <img src="https://user-images.githubusercontent.com/21050959/230716340-dea52895-1713-4857-97e5-48cdff9c478f.png" width="1200">
111
+ </p>
112
+
113
+
114
+ ## Discussions
115
+
116
+ We encountered the challenges about the novelty issue during the rebuttal process.
117
+
118
+ We are ready to clarify again here:
119
+
120
+ 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
121
+ 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.
122
+ 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
123
+ 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).
124
+ 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
125
+
126
+ More discussions and details can be found in the [appendix](https://arxiv.org/abs/2304.09790) of our paper.
Helios-main/eval/utils/third_party/amt/environment.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: amt
2
+ channels:
3
+ - pytorch
4
+ - conda-forge
5
+ - defaults
6
+ dependencies:
7
+ - python=3.8.5
8
+ - pip=20.3
9
+ - cudatoolkit=11.3
10
+ - pytorch=1.11.0
11
+ - torchvision=0.12.0
12
+ - numpy=1.21.5
13
+ - pip:
14
+ - opencv-python==4.1.2.30
15
+ - imageio==2.19.3
16
+ - omegaconf==2.3.0
17
+ - Pillow==9.4.0
18
+ - tqdm==4.64.1
19
+ - wandb==0.12.21
Helios-main/eval/utils/third_party/amt/losses/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/losses/loss.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+
7
+ class Loss(nn.Module):
8
+ def __init__(self, loss_weight, keys, mapping=None) -> None:
9
+ """
10
+ mapping: map the kwargs keys into desired ones.
11
+ """
12
+ super().__init__()
13
+ self.loss_weight = loss_weight
14
+ self.keys = keys
15
+ self.mapping = mapping
16
+ if isinstance(mapping, dict):
17
+ self.mapping = {k: v for k, v in mapping if v in keys}
18
+
19
+ def forward(self, **kwargs):
20
+ params = {k: v for k, v in kwargs.items() if k in self.keys}
21
+ if self.mapping is not None:
22
+ for k, v in kwargs.items():
23
+ if self.mapping.get(k) is not None:
24
+ params[self.mapping[k]] = v
25
+
26
+ return self._forward(**params) * self.loss_weight
27
+
28
+ def _forward(self, **kwargs):
29
+ pass
30
+
31
+
32
+ class CharbonnierLoss(Loss):
33
+ def __init__(self, loss_weight, keys) -> None:
34
+ super().__init__(loss_weight, keys)
35
+
36
+ def _forward(self, imgt_pred, imgt):
37
+ diff = imgt_pred - imgt
38
+ loss = ((diff**2 + 1e-6) ** 0.5).mean()
39
+ return loss
40
+
41
+
42
+ class AdaCharbonnierLoss(Loss):
43
+ def __init__(self, loss_weight, keys) -> None:
44
+ super().__init__(loss_weight, keys)
45
+
46
+ def _forward(self, imgt_pred, imgt, weight):
47
+ alpha = weight / 2
48
+ epsilon = 10 ** (-(10 * weight - 1) / 3)
49
+
50
+ diff = imgt_pred - imgt
51
+ loss = ((diff**2 + epsilon**2) ** alpha).mean()
52
+ return loss
53
+
54
+
55
+ class TernaryLoss(Loss):
56
+ def __init__(self, loss_weight, keys, patch_size=7):
57
+ super().__init__(loss_weight, keys)
58
+ self.patch_size = patch_size
59
+ out_channels = patch_size * patch_size
60
+ self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels))
61
+ self.w = np.transpose(self.w, (3, 2, 0, 1))
62
+ self.w = torch.tensor(self.w, dtype=torch.float32)
63
+
64
+ def transform(self, tensor):
65
+ self.w = self.w.to(tensor.device)
66
+ tensor_ = tensor.mean(dim=1, keepdim=True)
67
+ patches = F.conv2d(tensor_, self.w, padding=self.patch_size // 2, bias=None)
68
+ loc_diff = patches - tensor_
69
+ loc_diff_norm = loc_diff / torch.sqrt(0.81 + loc_diff**2)
70
+ return loc_diff_norm
71
+
72
+ def valid_mask(self, tensor):
73
+ padding = self.patch_size // 2
74
+ b, c, h, w = tensor.size()
75
+ inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor)
76
+ mask = F.pad(inner, [padding] * 4)
77
+ return mask
78
+
79
+ def _forward(self, imgt_pred, imgt):
80
+ loc_diff_x = self.transform(imgt_pred)
81
+ loc_diff_y = self.transform(imgt)
82
+ diff = loc_diff_x - loc_diff_y.detach()
83
+ dist = (diff**2 / (0.1 + diff**2)).mean(dim=1, keepdim=True)
84
+ mask = self.valid_mask(imgt_pred)
85
+ loss = (dist * mask).mean()
86
+ return loss
87
+
88
+
89
+ class GeometryLoss(Loss):
90
+ def __init__(self, loss_weight, keys, patch_size=3):
91
+ super().__init__(loss_weight, keys)
92
+ self.patch_size = patch_size
93
+ out_channels = patch_size * patch_size
94
+ self.w = np.eye(out_channels).reshape((patch_size, patch_size, 1, out_channels))
95
+ self.w = np.transpose(self.w, (3, 2, 0, 1))
96
+ self.w = torch.tensor(self.w).float()
97
+
98
+ def transform(self, tensor):
99
+ b, c, h, w = tensor.size()
100
+ self.w = self.w.to(tensor.device)
101
+ tensor_ = tensor.reshape(b * c, 1, h, w)
102
+ patches = F.conv2d(tensor_, self.w, padding=self.patch_size // 2, bias=None)
103
+ loc_diff = patches - tensor_
104
+ loc_diff_ = loc_diff.reshape(b, c * (self.patch_size**2), h, w)
105
+ loc_diff_norm = loc_diff_ / torch.sqrt(0.81 + loc_diff_**2)
106
+ return loc_diff_norm
107
+
108
+ def valid_mask(self, tensor):
109
+ padding = self.patch_size // 2
110
+ b, c, h, w = tensor.size()
111
+ inner = torch.ones(b, 1, h - 2 * padding, w - 2 * padding).type_as(tensor)
112
+ mask = F.pad(inner, [padding] * 4)
113
+ return mask
114
+
115
+ def _forward(self, ft_pred, ft_gt):
116
+ loss = 0.0
117
+ for pred, gt in zip(ft_pred, ft_gt):
118
+ loc_diff_x = self.transform(pred)
119
+ loc_diff_y = self.transform(gt)
120
+ diff = loc_diff_x - loc_diff_y
121
+ dist = (diff**2 / (0.1 + diff**2)).mean(dim=1, keepdim=True)
122
+ mask = self.valid_mask(pred)
123
+ loss = loss + (dist * mask).mean()
124
+ return loss
125
+
126
+
127
+ class IFRFlowLoss(Loss):
128
+ def __init__(self, loss_weight, keys, beta=0.3) -> None:
129
+ super().__init__(loss_weight, keys)
130
+ self.beta = beta
131
+ self.ada_cb_loss = AdaCharbonnierLoss(1.0, ["imgt_pred", "imgt", "weight"])
132
+
133
+ def _forward(self, flow0_pred, flow1_pred, flow):
134
+ robust_weight0 = self.get_robust_weight(flow0_pred[0], flow[:, 0:2])
135
+ robust_weight1 = self.get_robust_weight(flow1_pred[0], flow[:, 2:4])
136
+ loss = 0
137
+ for lvl in range(1, len(flow0_pred)):
138
+ scale_factor = 2**lvl
139
+ loss = loss + self.ada_cb_loss(
140
+ **{
141
+ "imgt_pred": self.resize(flow0_pred[lvl], scale_factor),
142
+ "imgt": flow[:, 0:2],
143
+ "weight": robust_weight0,
144
+ }
145
+ )
146
+ loss = loss + self.ada_cb_loss(
147
+ **{
148
+ "imgt_pred": self.resize(flow1_pred[lvl], scale_factor),
149
+ "imgt": flow[:, 2:4],
150
+ "weight": robust_weight1,
151
+ }
152
+ )
153
+ return loss
154
+
155
+ def resize(self, x, scale_factor):
156
+ return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
157
+
158
+ def get_robust_weight(self, flow_pred, flow_gt):
159
+ epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=1, keepdim=True) ** 0.5
160
+ robust_weight = torch.exp(-self.beta * epe)
161
+ return robust_weight
162
+
163
+
164
+ class MultipleFlowLoss(Loss):
165
+ def __init__(self, loss_weight, keys, beta=0.3) -> None:
166
+ super().__init__(loss_weight, keys)
167
+ self.beta = beta
168
+ self.ada_cb_loss = AdaCharbonnierLoss(1.0, ["imgt_pred", "imgt", "weight"])
169
+
170
+ def _forward(self, flow0_pred, flow1_pred, flow):
171
+ robust_weight0 = self.get_mutli_flow_robust_weight(flow0_pred[0], flow[:, 0:2])
172
+ robust_weight1 = self.get_mutli_flow_robust_weight(flow1_pred[0], flow[:, 2:4])
173
+ loss = 0
174
+ for lvl in range(1, len(flow0_pred)):
175
+ scale_factor = 2**lvl
176
+ loss = loss + self.ada_cb_loss(
177
+ **{
178
+ "imgt_pred": self.resize(flow0_pred[lvl], scale_factor),
179
+ "imgt": flow[:, 0:2],
180
+ "weight": robust_weight0,
181
+ }
182
+ )
183
+ loss = loss + self.ada_cb_loss(
184
+ **{
185
+ "imgt_pred": self.resize(flow1_pred[lvl], scale_factor),
186
+ "imgt": flow[:, 2:4],
187
+ "weight": robust_weight1,
188
+ }
189
+ )
190
+ return loss
191
+
192
+ def resize(self, x, scale_factor):
193
+ return scale_factor * F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
194
+
195
+ def get_mutli_flow_robust_weight(self, flow_pred, flow_gt):
196
+ b, num_flows, c, h, w = flow_pred.shape
197
+ flow_pred = flow_pred.view(b, num_flows, c, h, w)
198
+ flow_gt = flow_gt.repeat(1, num_flows, 1, 1).view(b, num_flows, c, h, w)
199
+ epe = ((flow_pred.detach() - flow_gt) ** 2).sum(dim=2, keepdim=True).max(1)[0] ** 0.5
200
+ robust_weight = torch.exp(-self.beta * epe)
201
+ return robust_weight
Helios-main/eval/utils/third_party/amt/metrics/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/metrics/psnr_ssim.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import exp
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+
7
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
+
9
+
10
+ def gaussian(window_size, sigma):
11
+ gauss = torch.Tensor([exp(-((x - window_size // 2) ** 2) / float(2 * sigma**2)) for x in range(window_size)])
12
+ return gauss / gauss.sum()
13
+
14
+
15
+ def create_window(window_size, channel=1):
16
+ _1D_window = gaussian(window_size, 1.5).unsqueeze(1)
17
+ _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0).to(device)
18
+ window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
19
+ return window
20
+
21
+
22
+ def create_window_3d(window_size, channel=1):
23
+ _1D_window = gaussian(window_size, 1.5).unsqueeze(1)
24
+ _2D_window = _1D_window.mm(_1D_window.t())
25
+ _3D_window = _2D_window.unsqueeze(2) @ (_1D_window.t())
26
+ window = _3D_window.expand(1, channel, window_size, window_size, window_size).contiguous().to(device)
27
+ return window
28
+
29
+
30
+ def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
31
+ if val_range is None:
32
+ if torch.max(img1) > 128:
33
+ max_val = 255
34
+ else:
35
+ max_val = 1
36
+
37
+ if torch.min(img1) < -0.5:
38
+ min_val = -1
39
+ else:
40
+ min_val = 0
41
+ L = max_val - min_val
42
+ else:
43
+ L = val_range
44
+
45
+ padd = 0
46
+ (_, channel, height, width) = img1.size()
47
+ if window is None:
48
+ real_size = min(window_size, height, width)
49
+ window = create_window(real_size, channel=channel).to(img1.device)
50
+
51
+ mu1 = F.conv2d(F.pad(img1, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel)
52
+ mu2 = F.conv2d(F.pad(img2, (5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=channel)
53
+
54
+ mu1_sq = mu1.pow(2)
55
+ mu2_sq = mu2.pow(2)
56
+ mu1_mu2 = mu1 * mu2
57
+
58
+ sigma1_sq = F.conv2d(F.pad(img1 * img1, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_sq
59
+ sigma2_sq = F.conv2d(F.pad(img2 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu2_sq
60
+ sigma12 = F.conv2d(F.pad(img1 * img2, (5, 5, 5, 5), "replicate"), window, padding=padd, groups=channel) - mu1_mu2
61
+
62
+ C1 = (0.01 * L) ** 2
63
+ C2 = (0.03 * L) ** 2
64
+
65
+ v1 = 2.0 * sigma12 + C2
66
+ v2 = sigma1_sq + sigma2_sq + C2
67
+ cs = torch.mean(v1 / v2)
68
+
69
+ ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
70
+
71
+ if size_average:
72
+ ret = ssim_map.mean()
73
+ else:
74
+ ret = ssim_map.mean(1).mean(1).mean(1)
75
+
76
+ if full:
77
+ return ret, cs
78
+ return ret
79
+
80
+
81
+ def calculate_ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
82
+ if val_range is None:
83
+ if torch.max(img1) > 128:
84
+ max_val = 255
85
+ else:
86
+ max_val = 1
87
+
88
+ if torch.min(img1) < -0.5:
89
+ min_val = -1
90
+ else:
91
+ min_val = 0
92
+ L = max_val - min_val
93
+ else:
94
+ L = val_range
95
+
96
+ padd = 0
97
+ (_, _, height, width) = img1.size()
98
+ if window is None:
99
+ real_size = min(window_size, height, width)
100
+ window = create_window_3d(real_size, channel=1).to(img1.device)
101
+
102
+ img1 = img1.unsqueeze(1)
103
+ img2 = img2.unsqueeze(1)
104
+
105
+ mu1 = F.conv3d(F.pad(img1, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1)
106
+ mu2 = F.conv3d(F.pad(img2, (5, 5, 5, 5, 5, 5), mode="replicate"), window, padding=padd, groups=1)
107
+
108
+ mu1_sq = mu1.pow(2)
109
+ mu2_sq = mu2.pow(2)
110
+ mu1_mu2 = mu1 * mu2
111
+
112
+ sigma1_sq = F.conv3d(F.pad(img1 * img1, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_sq
113
+ sigma2_sq = F.conv3d(F.pad(img2 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu2_sq
114
+ sigma12 = F.conv3d(F.pad(img1 * img2, (5, 5, 5, 5, 5, 5), "replicate"), window, padding=padd, groups=1) - mu1_mu2
115
+
116
+ C1 = (0.01 * L) ** 2
117
+ C2 = (0.03 * L) ** 2
118
+
119
+ v1 = 2.0 * sigma12 + C2
120
+ v2 = sigma1_sq + sigma2_sq + C2
121
+ cs = torch.mean(v1 / v2)
122
+
123
+ ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2)
124
+
125
+ if size_average:
126
+ ret = ssim_map.mean()
127
+ else:
128
+ ret = ssim_map.mean(1).mean(1).mean(1)
129
+
130
+ if full:
131
+ return ret, cs
132
+ return ret.detach().cpu().numpy()
133
+
134
+
135
+ def calculate_psnr(img1, img2):
136
+ psnr = -10 * torch.log10(((img1 - img2) * (img1 - img2)).mean())
137
+ return psnr.detach().cpu().numpy()
138
+
139
+
140
+ def calculate_ie(img1, img2):
141
+ ie = torch.abs(torch.round(img1 * 255.0) - torch.round(img2 * 255.0)).mean()
142
+ return ie.detach().cpu().numpy()
Helios-main/eval/utils/third_party/amt/networks/AMT-G.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from utils.third_party.amt.networks.blocks.feat_enc import LargeEncoder
5
+ from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize
6
+ from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine
7
+ from utils.third_party.amt.networks.blocks.raft import BasicUpdateBlock, BidirCorrBlock, coords_grid
8
+
9
+
10
+ class Model(nn.Module):
11
+ def __init__(self, corr_radius=3, corr_lvls=4, num_flows=5, channels=[84, 96, 112, 128], skip_channels=84):
12
+ super(Model, self).__init__()
13
+ self.radius = corr_radius
14
+ self.corr_levels = corr_lvls
15
+ self.num_flows = num_flows
16
+
17
+ self.feat_encoder = LargeEncoder(output_dim=128, norm_fn="instance", dropout=0.0)
18
+ self.encoder = Encoder(channels, large=True)
19
+ self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels)
20
+ self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels)
21
+ self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels)
22
+ self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
23
+
24
+ self.update4 = self._get_updateblock(112, None)
25
+ self.update3_low = self._get_updateblock(96, 2.0)
26
+ self.update2_low = self._get_updateblock(84, 4.0)
27
+
28
+ self.update3_high = self._get_updateblock(96, None)
29
+ self.update2_high = self._get_updateblock(84, None)
30
+
31
+ self.comb_block = nn.Sequential(
32
+ nn.Conv2d(3 * self.num_flows, 6 * self.num_flows, 7, 1, 3),
33
+ nn.PReLU(6 * self.num_flows),
34
+ nn.Conv2d(6 * self.num_flows, 3, 7, 1, 3),
35
+ )
36
+
37
+ def _get_updateblock(self, cdim, scale_factor=None):
38
+ return BasicUpdateBlock(
39
+ cdim=cdim,
40
+ hidden_dim=192,
41
+ flow_dim=64,
42
+ corr_dim=256,
43
+ corr_dim2=192,
44
+ fc_dim=188,
45
+ scale_factor=scale_factor,
46
+ corr_levels=self.corr_levels,
47
+ radius=self.radius,
48
+ )
49
+
50
+ def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1):
51
+ # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0
52
+ # based on linear assumption
53
+ t1_scale = 1.0 / embt
54
+ t0_scale = 1.0 / (1.0 - embt)
55
+ if downsample != 1:
56
+ inv = 1 / downsample
57
+ flow0 = inv * resize(flow0, scale_factor=inv)
58
+ flow1 = inv * resize(flow1, scale_factor=inv)
59
+
60
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
61
+ corr = torch.cat([corr0, corr1], dim=1)
62
+ flow = torch.cat([flow0, flow1], dim=1)
63
+ return corr, flow
64
+
65
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
66
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
67
+ img0 = img0 - mean_
68
+ img1 = img1 - mean_
69
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
70
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
71
+ b, _, h, w = img0_.shape
72
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
73
+
74
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8]
75
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
76
+
77
+ # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4]
78
+ # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16]
79
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
80
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
81
+
82
+ ######################################### the 4th decoder #########################################
83
+ up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt)
84
+ corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1)
85
+
86
+ # residue update with lookup corr
87
+ delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4)
88
+ delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1)
89
+ up_flow0_4 = up_flow0_4 + delta_flow0_4
90
+ up_flow1_4 = up_flow1_4 + delta_flow1_4
91
+ ft_3_ = ft_3_ + delta_ft_3_
92
+
93
+ ######################################### the 3rd decoder #########################################
94
+ up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
95
+ corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2)
96
+
97
+ # residue update with lookup corr
98
+ delta_ft_2_, delta_flow_3 = self.update3_low(ft_2_, flow_3, corr_3)
99
+ delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1)
100
+ up_flow0_3 = up_flow0_3 + delta_flow0_3
101
+ up_flow1_3 = up_flow1_3 + delta_flow1_3
102
+ ft_2_ = ft_2_ + delta_ft_2_
103
+
104
+ # residue update with lookup corr (hr)
105
+ corr_3 = resize(corr_3, scale_factor=2.0)
106
+ up_flow_3 = torch.cat([up_flow0_3, up_flow1_3], dim=1)
107
+ delta_ft_2_, delta_up_flow_3 = self.update3_high(ft_2_, up_flow_3, corr_3)
108
+ ft_2_ += delta_ft_2_
109
+ up_flow0_3 += delta_up_flow_3[:, 0:2]
110
+ up_flow1_3 += delta_up_flow_3[:, 2:4]
111
+
112
+ ######################################### the 2nd decoder #########################################
113
+ up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
114
+ corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4)
115
+
116
+ # residue update with lookup corr
117
+ delta_ft_1_, delta_flow_2 = self.update2_low(ft_1_, flow_2, corr_2)
118
+ delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1)
119
+ up_flow0_2 = up_flow0_2 + delta_flow0_2
120
+ up_flow1_2 = up_flow1_2 + delta_flow1_2
121
+ ft_1_ = ft_1_ + delta_ft_1_
122
+
123
+ # residue update with lookup corr (hr)
124
+ corr_2 = resize(corr_2, scale_factor=4.0)
125
+ up_flow_2 = torch.cat([up_flow0_2, up_flow1_2], dim=1)
126
+ delta_ft_1_, delta_up_flow_2 = self.update2_high(ft_1_, up_flow_2, corr_2)
127
+ ft_1_ += delta_ft_1_
128
+ up_flow0_2 += delta_up_flow_2[:, 0:2]
129
+ up_flow1_2 += delta_up_flow_2[:, 2:4]
130
+
131
+ ######################################### the 1st decoder #########################################
132
+ up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
133
+
134
+ if scale_factor != 1.0:
135
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
136
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
137
+ mask = resize(mask, scale_factor=(1.0 / scale_factor))
138
+ img_res = resize(img_res, scale_factor=(1.0 / scale_factor))
139
+
140
+ # Merge multiple predictions
141
+ imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_)
142
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
143
+
144
+ if eval:
145
+ return {
146
+ "imgt_pred": imgt_pred,
147
+ }
148
+ else:
149
+ up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w)
150
+ up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w)
151
+ return {
152
+ "imgt_pred": imgt_pred,
153
+ "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
154
+ "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
155
+ "ft_pred": [ft_1_, ft_2_, ft_3_],
156
+ }
Helios-main/eval/utils/third_party/amt/networks/AMT-L.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from utils.third_party.amt.networks.blocks.feat_enc import (
5
+ BasicEncoder,
6
+ )
7
+ from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize
8
+ from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine
9
+ from utils.third_party.amt.networks.blocks.raft import BasicUpdateBlock, BidirCorrBlock, coords_grid
10
+
11
+
12
+ class Model(nn.Module):
13
+ def __init__(self, corr_radius=3, corr_lvls=4, num_flows=5, channels=[48, 64, 72, 128], skip_channels=48):
14
+ super(Model, self).__init__()
15
+ self.radius = corr_radius
16
+ self.corr_levels = corr_lvls
17
+ self.num_flows = num_flows
18
+
19
+ self.feat_encoder = BasicEncoder(output_dim=128, norm_fn="instance", dropout=0.0)
20
+ self.encoder = Encoder([48, 64, 72, 128], large=True)
21
+
22
+ self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels)
23
+ self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels)
24
+ self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels)
25
+ self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
26
+
27
+ self.update4 = self._get_updateblock(72, None)
28
+ self.update3 = self._get_updateblock(64, 2.0)
29
+ self.update2 = self._get_updateblock(48, 4.0)
30
+
31
+ self.comb_block = nn.Sequential(
32
+ nn.Conv2d(3 * self.num_flows, 6 * self.num_flows, 7, 1, 3),
33
+ nn.PReLU(6 * self.num_flows),
34
+ nn.Conv2d(6 * self.num_flows, 3, 7, 1, 3),
35
+ )
36
+
37
+ def _get_updateblock(self, cdim, scale_factor=None):
38
+ return BasicUpdateBlock(
39
+ cdim=cdim,
40
+ hidden_dim=128,
41
+ flow_dim=48,
42
+ corr_dim=256,
43
+ corr_dim2=160,
44
+ fc_dim=124,
45
+ scale_factor=scale_factor,
46
+ corr_levels=self.corr_levels,
47
+ radius=self.radius,
48
+ )
49
+
50
+ def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1):
51
+ # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0
52
+ # based on linear assumption
53
+ t1_scale = 1.0 / embt
54
+ t0_scale = 1.0 / (1.0 - embt)
55
+ if downsample != 1:
56
+ inv = 1 / downsample
57
+ flow0 = inv * resize(flow0, scale_factor=inv)
58
+ flow1 = inv * resize(flow1, scale_factor=inv)
59
+
60
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
61
+ corr = torch.cat([corr0, corr1], dim=1)
62
+ flow = torch.cat([flow0, flow1], dim=1)
63
+ return corr, flow
64
+
65
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
66
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
67
+ img0 = img0 - mean_
68
+ img1 = img1 - mean_
69
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
70
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
71
+ b, _, h, w = img0_.shape
72
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
73
+
74
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8]
75
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
76
+
77
+ # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4]
78
+ # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16]
79
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
80
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
81
+
82
+ ######################################### the 4th decoder #########################################
83
+ up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt)
84
+ corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1)
85
+
86
+ # residue update with lookup corr
87
+ delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4)
88
+ delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1)
89
+ up_flow0_4 = up_flow0_4 + delta_flow0_4
90
+ up_flow1_4 = up_flow1_4 + delta_flow1_4
91
+ ft_3_ = ft_3_ + delta_ft_3_
92
+
93
+ ######################################### the 3rd decoder #########################################
94
+ up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
95
+ corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2)
96
+
97
+ # residue update with lookup corr
98
+ delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3)
99
+ delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1)
100
+ up_flow0_3 = up_flow0_3 + delta_flow0_3
101
+ up_flow1_3 = up_flow1_3 + delta_flow1_3
102
+ ft_2_ = ft_2_ + delta_ft_2_
103
+
104
+ ######################################### the 2nd decoder #########################################
105
+ up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
106
+ corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4)
107
+
108
+ # residue update with lookup corr
109
+ delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2)
110
+ delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1)
111
+ up_flow0_2 = up_flow0_2 + delta_flow0_2
112
+ up_flow1_2 = up_flow1_2 + delta_flow1_2
113
+ ft_1_ = ft_1_ + delta_ft_1_
114
+
115
+ ######################################### the 1st decoder #########################################
116
+ up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
117
+
118
+ if scale_factor != 1.0:
119
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
120
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
121
+ mask = resize(mask, scale_factor=(1.0 / scale_factor))
122
+ img_res = resize(img_res, scale_factor=(1.0 / scale_factor))
123
+
124
+ # Merge multiple predictions
125
+ imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_)
126
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
127
+
128
+ if eval:
129
+ return {
130
+ "imgt_pred": imgt_pred,
131
+ }
132
+ else:
133
+ up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w)
134
+ up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w)
135
+ return {
136
+ "imgt_pred": imgt_pred,
137
+ "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
138
+ "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
139
+ "ft_pred": [ft_1_, ft_2_, ft_3_],
140
+ }
Helios-main/eval/utils/third_party/amt/networks/AMT-S.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from utils.third_party.amt.networks.blocks.feat_enc import SmallEncoder
5
+ from utils.third_party.amt.networks.blocks.ifrnet import Encoder, InitDecoder, IntermediateDecoder, resize
6
+ from utils.third_party.amt.networks.blocks.multi_flow import MultiFlowDecoder, multi_flow_combine
7
+ from utils.third_party.amt.networks.blocks.raft import BidirCorrBlock, SmallUpdateBlock, coords_grid
8
+
9
+
10
+ class Model(nn.Module):
11
+ def __init__(self, corr_radius=3, corr_lvls=4, num_flows=3, channels=[20, 32, 44, 56], skip_channels=20):
12
+ super(Model, self).__init__()
13
+ self.radius = corr_radius
14
+ self.corr_levels = corr_lvls
15
+ self.num_flows = num_flows
16
+ self.channels = channels
17
+ self.skip_channels = skip_channels
18
+
19
+ self.feat_encoder = SmallEncoder(output_dim=84, norm_fn="instance", dropout=0.0)
20
+ self.encoder = Encoder(channels)
21
+
22
+ self.decoder4 = InitDecoder(channels[3], channels[2], skip_channels)
23
+ self.decoder3 = IntermediateDecoder(channels[2], channels[1], skip_channels)
24
+ self.decoder2 = IntermediateDecoder(channels[1], channels[0], skip_channels)
25
+ self.decoder1 = MultiFlowDecoder(channels[0], skip_channels, num_flows)
26
+
27
+ self.update4 = self._get_updateblock(44)
28
+ self.update3 = self._get_updateblock(32, 2)
29
+ self.update2 = self._get_updateblock(20, 4)
30
+
31
+ self.comb_block = nn.Sequential(
32
+ nn.Conv2d(3 * num_flows, 6 * num_flows, 3, 1, 1),
33
+ nn.PReLU(6 * num_flows),
34
+ nn.Conv2d(6 * num_flows, 3, 3, 1, 1),
35
+ )
36
+
37
+ def _get_updateblock(self, cdim, scale_factor=None):
38
+ return SmallUpdateBlock(
39
+ cdim=cdim,
40
+ hidden_dim=76,
41
+ flow_dim=20,
42
+ corr_dim=64,
43
+ fc_dim=68,
44
+ scale_factor=scale_factor,
45
+ corr_levels=self.corr_levels,
46
+ radius=self.radius,
47
+ )
48
+
49
+ def _corr_scale_lookup(self, corr_fn, coord, flow0, flow1, embt, downsample=1):
50
+ # convert t -> 0 to 0 -> 1 | convert t -> 1 to 1 -> 0
51
+ # based on linear assumption
52
+ t1_scale = 1.0 / embt
53
+ t0_scale = 1.0 / (1.0 - embt)
54
+ if downsample != 1:
55
+ inv = 1 / downsample
56
+ flow0 = inv * resize(flow0, scale_factor=inv)
57
+ flow1 = inv * resize(flow1, scale_factor=inv)
58
+
59
+ corr0, corr1 = corr_fn(coord + flow1 * t1_scale, coord + flow0 * t0_scale)
60
+ corr = torch.cat([corr0, corr1], dim=1)
61
+ flow = torch.cat([flow0, flow1], dim=1)
62
+ return corr, flow
63
+
64
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
65
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
66
+ img0 = img0 - mean_
67
+ img1 = img1 - mean_
68
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
69
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
70
+ b, _, h, w = img0_.shape
71
+ coord = coords_grid(b, h // 8, w // 8, img0.device)
72
+
73
+ fmap0, fmap1 = self.feat_encoder([img0_, img1_]) # [1, 128, H//8, W//8]
74
+ corr_fn = BidirCorrBlock(fmap0, fmap1, radius=self.radius, num_levels=self.corr_levels)
75
+
76
+ # f0_1: [1, c0, H//2, W//2] | f0_2: [1, c1, H//4, W//4]
77
+ # f0_3: [1, c2, H//8, W//8] | f0_4: [1, c3, H//16, W//16]
78
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
79
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
80
+
81
+ ######################################### the 4th decoder #########################################
82
+ up_flow0_4, up_flow1_4, ft_3_ = self.decoder4(f0_4, f1_4, embt)
83
+ corr_4, flow_4 = self._corr_scale_lookup(corr_fn, coord, up_flow0_4, up_flow1_4, embt, downsample=1)
84
+
85
+ # residue update with lookup corr
86
+ delta_ft_3_, delta_flow_4 = self.update4(ft_3_, flow_4, corr_4)
87
+ delta_flow0_4, delta_flow1_4 = torch.chunk(delta_flow_4, 2, 1)
88
+ up_flow0_4 = up_flow0_4 + delta_flow0_4
89
+ up_flow1_4 = up_flow1_4 + delta_flow1_4
90
+ ft_3_ = ft_3_ + delta_ft_3_
91
+
92
+ ######################################### the 3rd decoder #########################################
93
+ up_flow0_3, up_flow1_3, ft_2_ = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
94
+ corr_3, flow_3 = self._corr_scale_lookup(corr_fn, coord, up_flow0_3, up_flow1_3, embt, downsample=2)
95
+
96
+ # residue update with lookup corr
97
+ delta_ft_2_, delta_flow_3 = self.update3(ft_2_, flow_3, corr_3)
98
+ delta_flow0_3, delta_flow1_3 = torch.chunk(delta_flow_3, 2, 1)
99
+ up_flow0_3 = up_flow0_3 + delta_flow0_3
100
+ up_flow1_3 = up_flow1_3 + delta_flow1_3
101
+ ft_2_ = ft_2_ + delta_ft_2_
102
+
103
+ ######################################### the 2nd decoder #########################################
104
+ up_flow0_2, up_flow1_2, ft_1_ = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
105
+ corr_2, flow_2 = self._corr_scale_lookup(corr_fn, coord, up_flow0_2, up_flow1_2, embt, downsample=4)
106
+
107
+ # residue update with lookup corr
108
+ delta_ft_1_, delta_flow_2 = self.update2(ft_1_, flow_2, corr_2)
109
+ delta_flow0_2, delta_flow1_2 = torch.chunk(delta_flow_2, 2, 1)
110
+ up_flow0_2 = up_flow0_2 + delta_flow0_2
111
+ up_flow1_2 = up_flow1_2 + delta_flow1_2
112
+ ft_1_ = ft_1_ + delta_ft_1_
113
+
114
+ ######################################### the 1st decoder #########################################
115
+ up_flow0_1, up_flow1_1, mask, img_res = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
116
+
117
+ if scale_factor != 1.0:
118
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
119
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
120
+ mask = resize(mask, scale_factor=(1.0 / scale_factor))
121
+ img_res = resize(img_res, scale_factor=(1.0 / scale_factor))
122
+
123
+ # Merge multiple predictions
124
+ imgt_pred = multi_flow_combine(self.comb_block, img0, img1, up_flow0_1, up_flow1_1, mask, img_res, mean_)
125
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
126
+
127
+ if eval:
128
+ return {
129
+ "imgt_pred": imgt_pred,
130
+ }
131
+ else:
132
+ up_flow0_1 = up_flow0_1.reshape(b, self.num_flows, 2, h, w)
133
+ up_flow1_1 = up_flow1_1.reshape(b, self.num_flows, 2, h, w)
134
+ return {
135
+ "imgt_pred": imgt_pred,
136
+ "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
137
+ "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
138
+ "ft_pred": [ft_1_, ft_2_, ft_3_],
139
+ }
Helios-main/eval/utils/third_party/amt/networks/IFRNet.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from utils.third_party.amt.networks.blocks.ifrnet import (
5
+ ResBlock,
6
+ convrelu,
7
+ resize,
8
+ )
9
+ from utils.third_party.amt.utils.flow_utils import warp
10
+
11
+
12
+ class Encoder(nn.Module):
13
+ def __init__(self):
14
+ super(Encoder, self).__init__()
15
+ self.pyramid1 = nn.Sequential(convrelu(3, 32, 3, 2, 1), convrelu(32, 32, 3, 1, 1))
16
+ self.pyramid2 = nn.Sequential(convrelu(32, 48, 3, 2, 1), convrelu(48, 48, 3, 1, 1))
17
+ self.pyramid3 = nn.Sequential(convrelu(48, 72, 3, 2, 1), convrelu(72, 72, 3, 1, 1))
18
+ self.pyramid4 = nn.Sequential(convrelu(72, 96, 3, 2, 1), convrelu(96, 96, 3, 1, 1))
19
+
20
+ def forward(self, img):
21
+ f1 = self.pyramid1(img)
22
+ f2 = self.pyramid2(f1)
23
+ f3 = self.pyramid3(f2)
24
+ f4 = self.pyramid4(f3)
25
+ return f1, f2, f3, f4
26
+
27
+
28
+ class Decoder4(nn.Module):
29
+ def __init__(self):
30
+ super(Decoder4, self).__init__()
31
+ self.convblock = nn.Sequential(
32
+ convrelu(192 + 1, 192), ResBlock(192, 32), nn.ConvTranspose2d(192, 76, 4, 2, 1, bias=True)
33
+ )
34
+
35
+ def forward(self, f0, f1, embt):
36
+ b, c, h, w = f0.shape
37
+ embt = embt.repeat(1, 1, h, w)
38
+ f_in = torch.cat([f0, f1, embt], 1)
39
+ f_out = self.convblock(f_in)
40
+ return f_out
41
+
42
+
43
+ class Decoder3(nn.Module):
44
+ def __init__(self):
45
+ super(Decoder3, self).__init__()
46
+ self.convblock = nn.Sequential(
47
+ convrelu(220, 216), ResBlock(216, 32), nn.ConvTranspose2d(216, 52, 4, 2, 1, bias=True)
48
+ )
49
+
50
+ def forward(self, ft_, f0, f1, up_flow0, up_flow1):
51
+ f0_warp = warp(f0, up_flow0)
52
+ f1_warp = warp(f1, up_flow1)
53
+ f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1)
54
+ f_out = self.convblock(f_in)
55
+ return f_out
56
+
57
+
58
+ class Decoder2(nn.Module):
59
+ def __init__(self):
60
+ super(Decoder2, self).__init__()
61
+ self.convblock = nn.Sequential(
62
+ convrelu(148, 144), ResBlock(144, 32), nn.ConvTranspose2d(144, 36, 4, 2, 1, bias=True)
63
+ )
64
+
65
+ def forward(self, ft_, f0, f1, up_flow0, up_flow1):
66
+ f0_warp = warp(f0, up_flow0)
67
+ f1_warp = warp(f1, up_flow1)
68
+ f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1)
69
+ f_out = self.convblock(f_in)
70
+ return f_out
71
+
72
+
73
+ class Decoder1(nn.Module):
74
+ def __init__(self):
75
+ super(Decoder1, self).__init__()
76
+ self.convblock = nn.Sequential(
77
+ convrelu(100, 96), ResBlock(96, 32), nn.ConvTranspose2d(96, 8, 4, 2, 1, bias=True)
78
+ )
79
+
80
+ def forward(self, ft_, f0, f1, up_flow0, up_flow1):
81
+ f0_warp = warp(f0, up_flow0)
82
+ f1_warp = warp(f1, up_flow1)
83
+ f_in = torch.cat([ft_, f0_warp, f1_warp, up_flow0, up_flow1], 1)
84
+ f_out = self.convblock(f_in)
85
+ return f_out
86
+
87
+
88
+ class Model(nn.Module):
89
+ def __init__(self):
90
+ super(Model, self).__init__()
91
+ self.encoder = Encoder()
92
+ self.decoder4 = Decoder4()
93
+ self.decoder3 = Decoder3()
94
+ self.decoder2 = Decoder2()
95
+ self.decoder1 = Decoder1()
96
+
97
+ def forward(self, img0, img1, embt, scale_factor=1.0, eval=False, **kwargs):
98
+ mean_ = torch.cat([img0, img1], 2).mean(1, keepdim=True).mean(2, keepdim=True).mean(3, keepdim=True)
99
+ img0 = img0 - mean_
100
+ img1 = img1 - mean_
101
+
102
+ img0_ = resize(img0, scale_factor) if scale_factor != 1.0 else img0
103
+ img1_ = resize(img1, scale_factor) if scale_factor != 1.0 else img1
104
+
105
+ f0_1, f0_2, f0_3, f0_4 = self.encoder(img0_)
106
+ f1_1, f1_2, f1_3, f1_4 = self.encoder(img1_)
107
+
108
+ out4 = self.decoder4(f0_4, f1_4, embt)
109
+ up_flow0_4 = out4[:, 0:2]
110
+ up_flow1_4 = out4[:, 2:4]
111
+ ft_3_ = out4[:, 4:]
112
+
113
+ out3 = self.decoder3(ft_3_, f0_3, f1_3, up_flow0_4, up_flow1_4)
114
+ up_flow0_3 = out3[:, 0:2] + 2.0 * resize(up_flow0_4, scale_factor=2.0)
115
+ up_flow1_3 = out3[:, 2:4] + 2.0 * resize(up_flow1_4, scale_factor=2.0)
116
+ ft_2_ = out3[:, 4:]
117
+
118
+ out2 = self.decoder2(ft_2_, f0_2, f1_2, up_flow0_3, up_flow1_3)
119
+ up_flow0_2 = out2[:, 0:2] + 2.0 * resize(up_flow0_3, scale_factor=2.0)
120
+ up_flow1_2 = out2[:, 2:4] + 2.0 * resize(up_flow1_3, scale_factor=2.0)
121
+ ft_1_ = out2[:, 4:]
122
+
123
+ out1 = self.decoder1(ft_1_, f0_1, f1_1, up_flow0_2, up_flow1_2)
124
+ up_flow0_1 = out1[:, 0:2] + 2.0 * resize(up_flow0_2, scale_factor=2.0)
125
+ up_flow1_1 = out1[:, 2:4] + 2.0 * resize(up_flow1_2, scale_factor=2.0)
126
+ up_mask_1 = torch.sigmoid(out1[:, 4:5])
127
+ up_res_1 = out1[:, 5:]
128
+
129
+ if scale_factor != 1.0:
130
+ up_flow0_1 = resize(up_flow0_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
131
+ up_flow1_1 = resize(up_flow1_1, scale_factor=(1.0 / scale_factor)) * (1.0 / scale_factor)
132
+ up_mask_1 = resize(up_mask_1, scale_factor=(1.0 / scale_factor))
133
+ up_res_1 = resize(up_res_1, scale_factor=(1.0 / scale_factor))
134
+
135
+ img0_warp = warp(img0, up_flow0_1)
136
+ img1_warp = warp(img1, up_flow1_1)
137
+ imgt_merge = up_mask_1 * img0_warp + (1 - up_mask_1) * img1_warp + mean_
138
+ imgt_pred = imgt_merge + up_res_1
139
+ imgt_pred = torch.clamp(imgt_pred, 0, 1)
140
+
141
+ if eval:
142
+ return {
143
+ "imgt_pred": imgt_pred,
144
+ }
145
+ else:
146
+ return {
147
+ "imgt_pred": imgt_pred,
148
+ "flow0_pred": [up_flow0_1, up_flow0_2, up_flow0_3, up_flow0_4],
149
+ "flow1_pred": [up_flow1_1, up_flow1_2, up_flow1_3, up_flow1_4],
150
+ "ft_pred": [ft_1_, ft_2_, ft_3_],
151
+ "img0_warp": img0_warp,
152
+ "img1_warp": img1_warp,
153
+ }
Helios-main/eval/utils/third_party/amt/networks/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/scripts/train.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ NUM_GPU=$1
2
+ CFG=$2
3
+ PORT=$3
4
+ python -m torch.distributed.launch \
5
+ --nproc_per_node $NUM_GPU \
6
+ --master_port $PORT train.py -c $CFG
Helios-main/eval/utils/third_party/amt/train.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import datetime
3
+ import importlib
4
+ import os
5
+ from shutil import copyfile
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ from omegaconf import OmegaConf
10
+
11
+ from utils.dist_utils import (
12
+ get_world_size,
13
+ )
14
+ from utils.utils import seed_all
15
+
16
+
17
+ parser = argparse.ArgumentParser(description="VFI")
18
+ parser.add_argument("-c", "--config", type=str)
19
+ parser.add_argument("-p", "--port", default="23455", type=str)
20
+ parser.add_argument("--local_rank", default="0")
21
+
22
+ args = parser.parse_args()
23
+
24
+
25
+ def main_worker(rank, config):
26
+ if "local_rank" not in config:
27
+ config["local_rank"] = config["global_rank"] = rank
28
+ if torch.cuda.is_available():
29
+ print(f"Rank {rank} is available")
30
+ config["device"] = f"cuda:{rank}"
31
+ if config["distributed"]:
32
+ dist.init_process_group(backend="nccl", timeout=datetime.timedelta(seconds=5400))
33
+ else:
34
+ config["device"] = "cpu"
35
+
36
+ cfg_name = os.path.basename(args.config).split(".")[0]
37
+ config["exp_name"] = cfg_name + "_" + config["exp_name"]
38
+ config["save_dir"] = os.path.join(config["save_dir"], config["exp_name"])
39
+
40
+ if (not config["distributed"]) or rank == 0:
41
+ os.makedirs(config["save_dir"], exist_ok=True)
42
+ os.makedirs(f"{config['save_dir']}/ckpts", exist_ok=True)
43
+ config_path = os.path.join(config["save_dir"], args.config.split("/")[-1])
44
+ if not os.path.isfile(config_path):
45
+ copyfile(args.config, config_path)
46
+ print("[**] create folder {}".format(config["save_dir"]))
47
+
48
+ trainer_name = config.get("trainer_type", "base_trainer")
49
+ print(f"using GPU {rank} for training")
50
+ if rank == 0:
51
+ print(trainer_name)
52
+ trainer_pack = importlib.import_module("trainers." + trainer_name)
53
+ trainer = trainer_pack.Trainer(config)
54
+
55
+ trainer.train()
56
+
57
+
58
+ if __name__ == "__main__":
59
+ torch.backends.cudnn.benchmark = True
60
+ cfg = OmegaConf.load(args.config)
61
+ seed_all(cfg.seed)
62
+ rank = int(args.local_rank)
63
+ torch.cuda.set_device(torch.device(f"cuda:{rank}"))
64
+ # setting distributed cfgurations
65
+ cfg["world_size"] = get_world_size()
66
+ cfg["local_rank"] = rank
67
+ if rank == 0:
68
+ print("world_size: ", cfg["world_size"])
69
+ main_worker(rank, cfg)
Helios-main/eval/utils/third_party/amt/trainers/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/trainers/base_trainer.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os.path as osp
3
+ import time
4
+ from collections import OrderedDict
5
+
6
+ import numpy as np
7
+ import torch
8
+ import wandb
9
+ from metrics.psnr_ssim import calculate_psnr
10
+ from torch.nn.parallel import DistributedDataParallel as DDP
11
+ from torch.optim import AdamW
12
+ from torch.utils.data import DataLoader
13
+ from torch.utils.data.distributed import DistributedSampler
14
+
15
+ from utils.build_utils import build_from_cfg
16
+ from utils.utils import AverageMeterGroups
17
+
18
+ from .logger import CustomLogger
19
+
20
+
21
+ class Trainer:
22
+ def __init__(self, config):
23
+ super().__init__()
24
+ self.config = config
25
+ self.rank = self.config["local_rank"]
26
+ init_log = self._init_logger()
27
+ self._init_dataset()
28
+ self._init_loss()
29
+ self.model_name = config["exp_name"]
30
+ self.model = build_from_cfg(config.network).to(self.config.device)
31
+
32
+ if config["distributed"]:
33
+ self.model = DDP(
34
+ self.model,
35
+ device_ids=[self.rank],
36
+ output_device=self.rank,
37
+ broadcast_buffers=True,
38
+ find_unused_parameters=False,
39
+ )
40
+
41
+ init_log += str(self.model)
42
+ self.optimizer = AdamW(self.model.parameters(), lr=config.lr, weight_decay=config.weight_decay)
43
+ if self.rank == 0:
44
+ print(init_log)
45
+ self.logger(init_log)
46
+ self.resume_training()
47
+
48
+ def resume_training(self):
49
+ ckpt_path = self.config.get("resume_state")
50
+ if ckpt_path is not None:
51
+ ckpt = torch.load(self.config["resume_state"])
52
+ if self.config["distributed"]:
53
+ self.model.module.load_state_dict(ckpt["state_dict"])
54
+ else:
55
+ self.model.load_state_dict(ckpt["state_dict"])
56
+ self.optimizer.load_state_dict(ckpt["optim"])
57
+ self.resume_epoch = ckpt.get("epoch")
58
+ self.logger(f"load model from {ckpt_path} and training resumes from epoch {self.resume_epoch}")
59
+ else:
60
+ self.resume_epoch = 0
61
+
62
+ def _init_logger(self):
63
+ init_log = ""
64
+ console_cfg = {
65
+ "level": logging.INFO,
66
+ "format": "%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s",
67
+ "datefmt": "%a, %d %b %Y %H:%M:%S",
68
+ "filename": f"{self.config['save_dir']}/log",
69
+ "filemode": "w",
70
+ }
71
+ tb_cfg = {"log_dir": osp.join(self.config["save_dir"], "tb_logger")}
72
+ wandb_cfg = None
73
+ use_wandb = self.config["logger"].get("use_wandb", False)
74
+ if use_wandb:
75
+ resume_id = self.config["logger"].get("resume_id", None)
76
+ if resume_id:
77
+ wandb_id = resume_id
78
+ resume = "allow"
79
+ init_log += f"Resume wandb logger with id={wandb_id}."
80
+ else:
81
+ wandb_id = wandb.util.generate_id()
82
+ resume = "never"
83
+
84
+ wandb_cfg = {
85
+ "id": wandb_id,
86
+ "resume": resume,
87
+ "name": osp.basename(self.config["save_dir"]),
88
+ "config": self.config,
89
+ "project": "YOUR PROJECT",
90
+ "entity": "YOUR ENTITY",
91
+ "sync_tensorboard": True,
92
+ }
93
+ init_log += f"Use wandb logger with id={wandb_id}; project=[YOUR PROJECT]."
94
+ self.logger = CustomLogger(console_cfg, tb_cfg, wandb_cfg, self.rank)
95
+ return init_log
96
+
97
+ def _init_dataset(self):
98
+ dataset_train = build_from_cfg(self.config.data.train)
99
+ dataset_val = build_from_cfg(self.config.data.val)
100
+
101
+ self.sampler = DistributedSampler(
102
+ dataset_train, num_replicas=self.config["world_size"], rank=self.config["local_rank"]
103
+ )
104
+ self.config.data.train_loader.batch_size //= self.config["world_size"]
105
+ self.loader_train = DataLoader(
106
+ dataset_train, **self.config.data.train_loader, pin_memory=True, drop_last=True, sampler=self.sampler
107
+ )
108
+
109
+ self.loader_val = DataLoader(
110
+ dataset_val, **self.config.data.val_loader, pin_memory=True, shuffle=False, drop_last=False
111
+ )
112
+
113
+ def _init_loss(self):
114
+ self.loss_dict = {}
115
+ for loss_cfg in self.config.losses:
116
+ loss = build_from_cfg(loss_cfg)
117
+ self.loss_dict[loss_cfg["nickname"]] = loss
118
+
119
+ def set_lr(self, optimizer, lr):
120
+ for param_group in optimizer.param_groups:
121
+ param_group["lr"] = lr
122
+
123
+ def get_lr(self, iters):
124
+ ratio = 0.5 * (1.0 + np.cos(iters / (self.config["epochs"] * self.loader_train.__len__()) * np.pi))
125
+ lr = (self.config["lr"] - self.config["lr_min"]) * ratio + self.config["lr_min"]
126
+ return lr
127
+
128
+ def train(self):
129
+ local_rank = self.config["local_rank"]
130
+ best_psnr = 0.0
131
+ loss_group = AverageMeterGroups()
132
+ time_group = AverageMeterGroups()
133
+ iters_per_epoch = self.loader_train.__len__()
134
+ iters = self.resume_epoch * iters_per_epoch
135
+ total_iters = self.config["epochs"] * iters_per_epoch
136
+
137
+ start_t = time.time()
138
+ total_t = 0
139
+ for epoch in range(self.resume_epoch, self.config["epochs"]):
140
+ self.sampler.set_epoch(epoch)
141
+ for data in self.loader_train:
142
+ for k, v in data.items():
143
+ data[k] = v.to(self.config["device"])
144
+ data_t = time.time() - start_t
145
+
146
+ lr = self.get_lr(iters)
147
+ self.set_lr(self.optimizer, lr)
148
+
149
+ self.optimizer.zero_grad()
150
+ results = self.model(**data)
151
+ total_loss = torch.tensor(0.0, device=self.config["device"])
152
+ for name, loss in self.loss_dict.items():
153
+ l = loss(**results, **data)
154
+ loss_group.update({name: l.cpu().data})
155
+ total_loss += l
156
+ total_loss.backward()
157
+ self.optimizer.step()
158
+
159
+ iters += 1
160
+
161
+ iter_t = time.time() - start_t
162
+ total_t += iter_t
163
+ time_group.update({"data_t": data_t, "iter_t": iter_t})
164
+
165
+ if (iters + 1) % 100 == 0 and local_rank == 0:
166
+ tpi = total_t / (iters - self.resume_epoch * iters_per_epoch)
167
+ eta = total_iters * tpi
168
+ remainder = (total_iters - iters) * tpi
169
+ eta = self.eta_format(eta)
170
+
171
+ remainder = self.eta_format(remainder)
172
+ log_str = f"[{self.model_name}]epoch:{epoch + 1}/{self.config['epochs']} "
173
+ log_str += f"iter:{iters + 1}/{self.config['epochs'] * iters_per_epoch} "
174
+ log_str += f"time:{time_group.avg('iter_t'):.3f}({time_group.avg('data_t'):.3f}) "
175
+ log_str += f"lr:{lr:.3e} eta:{remainder}({eta})\n"
176
+ for name in self.loss_dict.keys():
177
+ avg_l = loss_group.avg(name)
178
+ log_str += f"{name}:{avg_l:.3e} "
179
+ self.logger(tb_msg=[f"loss/{name}", avg_l, iters])
180
+ log_str += f"best:{best_psnr:.2f}dB\n\n"
181
+ self.logger(log_str)
182
+ loss_group.reset()
183
+ time_group.reset()
184
+ start_t = time.time()
185
+
186
+ if (epoch + 1) % self.config["eval_interval"] == 0 and local_rank == 0:
187
+ psnr, eval_t = self.evaluate(epoch)
188
+ total_t += eval_t
189
+ self.logger(tb_msg=["eval/psnr", psnr, epoch])
190
+ if psnr > best_psnr:
191
+ best_psnr = psnr
192
+ self.save("psnr_best.pth", epoch)
193
+ if self.logger.enable_wandb:
194
+ wandb.run.summary["best_psnr"] = best_psnr
195
+ if (epoch + 1) % 50 == 0:
196
+ self.save(f"epoch_{epoch + 1}.pth", epoch)
197
+ self.save("latest.pth", epoch)
198
+
199
+ self.logger.close()
200
+
201
+ def evaluate(self, epoch):
202
+ psnr_list = []
203
+ time_stamp = time.time()
204
+ for i, data in enumerate(self.loader_val):
205
+ for k, v in data.items():
206
+ data[k] = v.to(self.config["device"])
207
+
208
+ with torch.no_grad():
209
+ results = self.model(**data, eval=True)
210
+ imgt_pred = results["imgt_pred"]
211
+ for j in range(data["img0"].shape[0]):
212
+ psnr = calculate_psnr(imgt_pred[j].detach().unsqueeze(0), data["imgt"][j].unsqueeze(0)).cpu().data
213
+ psnr_list.append(psnr)
214
+
215
+ eval_time = time.time() - time_stamp
216
+
217
+ self.logger(
218
+ "eval epoch:{}/{} time:{:.2f} psnr:{:.3f}".format(
219
+ epoch + 1, self.config["epochs"], eval_time, np.array(psnr_list).mean()
220
+ )
221
+ )
222
+ return np.array(psnr_list).mean(), eval_time
223
+
224
+ def save(self, name, epoch):
225
+ save_path = "{}/{}/{}".format(self.config["save_dir"], "ckpts", name)
226
+ ckpt = OrderedDict(epoch=epoch)
227
+ if self.config["distributed"]:
228
+ ckpt["state_dict"] = self.model.module.state_dict()
229
+ else:
230
+ ckpt["state_dict"] = self.model.state_dict()
231
+ ckpt["optim"] = self.optimizer.state_dict()
232
+ torch.save(ckpt, save_path)
233
+
234
+ def eta_format(self, eta):
235
+ time_str = ""
236
+ if eta >= 3600:
237
+ hours = int(eta // 3600)
238
+ eta -= hours * 3600
239
+ time_str = f"{hours}"
240
+
241
+ if eta >= 60:
242
+ mins = int(eta // 60)
243
+ eta -= mins * 60
244
+ time_str = f"{time_str}:{mins:02}"
245
+
246
+ eta = int(eta)
247
+ time_str = f"{time_str}:{eta:02}"
248
+ return time_str
Helios-main/eval/utils/third_party/amt/trainers/logger.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os.path as osp
3
+ import shutil
4
+ import time
5
+
6
+ import wandb
7
+ from torch.utils.tensorboard import SummaryWriter
8
+
9
+
10
+ def mv_archived_logger(name):
11
+ timestamp = time.strftime("%Y-%m-%d_%H:%M:%S_", time.localtime())
12
+ basename = "archived_" + timestamp + osp.basename(name)
13
+ archived_name = osp.join(osp.dirname(name), basename)
14
+ shutil.move(name, archived_name)
15
+
16
+
17
+ class CustomLogger:
18
+ def __init__(self, common_cfg, tb_cfg=None, wandb_cfg=None, rank=0):
19
+ global global_logger
20
+ self.rank = rank
21
+
22
+ if self.rank == 0:
23
+ self.logger = logging.getLogger("VFI")
24
+ self.logger.setLevel(logging.INFO)
25
+ format_str = logging.Formatter(common_cfg["format"])
26
+
27
+ console_handler = logging.StreamHandler()
28
+ console_handler.setFormatter(format_str)
29
+
30
+ if osp.exists(common_cfg["filename"]):
31
+ mv_archived_logger(common_cfg["filename"])
32
+
33
+ file_handler = logging.FileHandler(common_cfg["filename"], common_cfg["filemode"])
34
+ file_handler.setFormatter(format_str)
35
+
36
+ self.logger.addHandler(console_handler)
37
+ self.logger.addHandler(file_handler)
38
+ self.tb_logger = None
39
+
40
+ self.enable_wandb = False
41
+
42
+ if wandb_cfg is not None:
43
+ self.enable_wandb = True
44
+ wandb.init(**wandb_cfg)
45
+
46
+ if tb_cfg is not None:
47
+ self.tb_logger = SummaryWriter(**tb_cfg)
48
+
49
+ global_logger = self
50
+
51
+ def __call__(self, msg=None, level=logging.INFO, tb_msg=None):
52
+ if self.rank != 0:
53
+ return
54
+ if msg is not None:
55
+ self.logger.log(level, msg)
56
+
57
+ if self.tb_logger is not None and tb_msg is not None:
58
+ self.tb_logger.add_scalar(*tb_msg)
59
+
60
+ def close(self):
61
+ if self.rank == 0 and self.enable_wandb:
62
+ wandb.finish()
Helios-main/eval/utils/third_party/amt/utils/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/utils/build_utils.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+ import sys
4
+
5
+
6
+ CUR_DIR = os.path.dirname(os.path.abspath(__file__))
7
+ sys.path.append(os.path.join(CUR_DIR, "../"))
8
+
9
+
10
+ def base_build_fn(module, cls, params):
11
+ return getattr(importlib.import_module(module, package=None), cls)(**params)
12
+
13
+
14
+ def build_from_cfg(config):
15
+ module, cls = config["name"].rsplit(".", 1)
16
+ params = config.get("params", {})
17
+ return base_build_fn(module, cls, params)
Helios-main/eval/utils/third_party/amt/utils/dist_utils.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+
5
+
6
+ def get_world_size():
7
+ """Find OMPI world size without calling mpi functions
8
+ :rtype: int
9
+ """
10
+ if os.environ.get("PMI_SIZE") is not None:
11
+ return int(os.environ.get("PMI_SIZE") or 1)
12
+ elif os.environ.get("OMPI_COMM_WORLD_SIZE") is not None:
13
+ return int(os.environ.get("OMPI_COMM_WORLD_SIZE") or 1)
14
+ else:
15
+ return torch.cuda.device_count()
16
+
17
+
18
+ def get_global_rank():
19
+ """Find OMPI world rank without calling mpi functions
20
+ :rtype: int
21
+ """
22
+ if os.environ.get("PMI_RANK") is not None:
23
+ return int(os.environ.get("PMI_RANK") or 0)
24
+ elif os.environ.get("OMPI_COMM_WORLD_RANK") is not None:
25
+ return int(os.environ.get("OMPI_COMM_WORLD_RANK") or 0)
26
+ else:
27
+ return 0
28
+
29
+
30
+ def get_local_rank():
31
+ """Find OMPI local rank without calling mpi functions
32
+ :rtype: int
33
+ """
34
+ if os.environ.get("MPI_LOCALRANKID") is not None:
35
+ return int(os.environ.get("MPI_LOCALRANKID") or 0)
36
+ elif os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK") is not None:
37
+ return int(os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK") or 0)
38
+ else:
39
+ return 0
40
+
41
+
42
+ def get_master_ip():
43
+ if os.environ.get("AZ_BATCH_MASTER_NODE") is not None:
44
+ return os.environ.get("AZ_BATCH_MASTER_NODE").split(":")[0]
45
+ elif os.environ.get("AZ_BATCHAI_MPI_MASTER_NODE") is not None:
46
+ return os.environ.get("AZ_BATCHAI_MPI_MASTER_NODE")
47
+ else:
48
+ return "127.0.0.1"
Helios-main/eval/utils/third_party/amt/utils/flow_utils.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from PIL import ImageFile
5
+
6
+
7
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
8
+
9
+
10
+ def warp(img, flow):
11
+ B, _, H, W = flow.shape
12
+ xx = torch.linspace(-1.0, 1.0, W).view(1, 1, 1, W).expand(B, -1, H, -1)
13
+ yy = torch.linspace(-1.0, 1.0, H).view(1, 1, H, 1).expand(B, -1, -1, W)
14
+ grid = torch.cat([xx, yy], 1).to(img)
15
+ flow_ = torch.cat([flow[:, 0:1, :, :] / ((W - 1.0) / 2.0), flow[:, 1:2, :, :] / ((H - 1.0) / 2.0)], 1)
16
+ grid_ = (grid + flow_).permute(0, 2, 3, 1)
17
+ output = F.grid_sample(input=img, grid=grid_, mode="bilinear", padding_mode="border", align_corners=True)
18
+ return output
19
+
20
+
21
+ def make_colorwheel():
22
+ """
23
+ Generates a color wheel for optical flow visualization as presented in:
24
+ Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007)
25
+ URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf
26
+ Code follows the original C++ source code of Daniel Scharstein.
27
+ Code follows the the Matlab source code of Deqing Sun.
28
+ Returns:
29
+ np.ndarray: Color wheel
30
+ """
31
+
32
+ RY = 15
33
+ YG = 6
34
+ GC = 4
35
+ CB = 11
36
+ BM = 13
37
+ MR = 6
38
+
39
+ ncols = RY + YG + GC + CB + BM + MR
40
+ colorwheel = np.zeros((ncols, 3))
41
+ col = 0
42
+
43
+ # RY
44
+ colorwheel[0:RY, 0] = 255
45
+ colorwheel[0:RY, 1] = np.floor(255 * np.arange(0, RY) / RY)
46
+ col = col + RY
47
+ # YG
48
+ colorwheel[col : col + YG, 0] = 255 - np.floor(255 * np.arange(0, YG) / YG)
49
+ colorwheel[col : col + YG, 1] = 255
50
+ col = col + YG
51
+ # GC
52
+ colorwheel[col : col + GC, 1] = 255
53
+ colorwheel[col : col + GC, 2] = np.floor(255 * np.arange(0, GC) / GC)
54
+ col = col + GC
55
+ # CB
56
+ colorwheel[col : col + CB, 1] = 255 - np.floor(255 * np.arange(CB) / CB)
57
+ colorwheel[col : col + CB, 2] = 255
58
+ col = col + CB
59
+ # BM
60
+ colorwheel[col : col + BM, 2] = 255
61
+ colorwheel[col : col + BM, 0] = np.floor(255 * np.arange(0, BM) / BM)
62
+ col = col + BM
63
+ # MR
64
+ colorwheel[col : col + MR, 2] = 255 - np.floor(255 * np.arange(MR) / MR)
65
+ colorwheel[col : col + MR, 0] = 255
66
+ return colorwheel
67
+
68
+
69
+ def flow_uv_to_colors(u, v, convert_to_bgr=False):
70
+ """
71
+ Applies the flow color wheel to (possibly clipped) flow components u and v.
72
+ According to the C++ source code of Daniel Scharstein
73
+ According to the Matlab source code of Deqing Sun
74
+ Args:
75
+ u (np.ndarray): Input horizontal flow of shape [H,W]
76
+ v (np.ndarray): Input vertical flow of shape [H,W]
77
+ convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False.
78
+ Returns:
79
+ np.ndarray: Flow visualization image of shape [H,W,3]
80
+ """
81
+ flow_image = np.zeros((u.shape[0], u.shape[1], 3), np.uint8)
82
+ colorwheel = make_colorwheel() # shape [55x3]
83
+ ncols = colorwheel.shape[0]
84
+ rad = np.sqrt(np.square(u) + np.square(v))
85
+ a = np.arctan2(-v, -u) / np.pi
86
+ fk = (a + 1) / 2 * (ncols - 1)
87
+ k0 = np.floor(fk).astype(np.int32)
88
+ k1 = k0 + 1
89
+ k1[k1 == ncols] = 0
90
+ f = fk - k0
91
+ for i in range(colorwheel.shape[1]):
92
+ tmp = colorwheel[:, i]
93
+ col0 = tmp[k0] / 255.0
94
+ col1 = tmp[k1] / 255.0
95
+ col = (1 - f) * col0 + f * col1
96
+ idx = rad <= 1
97
+ col[idx] = 1 - rad[idx] * (1 - col[idx])
98
+ col[~idx] = col[~idx] * 0.75 # out of range
99
+ # Note the 2-i => BGR instead of RGB
100
+ ch_idx = 2 - i if convert_to_bgr else i
101
+ flow_image[:, :, ch_idx] = np.floor(255 * col)
102
+ return flow_image
103
+
104
+
105
+ def flow_to_image(flow_uv, clip_flow=None, convert_to_bgr=False):
106
+ """
107
+ Expects a two dimensional flow image of shape.
108
+ Args:
109
+ flow_uv (np.ndarray): Flow UV image of shape [H,W,2]
110
+ clip_flow (float, optional): Clip maximum of flow values. Defaults to None.
111
+ convert_to_bgr (bool, optional): Convert output image to BGR. Defaults to False.
112
+ Returns:
113
+ np.ndarray: Flow visualization image of shape [H,W,3]
114
+ """
115
+ assert flow_uv.ndim == 3, "input flow must have three dimensions"
116
+ assert flow_uv.shape[2] == 2, "input flow must have shape [H,W,2]"
117
+ if clip_flow is not None:
118
+ flow_uv = np.clip(flow_uv, 0, clip_flow)
119
+ u = flow_uv[:, :, 0]
120
+ v = flow_uv[:, :, 1]
121
+ rad = np.sqrt(np.square(u) + np.square(v))
122
+ rad_max = np.max(rad)
123
+ epsilon = 1e-5
124
+ u = u / (rad_max + epsilon)
125
+ v = v / (rad_max + epsilon)
126
+ return flow_uv_to_colors(u, v, convert_to_bgr)
Helios-main/eval/utils/third_party/amt/utils/utils.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import re
3
+ import sys
4
+
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from imageio import imread, imwrite
9
+ from PIL import ImageFile
10
+
11
+
12
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
13
+
14
+
15
+ class AverageMeter:
16
+ def __init__(self):
17
+ self.reset()
18
+
19
+ def reset(self):
20
+ self.val = 0.0
21
+ self.avg = 0.0
22
+ self.sum = 0.0
23
+ self.count = 0
24
+
25
+ def update(self, val, n=1):
26
+ self.val = val
27
+ self.sum += val * n
28
+ self.count += n
29
+ self.avg = self.sum / self.count
30
+
31
+
32
+ class AverageMeterGroups:
33
+ def __init__(self) -> None:
34
+ self.meter_dict = {}
35
+
36
+ def update(self, dict, n=1):
37
+ for name, val in dict.items():
38
+ if self.meter_dict.get(name) is None:
39
+ self.meter_dict[name] = AverageMeter()
40
+ self.meter_dict[name].update(val, n)
41
+
42
+ def reset(self, name=None):
43
+ if name is None:
44
+ for v in self.meter_dict.values():
45
+ v.reset()
46
+ else:
47
+ meter = self.meter_dict.get(name)
48
+ if meter is not None:
49
+ meter.reset()
50
+
51
+ def avg(self, name):
52
+ meter = self.meter_dict.get(name)
53
+ if meter is not None:
54
+ return meter.avg
55
+
56
+
57
+ class InputPadder:
58
+ """Pads images such that dimensions are divisible by divisor"""
59
+
60
+ def __init__(self, dims, divisor=16):
61
+ self.ht, self.wd = dims[-2:]
62
+ pad_ht = (((self.ht // divisor) + 1) * divisor - self.ht) % divisor
63
+ pad_wd = (((self.wd // divisor) + 1) * divisor - self.wd) % divisor
64
+ self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2]
65
+
66
+ def pad(self, *inputs):
67
+ if len(inputs) == 1:
68
+ return F.pad(inputs[0], self._pad, mode="replicate")
69
+ else:
70
+ return [F.pad(x, self._pad, mode="replicate") for x in inputs]
71
+
72
+ def unpad(self, *inputs):
73
+ if len(inputs) == 1:
74
+ return self._unpad(inputs[0])
75
+ else:
76
+ return [self._unpad(x) for x in inputs]
77
+
78
+ def _unpad(self, x):
79
+ ht, wd = x.shape[-2:]
80
+ c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]]
81
+ return x[..., c[0] : c[1], c[2] : c[3]]
82
+
83
+
84
+ def img2tensor(img):
85
+ if img.shape[-1] > 3:
86
+ img = img[:, :, :3]
87
+ return torch.tensor(img).permute(2, 0, 1).unsqueeze(0) / 255.0
88
+
89
+
90
+ def tensor2img(img_t):
91
+ return (img_t * 255.0).detach().squeeze(0).permute(1, 2, 0).cpu().numpy().clip(0, 255).astype(np.uint8)
92
+
93
+
94
+ def seed_all(seed):
95
+ random.seed(seed)
96
+ np.random.seed(seed)
97
+ torch.manual_seed(seed)
98
+ torch.cuda.manual_seed_all(seed)
99
+
100
+
101
+ def read(file):
102
+ if file.endswith(".float3"):
103
+ return readFloat(file)
104
+ elif file.endswith(".flo"):
105
+ return readFlow(file)
106
+ elif file.endswith(".ppm"):
107
+ return readImage(file)
108
+ elif file.endswith(".pgm"):
109
+ return readImage(file)
110
+ elif file.endswith(".png"):
111
+ return readImage(file)
112
+ elif file.endswith(".jpg"):
113
+ return readImage(file)
114
+ elif file.endswith(".pfm"):
115
+ return readPFM(file)[0]
116
+ else:
117
+ raise Exception("don't know how to read %s" % file)
118
+
119
+
120
+ def write(file, data):
121
+ if file.endswith(".float3"):
122
+ return writeFloat(file, data)
123
+ elif file.endswith(".flo"):
124
+ return writeFlow(file, data)
125
+ elif file.endswith(".ppm"):
126
+ return writeImage(file, data)
127
+ elif file.endswith(".pgm"):
128
+ return writeImage(file, data)
129
+ elif file.endswith(".png"):
130
+ return writeImage(file, data)
131
+ elif file.endswith(".jpg"):
132
+ return writeImage(file, data)
133
+ elif file.endswith(".pfm"):
134
+ return writePFM(file, data)
135
+ else:
136
+ raise Exception("don't know how to write %s" % file)
137
+
138
+
139
+ def readPFM(file):
140
+ file = open(file, "rb")
141
+
142
+ color = None
143
+ width = None
144
+ height = None
145
+ scale = None
146
+ endian = None
147
+
148
+ header = file.readline().rstrip()
149
+ if header.decode("ascii") == "PF":
150
+ color = True
151
+ elif header.decode("ascii") == "Pf":
152
+ color = False
153
+ else:
154
+ raise Exception("Not a PFM file.")
155
+
156
+ dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii"))
157
+ if dim_match:
158
+ width, height = list(map(int, dim_match.groups()))
159
+ else:
160
+ raise Exception("Malformed PFM header.")
161
+
162
+ scale = float(file.readline().decode("ascii").rstrip())
163
+ if scale < 0:
164
+ endian = "<"
165
+ scale = -scale
166
+ else:
167
+ endian = ">"
168
+
169
+ data = np.fromfile(file, endian + "f")
170
+ shape = (height, width, 3) if color else (height, width)
171
+
172
+ data = np.reshape(data, shape)
173
+ data = np.flipud(data)
174
+ return data, scale
175
+
176
+
177
+ def writePFM(file, image, scale=1):
178
+ file = open(file, "wb")
179
+
180
+ color = None
181
+
182
+ if image.dtype.name != "float32":
183
+ raise Exception("Image dtype must be float32.")
184
+
185
+ image = np.flipud(image)
186
+
187
+ if len(image.shape) == 3 and image.shape[2] == 3:
188
+ color = True
189
+ elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1:
190
+ color = False
191
+ else:
192
+ raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.")
193
+
194
+ file.write("PF\n" if color else "Pf\n".encode())
195
+ file.write("%d %d\n".encode() % (image.shape[1], image.shape[0]))
196
+
197
+ endian = image.dtype.byteorder
198
+
199
+ if endian == "<" or endian == "=" and sys.byteorder == "little":
200
+ scale = -scale
201
+
202
+ file.write("%f\n".encode() % scale)
203
+
204
+ image.tofile(file)
205
+
206
+
207
+ def readFlow(name):
208
+ if name.endswith(".pfm") or name.endswith(".PFM"):
209
+ return readPFM(name)[0][:, :, 0:2]
210
+
211
+ f = open(name, "rb")
212
+
213
+ header = f.read(4)
214
+ if header.decode("utf-8") != "PIEH":
215
+ raise Exception("Flow file header does not contain PIEH")
216
+
217
+ width = np.fromfile(f, np.int32, 1).squeeze()
218
+ height = np.fromfile(f, np.int32, 1).squeeze()
219
+
220
+ flow = np.fromfile(f, np.float32, width * height * 2).reshape((height, width, 2))
221
+
222
+ return flow.astype(np.float32)
223
+
224
+
225
+ def readImage(name):
226
+ if name.endswith(".pfm") or name.endswith(".PFM"):
227
+ data = readPFM(name)[0]
228
+ if len(data.shape) == 3:
229
+ return data[:, :, 0:3]
230
+ else:
231
+ return data
232
+ return imread(name)
233
+
234
+
235
+ def writeImage(name, data):
236
+ if name.endswith(".pfm") or name.endswith(".PFM"):
237
+ return writePFM(name, data, 1)
238
+ return imwrite(name, data)
239
+
240
+
241
+ def writeFlow(name, flow):
242
+ f = open(name, "wb")
243
+ f.write("PIEH".encode("utf-8"))
244
+ np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f)
245
+ flow = flow.astype(np.float32)
246
+ flow.tofile(f)
247
+
248
+
249
+ def readFloat(name):
250
+ f = open(name, "rb")
251
+
252
+ if (f.readline().decode("utf-8")) != "float\n":
253
+ raise Exception("float file %s did not contain <float> keyword" % name)
254
+
255
+ dim = int(f.readline())
256
+
257
+ dims = []
258
+ count = 1
259
+ for i in range(0, dim):
260
+ d = int(f.readline())
261
+ dims.append(d)
262
+ count *= d
263
+
264
+ dims = list(reversed(dims))
265
+
266
+ data = np.fromfile(f, np.float32, count).reshape(dims)
267
+ if dim > 2:
268
+ data = np.transpose(data, (2, 1, 0))
269
+ data = np.transpose(data, (1, 0, 2))
270
+
271
+ return data
272
+
273
+
274
+ def writeFloat(name, data):
275
+ f = open(name, "wb")
276
+
277
+ dim = len(data.shape)
278
+ if dim > 3:
279
+ raise Exception("bad float file dimension: %d" % dim)
280
+
281
+ f.write(("float\n").encode("ascii"))
282
+ f.write(("%d\n" % dim).encode("ascii"))
283
+
284
+ if dim == 1:
285
+ f.write(("%d\n" % data.shape[0]).encode("ascii"))
286
+ else:
287
+ f.write(("%d\n" % data.shape[1]).encode("ascii"))
288
+ f.write(("%d\n" % data.shape[0]).encode("ascii"))
289
+ for i in range(2, dim):
290
+ f.write(("%d\n" % data.shape[i]).encode("ascii"))
291
+
292
+ data = data.astype(np.float32)
293
+ if dim == 2:
294
+ data.tofile(f)
295
+
296
+ else:
297
+ np.transpose(data, (2, 0, 1)).tofile(f)
298
+
299
+
300
+ def check_dim_and_resize(tensor_list):
301
+ shape_list = []
302
+ for t in tensor_list:
303
+ shape_list.append(t.shape[2:])
304
+
305
+ if len(set(shape_list)) > 1:
306
+ desired_shape = shape_list[0]
307
+ print(f"Inconsistent size of input video frames. All frames will be resized to {desired_shape}")
308
+
309
+ resize_tensor_list = []
310
+ for t in tensor_list:
311
+ resize_tensor_list.append(torch.nn.functional.interpolate(t, size=tuple(desired_shape), mode="bilinear"))
312
+
313
+ tensor_list = resize_tensor_list
314
+
315
+ return tensor_list
Helios-main/eval/utils/utils.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image, ImageSequence
6
+ from torchvision import transforms
7
+ from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
8
+ from video_reader import PyVideoReader
9
+
10
+
11
+ try:
12
+ from torchvision.transforms import InterpolationMode
13
+
14
+ BICUBIC = InterpolationMode.BICUBIC
15
+ BILINEAR = InterpolationMode.BILINEAR
16
+ except ImportError:
17
+ BICUBIC = Image.BICUBIC
18
+ BILINEAR = Image.BILINEAR
19
+
20
+
21
+ def clip_transform(n_px):
22
+ return Compose(
23
+ [
24
+ Resize(n_px, interpolation=BICUBIC, antialias=False),
25
+ CenterCrop(n_px),
26
+ transforms.Lambda(lambda x: x.float().div(255.0)),
27
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
28
+ ]
29
+ )
30
+
31
+
32
+ def clip_transform_Image(n_px):
33
+ return Compose(
34
+ [
35
+ Resize(n_px, interpolation=BICUBIC, antialias=False),
36
+ CenterCrop(n_px),
37
+ ToTensor(),
38
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
39
+ ]
40
+ )
41
+
42
+
43
+ def get_frame_indices(num_frames, vlen, sample="rand", fix_start=None, input_fps=1, max_num_frames=-1):
44
+ if sample in ["rand", "middle"]: # uniform sampling
45
+ acc_samples = min(num_frames, vlen)
46
+ # split the video into `acc_samples` intervals, and sample from each interval.
47
+ intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int)
48
+ ranges = []
49
+ for idx, interv in enumerate(intervals[:-1]):
50
+ ranges.append((interv, intervals[idx + 1] - 1))
51
+ if sample == "rand":
52
+ try:
53
+ frame_indices = [random.choice(range(x[0], x[1])) for x in ranges]
54
+ except Exception:
55
+ frame_indices = np.random.permutation(vlen)[:acc_samples]
56
+ frame_indices.sort()
57
+ frame_indices = list(frame_indices)
58
+ elif fix_start is not None:
59
+ frame_indices = [x[0] + fix_start for x in ranges]
60
+ elif sample == "middle":
61
+ frame_indices = [(x[0] + x[1]) // 2 for x in ranges]
62
+ else:
63
+ raise NotImplementedError
64
+
65
+ if len(frame_indices) < num_frames: # padded with last frame
66
+ padded_frame_indices = [frame_indices[-1]] * num_frames
67
+ padded_frame_indices[: len(frame_indices)] = frame_indices
68
+ frame_indices = padded_frame_indices
69
+ elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps
70
+ output_fps = float(sample[3:])
71
+ duration = float(vlen) / input_fps
72
+ delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents
73
+ frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta)
74
+ frame_indices = np.around(frame_seconds * input_fps).astype(int)
75
+ frame_indices = [e for e in frame_indices if e < vlen]
76
+ if max_num_frames > 0 and len(frame_indices) > max_num_frames:
77
+ frame_indices = frame_indices[:max_num_frames]
78
+ # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames)
79
+ else:
80
+ raise ValueError
81
+ return frame_indices
82
+
83
+
84
+ def align_dimension(value, alignment=2):
85
+ return int(round(value / alignment) * alignment)
86
+
87
+
88
+ def load_video(video_path, data_transform=None, num_frames=None, return_tensor=True, width=None, height=None):
89
+ if video_path.endswith(".gif"):
90
+ frame_ls = []
91
+ img = Image.open(video_path)
92
+ for frame in ImageSequence.Iterator(img):
93
+ frame = frame.convert("RGB")
94
+ frame = np.array(frame).astype(np.uint8)
95
+ frame_ls.append(frame)
96
+ buffer = np.array(frame_ls).astype(np.uint8)
97
+ elif video_path.endswith(".png"):
98
+ frame = Image.open(video_path)
99
+ frame = frame.convert("RGB")
100
+ frame = np.array(frame).astype(np.uint8)
101
+ frame_ls = [frame]
102
+ buffer = np.array(frame_ls)
103
+ elif video_path.endswith(".mp4"):
104
+ vr = PyVideoReader(video_path, threads=0)
105
+ if width is not None and height is not None:
106
+ (_, original_height, original_width) = vr.get_shape()
107
+ original_aspect_ratio = original_width / original_height
108
+ if width > height:
109
+ target_width = width
110
+ target_height = int(width / original_aspect_ratio)
111
+ else:
112
+ target_height = height
113
+ target_width = int(height * original_aspect_ratio)
114
+ target_height = align_dimension(target_height, 2)
115
+ target_width = align_dimension(target_width, 2)
116
+ vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0)
117
+ buffer = vr.decode()
118
+ vr = None
119
+ del vr
120
+ else:
121
+ raise NotImplementedError
122
+
123
+ frames = buffer
124
+ if num_frames and not video_path.endswith(".mp4"):
125
+ frame_indices = get_frame_indices(num_frames, len(frames), sample="middle")
126
+ frames = frames[frame_indices]
127
+
128
+ if data_transform:
129
+ frames = data_transform(frames)
130
+ elif return_tensor:
131
+ frames = torch.Tensor(frames)
132
+ frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
133
+
134
+ return frames
135
+
136
+
137
+ def read_frames_decord_by_fps(
138
+ video_path,
139
+ sample_fps=2,
140
+ sample="rand",
141
+ fix_start=None,
142
+ max_num_frames=-1,
143
+ trimmed30=False,
144
+ num_frames=8,
145
+ width=None,
146
+ height=None,
147
+ ):
148
+ vr_info = PyVideoReader(video_path, threads=0)
149
+ (vlen, original_height, original_width) = vr_info.get_shape()
150
+ fps = vr_info.get_fps()
151
+ duration = vlen / float(fps)
152
+ vr_info = None
153
+ del vr_info
154
+
155
+ if trimmed30 and duration > 30:
156
+ duration = 30
157
+ vlen = int(30 * float(fps))
158
+
159
+ target_width = None
160
+ target_height = None
161
+ if width is not None and height is not None:
162
+ original_aspect_ratio = original_width / original_height
163
+ if width > height:
164
+ target_width = width
165
+ target_height = int(width / original_aspect_ratio)
166
+ else:
167
+ target_height = height
168
+ target_width = int(height * original_aspect_ratio)
169
+ target_height = align_dimension(target_height, 2)
170
+ target_width = align_dimension(target_width, 2)
171
+
172
+ frame_indices = get_frame_indices(
173
+ num_frames, vlen, sample=sample, fix_start=fix_start, input_fps=fps, max_num_frames=max_num_frames
174
+ )
175
+
176
+ vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0)
177
+ buffer = vr.decode()
178
+ vr = None
179
+ del vr
180
+
181
+ frames = buffer[frame_indices]
182
+ if not isinstance(frames, torch.Tensor):
183
+ frames = torch.from_numpy(frames)
184
+
185
+ frames = frames.permute(0, 3, 1, 2) # (T, H, W, C) -> (T, C, H, W)
186
+
187
+ return frames
188
+
189
+
190
+ def load_video_frames(video_path, start_ratio=0.0, end_ratio=1.0, num_frames=8, height=384, width=640):
191
+ # First pass: get video shape
192
+ vr = PyVideoReader(video_path, threads=0)
193
+ (total_frames, original_height, original_width) = vr.get_shape()
194
+
195
+ # Calculate target dimensions maintaining aspect ratio
196
+ original_aspect_ratio = original_width / original_height
197
+ if width > height:
198
+ target_width = width
199
+ target_height = int(width / original_aspect_ratio)
200
+ else:
201
+ target_height = height
202
+ target_width = int(height * original_aspect_ratio)
203
+
204
+ target_height = align_dimension(target_height, 2)
205
+ target_width = align_dimension(target_width, 2)
206
+
207
+ # Calculate frame range
208
+ start_frame = int(total_frames * start_ratio)
209
+ end_frame = int(total_frames * end_ratio)
210
+ portion_length = end_frame - start_frame
211
+
212
+ if portion_length < num_frames:
213
+ # Expand the range to accommodate num_frames
214
+ needed_frames = num_frames - portion_length
215
+ expansion = needed_frames / 2
216
+
217
+ # Try to expand symmetrically
218
+ new_start = max(0, start_frame - int(np.ceil(expansion)))
219
+ new_end = min(total_frames, end_frame + int(np.floor(expansion)))
220
+
221
+ # If still not enough, expand further in available direction
222
+ if new_end - new_start < num_frames:
223
+ if new_start == 0:
224
+ new_end = min(total_frames, new_start + num_frames)
225
+ elif new_end == total_frames:
226
+ new_start = max(0, new_end - num_frames)
227
+
228
+ start_frame = new_start
229
+ end_frame = new_end
230
+ portion_length = end_frame - start_frame
231
+
232
+ # Now sample frames
233
+ frame_indices = np.linspace(start_frame, end_frame - 1, num_frames, dtype=int)
234
+ else:
235
+ # Sample uniformly from the portion
236
+ step = portion_length / num_frames
237
+ frame_indices = [int(start_frame + i * step) for i in range(num_frames)]
238
+
239
+ # Ensure indices are within bounds
240
+ frame_indices = [min(idx, total_frames - 1) for idx in frame_indices]
241
+
242
+ # Second pass: decode only needed frames with target dimensions
243
+ vr = PyVideoReader(video_path, target_height=target_height, target_width=target_width, threads=0)
244
+ frames = vr.get_batch(frame_indices) # Only decode needed frames (num_frames, H, W, C)
245
+
246
+ # Convert to tensor if needed and permute to (T, C, H, W)
247
+ if not isinstance(frames, torch.Tensor):
248
+ frames = torch.from_numpy(frames)
249
+ frames = frames.permute(0, 3, 1, 2) # (T, C, H, W)
250
+
251
+ # Clean up
252
+ vr = None
253
+ del vr
254
+
255
+ return frames
256
+
257
+
258
+ def extract_video_segment(input_path, output_path, start_ratio, end_ratio):
259
+ """
260
+ 尽可能保持原视频编码参数
261
+ """
262
+ import ffmpeg
263
+
264
+ # 获取原视频信息
265
+ probe = ffmpeg.probe(input_path)
266
+ video_stream = next(s for s in probe["streams"] if s["codec_type"] == "video")
267
+
268
+ duration = float(probe["format"]["duration"])
269
+ start_time = duration * start_ratio
270
+ segment_duration = duration * (end_ratio - start_ratio)
271
+
272
+ # 检测原视频编码参数
273
+ orig_codec = video_stream.get("codec_name", "h264")
274
+ orig_pix_fmt = video_stream.get("pix_fmt", "yuv420p")
275
+
276
+ # 如果原视频是 h264/h265,使用相同编码器
277
+ if orig_codec in ["h264", "hevc"]:
278
+ codec_name = "libx264" if orig_codec == "h264" else "libx265"
279
+ else:
280
+ codec_name = "libx264" # fallback
281
+
282
+ (
283
+ ffmpeg.input(input_path, ss=start_time)
284
+ .output(
285
+ output_path,
286
+ t=segment_duration,
287
+ vcodec=codec_name,
288
+ crf=0,
289
+ preset="medium",
290
+ pix_fmt=orig_pix_fmt,
291
+ acodec="copy",
292
+ vsync="cfr",
293
+ map_metadata=0,
294
+ )
295
+ .overwrite_output()
296
+ .run(quiet=True)
297
+ )
Helios-main/helios/diffusers_version/__init__.py ADDED
File without changes
Helios-main/helios/diffusers_version/pipeline_helios_diffusers.py ADDED
@@ -0,0 +1,1359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import html
16
+ import math
17
+ from itertools import accumulate
18
+ from typing import Any, Callable
19
+
20
+ import numpy as np
21
+ import regex as re
22
+ import torch
23
+ import torch.nn.functional as F
24
+ from transformers import AutoTokenizer, UMT5EncoderModel
25
+
26
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
27
+ from diffusers.image_processor import PipelineImageInput
28
+ from diffusers.loaders import HeliosLoraLoaderMixin
29
+ from diffusers.models import AutoencoderKLWan, HeliosTransformer3DModel
30
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
31
+ from diffusers.schedulers import HeliosScheduler
32
+ from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
33
+ from diffusers.utils.torch_utils import randn_tensor
34
+ from diffusers.video_processor import VideoProcessor
35
+
36
+ from ..pipelines.pipeline_output import HeliosPipelineOutput
37
+
38
+
39
+ if is_torch_xla_available():
40
+ import torch_xla.core.xla_model as xm
41
+
42
+ XLA_AVAILABLE = True
43
+ else:
44
+ XLA_AVAILABLE = False
45
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+ if is_ftfy_available():
49
+ import ftfy
50
+
51
+
52
+ EXAMPLE_DOC_STRING = """
53
+ Examples:
54
+ ```python
55
+ >>> import torch
56
+ >>> from diffusers.utils import export_to_video
57
+ >>> from diffusers import AutoencoderKLWan, HeliosPipeline
58
+
59
+ >>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled
60
+ >>> model_id = "BestWishYsh/Helios-Base"
61
+ >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
62
+ >>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
63
+ >>> pipe.to("cuda")
64
+
65
+ >>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
66
+ >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
67
+
68
+ >>> output = pipe(
69
+ ... prompt=prompt,
70
+ ... negative_prompt=negative_prompt,
71
+ ... height=384,
72
+ ... width=640,
73
+ ... num_frames=132,
74
+ ... guidance_scale=5.0,
75
+ ... ).frames[0]
76
+ >>> export_to_video(output, "output.mp4", fps=24)
77
+ ```
78
+ """
79
+
80
+
81
+ def optimized_scale(positive_flat, negative_flat):
82
+ positive_flat = positive_flat.float()
83
+ negative_flat = negative_flat.float()
84
+ # Calculate dot production
85
+ dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
86
+ # Squared norm of uncondition
87
+ squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
88
+ # st_star = v_cond^T * v_uncond / ||v_uncond||^2
89
+ st_star = dot_product / squared_norm
90
+ return st_star
91
+
92
+
93
+ def basic_clean(text):
94
+ text = ftfy.fix_text(text)
95
+ text = html.unescape(html.unescape(text))
96
+ return text.strip()
97
+
98
+
99
+ def whitespace_clean(text):
100
+ text = re.sub(r"\s+", " ", text)
101
+ text = text.strip()
102
+ return text
103
+
104
+
105
+ def prompt_clean(text):
106
+ text = whitespace_clean(basic_clean(text))
107
+ return text
108
+
109
+
110
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
111
+ def calculate_shift(
112
+ image_seq_len,
113
+ base_seq_len: int = 256,
114
+ max_seq_len: int = 4096,
115
+ base_shift: float = 0.5,
116
+ max_shift: float = 1.15,
117
+ ):
118
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
119
+ b = base_shift - m * base_seq_len
120
+ mu = image_seq_len * m + b
121
+ return mu
122
+
123
+
124
+ class HeliosPipeline(DiffusionPipeline, HeliosLoraLoaderMixin):
125
+ r"""
126
+ Pipeline for text-to-video / image-to-video / video-to-video generation using Helios.
127
+
128
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
129
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
130
+
131
+ Args:
132
+ tokenizer ([`T5Tokenizer`]):
133
+ Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
134
+ specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
135
+ text_encoder ([`T5EncoderModel`]):
136
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
137
+ the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
138
+ transformer ([`HeliosTransformer3DModel`]):
139
+ Conditional Transformer to denoise the input latents.
140
+ scheduler ([`HeliosScheduler`]):
141
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
142
+ vae ([`AutoencoderKLWan`]):
143
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
144
+ """
145
+
146
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
147
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
148
+ _optional_components = ["transformer"]
149
+
150
+ def __init__(
151
+ self,
152
+ tokenizer: AutoTokenizer,
153
+ text_encoder: UMT5EncoderModel,
154
+ vae: AutoencoderKLWan,
155
+ scheduler: HeliosScheduler,
156
+ transformer: HeliosTransformer3DModel,
157
+ is_cfg_zero_star: bool = False,
158
+ is_distilled: bool = False,
159
+ ):
160
+ super().__init__()
161
+
162
+ self.register_modules(
163
+ vae=vae,
164
+ text_encoder=text_encoder,
165
+ tokenizer=tokenizer,
166
+ transformer=transformer,
167
+ scheduler=scheduler,
168
+ )
169
+ self.register_to_config(is_cfg_zero_star=is_cfg_zero_star)
170
+ self.register_to_config(is_distilled=is_distilled)
171
+ self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
172
+ self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
173
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
174
+
175
+ def _get_t5_prompt_embeds(
176
+ self,
177
+ prompt: str | list[str] = None,
178
+ num_videos_per_prompt: int = 1,
179
+ max_sequence_length: int = 226,
180
+ device: torch.device | None = None,
181
+ dtype: torch.dtype | None = None,
182
+ ):
183
+ device = device or self._execution_device
184
+ dtype = dtype or self.text_encoder.dtype
185
+
186
+ prompt = [prompt] if isinstance(prompt, str) else prompt
187
+ prompt = [prompt_clean(u) for u in prompt]
188
+ batch_size = len(prompt)
189
+
190
+ text_inputs = self.tokenizer(
191
+ prompt,
192
+ padding="max_length",
193
+ max_length=max_sequence_length,
194
+ truncation=True,
195
+ add_special_tokens=True,
196
+ return_attention_mask=True,
197
+ return_tensors="pt",
198
+ )
199
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
200
+ seq_lens = mask.gt(0).sum(dim=1).long()
201
+
202
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
203
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
204
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
205
+ prompt_embeds = torch.stack(
206
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
207
+ )
208
+
209
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
210
+ _, seq_len, _ = prompt_embeds.shape
211
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
212
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
213
+
214
+ return prompt_embeds, text_inputs.attention_mask.bool()
215
+
216
+ def encode_prompt(
217
+ self,
218
+ prompt: str | list[str],
219
+ negative_prompt: str | list[str] | None = None,
220
+ do_classifier_free_guidance: bool = True,
221
+ num_videos_per_prompt: int = 1,
222
+ prompt_embeds: torch.Tensor | None = None,
223
+ negative_prompt_embeds: torch.Tensor | None = None,
224
+ max_sequence_length: int = 226,
225
+ device: torch.device | None = None,
226
+ dtype: torch.dtype | None = None,
227
+ ):
228
+ r"""
229
+ Encodes the prompt into text encoder hidden states.
230
+
231
+ Args:
232
+ prompt (`str` or `list[str]`, *optional*):
233
+ prompt to be encoded
234
+ negative_prompt (`str` or `list[str]`, *optional*):
235
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
236
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
237
+ less than `1`).
238
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
239
+ Whether to use classifier free guidance or not.
240
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
241
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
242
+ prompt_embeds (`torch.Tensor`, *optional*):
243
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
244
+ provided, text embeddings will be generated from `prompt` input argument.
245
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
246
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
247
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
248
+ argument.
249
+ device: (`torch.device`, *optional*):
250
+ torch device
251
+ dtype: (`torch.dtype`, *optional*):
252
+ torch dtype
253
+ """
254
+ device = device or self._execution_device
255
+
256
+ prompt = [prompt] if isinstance(prompt, str) else prompt
257
+ if prompt is not None:
258
+ batch_size = len(prompt)
259
+ else:
260
+ batch_size = prompt_embeds.shape[0]
261
+
262
+ if prompt_embeds is None:
263
+ prompt_embeds, _ = self._get_t5_prompt_embeds(
264
+ prompt=prompt,
265
+ num_videos_per_prompt=num_videos_per_prompt,
266
+ max_sequence_length=max_sequence_length,
267
+ device=device,
268
+ dtype=dtype,
269
+ )
270
+
271
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
272
+ negative_prompt = negative_prompt or ""
273
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
274
+
275
+ if prompt is not None and type(prompt) is not type(negative_prompt):
276
+ raise TypeError(
277
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
278
+ f" {type(prompt)}."
279
+ )
280
+ elif batch_size != len(negative_prompt):
281
+ raise ValueError(
282
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
283
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
284
+ " the batch size of `prompt`."
285
+ )
286
+
287
+ negative_prompt_embeds, _ = self._get_t5_prompt_embeds(
288
+ prompt=negative_prompt,
289
+ num_videos_per_prompt=num_videos_per_prompt,
290
+ max_sequence_length=max_sequence_length,
291
+ device=device,
292
+ dtype=dtype,
293
+ )
294
+
295
+ return prompt_embeds, negative_prompt_embeds
296
+
297
+ def check_inputs(
298
+ self,
299
+ prompt,
300
+ negative_prompt,
301
+ height,
302
+ width,
303
+ prompt_embeds=None,
304
+ negative_prompt_embeds=None,
305
+ callback_on_step_end_tensor_inputs=None,
306
+ image=None,
307
+ video=None,
308
+ use_interpolate_prompt=False,
309
+ num_videos_per_prompt=None,
310
+ interpolate_time_list=None,
311
+ interpolation_steps=None,
312
+ guidance_scale=None,
313
+ ):
314
+ if height % 16 != 0 or width % 16 != 0:
315
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
316
+
317
+ if callback_on_step_end_tensor_inputs is not None and not all(
318
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
319
+ ):
320
+ raise ValueError(
321
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
322
+ )
323
+
324
+ if prompt is not None and prompt_embeds is not None:
325
+ raise ValueError(
326
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
327
+ " only forward one of the two."
328
+ )
329
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
330
+ raise ValueError(
331
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
332
+ " only forward one of the two."
333
+ )
334
+ elif prompt is None and prompt_embeds is None:
335
+ raise ValueError(
336
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
337
+ )
338
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
339
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
340
+ elif negative_prompt is not None and (
341
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
342
+ ):
343
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
344
+
345
+ if image is not None and video is not None:
346
+ raise ValueError("image and video cannot be provided simultaneously")
347
+
348
+ if use_interpolate_prompt:
349
+ assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}"
350
+ assert isinstance(prompt, list), "prompt must be a list"
351
+ assert len(prompt) == len(interpolate_time_list), (
352
+ f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}"
353
+ )
354
+ assert min(interpolate_time_list) > interpolation_steps, (
355
+ f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}"
356
+ )
357
+
358
+ if guidance_scale > 1.0 and self.config.is_distilled:
359
+ logger.warning(f"Guidance scale {guidance_scale} is ignored for step-wise distilled models.")
360
+
361
+ def prepare_latents(
362
+ self,
363
+ batch_size: int,
364
+ num_channels_latents: int = 16,
365
+ height: int = 384,
366
+ width: int = 640,
367
+ num_frames: int = 33,
368
+ dtype: torch.dtype | None = None,
369
+ device: torch.device | None = None,
370
+ generator: torch.Generator | list[torch.Generator] | None = None,
371
+ latents: torch.Tensor | None = None,
372
+ ) -> torch.Tensor:
373
+ if latents is not None:
374
+ return latents.to(device=device, dtype=dtype)
375
+
376
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
377
+ shape = (
378
+ batch_size,
379
+ num_channels_latents,
380
+ num_latent_frames,
381
+ int(height) // self.vae_scale_factor_spatial,
382
+ int(width) // self.vae_scale_factor_spatial,
383
+ )
384
+ if isinstance(generator, list) and len(generator) != batch_size:
385
+ raise ValueError(
386
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
387
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
388
+ )
389
+
390
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
391
+ return latents
392
+
393
+ def prepare_image_latents(
394
+ self,
395
+ image: torch.Tensor,
396
+ latents_mean: torch.Tensor,
397
+ latents_std: torch.Tensor,
398
+ num_latent_frames_per_chunk: int,
399
+ dtype: torch.dtype | None = None,
400
+ device: torch.device | None = None,
401
+ generator: torch.Generator | list[torch.Generator] | None = None,
402
+ latents: torch.Tensor | None = None,
403
+ fake_latents: torch.Tensor | None = None,
404
+ ) -> torch.Tensor:
405
+ device = device or self._execution_device
406
+ if latents is None:
407
+ image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype)
408
+ latents = self.vae.encode(image).latent_dist.sample(generator=generator)
409
+ latents = (latents - latents_mean) * latents_std
410
+ if fake_latents is None:
411
+ min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
412
+ fake_video = image.repeat(1, 1, min_frames, 1, 1).to(device=device, dtype=self.vae.dtype)
413
+ fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator)
414
+ fake_latents_full = (fake_latents_full - latents_mean) * latents_std
415
+ fake_latents = fake_latents_full[:, :, -1:, :, :]
416
+ return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype)
417
+
418
+ def prepare_video_latents(
419
+ self,
420
+ video: torch.Tensor,
421
+ latents_mean: torch.Tensor,
422
+ latents_std: torch.Tensor,
423
+ num_latent_frames_per_chunk: int,
424
+ dtype: torch.dtype | None = None,
425
+ device: torch.device | None = None,
426
+ generator: torch.Generator | list[torch.Generator] | None = None,
427
+ latents: torch.Tensor | None = None,
428
+ ) -> torch.Tensor:
429
+ device = device or self._execution_device
430
+ video = video.to(device=device, dtype=self.vae.dtype)
431
+ if latents is None:
432
+ num_frames = video.shape[2]
433
+ min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
434
+ num_chunks = num_frames // min_frames
435
+ if num_chunks == 0:
436
+ raise ValueError(
437
+ f"Video must have at least {min_frames} frames "
438
+ f"(got {num_frames} frames). "
439
+ f"Required: (num_latent_frames_per_chunk - 1) * {self.vae_scale_factor_temporal} + 1 = ({num_latent_frames_per_chunk} - 1) * {self.vae_scale_factor_temporal} + 1 = {min_frames}"
440
+ )
441
+ total_valid_frames = num_chunks * min_frames
442
+ start_frame = num_frames - total_valid_frames
443
+
444
+ first_frame = video[:, :, 0:1, :, :]
445
+ first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator)
446
+ first_frame_latent = (first_frame_latent - latents_mean) * latents_std
447
+
448
+ latents_chunks = []
449
+ for i in range(num_chunks):
450
+ chunk_start = start_frame + i * min_frames
451
+ chunk_end = chunk_start + min_frames
452
+ video_chunk = video[:, :, chunk_start:chunk_end, :, :]
453
+ chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator)
454
+ chunk_latents = (chunk_latents - latents_mean) * latents_std
455
+ latents_chunks.append(chunk_latents)
456
+ latents = torch.cat(latents_chunks, dim=2)
457
+ return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype)
458
+
459
+ def interpolate_prompt_embeds(
460
+ self,
461
+ prompt_embeds_1: torch.Tensor,
462
+ prompt_embeds_2: torch.Tensor,
463
+ interpolation_steps: int = 3,
464
+ ):
465
+ x = torch.lerp(
466
+ prompt_embeds_1,
467
+ prompt_embeds_2,
468
+ torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1),
469
+ )
470
+ interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0))
471
+ return interpolated_prompt_embeds
472
+
473
+ def sample_block_noise(
474
+ self,
475
+ batch_size,
476
+ channel,
477
+ num_frames,
478
+ height,
479
+ width,
480
+ patch_size: tuple[int, ...] = (1, 2, 2),
481
+ device: torch.device | None = None,
482
+ generator: torch.Generator | None = None,
483
+ ):
484
+ # NOTE: A generator must be provided to ensure correct and reproducible results.
485
+ # Creating a default generator here is a fallback only — without a fixed seed,
486
+ # the output will be non-deterministic and may produce incorrect results in CP context.
487
+ if generator is None:
488
+ generator = torch.Generator(device=device)
489
+ elif isinstance(generator, list):
490
+ generator = generator[0]
491
+
492
+ gamma = self.scheduler.config.gamma
493
+ _, ph, pw = patch_size
494
+ block_size = ph * pw
495
+
496
+ cov = (
497
+ torch.eye(block_size, device=device) * (1 + gamma)
498
+ - torch.ones(block_size, block_size, device=device) * gamma
499
+ )
500
+ cov += torch.eye(block_size, device=device) * 1e-8
501
+ cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16.
502
+
503
+ L = torch.linalg.cholesky(cov)
504
+ block_number = batch_size * channel * num_frames * (height // ph) * (width // pw)
505
+ z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device)
506
+ noise = z @ L.T
507
+
508
+ noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw)
509
+ noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width)
510
+
511
+ return noise
512
+
513
+ def stage1_sample(
514
+ self,
515
+ latents: torch.Tensor = None,
516
+ prompt_embeds: torch.Tensor = None,
517
+ negative_prompt_embeds: torch.Tensor = None,
518
+ timesteps: torch.Tensor = None,
519
+ guidance_scale: float | None = 5.0,
520
+ indices_hidden_states: torch.Tensor = None,
521
+ indices_latents_history_short: torch.Tensor = None,
522
+ indices_latents_history_mid: torch.Tensor = None,
523
+ indices_latents_history_long: torch.Tensor = None,
524
+ latents_history_short: torch.Tensor = None,
525
+ latents_history_mid: torch.Tensor = None,
526
+ latents_history_long: torch.Tensor = None,
527
+ attention_kwargs: dict | None = None,
528
+ device: torch.device | None = None,
529
+ transformer_dtype: torch.dtype = None,
530
+ generator: torch.Generator | None = None,
531
+ num_warmup_steps: int | None = None,
532
+ # ------------ CFG Zero ------------
533
+ use_zero_init: bool | None = True,
534
+ zero_steps: int | None = 1,
535
+ # ------------ Callback ------------
536
+ callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
537
+ callback_on_step_end_tensor_inputs: list[str] = ["latents"],
538
+ progress_bar=None,
539
+ ):
540
+ batch_size = latents.shape[0]
541
+
542
+ for i, t in enumerate(timesteps):
543
+ if self.interrupt:
544
+ continue
545
+
546
+ self._current_timestep = t
547
+ timestep = t.expand(latents.shape[0])
548
+
549
+ latent_model_input = latents.to(transformer_dtype)
550
+ with self.transformer.cache_context("cond"):
551
+ noise_pred = self.transformer(
552
+ hidden_states=latent_model_input,
553
+ timestep=timestep,
554
+ encoder_hidden_states=prompt_embeds,
555
+ indices_hidden_states=indices_hidden_states,
556
+ indices_latents_history_short=indices_latents_history_short,
557
+ indices_latents_history_mid=indices_latents_history_mid,
558
+ indices_latents_history_long=indices_latents_history_long,
559
+ latents_history_short=latents_history_short.to(transformer_dtype),
560
+ latents_history_mid=latents_history_mid.to(transformer_dtype),
561
+ latents_history_long=latents_history_long.to(transformer_dtype),
562
+ attention_kwargs=attention_kwargs,
563
+ return_dict=False,
564
+ )[0]
565
+
566
+ if self.do_classifier_free_guidance:
567
+ with self.transformer.cache_context("uncond"):
568
+ noise_uncond = self.transformer(
569
+ hidden_states=latent_model_input,
570
+ timestep=timestep,
571
+ encoder_hidden_states=negative_prompt_embeds,
572
+ indices_hidden_states=indices_hidden_states,
573
+ indices_latents_history_short=indices_latents_history_short,
574
+ indices_latents_history_mid=indices_latents_history_mid,
575
+ indices_latents_history_long=indices_latents_history_long,
576
+ latents_history_short=latents_history_short.to(transformer_dtype),
577
+ latents_history_mid=latents_history_mid.to(transformer_dtype),
578
+ latents_history_long=latents_history_long.to(transformer_dtype),
579
+ attention_kwargs=attention_kwargs,
580
+ return_dict=False,
581
+ )[0]
582
+
583
+ if self.config.is_cfg_zero_star:
584
+ noise_pred_text = noise_pred
585
+ positive_flat = noise_pred_text.view(batch_size, -1)
586
+ negative_flat = noise_uncond.view(batch_size, -1)
587
+
588
+ alpha = optimized_scale(positive_flat, negative_flat)
589
+ alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
590
+ alpha = alpha.to(noise_pred_text.dtype)
591
+
592
+ if (i <= zero_steps) and use_zero_init:
593
+ noise_pred = noise_pred_text * 0.0
594
+ else:
595
+ noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha)
596
+ else:
597
+ noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
598
+
599
+ latents = self.scheduler.step(
600
+ noise_pred,
601
+ t,
602
+ latents,
603
+ return_dict=False,
604
+ )[0]
605
+
606
+ if callback_on_step_end is not None:
607
+ callback_kwargs = {}
608
+ for k in callback_on_step_end_tensor_inputs:
609
+ callback_kwargs[k] = locals()[k]
610
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
611
+
612
+ latents = callback_outputs.pop("latents", latents)
613
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
614
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
615
+
616
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
617
+ progress_bar.update()
618
+
619
+ if XLA_AVAILABLE:
620
+ xm.mark_step()
621
+
622
+ return latents
623
+
624
+ def stage2_sample(
625
+ self,
626
+ latents: torch.Tensor = None,
627
+ pyramid_num_stages: int = None,
628
+ pyramid_num_inference_steps_list: list[int] = None,
629
+ prompt_embeds: torch.Tensor = None,
630
+ negative_prompt_embeds: torch.Tensor = None,
631
+ guidance_scale: float | None = 5.0,
632
+ indices_hidden_states: torch.Tensor = None,
633
+ indices_latents_history_short: torch.Tensor = None,
634
+ indices_latents_history_mid: torch.Tensor = None,
635
+ indices_latents_history_long: torch.Tensor = None,
636
+ latents_history_short: torch.Tensor = None,
637
+ latents_history_mid: torch.Tensor = None,
638
+ latents_history_long: torch.Tensor = None,
639
+ attention_kwargs: dict | None = None,
640
+ device: torch.device | None = None,
641
+ transformer_dtype: torch.dtype = None,
642
+ generator: torch.Generator | None = None,
643
+ # ------------ CFG Zero ------------
644
+ use_zero_init: bool | None = True,
645
+ zero_steps: int | None = 1,
646
+ # -------------- DMD --------------
647
+ is_amplify_first_chunk: bool = False,
648
+ # ------------ Callback ------------
649
+ callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
650
+ callback_on_step_end_tensor_inputs: list[str] = ["latents"],
651
+ progress_bar=None,
652
+ ):
653
+ batch_size, num_channel, num_frames, height, width = latents.shape
654
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, num_channel, height, width)
655
+ for _ in range(pyramid_num_stages - 1):
656
+ height //= 2
657
+ width //= 2
658
+ latents = (
659
+ F.interpolate(
660
+ latents,
661
+ size=(height, width),
662
+ mode="bilinear",
663
+ )
664
+ * 2
665
+ )
666
+ latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4)
667
+
668
+ batch_size = latents.shape[0]
669
+ start_point_list = None
670
+ if self.config.is_distilled:
671
+ start_point_list = [latents]
672
+
673
+ i = 0
674
+ for i_s in range(pyramid_num_stages):
675
+ patch_size = self.transformer.config.patch_size
676
+ image_seq_len = (latents.shape[-1] * latents.shape[-2] * latents.shape[-3]) // (
677
+ patch_size[0] * patch_size[1] * patch_size[2]
678
+ )
679
+ mu = calculate_shift(
680
+ image_seq_len,
681
+ self.scheduler.config.get("base_image_seq_len", 256),
682
+ self.scheduler.config.get("max_image_seq_len", 4096),
683
+ self.scheduler.config.get("base_shift", 0.5),
684
+ self.scheduler.config.get("max_shift", 1.15),
685
+ )
686
+ self.scheduler.set_timesteps(
687
+ pyramid_num_inference_steps_list[i_s],
688
+ i_s,
689
+ device=device,
690
+ mu=mu,
691
+ is_amplify_first_chunk=is_amplify_first_chunk,
692
+ )
693
+ timesteps = self.scheduler.timesteps
694
+
695
+ if i_s > 0:
696
+ height *= 2
697
+ width *= 2
698
+ num_frames = latents.shape[2]
699
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(
700
+ batch_size * num_frames, num_channel, height // 2, width // 2
701
+ )
702
+ latents = F.interpolate(latents, size=(height, width), mode="nearest")
703
+ latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4)
704
+ # Fix the stage
705
+ ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal
706
+ gamma = self.scheduler.config.gamma
707
+ alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
708
+ beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
709
+
710
+ batch_size, channel, num_frames, height, width = latents.shape
711
+ noise = self.sample_block_noise(
712
+ batch_size, channel, num_frames, height, width, patch_size, device, generator
713
+ )
714
+ noise = noise.to(device=device, dtype=transformer_dtype)
715
+ latents = alpha * latents + beta * noise # To fix the block artifact
716
+
717
+ if self.config.is_distilled:
718
+ start_point_list.append(latents)
719
+
720
+ for idx, t in enumerate(timesteps):
721
+ timestep = t.expand(latents.shape[0]).to(torch.int64)
722
+
723
+ with self.transformer.cache_context("cond"):
724
+ noise_pred = self.transformer(
725
+ hidden_states=latents.to(transformer_dtype),
726
+ timestep=timestep,
727
+ encoder_hidden_states=prompt_embeds,
728
+ attention_kwargs=attention_kwargs,
729
+ return_dict=False,
730
+ indices_hidden_states=indices_hidden_states,
731
+ indices_latents_history_short=indices_latents_history_short,
732
+ indices_latents_history_mid=indices_latents_history_mid,
733
+ indices_latents_history_long=indices_latents_history_long,
734
+ latents_history_short=latents_history_short.to(transformer_dtype),
735
+ latents_history_mid=latents_history_mid.to(transformer_dtype),
736
+ latents_history_long=latents_history_long.to(transformer_dtype),
737
+ )[0]
738
+
739
+ if self.do_classifier_free_guidance:
740
+ with self.transformer.cache_context("uncond"):
741
+ noise_uncond = self.transformer(
742
+ hidden_states=latents.to(transformer_dtype),
743
+ timestep=timestep,
744
+ encoder_hidden_states=negative_prompt_embeds,
745
+ attention_kwargs=attention_kwargs,
746
+ return_dict=False,
747
+ indices_hidden_states=indices_hidden_states,
748
+ indices_latents_history_short=indices_latents_history_short,
749
+ indices_latents_history_mid=indices_latents_history_mid,
750
+ indices_latents_history_long=indices_latents_history_long,
751
+ latents_history_short=latents_history_short.to(transformer_dtype),
752
+ latents_history_mid=latents_history_mid.to(transformer_dtype),
753
+ latents_history_long=latents_history_long.to(transformer_dtype),
754
+ )[0]
755
+
756
+ if self.config.is_cfg_zero_star:
757
+ noise_pred_text = noise_pred
758
+ positive_flat = noise_pred_text.view(batch_size, -1)
759
+ negative_flat = noise_uncond.view(batch_size, -1)
760
+
761
+ alpha = optimized_scale(positive_flat, negative_flat)
762
+ alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
763
+ alpha = alpha.to(noise_pred_text.dtype)
764
+
765
+ if (i_s == 0 and idx <= zero_steps) and use_zero_init:
766
+ noise_pred = noise_pred_text * 0.0
767
+ else:
768
+ noise_pred = noise_uncond * alpha + guidance_scale * (
769
+ noise_pred_text - noise_uncond * alpha
770
+ )
771
+ else:
772
+ noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
773
+
774
+ latents = self.scheduler.step(
775
+ noise_pred,
776
+ t,
777
+ latents,
778
+ generator=generator,
779
+ return_dict=False,
780
+ cur_sampling_step=idx,
781
+ dmd_noisy_tensor=start_point_list[i_s] if start_point_list is not None else None,
782
+ dmd_sigmas=self.scheduler.sigmas,
783
+ dmd_timesteps=self.scheduler.timesteps,
784
+ all_timesteps=timesteps,
785
+ )[0]
786
+
787
+ if callback_on_step_end is not None:
788
+ callback_kwargs = {}
789
+ for k in callback_on_step_end_tensor_inputs:
790
+ callback_kwargs[k] = locals()[k]
791
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
792
+
793
+ latents = callback_outputs.pop("latents", latents)
794
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
795
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
796
+
797
+ progress_bar.update()
798
+
799
+ if XLA_AVAILABLE:
800
+ xm.mark_step()
801
+
802
+ i += 1
803
+
804
+ return latents
805
+
806
+ @property
807
+ def guidance_scale(self):
808
+ return self._guidance_scale
809
+
810
+ @property
811
+ def do_classifier_free_guidance(self):
812
+ return self._guidance_scale > 1.0
813
+
814
+ @property
815
+ def num_timesteps(self):
816
+ return self._num_timesteps
817
+
818
+ @property
819
+ def current_timestep(self):
820
+ return self._current_timestep
821
+
822
+ @property
823
+ def interrupt(self):
824
+ return self._interrupt
825
+
826
+ @property
827
+ def attention_kwargs(self):
828
+ return self._attention_kwargs
829
+
830
+ @torch.no_grad()
831
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
832
+ def __call__(
833
+ self,
834
+ prompt: str | list[str] = None,
835
+ negative_prompt: str | list[str] = None,
836
+ height: int = 384,
837
+ width: int = 640,
838
+ num_frames: int = 132,
839
+ num_inference_steps: int = 50,
840
+ sigmas: list[float] = None,
841
+ guidance_scale: float = 5.0,
842
+ num_videos_per_prompt: int | None = 1,
843
+ generator: torch.Generator | list[torch.Generator] | None = None,
844
+ latents: torch.Tensor | None = None,
845
+ prompt_embeds: torch.Tensor | None = None,
846
+ negative_prompt_embeds: torch.Tensor | None = None,
847
+ output_type: str | None = "np",
848
+ return_dict: bool = True,
849
+ attention_kwargs: dict[str, Any] | None = None,
850
+ callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
851
+ callback_on_step_end_tensor_inputs: list[str] = ["latents"],
852
+ max_sequence_length: int = 512,
853
+ # ------------ I2V ------------
854
+ image: PipelineImageInput | None = None,
855
+ image_latents: torch.Tensor | None = None,
856
+ fake_image_latents: torch.Tensor | None = None,
857
+ add_noise_to_image_latents: bool = True,
858
+ image_noise_sigma_min: float = 0.111,
859
+ image_noise_sigma_max: float = 0.135,
860
+ # ------------ V2V ------------
861
+ video: PipelineImageInput | None = None,
862
+ video_latents: torch.Tensor | None = None,
863
+ add_noise_to_video_latents: bool = True,
864
+ video_noise_sigma_min: float = 0.111,
865
+ video_noise_sigma_max: float = 0.135,
866
+ # ------------ Interactive ------------
867
+ use_interpolate_prompt: bool = False,
868
+ interpolate_time_list: list = [7, 7, 7],
869
+ interpolation_steps: int = 3,
870
+ # ------------ Stage 1 ------------
871
+ history_sizes: list = [16, 2, 1],
872
+ num_latent_frames_per_chunk: int = 9,
873
+ keep_first_frame: bool = True,
874
+ is_skip_first_chunk: bool = False,
875
+ # ------------ Stage 2 ------------
876
+ is_enable_stage2: bool = False,
877
+ pyramid_num_stages: int = 3,
878
+ pyramid_num_inference_steps_list: list = [10, 10, 10],
879
+ # ------------ CFG Zero ------------
880
+ use_zero_init: bool | None = True,
881
+ zero_steps: int | None = 1,
882
+ # ------------ DMD ------------
883
+ is_amplify_first_chunk: bool = False,
884
+ ):
885
+ r"""
886
+ The call function to the pipeline for generation.
887
+
888
+ Args:
889
+ prompt (`str` or `list[str]`, *optional*):
890
+ The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
891
+ negative_prompt (`str` or `list[str]`, *optional*):
892
+ The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
893
+ instead. Ignored when not using guidance (`guidance_scale` < `1`).
894
+ height (`int`, defaults to `384`):
895
+ The height in pixels of the generated image.
896
+ width (`int`, defaults to `640`):
897
+ The width in pixels of the generated image.
898
+ num_frames (`int`, defaults to `132`):
899
+ The number of frames in the generated video.
900
+ num_inference_steps (`int`, defaults to `50`):
901
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
902
+ expense of slower inference.
903
+ guidance_scale (`float`, defaults to `5.0`):
904
+ Guidance scale as defined in [Classifier-Free Diffusion
905
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
906
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
907
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
908
+ the text `prompt`, usually at the expense of lower image quality.
909
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
910
+ The number of images to generate per prompt.
911
+ generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
912
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
913
+ generation deterministic.
914
+ latents (`torch.Tensor`, *optional*):
915
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
916
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
917
+ tensor is generated by sampling using the supplied random `generator`.
918
+ prompt_embeds (`torch.Tensor`, *optional*):
919
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
920
+ provided, text embeddings are generated from the `prompt` input argument.
921
+ output_type (`str`, *optional*, defaults to `"np"`):
922
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
923
+ return_dict (`bool`, *optional*, defaults to `True`):
924
+ Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple.
925
+ attention_kwargs (`dict`, *optional*):
926
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
927
+ `self.processor` in
928
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
929
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
930
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
931
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
932
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
933
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
934
+ callback_on_step_end_tensor_inputs (`list`, *optional*):
935
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
936
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
937
+ `._callback_tensor_inputs` attribute of your pipeline class.
938
+ max_sequence_length (`int`, defaults to `512`):
939
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
940
+ truncated. If the prompt is shorter, it will be padded to this length.
941
+
942
+ Examples:
943
+
944
+ Returns:
945
+ [`~HeliosPipelineOutput`] or `tuple`:
946
+ If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where
947
+ the first element is a list with the generated images and the second element is a list of `bool`s
948
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
949
+ """
950
+
951
+ if image is not None and video is not None:
952
+ raise ValueError("image and video cannot be provided simultaneously")
953
+
954
+ history_sizes = sorted(history_sizes, reverse=True) # From big to small
955
+
956
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
957
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
958
+
959
+ # 1. Check inputs. Raise error if not correct
960
+ self.check_inputs(
961
+ prompt,
962
+ negative_prompt,
963
+ height,
964
+ width,
965
+ prompt_embeds,
966
+ negative_prompt_embeds,
967
+ callback_on_step_end_tensor_inputs,
968
+ image,
969
+ video,
970
+ use_interpolate_prompt,
971
+ num_videos_per_prompt,
972
+ interpolate_time_list,
973
+ interpolation_steps,
974
+ guidance_scale,
975
+ )
976
+
977
+ num_frames = max(num_frames, 1)
978
+
979
+ self._guidance_scale = guidance_scale
980
+ self._attention_kwargs = attention_kwargs
981
+ self._current_timestep = None
982
+ self._interrupt = False
983
+
984
+ device = self._execution_device
985
+ vae_dtype = self.vae.dtype
986
+
987
+ latents_mean = (
988
+ torch.tensor(self.vae.config.latents_mean)
989
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
990
+ .to(device, self.vae.dtype)
991
+ )
992
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
993
+ device, self.vae.dtype
994
+ )
995
+
996
+ # 2. Define call parameters
997
+ if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)):
998
+ batch_size = 1
999
+ elif prompt is not None and isinstance(prompt, list):
1000
+ batch_size = len(prompt)
1001
+ else:
1002
+ batch_size = prompt_embeds.shape[0]
1003
+
1004
+ # 3. Encode input prompt
1005
+ if use_interpolate_prompt:
1006
+ interpolate_interval_idx = None
1007
+ interpolate_embeds = None
1008
+ interpolate_cumulative_list = list(accumulate(interpolate_time_list))
1009
+
1010
+ all_prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1011
+ prompt=prompt,
1012
+ negative_prompt=negative_prompt,
1013
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1014
+ num_videos_per_prompt=num_videos_per_prompt,
1015
+ prompt_embeds=prompt_embeds,
1016
+ negative_prompt_embeds=negative_prompt_embeds,
1017
+ max_sequence_length=max_sequence_length,
1018
+ device=device,
1019
+ )
1020
+
1021
+ transformer_dtype = self.transformer.dtype
1022
+ all_prompt_embeds = all_prompt_embeds.to(transformer_dtype)
1023
+ if negative_prompt_embeds is not None:
1024
+ if use_interpolate_prompt:
1025
+ negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0)
1026
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
1027
+
1028
+ # 4. Prepare image or video
1029
+ if image is not None:
1030
+ image = self.video_processor.preprocess(image, height=height, width=width)
1031
+ image_latents, fake_image_latents = self.prepare_image_latents(
1032
+ image,
1033
+ latents_mean=latents_mean,
1034
+ latents_std=latents_std,
1035
+ num_latent_frames_per_chunk=num_latent_frames_per_chunk,
1036
+ dtype=torch.float32,
1037
+ device=device,
1038
+ generator=generator,
1039
+ latents=image_latents,
1040
+ fake_latents=fake_image_latents,
1041
+ )
1042
+
1043
+ if image_latents is not None and add_noise_to_image_latents:
1044
+ image_noise_sigma = (
1045
+ torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
1046
+ + image_noise_sigma_min
1047
+ )
1048
+ image_latents = (
1049
+ image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
1050
+ + (1 - image_noise_sigma) * image_latents
1051
+ )
1052
+ fake_image_noise_sigma = (
1053
+ torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min)
1054
+ + video_noise_sigma_min
1055
+ )
1056
+ fake_image_latents = (
1057
+ fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device)
1058
+ + (1 - fake_image_noise_sigma) * fake_image_latents
1059
+ )
1060
+
1061
+ if video is not None:
1062
+ video = self.video_processor.preprocess_video(video, height=height, width=width)
1063
+ image_latents, video_latents = self.prepare_video_latents(
1064
+ video,
1065
+ latents_mean=latents_mean,
1066
+ latents_std=latents_std,
1067
+ num_latent_frames_per_chunk=num_latent_frames_per_chunk,
1068
+ dtype=torch.float32,
1069
+ device=device,
1070
+ generator=generator,
1071
+ latents=video_latents,
1072
+ )
1073
+
1074
+ if video_latents is not None and add_noise_to_video_latents:
1075
+ image_noise_sigma = (
1076
+ torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
1077
+ + image_noise_sigma_min
1078
+ )
1079
+ image_latents = (
1080
+ image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
1081
+ + (1 - image_noise_sigma) * image_latents
1082
+ )
1083
+
1084
+ noisy_latents_chunks = []
1085
+ num_latent_chunks = video_latents.shape[2] // num_latent_frames_per_chunk
1086
+ for i in range(num_latent_chunks):
1087
+ chunk_start = i * num_latent_frames_per_chunk
1088
+ chunk_end = chunk_start + num_latent_frames_per_chunk
1089
+ latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :]
1090
+
1091
+ chunk_frames = latent_chunk.shape[2]
1092
+ frame_sigmas = (
1093
+ torch.rand(chunk_frames, device=device, generator=generator)
1094
+ * (video_noise_sigma_max - video_noise_sigma_min)
1095
+ + video_noise_sigma_min
1096
+ )
1097
+ frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1)
1098
+
1099
+ noisy_chunk = (
1100
+ frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device)
1101
+ + (1 - frame_sigmas) * latent_chunk
1102
+ )
1103
+ noisy_latents_chunks.append(noisy_chunk)
1104
+ video_latents = torch.cat(noisy_latents_chunks, dim=2)
1105
+
1106
+ # 5. Prepare latent variables
1107
+ num_channels_latents = self.transformer.config.in_channels
1108
+ window_num_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
1109
+ num_latent_chunk = max(1, (num_frames + window_num_frames - 1) // window_num_frames)
1110
+ num_history_latent_frames = sum(history_sizes)
1111
+ history_video = None
1112
+ total_generated_latent_frames = 0
1113
+
1114
+ if not keep_first_frame:
1115
+ history_sizes[-1] = history_sizes[-1] + 1
1116
+ history_latents = torch.zeros(
1117
+ batch_size,
1118
+ num_channels_latents,
1119
+ num_history_latent_frames,
1120
+ height // self.vae_scale_factor_spatial,
1121
+ width // self.vae_scale_factor_spatial,
1122
+ device=device,
1123
+ dtype=torch.float32,
1124
+ )
1125
+ if fake_image_latents is not None:
1126
+ history_latents = torch.cat([history_latents[:, :, :-1, :, :], fake_image_latents], dim=2)
1127
+ total_generated_latent_frames += 1
1128
+ if video_latents is not None:
1129
+ history_frames = history_latents.shape[2]
1130
+ video_frames = video_latents.shape[2]
1131
+ if video_frames < history_frames:
1132
+ keep_frames = history_frames - video_frames
1133
+ history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2)
1134
+ else:
1135
+ history_latents = video_latents
1136
+ total_generated_latent_frames += video_latents.shape[2]
1137
+
1138
+ if keep_first_frame:
1139
+ indices = torch.arange(0, sum([1, *history_sizes, num_latent_frames_per_chunk]))
1140
+ (
1141
+ indices_prefix,
1142
+ indices_latents_history_long,
1143
+ indices_latents_history_mid,
1144
+ indices_latents_history_1x,
1145
+ indices_hidden_states,
1146
+ ) = indices.split([1, *history_sizes, num_latent_frames_per_chunk], dim=0)
1147
+ indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
1148
+ else:
1149
+ indices = torch.arange(0, sum([*history_sizes, num_latent_frames_per_chunk]))
1150
+ (
1151
+ indices_latents_history_long,
1152
+ indices_latents_history_mid,
1153
+ indices_latents_history_short,
1154
+ indices_hidden_states,
1155
+ ) = indices.split([*history_sizes, num_latent_frames_per_chunk], dim=0)
1156
+ indices_hidden_states = indices_hidden_states.unsqueeze(0)
1157
+ indices_latents_history_short = indices_latents_history_short.unsqueeze(0)
1158
+ indices_latents_history_mid = indices_latents_history_mid.unsqueeze(0)
1159
+ indices_latents_history_long = indices_latents_history_long.unsqueeze(0)
1160
+
1161
+ # 6. Denoising loop
1162
+ if use_interpolate_prompt:
1163
+ if num_latent_chunk < max(interpolate_cumulative_list):
1164
+ num_latent_chunk = sum(interpolate_cumulative_list)
1165
+ print(f"Update num_latent_chunk to: {num_latent_chunk}")
1166
+
1167
+ if not is_enable_stage2:
1168
+ patch_size = self.transformer.config.patch_size
1169
+ image_seq_len = (
1170
+ num_latent_frames_per_chunk
1171
+ * (height // self.vae_scale_factor_spatial)
1172
+ * (width // self.vae_scale_factor_spatial)
1173
+ // (patch_size[0] * patch_size[1] * patch_size[2])
1174
+ )
1175
+ sigmas = np.linspace(0.999, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
1176
+ mu = calculate_shift(
1177
+ image_seq_len,
1178
+ self.scheduler.config.get("base_image_seq_len", 256),
1179
+ self.scheduler.config.get("max_image_seq_len", 4096),
1180
+ self.scheduler.config.get("base_shift", 0.5),
1181
+ self.scheduler.config.get("max_shift", 1.15),
1182
+ )
1183
+
1184
+ for k in range(num_latent_chunk):
1185
+ if use_interpolate_prompt:
1186
+ assert num_latent_chunk >= max(interpolate_cumulative_list)
1187
+
1188
+ current_interval_idx = 0
1189
+ for idx, cumulative_val in enumerate(interpolate_cumulative_list):
1190
+ if k < cumulative_val:
1191
+ current_interval_idx = idx
1192
+ break
1193
+
1194
+ if current_interval_idx == 0:
1195
+ prompt_embeds = all_prompt_embeds[0].unsqueeze(0)
1196
+ else:
1197
+ interval_start = interpolate_cumulative_list[current_interval_idx - 1]
1198
+ position_in_interval = k - interval_start
1199
+
1200
+ if position_in_interval < interpolation_steps:
1201
+ if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx:
1202
+ interpolate_embeds = self.interpolate_prompt_embeds(
1203
+ prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0),
1204
+ prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0),
1205
+ interpolation_steps=interpolation_steps,
1206
+ )
1207
+ interpolate_interval_idx = current_interval_idx
1208
+
1209
+ prompt_embeds = interpolate_embeds[position_in_interval]
1210
+ else:
1211
+ prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0)
1212
+ else:
1213
+ prompt_embeds = all_prompt_embeds
1214
+
1215
+ is_first_chunk = k == 0
1216
+ is_second_chunk = k == 1
1217
+ if keep_first_frame:
1218
+ latents_history_long, latents_history_mid, latents_history_1x = history_latents[
1219
+ :, :, -num_history_latent_frames:
1220
+ ].split(history_sizes, dim=2)
1221
+ if image_latents is None and is_first_chunk:
1222
+ latents_prefix = torch.zeros(
1223
+ (
1224
+ batch_size,
1225
+ num_channels_latents,
1226
+ 1,
1227
+ latents_history_1x.shape[-2],
1228
+ latents_history_1x.shape[-1],
1229
+ ),
1230
+ device=device,
1231
+ dtype=latents_history_1x.dtype,
1232
+ )
1233
+ else:
1234
+ latents_prefix = image_latents
1235
+ latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
1236
+ else:
1237
+ latents_history_long, latents_history_mid, latents_history_short = history_latents[
1238
+ :, :, -num_history_latent_frames:
1239
+ ].split(history_sizes, dim=2)
1240
+
1241
+ latents = self.prepare_latents(
1242
+ batch_size,
1243
+ num_channels_latents,
1244
+ height,
1245
+ width,
1246
+ window_num_frames,
1247
+ dtype=torch.float32,
1248
+ device=device,
1249
+ generator=generator,
1250
+ latents=None,
1251
+ )
1252
+
1253
+ if not is_enable_stage2:
1254
+ self.scheduler.set_timesteps(num_inference_steps, device=device, sigmas=sigmas, mu=mu)
1255
+ timesteps = self.scheduler.timesteps
1256
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1257
+ self._num_timesteps = len(timesteps)
1258
+ else:
1259
+ num_inference_steps = (
1260
+ sum(pyramid_num_inference_steps_list) * 2
1261
+ if is_amplify_first_chunk and self.config.is_distilled and is_first_chunk
1262
+ else sum(pyramid_num_inference_steps_list)
1263
+ )
1264
+
1265
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1266
+ if is_enable_stage2:
1267
+ latents = self.stage2_sample(
1268
+ latents=latents,
1269
+ pyramid_num_stages=pyramid_num_stages,
1270
+ pyramid_num_inference_steps_list=pyramid_num_inference_steps_list,
1271
+ prompt_embeds=prompt_embeds,
1272
+ negative_prompt_embeds=negative_prompt_embeds,
1273
+ guidance_scale=guidance_scale,
1274
+ indices_hidden_states=indices_hidden_states,
1275
+ indices_latents_history_short=indices_latents_history_short,
1276
+ indices_latents_history_mid=indices_latents_history_mid,
1277
+ indices_latents_history_long=indices_latents_history_long,
1278
+ latents_history_short=latents_history_short,
1279
+ latents_history_mid=latents_history_mid,
1280
+ latents_history_long=latents_history_long,
1281
+ attention_kwargs=attention_kwargs,
1282
+ device=device,
1283
+ transformer_dtype=transformer_dtype,
1284
+ # ------------ CFG Zero ------------
1285
+ use_zero_init=use_zero_init,
1286
+ zero_steps=zero_steps,
1287
+ # -------------- DMD --------------
1288
+ is_amplify_first_chunk=is_amplify_first_chunk and is_first_chunk,
1289
+ # ------------ Callback ------------
1290
+ callback_on_step_end=callback_on_step_end,
1291
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
1292
+ progress_bar=progress_bar,
1293
+ )
1294
+ else:
1295
+ latents = self.stage1_sample(
1296
+ latents=latents,
1297
+ prompt_embeds=prompt_embeds,
1298
+ negative_prompt_embeds=negative_prompt_embeds,
1299
+ timesteps=timesteps,
1300
+ guidance_scale=guidance_scale,
1301
+ indices_hidden_states=indices_hidden_states,
1302
+ indices_latents_history_short=indices_latents_history_short,
1303
+ indices_latents_history_mid=indices_latents_history_mid,
1304
+ indices_latents_history_long=indices_latents_history_long,
1305
+ latents_history_short=latents_history_short,
1306
+ latents_history_mid=latents_history_mid,
1307
+ latents_history_long=latents_history_long,
1308
+ attention_kwargs=attention_kwargs,
1309
+ device=device,
1310
+ transformer_dtype=transformer_dtype,
1311
+ generator=generator,
1312
+ num_warmup_steps=num_warmup_steps,
1313
+ # ------------ CFG Zero ------------
1314
+ use_zero_init=use_zero_init,
1315
+ zero_steps=zero_steps,
1316
+ # ------------ Callback ------------
1317
+ callback_on_step_end=callback_on_step_end,
1318
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
1319
+ progress_bar=progress_bar,
1320
+ )
1321
+
1322
+ if keep_first_frame and (
1323
+ (is_first_chunk and image_latents is None) or (is_skip_first_chunk and is_second_chunk)
1324
+ ):
1325
+ image_latents = latents[:, :, 0:1, :, :]
1326
+
1327
+ total_generated_latent_frames += latents.shape[2]
1328
+ history_latents = torch.cat([history_latents, latents], dim=2)
1329
+ real_history_latents = history_latents[:, :, -total_generated_latent_frames:]
1330
+ current_latents = (
1331
+ real_history_latents[:, :, -num_latent_frames_per_chunk:].to(vae_dtype) / latents_std
1332
+ + latents_mean
1333
+ )
1334
+ current_video = self.vae.decode(current_latents, return_dict=False)[0]
1335
+
1336
+ if history_video is None:
1337
+ history_video = current_video
1338
+ else:
1339
+ history_video = torch.cat([history_video, current_video], dim=2)
1340
+
1341
+ self._current_timestep = None
1342
+
1343
+ if output_type != "latent":
1344
+ generated_frames = history_video.size(2)
1345
+ generated_frames = (
1346
+ generated_frames - 1
1347
+ ) // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
1348
+ history_video = history_video[:, :, :generated_frames]
1349
+ video = self.video_processor.postprocess_video(history_video, output_type=output_type)
1350
+ else:
1351
+ video = real_history_latents
1352
+
1353
+ # Offload all models
1354
+ self.maybe_free_model_hooks()
1355
+
1356
+ if not return_dict:
1357
+ return (video,)
1358
+
1359
+ return HeliosPipelineOutput(frames=video)