Ouzhang commited on
Commit
3bdb1d6
·
verified ·
1 Parent(s): 8a5d8ba

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/playground/results/all_models_merged.json +31 -0
  2. Helios-main/eval/playground/results/toy-video/aesthetic_results.json +17 -0
  3. Helios-main/eval/playground/results/toy-video/drifting_aesthetic_results.json +22 -0
  4. Helios-main/eval/playground/results/toy-video/drifting_motion_smoothness_results.json +22 -0
  5. Helios-main/eval/playground/results/toy-video/drifting_naturalness_results.json +27 -0
  6. Helios-main/eval/playground/results/toy-video/drifting_semantic_results.json +24 -0
  7. Helios-main/eval/playground/results/toy-video/merged_results.json +74 -0
  8. Helios-main/eval/playground/results/toy-video/motion_amplitude_results.json +17 -0
  9. Helios-main/eval/playground/results/toy-video/motion_smoothness_results.json +17 -0
  10. Helios-main/eval/playground/results/toy-video/naturalness_results.json +21 -0
  11. Helios-main/eval/playground/results/toy-video/semantic_results.json +19 -0
  12. Helios-main/eval/utils/third_party/amt/benchmarks/xiph.py +117 -0
  13. Helios-main/eval/utils/third_party/amt/cfgs/AMT-G.yaml +62 -0
  14. Helios-main/eval/utils/third_party/amt/cfgs/AMT-L.yaml +62 -0
  15. Helios-main/eval/utils/third_party/amt/cfgs/AMT-S_gopro.yaml +56 -0
  16. Helios-main/eval/utils/third_party/amt/cfgs/IFRNet.yaml +67 -0
  17. Helios-main/eval/utils/third_party/amt/flow_generation/__init__.py +0 -0
  18. Helios-main/eval/utils/third_party/amt/flow_generation/gen_flow.py +76 -0
  19. Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/.__init__.py.baiduyun.uploading.cfg +0 -0
  20. Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/README.md +45 -0
  21. Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/__init__.py +0 -0
  22. Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md +1 -0
  23. Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py +446 -0
  24. Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/run.py +602 -0
  25. Helios-main/eval/utils/third_party/amt/networks/blocks/__init__.py +0 -0
  26. Helios-main/eval/utils/third_party/amt/networks/blocks/feat_enc.py +335 -0
  27. Helios-main/eval/utils/third_party/amt/networks/blocks/ifrnet.py +115 -0
  28. Helios-main/eval/utils/third_party/amt/networks/blocks/multi_flow.py +65 -0
  29. Helios-main/eval/utils/third_party/amt/networks/blocks/raft.py +213 -0
  30. Helios-main/eval/utils/third_party/amt/scripts/benchmark_arbitrary.sh +5 -0
  31. Helios-main/eval/utils/third_party/amt/scripts/benchmark_fixed.sh +7 -0
  32. Helios-main/helios/modules/helios_kernels/__init__.py +5 -0
  33. Helios-main/helios/modules/helios_kernels/attention_dispatch.py +167 -0
  34. Helios-main/helios/modules/helios_kernels/tiled_linear.py +399 -0
  35. Helios-main/helios/modules/helios_kernels/triton_norm.py +413 -0
  36. Helios-main/helios/modules/helios_kernels/utils.py +70 -0
  37. Helios-main/scripts/accelerate_configs/multi_node_example_zero2.yaml +14 -0
  38. Helios-main/scripts/accelerate_configs/multi_node_example_zero3.yaml +14 -0
  39. Helios-main/scripts/accelerate_configs/scheduler_config.json +28 -0
  40. Helios-main/scripts/accelerate_configs/zero2.json +25 -0
  41. Helios-main/scripts/accelerate_configs/zero3.json +30 -0
  42. Helios-main/scripts/training/train_ddp.sh +92 -0
  43. Helios-main/scripts/training/train_deepspeed.sh +92 -0
  44. LongLive-main/configs/default_config.yaml +21 -0
  45. LongLive-main/configs/longlive_inference.yaml +36 -0
  46. LongLive-main/configs/longlive_inference_infinity.yaml +36 -0
  47. LongLive-main/configs/longlive_interactive_inference.yaml +38 -0
  48. LongLive-main/configs/longlive_train_init.yaml +70 -0
  49. LongLive-main/configs/longlive_train_long.yaml +104 -0
  50. LongLive-main/docs/FLASH_ATTENTION_3_AND_HOPPER_SUPPORT.md +103 -0
Helios-main/eval/playground/results/all_models_merged.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "num_models": 1,
3
+ "score_type": "rating",
4
+ "metrics": [
5
+ "aesthetic",
6
+ "drifting_aesthetic",
7
+ "drifting_motion_smoothness",
8
+ "drifting_naturalness",
9
+ "drifting_semantic",
10
+ "motion_amplitude",
11
+ "motion_smoothness",
12
+ "naturalness",
13
+ "semantic",
14
+ "total_weighted_rating"
15
+ ],
16
+ "models": {
17
+ "toy-video": {
18
+ "aesthetic": 9,
19
+ "motion_amplitude": 3,
20
+ "motion_smoothness": 10,
21
+ "naturalness": 7,
22
+ "semantic": 8,
23
+ "drifting_aesthetic": 8,
24
+ "drifting_motion_smoothness": 10,
25
+ "drifting_naturalness": 10,
26
+ "drifting_semantic": 10,
27
+ "total_weighted_rating": 8.247
28
+ }
29
+ },
30
+ "rating_scale": 10
31
+ }
Helios-main/eval/playground/results/toy-video/aesthetic_results.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "aesthetic",
3
+ "average_score": 0.6564263701438904,
4
+ "num_videos": 2,
5
+ "per_video_results": [
6
+ {
7
+ "id": 2,
8
+ "video_name": "2_240_ori81.mp4",
9
+ "aesthetic_score": 0.6802743077278137
10
+ },
11
+ {
12
+ "id": 239,
13
+ "video_name": "239_120_ori129.mp4",
14
+ "aesthetic_score": 0.632578432559967
15
+ }
16
+ ]
17
+ }
Helios-main/eval/playground/results/toy-video/drifting_aesthetic_results.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "drifting_aesthetic",
3
+ "description": "Start-end contrast of aesthetic (first/last 15% frames)",
4
+ "average_drift_score": 0.027865678071975708,
5
+ "num_videos": 2,
6
+ "per_video_results": [
7
+ {
8
+ "id": 2,
9
+ "video_name": "2_240_ori81.mp4",
10
+ "drift_aesthetic_score": 0.002410709857940674,
11
+ "start_aesthetic_score": 0.6802361011505127,
12
+ "end_aesthetic_score": 0.677825391292572
13
+ },
14
+ {
15
+ "id": 239,
16
+ "video_name": "239_120_ori129.mp4",
17
+ "drift_aesthetic_score": 0.05332064628601074,
18
+ "start_aesthetic_score": 0.6535003185272217,
19
+ "end_aesthetic_score": 0.6001796722412109
20
+ }
21
+ ]
22
+ }
Helios-main/eval/playground/results/toy-video/drifting_motion_smoothness_results.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "drifting_motion_smoothness",
3
+ "description": "Start-end contrast of motion smoothness (first/last 15% frames)",
4
+ "average_drift_score": 0.0009624073235373065,
5
+ "num_videos": 2,
6
+ "per_video_results": [
7
+ {
8
+ "id": 2,
9
+ "video_name": "2_240_ori81.mp4",
10
+ "drift_motion_smoothness_score": 0.0016874511579993978,
11
+ "start_motion_smoothness_score": 0.9880413336530265,
12
+ "end_motion_smoothness_score": 0.9897287848110259
13
+ },
14
+ {
15
+ "id": 239,
16
+ "video_name": "239_120_ori129.mp4",
17
+ "drift_motion_smoothness_score": 0.0002373634890752152,
18
+ "start_motion_smoothness_score": 0.9948747067013198,
19
+ "end_motion_smoothness_score": 0.995112070190395
20
+ }
21
+ ]
22
+ }
Helios-main/eval/playground/results/toy-video/drifting_naturalness_results.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "drifting_naturalness",
3
+ "description": "Start-end contrast of naturalness (first/last 15% frames)",
4
+ "average_drift_score": 0.0,
5
+ "num_videos": 2,
6
+ "model_name": "gpt-5.2-2025-12-11",
7
+ "per_video_results": [
8
+ {
9
+ "id": 2,
10
+ "video_name": "2_240_ori81.mp4",
11
+ "drift_naturalness_score": 0.0,
12
+ "start_naturalness_score": 0.0,
13
+ "end_naturalness_score": 0.0,
14
+ "start_raw_score": "1",
15
+ "end_raw_score": "1"
16
+ },
17
+ {
18
+ "id": 239,
19
+ "video_name": "239_120_ori129.mp4",
20
+ "drift_naturalness_score": 0.0,
21
+ "start_naturalness_score": 0.75,
22
+ "end_naturalness_score": 0.75,
23
+ "start_raw_score": "4",
24
+ "end_raw_score": "4"
25
+ }
26
+ ]
27
+ }
Helios-main/eval/playground/results/toy-video/drifting_semantic_results.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "drifting_semantic",
3
+ "description": "Start-end contrast of semantic consistency (first/last 15% frames)",
4
+ "average_drift_score": 0.006637156009674072,
5
+ "num_videos": 2,
6
+ "per_video_results": [
7
+ {
8
+ "id": 2,
9
+ "video_name": "2_240_ori81.mp4",
10
+ "prompt": "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.",
11
+ "drift_semantic_score": 0.0044051408767700195,
12
+ "start_semantic_score": 0.2939550578594208,
13
+ "end_semantic_score": 0.2983601987361908
14
+ },
15
+ {
16
+ "id": 239,
17
+ "video_name": "239_120_ori129.mp4",
18
+ "prompt": "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.",
19
+ "drift_semantic_score": 0.008869171142578125,
20
+ "start_semantic_score": 0.2703956365585327,
21
+ "end_semantic_score": 0.2615264654159546
22
+ }
23
+ ]
24
+ }
Helios-main/eval/playground/results/toy-video/merged_results.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "rating_scale": 10,
3
+ "summary": {
4
+ "non_drifting": {
5
+ "aesthetic": {
6
+ "name": "Aesthetic",
7
+ "raw_score": 0.6564263701438904,
8
+ "normalized_score": 0.6564263701438904,
9
+ "rating": 9,
10
+ "num_videos": 2
11
+ },
12
+ "motion_amplitude": {
13
+ "name": "Motion Amplitude",
14
+ "raw_score": 0.12899818271398544,
15
+ "normalized_score": 0.12899818271398544,
16
+ "rating": 3,
17
+ "num_videos": 2
18
+ },
19
+ "motion_smoothness": {
20
+ "name": "Motion Smoothness",
21
+ "raw_score": 0.9922347277689807,
22
+ "normalized_score": 0.9922347277689807,
23
+ "rating": 10,
24
+ "num_videos": 2
25
+ },
26
+ "naturalness": {
27
+ "name": "Naturalness",
28
+ "raw_score": 0.5,
29
+ "normalized_score": 0.5,
30
+ "rating": 7,
31
+ "num_videos": 2
32
+ },
33
+ "semantic": {
34
+ "name": "Semantic",
35
+ "raw_score": 0.2817579507827759,
36
+ "normalized_score": 0.2817579507827759,
37
+ "rating": 8,
38
+ "num_videos": 2
39
+ }
40
+ },
41
+ "drifting": {
42
+ "drifting_aesthetic": {
43
+ "name": "Drifting Aesthetic",
44
+ "raw_score": 0.027865678071975708,
45
+ "normalized_score": 0.027865678071975708,
46
+ "rating": 8,
47
+ "num_videos": 2
48
+ },
49
+ "drifting_motion_smoothness": {
50
+ "name": "Drifting Motion Smoothness",
51
+ "raw_score": 0.0009624073235373065,
52
+ "normalized_score": 0.0009624073235373065,
53
+ "rating": 10,
54
+ "num_videos": 2
55
+ },
56
+ "drifting_naturalness": {
57
+ "name": "Drifting Naturalness",
58
+ "raw_score": 0.0,
59
+ "normalized_score": 0.0,
60
+ "rating": 10,
61
+ "num_videos": 2
62
+ },
63
+ "drifting_semantic": {
64
+ "name": "Drifting Semantic",
65
+ "raw_score": 0.006637156009674072,
66
+ "normalized_score": 0.006637156009674072,
67
+ "rating": 10,
68
+ "num_videos": 2
69
+ }
70
+ },
71
+ "total_weighted_rating": 8.247
72
+ },
73
+ "per_video": {}
74
+ }
Helios-main/eval/playground/results/toy-video/motion_amplitude_results.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "motion_fb",
3
+ "average_score": 0.12899818271398544,
4
+ "num_videos": 2,
5
+ "per_video_results": [
6
+ {
7
+ "id": 2,
8
+ "video_name": "2_240_ori81.mp4",
9
+ "motion_fb": 0.19912056624889374
10
+ },
11
+ {
12
+ "id": 239,
13
+ "video_name": "239_120_ori129.mp4",
14
+ "motion_fb": 0.05887579917907715
15
+ }
16
+ ]
17
+ }
Helios-main/eval/playground/results/toy-video/motion_smoothness_results.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "motion_smoothness",
3
+ "average_score": 0.9922347277689807,
4
+ "num_videos": 2,
5
+ "per_video_results": [
6
+ {
7
+ "id": 2,
8
+ "video_name": "2_240_ori81.mp4",
9
+ "motion_smoothness_score": 0.9896801291593404
10
+ },
11
+ {
12
+ "id": 239,
13
+ "video_name": "239_120_ori129.mp4",
14
+ "motion_smoothness_score": 0.9947893263786209
15
+ }
16
+ ]
17
+ }
Helios-main/eval/playground/results/toy-video/naturalness_results.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "naturalness",
3
+ "average_score": 0.5,
4
+ "num_videos": 2,
5
+ "model_name": "gpt-5.2-2025-12-11",
6
+ "num_frames_per_video": 16,
7
+ "per_video_results": [
8
+ {
9
+ "id": 2,
10
+ "video_name": "2_240_ori81.mp4",
11
+ "naturalness_score": 0.25,
12
+ "raw_score": "2"
13
+ },
14
+ {
15
+ "id": 239,
16
+ "video_name": "239_120_ori129.mp4",
17
+ "naturalness_score": 0.75,
18
+ "raw_score": "4"
19
+ }
20
+ ]
21
+ }
Helios-main/eval/playground/results/toy-video/semantic_results.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metric": "semantic",
3
+ "average_score": 0.2817579507827759,
4
+ "num_videos": 2,
5
+ "per_video_results": [
6
+ {
7
+ "id": 2,
8
+ "video_name": "2_240_ori81.mp4",
9
+ "prompt": "A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity.",
10
+ "semantic_score": 0.29471662640571594
11
+ },
12
+ {
13
+ "id": 239,
14
+ "video_name": "239_120_ori129.mp4",
15
+ "prompt": "An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man.",
16
+ "semantic_score": 0.2687992751598358
17
+ }
18
+ ]
19
+ }
Helios-main/eval/utils/third_party/amt/benchmarks/xiph.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import os
4
+ import os.path as osp
5
+ import sys
6
+
7
+ import cv2
8
+ import numpy as np
9
+ import torch
10
+ import tqdm
11
+ from omegaconf import OmegaConf
12
+
13
+
14
+ sys.path.append(".")
15
+ from metrics.psnr_ssim import calculate_psnr, calculate_ssim
16
+
17
+ from utils.build_utils import build_from_cfg
18
+ from utils.utils import InputPadder, img2tensor, read
19
+
20
+
21
+ parser = argparse.ArgumentParser(
22
+ prog="AMT",
23
+ description="Xiph evaluation",
24
+ )
25
+ parser.add_argument("-c", "--config", default="cfgs/AMT-S.yaml")
26
+ parser.add_argument("-p", "--ckpt", default="pretrained/amt-s.pth")
27
+ parser.add_argument("-r", "--root", default="data/xiph")
28
+ args = parser.parse_args()
29
+
30
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
31
+ cfg_path = args.config
32
+ ckpt_path = args.ckpt
33
+ root = args.root
34
+
35
+ network_cfg = OmegaConf.load(cfg_path).network
36
+ network_name = network_cfg.name
37
+ model = build_from_cfg(network_cfg)
38
+ ckpt = torch.load(ckpt_path)
39
+ model.load_state_dict(ckpt["state_dict"], False)
40
+ model = model.to(device)
41
+ model.eval()
42
+
43
+ ############################################# Prepare Dataset #############################################
44
+ download_links = [
45
+ "https://media.xiph.org/video/derf/ElFuente/Netflix_BoxingPractice_4096x2160_60fps_10bit_420.y4m",
46
+ "https://media.xiph.org/video/derf/ElFuente/Netflix_Crosswalk_4096x2160_60fps_10bit_420.y4m",
47
+ "https://media.xiph.org/video/derf/Chimera/Netflix_DrivingPOV_4096x2160_60fps_10bit_420.y4m",
48
+ "https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket_4096x2160_60fps_10bit_420.y4m",
49
+ "https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket2_4096x2160_60fps_10bit_420.y4m",
50
+ "https://media.xiph.org/video/derf/ElFuente/Netflix_RitualDance_4096x2160_60fps_10bit_420.y4m",
51
+ "https://media.xiph.org/video/derf/ElFuente/Netflix_SquareAndTimelapse_4096x2160_60fps_10bit_420.y4m",
52
+ "https://media.xiph.org/video/derf/ElFuente/Netflix_Tango_4096x2160_60fps_10bit_420.y4m",
53
+ ]
54
+ file_list = [
55
+ "BoxingPractice",
56
+ "Crosswalk",
57
+ "DrivingPOV",
58
+ "FoodMarket",
59
+ "FoodMarket2",
60
+ "RitualDance",
61
+ "SquareAndTimelapse",
62
+ "Tango",
63
+ ]
64
+
65
+ for file_name, link in zip(file_list, download_links):
66
+ data_dir = osp.join(root, file_name)
67
+ if osp.exists(data_dir) is False:
68
+ os.makedirs(data_dir)
69
+ if len(glob.glob(f"{data_dir}/*.png")) < 100:
70
+ os.system(f"ffmpeg -i {link} -pix_fmt rgb24 -vframes 100 {data_dir}/%03d.png")
71
+ ############################################### Prepare End ###############################################
72
+
73
+
74
+ divisor = 32
75
+ scale_factor = 0.5
76
+ for category in ["resized-2k", "cropped-4k"]:
77
+ psnr_list = []
78
+ ssim_list = []
79
+ pbar = tqdm.tqdm(file_list, total=len(file_list))
80
+ for flie_name in pbar:
81
+ dir_name = osp.join(root, flie_name)
82
+ for intFrame in range(2, 99, 2):
83
+ img0 = read(f"{dir_name}/{intFrame - 1:03d}.png")
84
+ img1 = read(f"{dir_name}/{intFrame + 1:03d}.png")
85
+ imgt = read(f"{dir_name}/{intFrame:03d}.png")
86
+
87
+ if category == "resized-2k":
88
+ img0 = cv2.resize(src=img0, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
89
+ img1 = cv2.resize(src=img1, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
90
+ imgt = cv2.resize(src=imgt, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
91
+
92
+ elif category == "cropped-4k":
93
+ img0 = img0[540:-540, 1024:-1024, :]
94
+ img1 = img1[540:-540, 1024:-1024, :]
95
+ imgt = imgt[540:-540, 1024:-1024, :]
96
+ img0 = img2tensor(img0).to(device)
97
+ imgt = img2tensor(imgt).to(device)
98
+ img1 = img2tensor(img1).to(device)
99
+ embt = torch.tensor(1 / 2).float().view(1, 1, 1, 1).to(device)
100
+
101
+ padder = InputPadder(img0.shape, divisor)
102
+ img0, img1 = padder.pad(img0, img1)
103
+
104
+ with torch.no_grad():
105
+ imgt_pred = model(img0, img1, embt, scale_factor=scale_factor, eval=True)["imgt_pred"]
106
+ imgt_pred = padder.unpad(imgt_pred)
107
+
108
+ psnr = calculate_psnr(imgt_pred, imgt)
109
+ ssim = calculate_ssim(imgt_pred, imgt)
110
+
111
+ avg_psnr = np.mean(psnr_list)
112
+ avg_ssim = np.mean(ssim_list)
113
+ psnr_list.append(psnr)
114
+ ssim_list.append(ssim)
115
+ desc_str = f"[{network_name}/Xiph] [{category}/{flie_name}] psnr: {avg_psnr:.02f}, ssim: {avg_ssim:.04f}"
116
+
117
+ pbar.set_description_str(desc_str)
Helios-main/eval/utils/third_party/amt/cfgs/AMT-G.yaml ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ exp_name: floloss1e-2_300epoch_bs24_lr1p5e-4
2
+ seed: 2023
3
+ epochs: 300
4
+ distributed: true
5
+ lr: 1.5e-4
6
+ lr_min: 2e-5
7
+ weight_decay: 0.0
8
+ resume_state: null
9
+ save_dir: work_dir
10
+ eval_interval: 1
11
+
12
+ network:
13
+ name: networks.AMT-G.Model
14
+ params:
15
+ corr_radius: 3
16
+ corr_lvls: 4
17
+ num_flows: 5
18
+ data:
19
+ train:
20
+ name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset
21
+ params:
22
+ dataset_dir: data/vimeo_triplet
23
+ val:
24
+ name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset
25
+ params:
26
+ dataset_dir: data/vimeo_triplet
27
+ train_loader:
28
+ batch_size: 24
29
+ num_workers: 12
30
+ val_loader:
31
+ batch_size: 24
32
+ num_workers: 3
33
+
34
+ logger:
35
+ use_wandb: true
36
+ resume_id: null
37
+
38
+ losses:
39
+ - {
40
+ name: losses.loss.CharbonnierLoss,
41
+ nickname: l_rec,
42
+ params: {
43
+ loss_weight: 1.0,
44
+ keys: [imgt_pred, imgt]
45
+ }
46
+ }
47
+ - {
48
+ name: losses.loss.TernaryLoss,
49
+ nickname: l_ter,
50
+ params: {
51
+ loss_weight: 1.0,
52
+ keys: [imgt_pred, imgt]
53
+ }
54
+ }
55
+ - {
56
+ name: losses.loss.MultipleFlowLoss,
57
+ nickname: l_flo,
58
+ params: {
59
+ loss_weight: 0.005,
60
+ keys: [flow0_pred, flow1_pred, flow]
61
+ }
62
+ }
Helios-main/eval/utils/third_party/amt/cfgs/AMT-L.yaml ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ exp_name: floloss1e-2_300epoch_bs24_lr2e-4
2
+ seed: 2023
3
+ epochs: 300
4
+ distributed: true
5
+ lr: 2e-4
6
+ lr_min: 2e-5
7
+ weight_decay: 0.0
8
+ resume_state: null
9
+ save_dir: work_dir
10
+ eval_interval: 1
11
+
12
+ network:
13
+ name: networks.AMT-L.Model
14
+ params:
15
+ corr_radius: 3
16
+ corr_lvls: 4
17
+ num_flows: 5
18
+ data:
19
+ train:
20
+ name: datasets.vimeo_datasets.Vimeo90K_Train_Dataset
21
+ params:
22
+ dataset_dir: data/vimeo_triplet
23
+ val:
24
+ name: datasets.vimeo_datasets.Vimeo90K_Test_Dataset
25
+ params:
26
+ dataset_dir: data/vimeo_triplet
27
+ train_loader:
28
+ batch_size: 24
29
+ num_workers: 12
30
+ val_loader:
31
+ batch_size: 24
32
+ num_workers: 3
33
+
34
+ logger:
35
+ use_wandb: true
36
+ resume_id: null
37
+
38
+ losses:
39
+ - {
40
+ name: losses.loss.CharbonnierLoss,
41
+ nickname: l_rec,
42
+ params: {
43
+ loss_weight: 1.0,
44
+ keys: [imgt_pred, imgt]
45
+ }
46
+ }
47
+ - {
48
+ name: losses.loss.TernaryLoss,
49
+ nickname: l_ter,
50
+ params: {
51
+ loss_weight: 1.0,
52
+ keys: [imgt_pred, imgt]
53
+ }
54
+ }
55
+ - {
56
+ name: losses.loss.MultipleFlowLoss,
57
+ nickname: l_flo,
58
+ params: {
59
+ loss_weight: 0.002,
60
+ keys: [flow0_pred, flow1_pred, flow]
61
+ }
62
+ }
Helios-main/eval/utils/third_party/amt/cfgs/AMT-S_gopro.yaml ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ exp_name: wofloloss_400epoch_bs24_lr2e-4
2
+ seed: 2023
3
+ epochs: 400
4
+ distributed: true
5
+ lr: 2e-4
6
+ lr_min: 2e-5
7
+ weight_decay: 0.0
8
+ resume_state: null
9
+ save_dir: work_dir
10
+ eval_interval: 1
11
+
12
+ network:
13
+ name: networks.AMT-S.Model
14
+ params:
15
+ corr_radius: 3
16
+ corr_lvls: 4
17
+ num_flows: 3
18
+
19
+ data:
20
+ train:
21
+ name: datasets.gopro_datasets.GoPro_Train_Dataset
22
+ params:
23
+ dataset_dir: data/GOPRO
24
+ val:
25
+ name: datasets.gopro_datasets.GoPro_Test_Dataset
26
+ params:
27
+ dataset_dir: data/GOPRO
28
+ train_loader:
29
+ batch_size: 24
30
+ num_workers: 12
31
+ val_loader:
32
+ batch_size: 24
33
+ num_workers: 3
34
+
35
+ logger:
36
+ use_wandb: false
37
+ resume_id: null
38
+
39
+ losses:
40
+ - {
41
+ name: losses.loss.CharbonnierLoss,
42
+ nickname: l_rec,
43
+ params: {
44
+ loss_weight: 1.0,
45
+ keys: [imgt_pred, imgt]
46
+ }
47
+ }
48
+ - {
49
+ name: losses.loss.TernaryLoss,
50
+ nickname: l_ter,
51
+ params: {
52
+ loss_weight: 1.0,
53
+ keys: [imgt_pred, imgt]
54
+ }
55
+ }
56
+
Helios-main/eval/utils/third_party/amt/cfgs/IFRNet.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ exp_name: floloss1e-2_geoloss1e-2_300epoch_bs24_lr1e-4
2
+ seed: 2023
3
+ epochs: 300
4
+ distributed: true
5
+ lr: 1e-4
6
+ lr_min: 1e-5
7
+ weight_decay: 1e-6
8
+ resume_state: null
9
+ save_dir: work_dir
10
+ eval_interval: 1
11
+
12
+ network:
13
+ name: networks.IFRNet.Model
14
+
15
+ data:
16
+ train:
17
+ name: datasets.datasets.Vimeo90K_Train_Dataset
18
+ params:
19
+ dataset_dir: data/vimeo_triplet
20
+ val:
21
+ name: datasets.datasets.Vimeo90K_Test_Dataset
22
+ params:
23
+ dataset_dir: data/vimeo_triplet
24
+ train_loader:
25
+ batch_size: 24
26
+ num_workers: 12
27
+ val_loader:
28
+ batch_size: 24
29
+ num_workers: 3
30
+
31
+ logger:
32
+ use_wandb: true
33
+ resume_id: null
34
+
35
+ losses:
36
+ - {
37
+ name: losses.loss.CharbonnierLoss,
38
+ nickname: l_rec,
39
+ params: {
40
+ loss_weight: 1.0,
41
+ keys: [imgt_pred, imgt]
42
+ }
43
+ }
44
+ - {
45
+ name: losses.loss.TernaryLoss,
46
+ nickname: l_ter,
47
+ params: {
48
+ loss_weight: 1.0,
49
+ keys: [imgt_pred, imgt]
50
+ }
51
+ }
52
+ - {
53
+ name: losses.loss.IFRFlowLoss,
54
+ nickname: l_flo,
55
+ params: {
56
+ loss_weight: 0.01,
57
+ keys: [flow0_pred, flow1_pred, flow]
58
+ }
59
+ }
60
+ - {
61
+ name: losses.loss.GeometryLoss,
62
+ nickname: l_geo,
63
+ params: {
64
+ loss_weight: 0.01,
65
+ keys: [ft_pred, ft_gt]
66
+ }
67
+ }
Helios-main/eval/utils/third_party/amt/flow_generation/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/flow_generation/gen_flow.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import os.path as osp
4
+ import sys
5
+
6
+ import torch
7
+
8
+
9
+ sys.path.append(".")
10
+ from flow_generation.liteflownet.run import estimate
11
+
12
+ from utils.utils import read, write
13
+
14
+
15
+ parser = argparse.ArgumentParser(
16
+ prog="AMT",
17
+ description="Flow generation",
18
+ )
19
+ parser.add_argument("-r", "--root", default="data/vimeo_triplet")
20
+ args = parser.parse_args()
21
+
22
+ vimeo90k_dir = args.root
23
+ vimeo90k_sequences_dir = osp.join(vimeo90k_dir, "sequences")
24
+ vimeo90k_flow_dir = osp.join(vimeo90k_dir, "flow")
25
+
26
+
27
+ def pred_flow(img1, img2):
28
+ img1 = torch.from_numpy(img1).float().permute(2, 0, 1) / 255.0
29
+ img2 = torch.from_numpy(img2).float().permute(2, 0, 1) / 255.0
30
+
31
+ flow = estimate(img1, img2)
32
+
33
+ flow = flow.permute(1, 2, 0).cpu().numpy()
34
+ return flow
35
+
36
+
37
+ print("Built Flow Path")
38
+ if not osp.exists(vimeo90k_flow_dir):
39
+ os.makedirs(vimeo90k_flow_dir)
40
+
41
+ for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)):
42
+ vimeo90k_sequences_path_dir = osp.join(vimeo90k_sequences_dir, sequences_path)
43
+ vimeo90k_flow_path_dir = osp.join(vimeo90k_flow_dir, sequences_path)
44
+ if not osp.exists(vimeo90k_flow_path_dir):
45
+ os.mkdir(vimeo90k_flow_path_dir)
46
+
47
+ for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)):
48
+ vimeo90k_flow_id_dir = osp.join(vimeo90k_flow_path_dir, sequences_id)
49
+ if not osp.exists(vimeo90k_flow_id_dir):
50
+ os.mkdir(vimeo90k_flow_id_dir)
51
+
52
+ for sequences_path in sorted(os.listdir(vimeo90k_sequences_dir)):
53
+ vimeo90k_sequences_path_dir = os.path.join(vimeo90k_sequences_dir, sequences_path)
54
+ vimeo90k_flow_path_dir = os.path.join(vimeo90k_flow_dir, sequences_path)
55
+
56
+ for sequences_id in sorted(os.listdir(vimeo90k_sequences_path_dir)):
57
+ vimeo90k_sequences_id_dir = os.path.join(vimeo90k_sequences_path_dir, sequences_id)
58
+ vimeo90k_flow_id_dir = os.path.join(vimeo90k_flow_path_dir, sequences_id)
59
+
60
+ img0_path = vimeo90k_sequences_id_dir + "/im1.png"
61
+ imgt_path = vimeo90k_sequences_id_dir + "/im2.png"
62
+ img1_path = vimeo90k_sequences_id_dir + "/im3.png"
63
+ flow_t0_path = vimeo90k_flow_id_dir + "/flow_t0.flo"
64
+ flow_t1_path = vimeo90k_flow_id_dir + "/flow_t1.flo"
65
+
66
+ img0 = read(img0_path)
67
+ imgt = read(imgt_path)
68
+ img1 = read(img1_path)
69
+
70
+ flow_t0 = pred_flow(imgt, img0)
71
+ flow_t1 = pred_flow(imgt, img1)
72
+
73
+ write(flow_t0_path, flow_t0)
74
+ write(flow_t1_path, flow_t1)
75
+
76
+ print("Written Sequences {}".format(sequences_path))
Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/.__init__.py.baiduyun.uploading.cfg ADDED
Binary file (766 Bytes). View file
 
Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pytorch-liteflownet
2
+ This is a personal reimplementation of LiteFlowNet [1] using PyTorch. Should you be making use of this work, please cite the paper accordingly. Also, make sure to adhere to the <a href="https://github.com/twhui/LiteFlowNet#license-and-citation">licensing terms</a> of the authors. Should you be making use of this particular implementation, please acknowledge it appropriately [2].
3
+
4
+ <a href="https://arxiv.org/abs/1805.07036" rel="Paper"><img src="http://www.arxiv-sanity.com/static/thumbs/1805.07036v1.pdf.jpg" alt="Paper" width="100%"></a>
5
+
6
+ For the original Caffe version of this work, please see: https://github.com/twhui/LiteFlowNet
7
+ <br />
8
+ Other optical flow implementations from me: [pytorch-pwc](https://github.com/sniklaus/pytorch-pwc), [pytorch-unflow](https://github.com/sniklaus/pytorch-unflow), [pytorch-spynet](https://github.com/sniklaus/pytorch-spynet)
9
+
10
+ ## setup
11
+ The correlation layer is implemented in CUDA using CuPy, which is why CuPy is a required dependency. It can be installed using `pip install cupy` or alternatively using one of the provided [binary packages](https://docs.cupy.dev/en/stable/install.html#installing-cupy) as outlined in the CuPy repository. If you would like to use Docker, you can take a look at [this](https://github.com/sniklaus/pytorch-liteflownet/pull/43) pull request to get started.
12
+
13
+ ## usage
14
+ To run it on your own pair of images, use the following command. You can choose between three models, please make sure to see their paper / the code for more details.
15
+
16
+ ```
17
+ python run.py --model default --one ./images/one.png --two ./images/two.png --out ./out.flo
18
+ ```
19
+
20
+ I am afraid that I cannot guarantee that this reimplementation is correct. However, it produced results pretty much identical to the implementation of the original authors in the examples that I tried. There are some numerical deviations that stem from differences in the `DownsampleLayer` of Caffe and the `torch.nn.functional.interpolate` function of PyTorch. Please feel free to contribute to this repository by submitting issues and pull requests.
21
+
22
+ ## comparison
23
+ <p align="center"><img src="comparison/comparison.gif?raw=true" alt="Comparison"></p>
24
+
25
+ ## license
26
+ As stated in the <a href="https://github.com/twhui/LiteFlowNet#license-and-citation">licensing terms</a> of the authors of the paper, their material is provided for research purposes only. Please make sure to further consult their licensing terms.
27
+
28
+ ## references
29
+ ```
30
+ [1] @inproceedings{Hui_CVPR_2018,
31
+ author = {Tak-Wai Hui and Xiaoou Tang and Chen Change Loy},
32
+ title = {{LiteFlowNet}: A Lightweight Convolutional Neural Network for Optical Flow Estimation},
33
+ booktitle = {IEEE Conference on Computer Vision and Pattern Recognition},
34
+ year = {2018}
35
+ }
36
+ ```
37
+
38
+ ```
39
+ [2] @misc{pytorch-liteflownet,
40
+ author = {Simon Niklaus},
41
+ title = {A Reimplementation of {LiteFlowNet} Using {PyTorch}},
42
+ year = {2019},
43
+ howpublished = {\url{https://github.com/sniklaus/pytorch-liteflownet}}
44
+ }
45
+ ```
Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ This is an adaptation of the FlowNet2 implementation in order to compute cost volumes. Should you be making use of this work, please make sure to adhere to the licensing terms of the original authors. Should you be making use or modify this particular implementation, please acknowledge it appropriately.
Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/correlation/correlation.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import math
4
+ import re
5
+
6
+ import cupy
7
+ import torch
8
+
9
+
10
+ kernel_Correlation_rearrange = """
11
+ extern "C" __global__ void kernel_Correlation_rearrange(
12
+ const int n,
13
+ const float* input,
14
+ float* output
15
+ ) {
16
+ int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x;
17
+ if (intIndex >= n) {
18
+ return;
19
+ }
20
+ int intSample = blockIdx.z;
21
+ int intChannel = blockIdx.y;
22
+ float fltValue = input[(((intSample * SIZE_1(input)) + intChannel) * SIZE_2(input) * SIZE_3(input)) + intIndex];
23
+ __syncthreads();
24
+ int intPaddedY = (intIndex / SIZE_3(input)) + 3*{{intStride}};
25
+ int intPaddedX = (intIndex % SIZE_3(input)) + 3*{{intStride}};
26
+ int intRearrange = ((SIZE_3(input) + 6*{{intStride}}) * intPaddedY) + intPaddedX;
27
+ output[(((intSample * SIZE_1(output) * SIZE_2(output)) + intRearrange) * SIZE_1(input)) + intChannel] = fltValue;
28
+ }
29
+ """
30
+
31
+ kernel_Correlation_updateOutput = """
32
+ extern "C" __global__ void kernel_Correlation_updateOutput(
33
+ const int n,
34
+ const float* rbot0,
35
+ const float* rbot1,
36
+ float* top
37
+ ) {
38
+ extern __shared__ char patch_data_char[];
39
+ float *patch_data = (float *)patch_data_char;
40
+ // First (upper left) position of kernel upper-left corner in current center position of neighborhood in image 1
41
+ int x1 = (blockIdx.x + 3) * {{intStride}};
42
+ int y1 = (blockIdx.y + 3) * {{intStride}};
43
+ int item = blockIdx.z;
44
+ int ch_off = threadIdx.x;
45
+ // Load 3D patch into shared shared memory
46
+ for (int j = 0; j < 1; j++) { // HEIGHT
47
+ for (int i = 0; i < 1; i++) { // WIDTH
48
+ int ji_off = (j + i) * SIZE_3(rbot0);
49
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
50
+ int idx1 = ((item * SIZE_1(rbot0) + y1+j) * SIZE_2(rbot0) + x1+i) * SIZE_3(rbot0) + ch;
51
+ int idxPatchData = ji_off + ch;
52
+ patch_data[idxPatchData] = rbot0[idx1];
53
+ }
54
+ }
55
+ }
56
+ __syncthreads();
57
+ __shared__ float sum[32];
58
+ // Compute correlation
59
+ for (int top_channel = 0; top_channel < SIZE_1(top); top_channel++) {
60
+ sum[ch_off] = 0;
61
+ int s2o = (top_channel % 7 - 3) * {{intStride}};
62
+ int s2p = (top_channel / 7 - 3) * {{intStride}};
63
+ for (int j = 0; j < 1; j++) { // HEIGHT
64
+ for (int i = 0; i < 1; i++) { // WIDTH
65
+ int ji_off = (j + i) * SIZE_3(rbot0);
66
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
67
+ int x2 = x1 + s2o;
68
+ int y2 = y1 + s2p;
69
+ int idxPatchData = ji_off + ch;
70
+ int idx2 = ((item * SIZE_1(rbot0) + y2+j) * SIZE_2(rbot0) + x2+i) * SIZE_3(rbot0) + ch;
71
+ sum[ch_off] += patch_data[idxPatchData] * rbot1[idx2];
72
+ }
73
+ }
74
+ }
75
+ __syncthreads();
76
+ if (ch_off == 0) {
77
+ float total_sum = 0;
78
+ for (int idx = 0; idx < 32; idx++) {
79
+ total_sum += sum[idx];
80
+ }
81
+ const int sumelems = SIZE_3(rbot0);
82
+ const int index = ((top_channel*SIZE_2(top) + blockIdx.y)*SIZE_3(top))+blockIdx.x;
83
+ top[index + item*SIZE_1(top)*SIZE_2(top)*SIZE_3(top)] = total_sum / (float)sumelems;
84
+ }
85
+ }
86
+ }
87
+ """
88
+
89
+ kernel_Correlation_updateGradOne = """
90
+ #define ROUND_OFF 50000
91
+ extern "C" __global__ void kernel_Correlation_updateGradOne(
92
+ const int n,
93
+ const int intSample,
94
+ const float* rbot0,
95
+ const float* rbot1,
96
+ const float* gradOutput,
97
+ float* gradOne,
98
+ float* gradTwo
99
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
100
+ int n = intIndex % SIZE_1(gradOne); // channels
101
+ int l = (intIndex / SIZE_1(gradOne)) % SIZE_3(gradOne) + 3*{{intStride}}; // w-pos
102
+ int m = (intIndex / SIZE_1(gradOne) / SIZE_3(gradOne)) % SIZE_2(gradOne) + 3*{{intStride}}; // h-pos
103
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
104
+ // We use a large offset, for the inner part not to become negative.
105
+ const int round_off = ROUND_OFF;
106
+ const int round_off_s1 = {{intStride}} * round_off;
107
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
108
+ int xmin = (l - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}}
109
+ int ymin = (m - 3*{{intStride}} + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}}) / {{intStride}}
110
+ // Same here:
111
+ int xmax = (l - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}}) / {{intStride}}
112
+ int ymax = (m - 3*{{intStride}} + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}}) / {{intStride}}
113
+ float sum = 0;
114
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
115
+ xmin = max(0,xmin);
116
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
117
+ ymin = max(0,ymin);
118
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
119
+ for (int p = -3; p <= 3; p++) {
120
+ for (int o = -3; o <= 3; o++) {
121
+ // Get rbot1 data:
122
+ int s2o = {{intStride}} * o;
123
+ int s2p = {{intStride}} * p;
124
+ int idxbot1 = ((intSample * SIZE_1(rbot0) + (m+s2p)) * SIZE_2(rbot0) + (l+s2o)) * SIZE_3(rbot0) + n;
125
+ float bot1tmp = rbot1[idxbot1]; // rbot1[l+s2o,m+s2p,n]
126
+ // Index offset for gradOutput in following loops:
127
+ int op = (p+3) * 7 + (o+3); // index[o,p]
128
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
129
+ for (int y = ymin; y <= ymax; y++) {
130
+ for (int x = xmin; x <= xmax; x++) {
131
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
132
+ sum += gradOutput[idxgradOutput] * bot1tmp;
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+ const int sumelems = SIZE_1(gradOne);
139
+ const int bot0index = ((n * SIZE_2(gradOne)) + (m-3*{{intStride}})) * SIZE_3(gradOne) + (l-3*{{intStride}});
140
+ gradOne[bot0index + intSample*SIZE_1(gradOne)*SIZE_2(gradOne)*SIZE_3(gradOne)] = sum / (float)sumelems;
141
+ } }
142
+ """
143
+
144
+ kernel_Correlation_updateGradTwo = """
145
+ #define ROUND_OFF 50000
146
+ extern "C" __global__ void kernel_Correlation_updateGradTwo(
147
+ const int n,
148
+ const int intSample,
149
+ const float* rbot0,
150
+ const float* rbot1,
151
+ const float* gradOutput,
152
+ float* gradOne,
153
+ float* gradTwo
154
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
155
+ int n = intIndex % SIZE_1(gradTwo); // channels
156
+ int l = (intIndex / SIZE_1(gradTwo)) % SIZE_3(gradTwo) + 3*{{intStride}}; // w-pos
157
+ int m = (intIndex / SIZE_1(gradTwo) / SIZE_3(gradTwo)) % SIZE_2(gradTwo) + 3*{{intStride}}; // h-pos
158
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
159
+ // We use a large offset, for the inner part not to become negative.
160
+ const int round_off = ROUND_OFF;
161
+ const int round_off_s1 = {{intStride}} * round_off;
162
+ float sum = 0;
163
+ for (int p = -3; p <= 3; p++) {
164
+ for (int o = -3; o <= 3; o++) {
165
+ int s2o = {{intStride}} * o;
166
+ int s2p = {{intStride}} * p;
167
+ //Get X,Y ranges and clamp
168
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
169
+ int xmin = (l - 3*{{intStride}} - s2o + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}}
170
+ int ymin = (m - 3*{{intStride}} - s2p + round_off_s1 - 1) / {{intStride}} + 1 - round_off; // ceil (l - 3*{{intStride}} - s2o) / {{intStride}}
171
+ // Same here:
172
+ int xmax = (l - 3*{{intStride}} - s2o + round_off_s1) / {{intStride}} - round_off; // floor (l - 3*{{intStride}} - s2o) / {{intStride}}
173
+ int ymax = (m - 3*{{intStride}} - s2p + round_off_s1) / {{intStride}} - round_off; // floor (m - 3*{{intStride}} - s2p) / {{intStride}}
174
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
175
+ xmin = max(0,xmin);
176
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
177
+ ymin = max(0,ymin);
178
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
179
+ // Get rbot0 data:
180
+ int idxbot0 = ((intSample * SIZE_1(rbot0) + (m-s2p)) * SIZE_2(rbot0) + (l-s2o)) * SIZE_3(rbot0) + n;
181
+ float bot0tmp = rbot0[idxbot0]; // rbot1[l+s2o,m+s2p,n]
182
+ // Index offset for gradOutput in following loops:
183
+ int op = (p+3) * 7 + (o+3); // index[o,p]
184
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
185
+ for (int y = ymin; y <= ymax; y++) {
186
+ for (int x = xmin; x <= xmax; x++) {
187
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
188
+ sum += gradOutput[idxgradOutput] * bot0tmp;
189
+ }
190
+ }
191
+ }
192
+ }
193
+ }
194
+ const int sumelems = SIZE_1(gradTwo);
195
+ const int bot1index = ((n * SIZE_2(gradTwo)) + (m-3*{{intStride}})) * SIZE_3(gradTwo) + (l-3*{{intStride}});
196
+ gradTwo[bot1index + intSample*SIZE_1(gradTwo)*SIZE_2(gradTwo)*SIZE_3(gradTwo)] = sum / (float)sumelems;
197
+ } }
198
+ """
199
+
200
+
201
+ def cupy_kernel(strFunction, objVariables):
202
+ strKernel = globals()[strFunction].replace("{{intStride}}", str(objVariables["intStride"]))
203
+
204
+ while True:
205
+ objMatch = re.search(r"(SIZE_)([0-4])(\()([^\)]*)(\))", strKernel)
206
+
207
+ if objMatch is None:
208
+ break
209
+ # end
210
+
211
+ intArg = int(objMatch.group(2))
212
+
213
+ strTensor = objMatch.group(4)
214
+ intSizes = objVariables[strTensor].size()
215
+
216
+ strKernel = strKernel.replace(
217
+ objMatch.group(),
218
+ str(intSizes[intArg] if not torch.is_tensor(intSizes[intArg]) else intSizes[intArg].item()),
219
+ )
220
+ # end
221
+
222
+ while True:
223
+ objMatch = re.search(r"(VALUE_)([0-4])(\()([^\)]+)(\))", strKernel)
224
+
225
+ if objMatch is None:
226
+ break
227
+ # end
228
+
229
+ intArgs = int(objMatch.group(2))
230
+ strArgs = objMatch.group(4).split(",")
231
+
232
+ strTensor = strArgs[0]
233
+ intStrides = objVariables[strTensor].stride()
234
+ strIndex = [
235
+ "(("
236
+ + strArgs[intArg + 1].replace("{", "(").replace("}", ")").strip()
237
+ + ")*"
238
+ + str(intStrides[intArg] if not torch.is_tensor(intStrides[intArg]) else intStrides[intArg].item())
239
+ + ")"
240
+ for intArg in range(intArgs)
241
+ ]
242
+
243
+ strKernel = strKernel.replace(objMatch.group(0), strTensor + "[" + str.join("+", strIndex) + "]")
244
+ # end
245
+
246
+ return strKernel
247
+
248
+
249
+ # end
250
+
251
+
252
+ @cupy.memoize(for_each_device=True)
253
+ def cupy_launch(strFunction, strKernel):
254
+ return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction)
255
+
256
+
257
+ # end
258
+
259
+
260
+ class _FunctionCorrelation(torch.autograd.Function):
261
+ @staticmethod
262
+ def forward(self, one, two, intStride):
263
+ rbot0 = one.new_zeros(
264
+ [one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1]]
265
+ )
266
+ rbot1 = one.new_zeros(
267
+ [one.shape[0], one.shape[2] + (6 * intStride), one.shape[3] + (6 * intStride), one.shape[1]]
268
+ )
269
+
270
+ self.intStride = intStride
271
+
272
+ one = one.contiguous()
273
+ assert one.is_cuda
274
+ two = two.contiguous()
275
+ assert two.is_cuda
276
+
277
+ output = one.new_zeros(
278
+ [one.shape[0], 49, int(math.ceil(one.shape[2] / intStride)), int(math.ceil(one.shape[3] / intStride))]
279
+ )
280
+
281
+ if one.is_cuda:
282
+ n = one.shape[2] * one.shape[3]
283
+ cupy_launch(
284
+ "kernel_Correlation_rearrange",
285
+ cupy_kernel(
286
+ "kernel_Correlation_rearrange", {"intStride": self.intStride, "input": one, "output": rbot0}
287
+ ),
288
+ )(
289
+ grid=(int((n + 16 - 1) / 16), one.shape[1], one.shape[0]),
290
+ block=(16, 1, 1),
291
+ args=[cupy.int32(n), one.data_ptr(), rbot0.data_ptr()],
292
+ )
293
+
294
+ n = two.shape[2] * two.shape[3]
295
+ cupy_launch(
296
+ "kernel_Correlation_rearrange",
297
+ cupy_kernel(
298
+ "kernel_Correlation_rearrange", {"intStride": self.intStride, "input": two, "output": rbot1}
299
+ ),
300
+ )(
301
+ grid=(int((n + 16 - 1) / 16), two.shape[1], two.shape[0]),
302
+ block=(16, 1, 1),
303
+ args=[cupy.int32(n), two.data_ptr(), rbot1.data_ptr()],
304
+ )
305
+
306
+ n = output.shape[1] * output.shape[2] * output.shape[3]
307
+ cupy_launch(
308
+ "kernel_Correlation_updateOutput",
309
+ cupy_kernel(
310
+ "kernel_Correlation_updateOutput",
311
+ {"intStride": self.intStride, "rbot0": rbot0, "rbot1": rbot1, "top": output},
312
+ ),
313
+ )(
314
+ grid=(output.shape[3], output.shape[2], output.shape[0]),
315
+ block=(32, 1, 1),
316
+ shared_mem=one.shape[1] * 4,
317
+ args=[cupy.int32(n), rbot0.data_ptr(), rbot1.data_ptr(), output.data_ptr()],
318
+ )
319
+
320
+ elif not one.is_cuda:
321
+ raise NotImplementedError()
322
+
323
+ # end
324
+
325
+ self.save_for_backward(one, two, rbot0, rbot1)
326
+
327
+ return output
328
+
329
+ # end
330
+
331
+ @staticmethod
332
+ def backward(self, gradOutput):
333
+ one, two, rbot0, rbot1 = self.saved_tensors
334
+
335
+ gradOutput = gradOutput.contiguous()
336
+ assert gradOutput.is_cuda
337
+
338
+ gradOne = (
339
+ one.new_zeros([one.shape[0], one.shape[1], one.shape[2], one.shape[3]])
340
+ if self.needs_input_grad[0]
341
+ else None
342
+ )
343
+ gradTwo = (
344
+ one.new_zeros([one.shape[0], one.shape[1], one.shape[2], one.shape[3]])
345
+ if self.needs_input_grad[1]
346
+ else None
347
+ )
348
+
349
+ if one.is_cuda:
350
+ if gradOne is not None:
351
+ for intSample in range(one.shape[0]):
352
+ n = one.shape[1] * one.shape[2] * one.shape[3]
353
+ cupy_launch(
354
+ "kernel_Correlation_updateGradOne",
355
+ cupy_kernel(
356
+ "kernel_Correlation_updateGradOne",
357
+ {
358
+ "intStride": self.intStride,
359
+ "rbot0": rbot0,
360
+ "rbot1": rbot1,
361
+ "gradOutput": gradOutput,
362
+ "gradOne": gradOne,
363
+ "gradTwo": None,
364
+ },
365
+ ),
366
+ )(
367
+ grid=(int((n + 512 - 1) / 512), 1, 1),
368
+ block=(512, 1, 1),
369
+ args=[
370
+ cupy.int32(n),
371
+ intSample,
372
+ rbot0.data_ptr(),
373
+ rbot1.data_ptr(),
374
+ gradOutput.data_ptr(),
375
+ gradOne.data_ptr(),
376
+ None,
377
+ ],
378
+ )
379
+ # end
380
+ # end
381
+
382
+ if gradTwo is not None:
383
+ for intSample in range(one.shape[0]):
384
+ n = one.shape[1] * one.shape[2] * one.shape[3]
385
+ cupy_launch(
386
+ "kernel_Correlation_updateGradTwo",
387
+ cupy_kernel(
388
+ "kernel_Correlation_updateGradTwo",
389
+ {
390
+ "intStride": self.intStride,
391
+ "rbot0": rbot0,
392
+ "rbot1": rbot1,
393
+ "gradOutput": gradOutput,
394
+ "gradOne": None,
395
+ "gradTwo": gradTwo,
396
+ },
397
+ ),
398
+ )(
399
+ grid=(int((n + 512 - 1) / 512), 1, 1),
400
+ block=(512, 1, 1),
401
+ args=[
402
+ cupy.int32(n),
403
+ intSample,
404
+ rbot0.data_ptr(),
405
+ rbot1.data_ptr(),
406
+ gradOutput.data_ptr(),
407
+ None,
408
+ gradTwo.data_ptr(),
409
+ ],
410
+ )
411
+ # end
412
+ # end
413
+
414
+ elif not one.is_cuda:
415
+ raise NotImplementedError()
416
+
417
+ # end
418
+
419
+ return gradOne, gradTwo, None
420
+
421
+ # end
422
+
423
+
424
+ # end
425
+
426
+
427
+ def FunctionCorrelation(tenOne, tenTwo, intStride):
428
+ return _FunctionCorrelation.apply(tenOne, tenTwo, intStride)
429
+
430
+
431
+ # end
432
+
433
+
434
+ class ModuleCorrelation(torch.nn.Module):
435
+ def __init__(self):
436
+ super().__init__()
437
+
438
+ # end
439
+
440
+ def forward(self, tenOne, tenTwo, intStride):
441
+ return _FunctionCorrelation.apply(tenOne, tenTwo, intStride)
442
+
443
+ # end
444
+
445
+
446
+ # end
Helios-main/eval/utils/third_party/amt/flow_generation/liteflownet/run.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import getopt
4
+ import math
5
+ import sys
6
+
7
+ import numpy
8
+ import PIL
9
+ import PIL.Image
10
+ import torch
11
+
12
+
13
+ try:
14
+ from .correlation import correlation # the custom cost volume layer
15
+ except Exception:
16
+ sys.path.insert(0, "./correlation")
17
+ import correlation # you should consider upgrading python
18
+ # end
19
+
20
+ ##########################################################
21
+
22
+ assert int(str("").join(torch.__version__.split(".")[0:2])) >= 13 # requires at least pytorch version 1.3.0
23
+
24
+ torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance
25
+
26
+ torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance
27
+
28
+ ##########################################################
29
+
30
+ arguments_strModel = "default" # 'default', or 'kitti', or 'sintel'
31
+ arguments_strOne = "./images/one.png"
32
+ arguments_strTwo = "./images/two.png"
33
+ arguments_strOut = "./out.flo"
34
+
35
+ for strOption, strArgument in getopt.getopt(
36
+ sys.argv[1:], "", [strParameter[2:] + "=" for strParameter in sys.argv[1::2]]
37
+ )[0]:
38
+ if strOption == "--model" and strArgument != "":
39
+ arguments_strModel = strArgument # which model to use
40
+ if strOption == "--one" and strArgument != "":
41
+ arguments_strOne = strArgument # path to the first frame
42
+ if strOption == "--two" and strArgument != "":
43
+ arguments_strTwo = strArgument # path to the second frame
44
+ if strOption == "--out" and strArgument != "":
45
+ arguments_strOut = strArgument # path to where the output should be stored
46
+ # end
47
+
48
+ ##########################################################
49
+
50
+ backwarp_tenGrid = {}
51
+
52
+
53
+ def backwarp(tenInput, tenFlow):
54
+ if str(tenFlow.shape) not in backwarp_tenGrid:
55
+ tenHor = (
56
+ torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3])
57
+ .view(1, 1, 1, -1)
58
+ .repeat(1, 1, tenFlow.shape[2], 1)
59
+ )
60
+ tenVer = (
61
+ torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2])
62
+ .view(1, 1, -1, 1)
63
+ .repeat(1, 1, 1, tenFlow.shape[3])
64
+ )
65
+
66
+ backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([tenHor, tenVer], 1).cuda()
67
+ # end
68
+
69
+ tenFlow = torch.cat(
70
+ [
71
+ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
72
+ tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0),
73
+ ],
74
+ 1,
75
+ )
76
+
77
+ return torch.nn.functional.grid_sample(
78
+ input=tenInput,
79
+ grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1),
80
+ mode="bilinear",
81
+ padding_mode="zeros",
82
+ align_corners=False,
83
+ )
84
+
85
+
86
+ # end
87
+
88
+ ##########################################################
89
+
90
+
91
+ class Network(torch.nn.Module):
92
+ def __init__(self):
93
+ super().__init__()
94
+
95
+ class Features(torch.nn.Module):
96
+ def __init__(self):
97
+ super().__init__()
98
+
99
+ self.netOne = torch.nn.Sequential(
100
+ torch.nn.Conv2d(in_channels=3, out_channels=32, kernel_size=7, stride=1, padding=3),
101
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
102
+ )
103
+
104
+ self.netTwo = torch.nn.Sequential(
105
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=2, padding=1),
106
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
107
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
108
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
109
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
110
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
111
+ )
112
+
113
+ self.netThr = torch.nn.Sequential(
114
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
115
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
116
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
117
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
118
+ )
119
+
120
+ self.netFou = torch.nn.Sequential(
121
+ torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
122
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
123
+ torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
124
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
125
+ )
126
+
127
+ self.netFiv = torch.nn.Sequential(
128
+ torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1),
129
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
130
+ )
131
+
132
+ self.netSix = torch.nn.Sequential(
133
+ torch.nn.Conv2d(in_channels=128, out_channels=192, kernel_size=3, stride=2, padding=1),
134
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
135
+ )
136
+
137
+ # end
138
+
139
+ def forward(self, tenInput):
140
+ tenOne = self.netOne(tenInput)
141
+ tenTwo = self.netTwo(tenOne)
142
+ tenThr = self.netThr(tenTwo)
143
+ tenFou = self.netFou(tenThr)
144
+ tenFiv = self.netFiv(tenFou)
145
+ tenSix = self.netSix(tenFiv)
146
+
147
+ return [tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix]
148
+
149
+ # end
150
+
151
+ # end
152
+
153
+ class Matching(torch.nn.Module):
154
+ def __init__(self, intLevel):
155
+ super().__init__()
156
+
157
+ self.fltBackwarp = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel]
158
+
159
+ if intLevel != 2:
160
+ self.netFeat = torch.nn.Sequential()
161
+
162
+ elif intLevel == 2:
163
+ self.netFeat = torch.nn.Sequential(
164
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0),
165
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
166
+ )
167
+
168
+ # end
169
+
170
+ if intLevel == 6:
171
+ self.netUpflow = None
172
+
173
+ elif intLevel != 6:
174
+ self.netUpflow = torch.nn.ConvTranspose2d(
175
+ in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1, bias=False, groups=2
176
+ )
177
+
178
+ # end
179
+
180
+ if intLevel >= 4:
181
+ self.netUpcorr = None
182
+
183
+ elif intLevel < 4:
184
+ self.netUpcorr = torch.nn.ConvTranspose2d(
185
+ in_channels=49, out_channels=49, kernel_size=4, stride=2, padding=1, bias=False, groups=49
186
+ )
187
+
188
+ # end
189
+
190
+ self.netMain = torch.nn.Sequential(
191
+ torch.nn.Conv2d(in_channels=49, out_channels=128, kernel_size=3, stride=1, padding=1),
192
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
193
+ torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1),
194
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
195
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
196
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
197
+ torch.nn.Conv2d(
198
+ in_channels=32,
199
+ out_channels=2,
200
+ kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel],
201
+ stride=1,
202
+ padding=[0, 0, 3, 2, 2, 1, 1][intLevel],
203
+ ),
204
+ )
205
+
206
+ # end
207
+
208
+ def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow):
209
+ tenFeaturesOne = self.netFeat(tenFeaturesOne)
210
+ tenFeaturesTwo = self.netFeat(tenFeaturesTwo)
211
+
212
+ if tenFlow is not None:
213
+ tenFlow = self.netUpflow(tenFlow)
214
+ # end
215
+
216
+ if tenFlow is not None:
217
+ tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackwarp)
218
+ # end
219
+
220
+ if self.netUpcorr is None:
221
+ tenCorrelation = torch.nn.functional.leaky_relu(
222
+ input=correlation.FunctionCorrelation(
223
+ tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=1
224
+ ),
225
+ negative_slope=0.1,
226
+ inplace=False,
227
+ )
228
+
229
+ elif self.netUpcorr is not None:
230
+ tenCorrelation = self.netUpcorr(
231
+ torch.nn.functional.leaky_relu(
232
+ input=correlation.FunctionCorrelation(
233
+ tenOne=tenFeaturesOne, tenTwo=tenFeaturesTwo, intStride=2
234
+ ),
235
+ negative_slope=0.1,
236
+ inplace=False,
237
+ )
238
+ )
239
+
240
+ # end
241
+
242
+ return (tenFlow if tenFlow is not None else 0.0) + self.netMain(tenCorrelation)
243
+
244
+ # end
245
+
246
+ # end
247
+
248
+ class Subpixel(torch.nn.Module):
249
+ def __init__(self, intLevel):
250
+ super().__init__()
251
+
252
+ self.fltBackward = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel]
253
+
254
+ if intLevel != 2:
255
+ self.netFeat = torch.nn.Sequential()
256
+
257
+ elif intLevel == 2:
258
+ self.netFeat = torch.nn.Sequential(
259
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=1, stride=1, padding=0),
260
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
261
+ )
262
+
263
+ # end
264
+
265
+ self.netMain = torch.nn.Sequential(
266
+ torch.nn.Conv2d(
267
+ in_channels=[0, 0, 130, 130, 194, 258, 386][intLevel],
268
+ out_channels=128,
269
+ kernel_size=3,
270
+ stride=1,
271
+ padding=1,
272
+ ),
273
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
274
+ torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1),
275
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
276
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
277
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
278
+ torch.nn.Conv2d(
279
+ in_channels=32,
280
+ out_channels=2,
281
+ kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel],
282
+ stride=1,
283
+ padding=[0, 0, 3, 2, 2, 1, 1][intLevel],
284
+ ),
285
+ )
286
+
287
+ # end
288
+
289
+ def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow):
290
+ tenFeaturesOne = self.netFeat(tenFeaturesOne)
291
+ tenFeaturesTwo = self.netFeat(tenFeaturesTwo)
292
+
293
+ if tenFlow is not None:
294
+ tenFeaturesTwo = backwarp(tenInput=tenFeaturesTwo, tenFlow=tenFlow * self.fltBackward)
295
+ # end
296
+
297
+ return (tenFlow if tenFlow is not None else 0.0) + self.netMain(
298
+ torch.cat([tenFeaturesOne, tenFeaturesTwo, tenFlow], 1)
299
+ )
300
+
301
+ # end
302
+
303
+ # end
304
+
305
+ class Regularization(torch.nn.Module):
306
+ def __init__(self, intLevel):
307
+ super().__init__()
308
+
309
+ self.fltBackward = [0.0, 0.0, 10.0, 5.0, 2.5, 1.25, 0.625][intLevel]
310
+
311
+ self.intUnfold = [0, 0, 7, 5, 5, 3, 3][intLevel]
312
+
313
+ if intLevel >= 5:
314
+ self.netFeat = torch.nn.Sequential()
315
+
316
+ elif intLevel < 5:
317
+ self.netFeat = torch.nn.Sequential(
318
+ torch.nn.Conv2d(
319
+ in_channels=[0, 0, 32, 64, 96, 128, 192][intLevel],
320
+ out_channels=128,
321
+ kernel_size=1,
322
+ stride=1,
323
+ padding=0,
324
+ ),
325
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
326
+ )
327
+
328
+ # end
329
+
330
+ self.netMain = torch.nn.Sequential(
331
+ torch.nn.Conv2d(
332
+ in_channels=[0, 0, 131, 131, 131, 131, 195][intLevel],
333
+ out_channels=128,
334
+ kernel_size=3,
335
+ stride=1,
336
+ padding=1,
337
+ ),
338
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
339
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
340
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
341
+ torch.nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1),
342
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
343
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
344
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
345
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
346
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
347
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
348
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
349
+ )
350
+
351
+ if intLevel >= 5:
352
+ self.netDist = torch.nn.Sequential(
353
+ torch.nn.Conv2d(
354
+ in_channels=32,
355
+ out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel],
356
+ kernel_size=[0, 0, 7, 5, 5, 3, 3][intLevel],
357
+ stride=1,
358
+ padding=[0, 0, 3, 2, 2, 1, 1][intLevel],
359
+ )
360
+ )
361
+
362
+ elif intLevel < 5:
363
+ self.netDist = torch.nn.Sequential(
364
+ torch.nn.Conv2d(
365
+ in_channels=32,
366
+ out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel],
367
+ kernel_size=([0, 0, 7, 5, 5, 3, 3][intLevel], 1),
368
+ stride=1,
369
+ padding=([0, 0, 3, 2, 2, 1, 1][intLevel], 0),
370
+ ),
371
+ torch.nn.Conv2d(
372
+ in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel],
373
+ out_channels=[0, 0, 49, 25, 25, 9, 9][intLevel],
374
+ kernel_size=(1, [0, 0, 7, 5, 5, 3, 3][intLevel]),
375
+ stride=1,
376
+ padding=(0, [0, 0, 3, 2, 2, 1, 1][intLevel]),
377
+ ),
378
+ )
379
+
380
+ # end
381
+
382
+ self.netScaleX = torch.nn.Conv2d(
383
+ in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0
384
+ )
385
+ self.netScaleY = torch.nn.Conv2d(
386
+ in_channels=[0, 0, 49, 25, 25, 9, 9][intLevel], out_channels=1, kernel_size=1, stride=1, padding=0
387
+ )
388
+
389
+ # eny
390
+
391
+ def forward(self, tenOne, tenTwo, tenFeaturesOne, tenFeaturesTwo, tenFlow):
392
+ tenDifference = (
393
+ ((tenOne - backwarp(tenInput=tenTwo, tenFlow=tenFlow * self.fltBackward)) ** 2)
394
+ .sum(1, True)
395
+ .sqrt()
396
+ .detach()
397
+ )
398
+
399
+ tenDist = self.netDist(
400
+ self.netMain(
401
+ torch.cat(
402
+ [
403
+ tenDifference,
404
+ tenFlow
405
+ - tenFlow.view(tenFlow.shape[0], 2, -1).mean(2, True).view(tenFlow.shape[0], 2, 1, 1),
406
+ self.netFeat(tenFeaturesOne),
407
+ ],
408
+ 1,
409
+ )
410
+ )
411
+ )
412
+ tenDist = (tenDist**2).neg()
413
+ tenDist = (tenDist - tenDist.max(1, True)[0]).exp()
414
+
415
+ tenDivisor = tenDist.sum(1, True).reciprocal()
416
+
417
+ tenScaleX = (
418
+ self.netScaleX(
419
+ tenDist
420
+ * torch.nn.functional.unfold(
421
+ input=tenFlow[:, 0:1, :, :],
422
+ kernel_size=self.intUnfold,
423
+ stride=1,
424
+ padding=int((self.intUnfold - 1) / 2),
425
+ ).view_as(tenDist)
426
+ )
427
+ * tenDivisor
428
+ )
429
+ tenScaleY = (
430
+ self.netScaleY(
431
+ tenDist
432
+ * torch.nn.functional.unfold(
433
+ input=tenFlow[:, 1:2, :, :],
434
+ kernel_size=self.intUnfold,
435
+ stride=1,
436
+ padding=int((self.intUnfold - 1) / 2),
437
+ ).view_as(tenDist)
438
+ )
439
+ * tenDivisor
440
+ )
441
+
442
+ return torch.cat([tenScaleX, tenScaleY], 1)
443
+
444
+ # end
445
+
446
+ # end
447
+
448
+ self.netFeatures = Features()
449
+ self.netMatching = torch.nn.ModuleList([Matching(intLevel) for intLevel in [2, 3, 4, 5, 6]])
450
+ self.netSubpixel = torch.nn.ModuleList([Subpixel(intLevel) for intLevel in [2, 3, 4, 5, 6]])
451
+ self.netRegularization = torch.nn.ModuleList([Regularization(intLevel) for intLevel in [2, 3, 4, 5, 6]])
452
+
453
+ self.load_state_dict(
454
+ {
455
+ strKey.replace("module", "net"): tenWeight
456
+ for strKey, tenWeight in torch.hub.load_state_dict_from_url(
457
+ url="http://content.sniklaus.com/github/pytorch-liteflownet/network-"
458
+ + arguments_strModel
459
+ + ".pytorch"
460
+ ).items()
461
+ }
462
+ )
463
+ # self.load_state_dict(torch.load('./liteflownet/network-default.pth'))
464
+
465
+ # end
466
+
467
+ def forward(self, tenOne, tenTwo):
468
+ tenOne[:, 0, :, :] = tenOne[:, 0, :, :] - 0.411618
469
+ tenOne[:, 1, :, :] = tenOne[:, 1, :, :] - 0.434631
470
+ tenOne[:, 2, :, :] = tenOne[:, 2, :, :] - 0.454253
471
+
472
+ tenTwo[:, 0, :, :] = tenTwo[:, 0, :, :] - 0.410782
473
+ tenTwo[:, 1, :, :] = tenTwo[:, 1, :, :] - 0.433645
474
+ tenTwo[:, 2, :, :] = tenTwo[:, 2, :, :] - 0.452793
475
+
476
+ tenFeaturesOne = self.netFeatures(tenOne)
477
+ tenFeaturesTwo = self.netFeatures(tenTwo)
478
+
479
+ tenOne = [tenOne]
480
+ tenTwo = [tenTwo]
481
+
482
+ for intLevel in [1, 2, 3, 4, 5]:
483
+ tenOne.append(
484
+ torch.nn.functional.interpolate(
485
+ input=tenOne[-1],
486
+ size=(tenFeaturesOne[intLevel].shape[2], tenFeaturesOne[intLevel].shape[3]),
487
+ mode="bilinear",
488
+ align_corners=False,
489
+ )
490
+ )
491
+ tenTwo.append(
492
+ torch.nn.functional.interpolate(
493
+ input=tenTwo[-1],
494
+ size=(tenFeaturesTwo[intLevel].shape[2], tenFeaturesTwo[intLevel].shape[3]),
495
+ mode="bilinear",
496
+ align_corners=False,
497
+ )
498
+ )
499
+ # end
500
+
501
+ tenFlow = None
502
+
503
+ for intLevel in [-1, -2, -3, -4, -5]:
504
+ tenFlow = self.netMatching[intLevel](
505
+ tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow
506
+ )
507
+ tenFlow = self.netSubpixel[intLevel](
508
+ tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow
509
+ )
510
+ tenFlow = self.netRegularization[intLevel](
511
+ tenOne[intLevel], tenTwo[intLevel], tenFeaturesOne[intLevel], tenFeaturesTwo[intLevel], tenFlow
512
+ )
513
+ # end
514
+
515
+ return tenFlow * 20.0
516
+
517
+ # end
518
+
519
+
520
+ # end
521
+
522
+ netNetwork = None
523
+
524
+ ##########################################################
525
+
526
+
527
+ def estimate(tenOne, tenTwo):
528
+ global netNetwork
529
+
530
+ if netNetwork is None:
531
+ netNetwork = Network().cuda().eval()
532
+ # end
533
+
534
+ assert tenOne.shape[1] == tenTwo.shape[1]
535
+ assert tenOne.shape[2] == tenTwo.shape[2]
536
+
537
+ intWidth = tenOne.shape[2]
538
+ intHeight = tenOne.shape[1]
539
+
540
+ # assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
541
+ # assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
542
+
543
+ tenPreprocessedOne = tenOne.cuda().view(1, 3, intHeight, intWidth)
544
+ tenPreprocessedTwo = tenTwo.cuda().view(1, 3, intHeight, intWidth)
545
+
546
+ intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 32.0) * 32.0))
547
+ intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 32.0) * 32.0))
548
+
549
+ tenPreprocessedOne = torch.nn.functional.interpolate(
550
+ input=tenPreprocessedOne,
551
+ size=(intPreprocessedHeight, intPreprocessedWidth),
552
+ mode="bilinear",
553
+ align_corners=False,
554
+ )
555
+ tenPreprocessedTwo = torch.nn.functional.interpolate(
556
+ input=tenPreprocessedTwo,
557
+ size=(intPreprocessedHeight, intPreprocessedWidth),
558
+ mode="bilinear",
559
+ align_corners=False,
560
+ )
561
+
562
+ tenFlow = torch.nn.functional.interpolate(
563
+ input=netNetwork(tenPreprocessedOne, tenPreprocessedTwo),
564
+ size=(intHeight, intWidth),
565
+ mode="bilinear",
566
+ align_corners=False,
567
+ )
568
+
569
+ tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
570
+ tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
571
+
572
+ return tenFlow[0, :, :, :].cpu()
573
+
574
+
575
+ # end
576
+
577
+ ##########################################################
578
+
579
+ if __name__ == "__main__":
580
+ tenOne = torch.FloatTensor(
581
+ numpy.ascontiguousarray(
582
+ numpy.array(PIL.Image.open(arguments_strOne))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32)
583
+ * (1.0 / 255.0)
584
+ )
585
+ )
586
+ tenTwo = torch.FloatTensor(
587
+ numpy.ascontiguousarray(
588
+ numpy.array(PIL.Image.open(arguments_strTwo))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32)
589
+ * (1.0 / 255.0)
590
+ )
591
+ )
592
+
593
+ tenOutput = estimate(tenOne, tenTwo)
594
+
595
+ objOutput = open(arguments_strOut, "wb")
596
+
597
+ numpy.array([80, 73, 69, 72], numpy.uint8).tofile(objOutput)
598
+ numpy.array([tenOutput.shape[2], tenOutput.shape[1]], numpy.int32).tofile(objOutput)
599
+ numpy.array(tenOutput.numpy().transpose(1, 2, 0), numpy.float32).tofile(objOutput)
600
+
601
+ objOutput.close()
602
+ # end
Helios-main/eval/utils/third_party/amt/networks/blocks/__init__.py ADDED
File without changes
Helios-main/eval/utils/third_party/amt/networks/blocks/feat_enc.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class BottleneckBlock(nn.Module):
6
+ def __init__(self, in_planes, planes, norm_fn="group", stride=1):
7
+ super(BottleneckBlock, self).__init__()
8
+
9
+ self.conv1 = nn.Conv2d(in_planes, planes // 4, kernel_size=1, padding=0)
10
+ self.conv2 = nn.Conv2d(planes // 4, planes // 4, kernel_size=3, padding=1, stride=stride)
11
+ self.conv3 = nn.Conv2d(planes // 4, planes, kernel_size=1, padding=0)
12
+ self.relu = nn.ReLU(inplace=True)
13
+
14
+ num_groups = planes // 8
15
+
16
+ if norm_fn == "group":
17
+ self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes // 4)
18
+ self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes // 4)
19
+ self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
20
+ if not stride == 1:
21
+ self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
22
+
23
+ elif norm_fn == "batch":
24
+ self.norm1 = nn.BatchNorm2d(planes // 4)
25
+ self.norm2 = nn.BatchNorm2d(planes // 4)
26
+ self.norm3 = nn.BatchNorm2d(planes)
27
+ if not stride == 1:
28
+ self.norm4 = nn.BatchNorm2d(planes)
29
+
30
+ elif norm_fn == "instance":
31
+ self.norm1 = nn.InstanceNorm2d(planes // 4)
32
+ self.norm2 = nn.InstanceNorm2d(planes // 4)
33
+ self.norm3 = nn.InstanceNorm2d(planes)
34
+ if not stride == 1:
35
+ self.norm4 = nn.InstanceNorm2d(planes)
36
+
37
+ elif norm_fn == "none":
38
+ self.norm1 = nn.Sequential()
39
+ self.norm2 = nn.Sequential()
40
+ self.norm3 = nn.Sequential()
41
+ if not stride == 1:
42
+ self.norm4 = nn.Sequential()
43
+
44
+ if stride == 1:
45
+ self.downsample = None
46
+
47
+ else:
48
+ self.downsample = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4)
49
+
50
+ def forward(self, x):
51
+ y = x
52
+ y = self.relu(self.norm1(self.conv1(y)))
53
+ y = self.relu(self.norm2(self.conv2(y)))
54
+ y = self.relu(self.norm3(self.conv3(y)))
55
+
56
+ if self.downsample is not None:
57
+ x = self.downsample(x)
58
+
59
+ return self.relu(x + y)
60
+
61
+
62
+ class ResidualBlock(nn.Module):
63
+ def __init__(self, in_planes, planes, norm_fn="group", stride=1):
64
+ super(ResidualBlock, self).__init__()
65
+
66
+ self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride)
67
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1)
68
+ self.relu = nn.ReLU(inplace=True)
69
+
70
+ num_groups = planes // 8
71
+
72
+ if norm_fn == "group":
73
+ self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
74
+ self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
75
+ if not stride == 1:
76
+ self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
77
+
78
+ elif norm_fn == "batch":
79
+ self.norm1 = nn.BatchNorm2d(planes)
80
+ self.norm2 = nn.BatchNorm2d(planes)
81
+ if not stride == 1:
82
+ self.norm3 = nn.BatchNorm2d(planes)
83
+
84
+ elif norm_fn == "instance":
85
+ self.norm1 = nn.InstanceNorm2d(planes)
86
+ self.norm2 = nn.InstanceNorm2d(planes)
87
+ if not stride == 1:
88
+ self.norm3 = nn.InstanceNorm2d(planes)
89
+
90
+ elif norm_fn == "none":
91
+ self.norm1 = nn.Sequential()
92
+ self.norm2 = nn.Sequential()
93
+ if not stride == 1:
94
+ self.norm3 = nn.Sequential()
95
+
96
+ if stride == 1:
97
+ self.downsample = None
98
+
99
+ else:
100
+ self.downsample = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm3)
101
+
102
+ def forward(self, x):
103
+ y = x
104
+ y = self.relu(self.norm1(self.conv1(y)))
105
+ y = self.relu(self.norm2(self.conv2(y)))
106
+
107
+ if self.downsample is not None:
108
+ x = self.downsample(x)
109
+
110
+ return self.relu(x + y)
111
+
112
+
113
+ class SmallEncoder(nn.Module):
114
+ def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0):
115
+ super(SmallEncoder, self).__init__()
116
+ self.norm_fn = norm_fn
117
+
118
+ if self.norm_fn == "group":
119
+ self.norm1 = nn.GroupNorm(num_groups=8, num_channels=32)
120
+
121
+ elif self.norm_fn == "batch":
122
+ self.norm1 = nn.BatchNorm2d(32)
123
+
124
+ elif self.norm_fn == "instance":
125
+ self.norm1 = nn.InstanceNorm2d(32)
126
+
127
+ elif self.norm_fn == "none":
128
+ self.norm1 = nn.Sequential()
129
+
130
+ self.conv1 = nn.Conv2d(3, 32, kernel_size=7, stride=2, padding=3)
131
+ self.relu1 = nn.ReLU(inplace=True)
132
+
133
+ self.in_planes = 32
134
+ self.layer1 = self._make_layer(32, stride=1)
135
+ self.layer2 = self._make_layer(64, stride=2)
136
+ self.layer3 = self._make_layer(96, stride=2)
137
+
138
+ self.dropout = None
139
+ if dropout > 0:
140
+ self.dropout = nn.Dropout2d(p=dropout)
141
+
142
+ self.conv2 = nn.Conv2d(96, output_dim, kernel_size=1)
143
+
144
+ for m in self.modules():
145
+ if isinstance(m, nn.Conv2d):
146
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
147
+ elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
148
+ if m.weight is not None:
149
+ nn.init.constant_(m.weight, 1)
150
+ if m.bias is not None:
151
+ nn.init.constant_(m.bias, 0)
152
+
153
+ def _make_layer(self, dim, stride=1):
154
+ layer1 = BottleneckBlock(self.in_planes, dim, self.norm_fn, stride=stride)
155
+ layer2 = BottleneckBlock(dim, dim, self.norm_fn, stride=1)
156
+ layers = (layer1, layer2)
157
+
158
+ self.in_planes = dim
159
+ return nn.Sequential(*layers)
160
+
161
+ def forward(self, x):
162
+ # if input is list, combine batch dimension
163
+ is_list = isinstance(x, tuple) or isinstance(x, list)
164
+ if is_list:
165
+ batch_dim = x[0].shape[0]
166
+ x = torch.cat(x, dim=0)
167
+
168
+ x = self.conv1(x)
169
+ x = self.norm1(x)
170
+ x = self.relu1(x)
171
+
172
+ x = self.layer1(x)
173
+ x = self.layer2(x)
174
+ x = self.layer3(x)
175
+ x = self.conv2(x)
176
+
177
+ if self.training and self.dropout is not None:
178
+ x = self.dropout(x)
179
+
180
+ if is_list:
181
+ x = torch.split(x, [batch_dim, batch_dim], dim=0)
182
+
183
+ return x
184
+
185
+
186
+ class BasicEncoder(nn.Module):
187
+ def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0):
188
+ super(BasicEncoder, self).__init__()
189
+ self.norm_fn = norm_fn
190
+
191
+ if self.norm_fn == "group":
192
+ self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64)
193
+
194
+ elif self.norm_fn == "batch":
195
+ self.norm1 = nn.BatchNorm2d(64)
196
+
197
+ elif self.norm_fn == "instance":
198
+ self.norm1 = nn.InstanceNorm2d(64)
199
+
200
+ elif self.norm_fn == "none":
201
+ self.norm1 = nn.Sequential()
202
+
203
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
204
+ self.relu1 = nn.ReLU(inplace=True)
205
+
206
+ self.in_planes = 64
207
+ self.layer1 = self._make_layer(64, stride=1)
208
+ self.layer2 = self._make_layer(72, stride=2)
209
+ self.layer3 = self._make_layer(128, stride=2)
210
+
211
+ # output convolution
212
+ self.conv2 = nn.Conv2d(128, output_dim, kernel_size=1)
213
+
214
+ self.dropout = None
215
+ if dropout > 0:
216
+ self.dropout = nn.Dropout2d(p=dropout)
217
+
218
+ for m in self.modules():
219
+ if isinstance(m, nn.Conv2d):
220
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
221
+ elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
222
+ if m.weight is not None:
223
+ nn.init.constant_(m.weight, 1)
224
+ if m.bias is not None:
225
+ nn.init.constant_(m.bias, 0)
226
+
227
+ def _make_layer(self, dim, stride=1):
228
+ layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride)
229
+ layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1)
230
+ layers = (layer1, layer2)
231
+
232
+ self.in_planes = dim
233
+ return nn.Sequential(*layers)
234
+
235
+ def forward(self, x):
236
+ # if input is list, combine batch dimension
237
+ is_list = isinstance(x, tuple) or isinstance(x, list)
238
+ if is_list:
239
+ batch_dim = x[0].shape[0]
240
+ x = torch.cat(x, dim=0)
241
+
242
+ x = self.conv1(x)
243
+ x = self.norm1(x)
244
+ x = self.relu1(x)
245
+
246
+ x = self.layer1(x)
247
+ x = self.layer2(x)
248
+ x = self.layer3(x)
249
+
250
+ x = self.conv2(x)
251
+
252
+ if self.training and self.dropout is not None:
253
+ x = self.dropout(x)
254
+
255
+ if is_list:
256
+ x = torch.split(x, [batch_dim, batch_dim], dim=0)
257
+
258
+ return x
259
+
260
+
261
+ class LargeEncoder(nn.Module):
262
+ def __init__(self, output_dim=128, norm_fn="batch", dropout=0.0):
263
+ super(LargeEncoder, self).__init__()
264
+ self.norm_fn = norm_fn
265
+
266
+ if self.norm_fn == "group":
267
+ self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64)
268
+
269
+ elif self.norm_fn == "batch":
270
+ self.norm1 = nn.BatchNorm2d(64)
271
+
272
+ elif self.norm_fn == "instance":
273
+ self.norm1 = nn.InstanceNorm2d(64)
274
+
275
+ elif self.norm_fn == "none":
276
+ self.norm1 = nn.Sequential()
277
+
278
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)
279
+ self.relu1 = nn.ReLU(inplace=True)
280
+
281
+ self.in_planes = 64
282
+ self.layer1 = self._make_layer(64, stride=1)
283
+ self.layer2 = self._make_layer(112, stride=2)
284
+ self.layer3 = self._make_layer(160, stride=2)
285
+ self.layer3_2 = self._make_layer(160, stride=1)
286
+
287
+ # output convolution
288
+ self.conv2 = nn.Conv2d(self.in_planes, output_dim, kernel_size=1)
289
+
290
+ self.dropout = None
291
+ if dropout > 0:
292
+ self.dropout = nn.Dropout2d(p=dropout)
293
+
294
+ for m in self.modules():
295
+ if isinstance(m, nn.Conv2d):
296
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
297
+ elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
298
+ if m.weight is not None:
299
+ nn.init.constant_(m.weight, 1)
300
+ if m.bias is not None:
301
+ nn.init.constant_(m.bias, 0)
302
+
303
+ def _make_layer(self, dim, stride=1):
304
+ layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride)
305
+ layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1)
306
+ layers = (layer1, layer2)
307
+
308
+ self.in_planes = dim
309
+ return nn.Sequential(*layers)
310
+
311
+ def forward(self, x):
312
+ # if input is list, combine batch dimension
313
+ is_list = isinstance(x, tuple) or isinstance(x, list)
314
+ if is_list:
315
+ batch_dim = x[0].shape[0]
316
+ x = torch.cat(x, dim=0)
317
+
318
+ x = self.conv1(x)
319
+ x = self.norm1(x)
320
+ x = self.relu1(x)
321
+
322
+ x = self.layer1(x)
323
+ x = self.layer2(x)
324
+ x = self.layer3(x)
325
+ x = self.layer3_2(x)
326
+
327
+ x = self.conv2(x)
328
+
329
+ if self.training and self.dropout is not None:
330
+ x = self.dropout(x)
331
+
332
+ if is_list:
333
+ x = torch.split(x, [batch_dim, batch_dim], dim=0)
334
+
335
+ return x
Helios-main/eval/utils/third_party/amt/networks/blocks/ifrnet.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ from utils.third_party.amt.utils.flow_utils import warp
6
+
7
+
8
+ def resize(x, scale_factor):
9
+ return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
10
+
11
+
12
+ def convrelu(in_channels, out_channels, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True):
13
+ return nn.Sequential(
14
+ nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias=bias),
15
+ nn.PReLU(out_channels),
16
+ )
17
+
18
+
19
+ class ResBlock(nn.Module):
20
+ def __init__(self, in_channels, side_channels, bias=True):
21
+ super(ResBlock, self).__init__()
22
+ self.side_channels = side_channels
23
+ self.conv1 = nn.Sequential(
24
+ nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias), nn.PReLU(in_channels)
25
+ )
26
+ self.conv2 = nn.Sequential(
27
+ nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias),
28
+ nn.PReLU(side_channels),
29
+ )
30
+ self.conv3 = nn.Sequential(
31
+ nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias), nn.PReLU(in_channels)
32
+ )
33
+ self.conv4 = nn.Sequential(
34
+ nn.Conv2d(side_channels, side_channels, kernel_size=3, stride=1, padding=1, bias=bias),
35
+ nn.PReLU(side_channels),
36
+ )
37
+ self.conv5 = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, bias=bias)
38
+ self.prelu = nn.PReLU(in_channels)
39
+
40
+ def forward(self, x):
41
+ out = self.conv1(x)
42
+
43
+ res_feat = out[:, : -self.side_channels, ...]
44
+ side_feat = out[:, -self.side_channels :, :, :]
45
+ side_feat = self.conv2(side_feat)
46
+ out = self.conv3(torch.cat([res_feat, side_feat], 1))
47
+
48
+ res_feat = out[:, : -self.side_channels, ...]
49
+ side_feat = out[:, -self.side_channels :, :, :]
50
+ side_feat = self.conv4(side_feat)
51
+ out = self.conv5(torch.cat([res_feat, side_feat], 1))
52
+
53
+ out = self.prelu(x + out)
54
+ return out
55
+
56
+
57
+ class Encoder(nn.Module):
58
+ def __init__(self, channels, large=False):
59
+ super(Encoder, self).__init__()
60
+ self.channels = channels
61
+ prev_ch = 3
62
+ for idx, ch in enumerate(channels, 1):
63
+ k = 7 if large and idx == 1 else 3
64
+ p = 3 if k == 7 else 1
65
+ self.register_module(
66
+ f"pyramid{idx}", nn.Sequential(convrelu(prev_ch, ch, k, 2, p), convrelu(ch, ch, 3, 1, 1))
67
+ )
68
+ prev_ch = ch
69
+
70
+ def forward(self, in_x):
71
+ fs = []
72
+ for idx in range(len(self.channels)):
73
+ out_x = getattr(self, f"pyramid{idx + 1}")(in_x)
74
+ fs.append(out_x)
75
+ in_x = out_x
76
+ return fs
77
+
78
+
79
+ class InitDecoder(nn.Module):
80
+ def __init__(self, in_ch, out_ch, skip_ch) -> None:
81
+ super().__init__()
82
+ self.convblock = nn.Sequential(
83
+ convrelu(in_ch * 2 + 1, in_ch * 2),
84
+ ResBlock(in_ch * 2, skip_ch),
85
+ nn.ConvTranspose2d(in_ch * 2, out_ch + 4, 4, 2, 1, bias=True),
86
+ )
87
+
88
+ def forward(self, f0, f1, embt):
89
+ h, w = f0.shape[2:]
90
+ embt = embt.repeat(1, 1, h, w)
91
+ out = self.convblock(torch.cat([f0, f1, embt], 1))
92
+ flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1)
93
+ ft_ = out[:, 4:, ...]
94
+ return flow0, flow1, ft_
95
+
96
+
97
+ class IntermediateDecoder(nn.Module):
98
+ def __init__(self, in_ch, out_ch, skip_ch) -> None:
99
+ super().__init__()
100
+ self.convblock = nn.Sequential(
101
+ convrelu(in_ch * 3 + 4, in_ch * 3),
102
+ ResBlock(in_ch * 3, skip_ch),
103
+ nn.ConvTranspose2d(in_ch * 3, out_ch + 4, 4, 2, 1, bias=True),
104
+ )
105
+
106
+ def forward(self, ft_, f0, f1, flow0_in, flow1_in):
107
+ f0_warp = warp(f0, flow0_in)
108
+ f1_warp = warp(f1, flow1_in)
109
+ f_in = torch.cat([ft_, f0_warp, f1_warp, flow0_in, flow1_in], 1)
110
+ out = self.convblock(f_in)
111
+ flow0, flow1 = torch.chunk(out[:, :4, ...], 2, 1)
112
+ ft_ = out[:, 4:, ...]
113
+ flow0 = flow0 + 2.0 * resize(flow0_in, scale_factor=2.0)
114
+ flow1 = flow1 + 2.0 * resize(flow1_in, scale_factor=2.0)
115
+ return flow0, flow1, ft_
Helios-main/eval/utils/third_party/amt/networks/blocks/multi_flow.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def multi_flow_combine(comb_block, img0, img1, flow0, flow1, mask=None, img_res=None, mean=None):
13
+ """
14
+ A parallel implementation of multiple flow field warping
15
+ comb_block: An nn.Seqential object.
16
+ img shape: [b, c, h, w]
17
+ flow shape: [b, 2*num_flows, h, w]
18
+ mask (opt):
19
+ If 'mask' is None, the function conduct a simple average.
20
+ img_res (opt):
21
+ If 'img_res' is None, the function adds zero instead.
22
+ mean (opt):
23
+ If 'mean' is None, the function adds zero instead.
24
+ """
25
+ b, c, h, w = flow0.shape
26
+ num_flows = c // 2
27
+ flow0 = flow0.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w)
28
+ flow1 = flow1.reshape(b, num_flows, 2, h, w).reshape(-1, 2, h, w)
29
+
30
+ mask = mask.reshape(b, num_flows, 1, h, w).reshape(-1, 1, h, w) if mask is not None else None
31
+ img_res = img_res.reshape(b, num_flows, 3, h, w).reshape(-1, 3, h, w) if img_res is not None else 0
32
+ img0 = torch.stack([img0] * num_flows, 1).reshape(-1, 3, h, w)
33
+ img1 = torch.stack([img1] * num_flows, 1).reshape(-1, 3, h, w)
34
+ mean = torch.stack([mean] * num_flows, 1).reshape(-1, 1, 1, 1) if mean is not None else 0
35
+
36
+ img0_warp = warp(img0, flow0)
37
+ img1_warp = warp(img1, flow1)
38
+ img_warps = mask * img0_warp + (1 - mask) * img1_warp + mean + img_res
39
+ img_warps = img_warps.reshape(b, num_flows, 3, h, w)
40
+ imgt_pred = img_warps.mean(1) + comb_block(img_warps.view(b, -1, h, w))
41
+ return imgt_pred
42
+
43
+
44
+ class MultiFlowDecoder(nn.Module):
45
+ def __init__(self, in_ch, skip_ch, num_flows=3):
46
+ super(MultiFlowDecoder, self).__init__()
47
+ self.num_flows = num_flows
48
+ self.convblock = nn.Sequential(
49
+ convrelu(in_ch * 3 + 4, in_ch * 3),
50
+ ResBlock(in_ch * 3, skip_ch),
51
+ nn.ConvTranspose2d(in_ch * 3, 8 * num_flows, 4, 2, 1, bias=True),
52
+ )
53
+
54
+ def forward(self, ft_, f0, f1, flow0, flow1):
55
+ n = self.num_flows
56
+ f0_warp = warp(f0, flow0)
57
+ f1_warp = warp(f1, flow1)
58
+ out = self.convblock(torch.cat([ft_, f0_warp, f1_warp, flow0, flow1], 1))
59
+ delta_flow0, delta_flow1, mask, img_res = torch.split(out, [2 * n, 2 * n, n, 3 * n], 1)
60
+ mask = torch.sigmoid(mask)
61
+
62
+ flow0 = delta_flow0 + 2.0 * resize(flow0, scale_factor=2.0).repeat(1, self.num_flows, 1, 1)
63
+ flow1 = delta_flow1 + 2.0 * resize(flow1, scale_factor=2.0).repeat(1, self.num_flows, 1, 1)
64
+
65
+ return flow0, flow1, mask, img_res
Helios-main/eval/utils/third_party/amt/networks/blocks/raft.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ def resize(x, scale_factor):
7
+ return F.interpolate(x, scale_factor=scale_factor, mode="bilinear", align_corners=False)
8
+
9
+
10
+ def bilinear_sampler(img, coords, mask=False):
11
+ """Wrapper for grid_sample, uses pixel coordinates"""
12
+ H, W = img.shape[-2:]
13
+ xgrid, ygrid = coords.split([1, 1], dim=-1)
14
+ xgrid = 2 * xgrid / (W - 1) - 1
15
+ ygrid = 2 * ygrid / (H - 1) - 1
16
+
17
+ grid = torch.cat([xgrid, ygrid], dim=-1)
18
+ img = F.grid_sample(img, grid, align_corners=True)
19
+
20
+ if mask:
21
+ mask = (xgrid > -1) & (ygrid > -1) & (xgrid < 1) & (ygrid < 1)
22
+ return img, mask.float()
23
+
24
+ return img
25
+
26
+
27
+ def coords_grid(batch, ht, wd, device):
28
+ coords = torch.meshgrid(torch.arange(ht, device=device), torch.arange(wd, device=device), indexing="ij")
29
+ coords = torch.stack(coords[::-1], dim=0).float()
30
+ return coords[None].repeat(batch, 1, 1, 1)
31
+
32
+
33
+ class SmallUpdateBlock(nn.Module):
34
+ def __init__(self, cdim, hidden_dim, flow_dim, corr_dim, fc_dim, corr_levels=4, radius=3, scale_factor=None):
35
+ super(SmallUpdateBlock, self).__init__()
36
+ cor_planes = corr_levels * (2 * radius + 1) ** 2
37
+ self.scale_factor = scale_factor
38
+
39
+ self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0)
40
+ self.convf1 = nn.Conv2d(4, flow_dim * 2, 7, padding=3)
41
+ self.convf2 = nn.Conv2d(flow_dim * 2, flow_dim, 3, padding=1)
42
+ self.conv = nn.Conv2d(corr_dim + flow_dim, fc_dim, 3, padding=1)
43
+
44
+ self.gru = nn.Sequential(
45
+ nn.Conv2d(fc_dim + 4 + cdim, hidden_dim, 3, padding=1),
46
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
47
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
48
+ )
49
+
50
+ self.feat_head = nn.Sequential(
51
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
52
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
53
+ nn.Conv2d(hidden_dim, cdim, 3, padding=1),
54
+ )
55
+
56
+ self.flow_head = nn.Sequential(
57
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
58
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
59
+ nn.Conv2d(hidden_dim, 4, 3, padding=1),
60
+ )
61
+
62
+ self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
63
+
64
+ def forward(self, net, flow, corr):
65
+ net = resize(net, 1 / self.scale_factor) if self.scale_factor is not None else net
66
+ cor = self.lrelu(self.convc1(corr))
67
+ flo = self.lrelu(self.convf1(flow))
68
+ flo = self.lrelu(self.convf2(flo))
69
+ cor_flo = torch.cat([cor, flo], dim=1)
70
+ inp = self.lrelu(self.conv(cor_flo))
71
+ inp = torch.cat([inp, flow, net], dim=1)
72
+
73
+ out = self.gru(inp)
74
+ delta_net = self.feat_head(out)
75
+ delta_flow = self.flow_head(out)
76
+
77
+ if self.scale_factor is not None:
78
+ delta_net = resize(delta_net, scale_factor=self.scale_factor)
79
+ delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor)
80
+
81
+ return delta_net, delta_flow
82
+
83
+
84
+ class BasicUpdateBlock(nn.Module):
85
+ def __init__(
86
+ self,
87
+ cdim,
88
+ hidden_dim,
89
+ flow_dim,
90
+ corr_dim,
91
+ corr_dim2,
92
+ fc_dim,
93
+ corr_levels=4,
94
+ radius=3,
95
+ scale_factor=None,
96
+ out_num=1,
97
+ ):
98
+ super(BasicUpdateBlock, self).__init__()
99
+ cor_planes = corr_levels * (2 * radius + 1) ** 2
100
+
101
+ self.scale_factor = scale_factor
102
+ self.convc1 = nn.Conv2d(2 * cor_planes, corr_dim, 1, padding=0)
103
+ self.convc2 = nn.Conv2d(corr_dim, corr_dim2, 3, padding=1)
104
+ self.convf1 = nn.Conv2d(4, flow_dim * 2, 7, padding=3)
105
+ self.convf2 = nn.Conv2d(flow_dim * 2, flow_dim, 3, padding=1)
106
+ self.conv = nn.Conv2d(flow_dim + corr_dim2, fc_dim, 3, padding=1)
107
+
108
+ self.gru = nn.Sequential(
109
+ nn.Conv2d(fc_dim + 4 + cdim, hidden_dim, 3, padding=1),
110
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
111
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
112
+ )
113
+
114
+ self.feat_head = nn.Sequential(
115
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
116
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
117
+ nn.Conv2d(hidden_dim, cdim, 3, padding=1),
118
+ )
119
+
120
+ self.flow_head = nn.Sequential(
121
+ nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1),
122
+ nn.LeakyReLU(negative_slope=0.1, inplace=True),
123
+ nn.Conv2d(hidden_dim, 4 * out_num, 3, padding=1),
124
+ )
125
+
126
+ self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
127
+
128
+ def forward(self, net, flow, corr):
129
+ net = resize(net, 1 / self.scale_factor) if self.scale_factor is not None else net
130
+ cor = self.lrelu(self.convc1(corr))
131
+ cor = self.lrelu(self.convc2(cor))
132
+ flo = self.lrelu(self.convf1(flow))
133
+ flo = self.lrelu(self.convf2(flo))
134
+ cor_flo = torch.cat([cor, flo], dim=1)
135
+ inp = self.lrelu(self.conv(cor_flo))
136
+ inp = torch.cat([inp, flow, net], dim=1)
137
+
138
+ out = self.gru(inp)
139
+ delta_net = self.feat_head(out)
140
+ delta_flow = self.flow_head(out)
141
+
142
+ if self.scale_factor is not None:
143
+ delta_net = resize(delta_net, scale_factor=self.scale_factor)
144
+ delta_flow = self.scale_factor * resize(delta_flow, scale_factor=self.scale_factor)
145
+ return delta_net, delta_flow
146
+
147
+
148
+ class BidirCorrBlock:
149
+ def __init__(self, fmap1, fmap2, num_levels=4, radius=4):
150
+ self.num_levels = num_levels
151
+ self.radius = radius
152
+ self.corr_pyramid = []
153
+ self.corr_pyramid_T = []
154
+
155
+ corr = BidirCorrBlock.corr(fmap1, fmap2)
156
+ batch, h1, w1, dim, h2, w2 = corr.shape
157
+ corr_T = corr.clone().permute(0, 4, 5, 3, 1, 2)
158
+
159
+ corr = corr.reshape(batch * h1 * w1, dim, h2, w2)
160
+ corr_T = corr_T.reshape(batch * h2 * w2, dim, h1, w1)
161
+
162
+ self.corr_pyramid.append(corr)
163
+ self.corr_pyramid_T.append(corr_T)
164
+
165
+ for _ in range(self.num_levels - 1):
166
+ corr = F.avg_pool2d(corr, 2, stride=2)
167
+ corr_T = F.avg_pool2d(corr_T, 2, stride=2)
168
+ self.corr_pyramid.append(corr)
169
+ self.corr_pyramid_T.append(corr_T)
170
+
171
+ def __call__(self, coords0, coords1):
172
+ r = self.radius
173
+ coords0 = coords0.permute(0, 2, 3, 1)
174
+ coords1 = coords1.permute(0, 2, 3, 1)
175
+ assert coords0.shape == coords1.shape, f"coords0 shape: [{coords0.shape}] is not equal to [{coords1.shape}]"
176
+ batch, h1, w1, _ = coords0.shape
177
+
178
+ out_pyramid = []
179
+ out_pyramid_T = []
180
+ for i in range(self.num_levels):
181
+ corr = self.corr_pyramid[i]
182
+ corr_T = self.corr_pyramid_T[i]
183
+
184
+ dx = torch.linspace(-r, r, 2 * r + 1, device=coords0.device)
185
+ dy = torch.linspace(-r, r, 2 * r + 1, device=coords0.device)
186
+ delta = torch.stack(torch.meshgrid(dy, dx, indexing="ij"), axis=-1)
187
+ delta_lvl = delta.view(1, 2 * r + 1, 2 * r + 1, 2)
188
+
189
+ centroid_lvl_0 = coords0.reshape(batch * h1 * w1, 1, 1, 2) / 2**i
190
+ centroid_lvl_1 = coords1.reshape(batch * h1 * w1, 1, 1, 2) / 2**i
191
+ coords_lvl_0 = centroid_lvl_0 + delta_lvl
192
+ coords_lvl_1 = centroid_lvl_1 + delta_lvl
193
+
194
+ corr = bilinear_sampler(corr, coords_lvl_0)
195
+ corr_T = bilinear_sampler(corr_T, coords_lvl_1)
196
+ corr = corr.view(batch, h1, w1, -1)
197
+ corr_T = corr_T.view(batch, h1, w1, -1)
198
+ out_pyramid.append(corr)
199
+ out_pyramid_T.append(corr_T)
200
+
201
+ out = torch.cat(out_pyramid, dim=-1)
202
+ out_T = torch.cat(out_pyramid_T, dim=-1)
203
+ return out.permute(0, 3, 1, 2).contiguous().float(), out_T.permute(0, 3, 1, 2).contiguous().float()
204
+
205
+ @staticmethod
206
+ def corr(fmap1, fmap2):
207
+ batch, dim, ht, wd = fmap1.shape
208
+ fmap1 = fmap1.view(batch, dim, ht * wd)
209
+ fmap2 = fmap2.view(batch, dim, ht * wd)
210
+
211
+ corr = torch.matmul(fmap1.transpose(1, 2), fmap2)
212
+ corr = corr.view(batch, ht, wd, 1, ht, wd)
213
+ return corr / torch.sqrt(torch.tensor(dim).float())
Helios-main/eval/utils/third_party/amt/scripts/benchmark_arbitrary.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ CFG=$1
2
+ CKPT=$2
3
+
4
+ python benchmarks/gopro.py -c $CFG -p $CKPT
5
+ python benchmarks/adobe240.py -c $CFG -p $CKPT
Helios-main/eval/utils/third_party/amt/scripts/benchmark_fixed.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ CFG=$1
2
+ CKPT=$2
3
+
4
+ python benchmarks/vimeo90k.py -c $CFG -p $CKPT
5
+ python benchmarks/ucf101.py -c $CFG -p $CKPT
6
+ python benchmarks/snu_film.py -c $CFG -p $CKPT
7
+ python benchmarks/xiph.py -c $CFG -p $CKPT
Helios-main/helios/modules/helios_kernels/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .attention_dispatch import attn_varlen_func, create_navit_attention_masks
2
+ from .fp32_rmsnorm import replace_rmsnorm_with_fp32
3
+ from .tiled_linear import replace_linear_with_tiled_linear
4
+ from .triton_norm import replace_all_norms_with_flash_norms
5
+ from .triton_rope import replace_rope_with_flash_rope
Helios-main/helios/modules/helios_kernels/attention_dispatch.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from kernels import get_kernel
3
+
4
+
5
+ try:
6
+ # FA3 Only support Hopper (SM90, H100/H800)
7
+ major, _ = torch.cuda.get_device_capability()
8
+ if major < 9:
9
+ raise RuntimeError("FA3 requires Hopper (SM90+), current GPU not supported")
10
+ flash_attn3 = get_kernel("kernels-community/flash-attn3")
11
+ flash_attn_func = flash_attn3.flash_attn_func
12
+ flash_attn_varlen_func = flash_attn3.flash_attn_varlen_func
13
+ print("Flash Attn 3 is installed!")
14
+ except (ImportError, RuntimeError):
15
+ try:
16
+ flash_attn2 = get_kernel("kernels-community/flash-attn2")
17
+ flash_attn_func = flash_attn2.flash_attn_func
18
+ flash_attn_varlen_func = flash_attn2.flash_attn_varlen_func
19
+ print("Flash Attn 2 is installed!")
20
+ except ImportError:
21
+ print("Flash Attn 2 / 3 is not installed!")
22
+ flash_attn_varlen_func = None
23
+ flash_attn_func = None
24
+
25
+
26
+ try:
27
+ # raise NotImplementedError
28
+ from sageattention import sageattn, sageattn_varlen
29
+
30
+ print("Sage Attn is installed!")
31
+ except ImportError:
32
+ print("Sage Attn is not installed!")
33
+ sageattn_varlen = None
34
+ sageattn = None
35
+
36
+ try:
37
+ # raise NotImplementedError
38
+ from xformers.ops import memory_efficient_attention as xformers_attn_func
39
+
40
+ print("Xformers is installed!")
41
+ except ImportError:
42
+ print("Xformers is not installed!")
43
+ xformers_attn_func = None
44
+
45
+
46
+ def create_navit_attention_masks(
47
+ batch_size: int,
48
+ original_context_length_list: list,
49
+ history_context_length: int,
50
+ encoder_hidden_states_seq_len: int,
51
+ device: torch.device,
52
+ restrict_self_attn: bool = False,
53
+ guidance_cross_attn: bool = False,
54
+ ):
55
+ # For navit_hidden_attention_mask
56
+ if restrict_self_attn:
57
+ cu_seqlens_q = [0]
58
+ for _ in range(batch_size):
59
+ for length in original_context_length_list:
60
+ cu_seqlens_q.append(cu_seqlens_q[-1] + length)
61
+ cu_seqlens_q = torch.tensor(cu_seqlens_q, device=device, dtype=torch.int32)
62
+ max_seqlen_q = max(original_context_length_list)
63
+
64
+ cu_seqlens_kv = [0]
65
+ for _ in range(batch_size):
66
+ for length in original_context_length_list:
67
+ cu_seqlens_kv.append(cu_seqlens_kv[-1] + length + history_context_length)
68
+ cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
69
+ max_seqlen_kv = max(original_context_length_list) + history_context_length
70
+ else:
71
+ cu_seqlens_kv = [0]
72
+ for _ in range(batch_size):
73
+ for length in original_context_length_list:
74
+ cu_seqlens_kv.append(cu_seqlens_kv[-1] + length + history_context_length)
75
+ cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
76
+ max_seqlen_kv = max(original_context_length_list) + history_context_length
77
+ cu_seqlens_q = cu_seqlens_kv
78
+ max_seqlen_q = max_seqlen_kv
79
+ navit_hidden_attention_mask = cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv
80
+
81
+ # For navit_history_hidden_attention_mask
82
+ navit_history_hidden_attention_mask = None
83
+ if restrict_self_attn:
84
+ cu_seqlens_kv = [0]
85
+ for _ in range(batch_size):
86
+ for length in original_context_length_list:
87
+ cu_seqlens_kv.append(cu_seqlens_kv[-1] + history_context_length)
88
+ cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
89
+ max_seqlen_kv = history_context_length
90
+ cu_seqlens_q = cu_seqlens_kv
91
+ max_seqlen_q = max_seqlen_kv
92
+ navit_history_hidden_attention_mask = cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv
93
+
94
+ # For navit_encoder_attention_mask
95
+ if guidance_cross_attn:
96
+ cross_cu_seqlens_q = [0]
97
+ for _ in range(batch_size):
98
+ for length in original_context_length_list:
99
+ cross_cu_seqlens_q.append(cross_cu_seqlens_q[-1] + length)
100
+ cross_cu_seqlens_q = torch.tensor(cross_cu_seqlens_q, device=device, dtype=torch.int32)
101
+ cross_max_seqlen_q = max(original_context_length_list)
102
+ else:
103
+ cross_cu_seqlens_q = [0]
104
+ for _ in range(batch_size):
105
+ for length in original_context_length_list:
106
+ cross_cu_seqlens_q.append(cross_cu_seqlens_q[-1] + length + history_context_length)
107
+ cross_cu_seqlens_q = torch.tensor(cross_cu_seqlens_q, device=device, dtype=torch.int32)
108
+ cross_cu_seqlens_q[0] = 0
109
+ cross_max_seqlen_q = max(original_context_length_list) + history_context_length
110
+
111
+ cu_seqlens_kv = [0]
112
+ for _ in range(batch_size):
113
+ for length in original_context_length_list:
114
+ cu_seqlens_kv.append(cu_seqlens_kv[-1] + encoder_hidden_states_seq_len)
115
+ cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
116
+ max_seqlen_kv = encoder_hidden_states_seq_len
117
+ navit_encoder_attention_mask = cross_cu_seqlens_q, cu_seqlens_kv, cross_max_seqlen_q, max_seqlen_kv
118
+
119
+ return navit_hidden_attention_mask, navit_encoder_attention_mask, navit_history_hidden_attention_mask
120
+
121
+
122
+ @torch.compiler.disable
123
+ def _flash_attn_wrapper(q, k, v):
124
+ return flash_attn_func(q, k, v)
125
+
126
+
127
+ @torch.compiler.disable
128
+ def _flash_attn_varlen_wrapper(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv):
129
+ return flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)
130
+
131
+
132
+ def attn_varlen_func(q, k, v, attention_mask=None):
133
+ if attention_mask is None:
134
+ if flash_attn_func is not None:
135
+ x = _flash_attn_wrapper(q, k, v)
136
+ return x
137
+
138
+ if sageattn is not None:
139
+ x = sageattn(q, k, v, tensor_layout="NHD")
140
+ return x
141
+
142
+ if xformers_attn_func is not None:
143
+ x = xformers_attn_func(q, k, v)
144
+ return x
145
+
146
+ x = torch.nn.functional.scaled_dot_product_attention(
147
+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
148
+ ).transpose(1, 2)
149
+ return x
150
+
151
+ B, L, H, C = q.shape
152
+
153
+ q = q.flatten(0, 1)
154
+ k = k.flatten(0, 1)
155
+ v = v.flatten(0, 1)
156
+
157
+ cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv = attention_mask
158
+ if flash_attn_varlen_func is not None:
159
+ x = _flash_attn_varlen_wrapper(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)
160
+ elif sageattn_varlen is not None:
161
+ x = sageattn_varlen(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)
162
+ else:
163
+ raise NotImplementedError("No Attn Installed!")
164
+
165
+ x = x.unflatten(0, (B, L))
166
+
167
+ return x
Helios-main/helios/modules/helios_kernels/tiled_linear.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import math
3
+ from typing import Callable, List, Optional
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU, LinearActivation, SwiGLU
9
+ from diffusers.utils import deprecate
10
+
11
+
12
+ # ------------------------------- replace funtion -------------------------------
13
+
14
+
15
+ def replace_linear_with_tiled_linear(model, num_shards=None, patch_by_names=True, patch_by_types=True):
16
+ target_names = ["to_q", "to_k", "to_v", "add_k_proj", "add_v_proj"]
17
+ target_types = ["FeedForward"]
18
+
19
+ patched_count = 0
20
+
21
+ def tiled_forward(self, x):
22
+ compute_params = list(self.parameters())
23
+ return apply_tiled_linear(
24
+ fn=lambda module, input: module._original_forward(input),
25
+ mlp_module=self,
26
+ x=x,
27
+ num_shards=num_shards,
28
+ compute_params=compute_params,
29
+ )
30
+
31
+ for name, module in model.named_modules():
32
+ layer_name = name.rsplit(".", 1)[-1] if "." in name else name
33
+ module_type = type(module).__name__
34
+
35
+ should_patch = False
36
+ if patch_by_types and module_type in target_types:
37
+ should_patch = True
38
+ if patch_by_names and layer_name in target_names and isinstance(module, torch.nn.Linear):
39
+ should_patch = True
40
+
41
+ if should_patch:
42
+ module._original_forward = module.forward
43
+ module.forward = tiled_forward.__get__(module, module.__class__)
44
+ patched_count += 1
45
+ # print(f" Patched {module_type}: {name}")
46
+
47
+ print(f"Patched {patched_count} FeedForward modules with TiledMLP\n")
48
+ return model
49
+
50
+
51
+ # ------------------------------- Tiled MLP -------------------------------
52
+
53
+
54
+ def ensure_contiguous(fn):
55
+ @functools.wraps(fn)
56
+ def wrapper(ctx, *args, **kwargs):
57
+ def maybe_to_contiguous(x):
58
+ return x.contiguous() if isinstance(x, torch.Tensor) else x
59
+
60
+ args = [maybe_to_contiguous(arg) for arg in args]
61
+ kwargs = {k: maybe_to_contiguous(v) for k, v in kwargs.items()}
62
+ return fn(ctx, *args, **kwargs)
63
+
64
+ return wrapper
65
+
66
+
67
+ class TiledLinear(torch.autograd.Function):
68
+ """
69
+ Based on DeepSpeed's TiledMLP:
70
+ https://github.com/deepspeedai/DeepSpeed/blob/v0.18.2/deepspeed/runtime/sequence_parallel/ulysses_sp.py#L838
71
+
72
+ Perform a tiled MLP computation to massively reduce memory usage needed to compute MLP
73
+ when using very long sequence lengths.
74
+
75
+ This module re-computes `forward` in the `backward`. So the `forward` occurs twice each iteration.
76
+ And if you're using activation checkpointing it then occurs thrice.
77
+
78
+ Args:
79
+ fn: the function to call on sharded inputs (e.g., mlp.forward)
80
+ mlp_module: the MLP nn.Module object
81
+ x: the input to MLP.forward (hidden_states)
82
+ shards: how many shards to use
83
+ compute_params: a list of weights engaged in the compute
84
+
85
+ Returns:
86
+ the computed hidden_states
87
+ """
88
+
89
+ @staticmethod
90
+ @ensure_contiguous
91
+ def forward(
92
+ ctx,
93
+ fn: Callable,
94
+ mlp_module: torch.nn.Module,
95
+ x: torch.Tensor,
96
+ shards: int,
97
+ compute_params: Optional[List[torch.nn.Parameter]] = None,
98
+ ) -> torch.Tensor:
99
+ ctx.fn = fn
100
+ ctx.mlp_module = mlp_module
101
+ ctx.shards = shards
102
+ ctx.save_for_backward(x)
103
+
104
+ # x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts)
105
+ x_shards = list(torch.chunk(x, chunks=shards, dim=-2))
106
+ with torch.no_grad():
107
+ output_shards = [fn(mlp_module, x_shard) for x_shard in x_shards]
108
+ output_unsharded = torch.cat(output_shards, dim=-2)
109
+
110
+ return output_unsharded
111
+
112
+ @staticmethod
113
+ @ensure_contiguous
114
+ def backward(ctx, *grads) -> tuple:
115
+ fn = ctx.fn
116
+ (x,) = ctx.saved_tensors
117
+ mlp_module = ctx.mlp_module
118
+ shards = ctx.shards
119
+
120
+ x_requires_grad = x.requires_grad
121
+ x = x.detach()
122
+ # detach() unsets x.requires_grad, so restore it
123
+ x.requires_grad_(x_requires_grad)
124
+
125
+ # x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts)
126
+ hidden_size = x.shape[-1]
127
+ x_shape_orig = x.shape
128
+
129
+ # flatten bs+seqlen to avoid having stride issues when narrowing into seqlen w/ bs>1
130
+ x = x.view(-1, hidden_size)
131
+ incoming_grad = grads[0].view(-1, hidden_size)
132
+ x_grad = torch.zeros_like(x)
133
+
134
+ x_shards = list(torch.chunk(x, chunks=shards, dim=0))
135
+
136
+ trainable_params = [p for p in mlp_module.parameters() if p.requires_grad]
137
+
138
+ for i, x_shard in enumerate(x_shards):
139
+ x_shard = x_shard.detach().requires_grad_(x_requires_grad)
140
+
141
+ shard_step = x_shards[i].shape[0]
142
+ shard_offset = i * x_shards[0].shape[0]
143
+
144
+ incoming_grad_shard = incoming_grad.narrow(0, shard_offset, shard_step).view_as(x_shard)
145
+
146
+ with torch.enable_grad():
147
+ output = fn(mlp_module, x_shard)
148
+
149
+ grads_tuple = torch.autograd.grad(
150
+ outputs=output,
151
+ inputs=[x_shard] + trainable_params,
152
+ grad_outputs=incoming_grad_shard,
153
+ allow_unused=True,
154
+ retain_graph=False,
155
+ )
156
+
157
+ x_grad.narrow(0, shard_offset, shard_step).copy_(grads_tuple[0])
158
+
159
+ for param, grad in zip(trainable_params, grads_tuple[1:]):
160
+ if grad is not None:
161
+ if param.grad is None:
162
+ param.grad = grad
163
+ else:
164
+ param.grad.add_(grad)
165
+
166
+ # unflatten
167
+ x_grad = x_grad.view(x_shape_orig)
168
+
169
+ return (None, None, x_grad, None, None)
170
+
171
+
172
+ def apply_tiled_linear(
173
+ fn: Callable,
174
+ mlp_module: torch.nn.Module,
175
+ x: torch.Tensor,
176
+ num_shards: Optional[int] = None,
177
+ compute_params: Optional[List[torch.nn.Parameter]] = None,
178
+ ) -> torch.Tensor:
179
+ """
180
+ Apply tiled MLP computation for memory efficiency.
181
+
182
+ Args:
183
+ fn: the function to call on sharded inputs (e.g., lambda module, x: module(x))
184
+ mlp_module: the MLP nn.Module object
185
+ x: the input tensor with shape [bs, seqlen, hidden_size] or [seqlen, hidden_size]
186
+ num_shards: number of shards to use. If None, automatically calculated as ceil(seqlen / hidden_size)
187
+ compute_params: list of parameters for DeepSpeed ZeRO optimization
188
+
189
+ Returns:
190
+ output tensor with the same shape as input
191
+ """
192
+ if num_shards is None:
193
+ # x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size]
194
+ hidden_size = x.shape[-1]
195
+ seqlen = x.shape[-2]
196
+ num_shards = math.ceil(seqlen / hidden_size)
197
+
198
+ # Ensure num_shards is at least 1
199
+ num_shards = max(1, num_shards)
200
+
201
+ return TiledLinear.apply(
202
+ fn,
203
+ mlp_module,
204
+ x,
205
+ num_shards,
206
+ compute_params,
207
+ )
208
+
209
+
210
+ # ------------------------------- Tiled FeedForward -------------------------------
211
+ class FeedForward(nn.Module):
212
+ r"""
213
+ A feed-forward layer.
214
+
215
+ Parameters:
216
+ dim (`int`): The number of channels in the input.
217
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
218
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
219
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
220
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
221
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
222
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
223
+ """
224
+
225
+ def __init__(
226
+ self,
227
+ dim: int,
228
+ dim_out: Optional[int] = None,
229
+ mult: int = 4,
230
+ dropout: float = 0.0,
231
+ activation_fn: str = "geglu",
232
+ final_dropout: bool = False,
233
+ inner_dim=None,
234
+ bias: bool = True,
235
+ ):
236
+ super().__init__()
237
+ if inner_dim is None:
238
+ inner_dim = int(dim * mult)
239
+ dim_out = dim_out if dim_out is not None else dim
240
+
241
+ if activation_fn == "gelu":
242
+ act_fn = GELU(dim, inner_dim, bias=bias)
243
+ if activation_fn == "gelu-approximate":
244
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
245
+ elif activation_fn == "geglu":
246
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
247
+ elif activation_fn == "geglu-approximate":
248
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
249
+ elif activation_fn == "swiglu":
250
+ act_fn = SwiGLU(dim, inner_dim, bias=bias)
251
+ elif activation_fn == "linear-silu":
252
+ act_fn = LinearActivation(dim, inner_dim, bias=bias, activation="silu")
253
+
254
+ self.net = nn.ModuleList([])
255
+ # project in
256
+ self.net.append(act_fn)
257
+ # project dropout
258
+ self.net.append(nn.Dropout(dropout))
259
+ # project out
260
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
261
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
262
+ if final_dropout:
263
+ self.net.append(nn.Dropout(dropout))
264
+
265
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
266
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
267
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
268
+ deprecate("scale", "1.0.0", deprecation_message)
269
+ for module in self.net:
270
+ hidden_states = module(hidden_states)
271
+ return hidden_states
272
+
273
+
274
+ class TiledFeedForward(nn.Module):
275
+ """
276
+ Memory-efficient FeedForward using tiled computation (diffusers compatible)
277
+ Args:
278
+ dim: Input dimension
279
+ dim_out: Output dimension (default: dim)
280
+ mult: Multiplier for inner dimension (default: 4)
281
+ dropout: Dropout probability
282
+ activation_fn: Activation function ('geglu', 'gelu', 'gelu-approximate')
283
+ final_dropout: Apply dropout at the end
284
+ inner_dim: Inner dimension (overrides mult if provided)
285
+ bias: Use bias in linear layers
286
+ num_shards: Number of shards for tiling (None = auto)
287
+ """
288
+
289
+ def __init__(
290
+ self,
291
+ dim: int,
292
+ dim_out: Optional[int] = None,
293
+ mult: int = 4,
294
+ dropout: float = 0.0,
295
+ activation_fn: str = "geglu",
296
+ final_dropout: bool = False,
297
+ inner_dim: Optional[int] = None,
298
+ bias: bool = True,
299
+ num_shards: Optional[int] = None,
300
+ ):
301
+ super().__init__()
302
+
303
+ # Calculate dimensions
304
+ if inner_dim is None:
305
+ inner_dim = int(dim * mult)
306
+ dim_out = dim_out if dim_out is not None else dim
307
+
308
+ self.dim = dim
309
+ self.inner_dim = inner_dim
310
+ self.dim_out = dim_out
311
+ self.activation_fn = activation_fn
312
+ self.num_shards = num_shards
313
+
314
+ if activation_fn == "gelu":
315
+ act_fn = GELU(dim, inner_dim, bias=bias)
316
+ if activation_fn == "gelu-approximate":
317
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
318
+ elif activation_fn == "geglu":
319
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
320
+ elif activation_fn == "geglu-approximate":
321
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
322
+ elif activation_fn == "swiglu":
323
+ act_fn = SwiGLU(dim, inner_dim, bias=bias)
324
+ elif activation_fn == "linear-silu":
325
+ act_fn = LinearActivation(dim, inner_dim, bias=bias, activation="silu")
326
+
327
+ self.net = nn.ModuleList([])
328
+ # project in
329
+ self.net.append(act_fn)
330
+ # project dropout
331
+ self.net.append(nn.Dropout(dropout))
332
+ # project out
333
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
334
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
335
+ if final_dropout:
336
+ self.net.append(nn.Dropout(dropout))
337
+
338
+ def _mlp_forward(self, module, x):
339
+ """Internal MLP forward for tiled computation"""
340
+ for layer in module.net:
341
+ x = layer(x)
342
+ return x
343
+
344
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
345
+ """
346
+ Forward pass with tiled computation
347
+ Args:
348
+ hidden_states: [batch_size, seq_len, dim] or [seq_len, dim]
349
+ Returns:
350
+ Output tensor with same shape as input (but last dim = dim_out)
351
+ """
352
+ # Collect compute parameters
353
+ compute_params = list(self.parameters())
354
+
355
+ return apply_tiled_linear(
356
+ fn=self._mlp_forward,
357
+ mlp_module=self,
358
+ x=hidden_states,
359
+ num_shards=self.num_shards,
360
+ compute_params=compute_params,
361
+ )
362
+
363
+
364
+ if __name__ == "__main__":
365
+ import torch
366
+ import torch.nn as nn
367
+
368
+ # 设置随机种子保证可重复性
369
+ torch.manual_seed(42)
370
+
371
+ # 创建测试输入
372
+ batch_size, seq_len, hidden_dim = 2, 1024, 768
373
+ x = torch.randn(batch_size, seq_len, hidden_dim, requires_grad=True)
374
+
375
+ # 方法1: replace
376
+ model1 = FeedForward(dim=hidden_dim)
377
+ # model1 = replace_linear_with_tiled_linear(model1, num_shards=4)
378
+ out1 = model1(x)
379
+ loss1 = out1.sum()
380
+ loss1.backward()
381
+ grad1 = x.grad.clone()
382
+
383
+ # 方法2: TiledFeedForward
384
+ x.grad = None
385
+ # model2 = TiledFeedForward(dim=hidden_dim, num_shards=4)
386
+ model2 = FeedForward(dim=hidden_dim)
387
+ model2 = replace_linear_with_tiled_linear(model2, num_shards=4)
388
+ # 复制权重确保完全一致
389
+ model2.load_state_dict(model1.state_dict(), strict=True)
390
+ out2 = model2(x)
391
+ loss2 = out2.sum()
392
+ loss2.backward()
393
+ grad2 = x.grad.clone()
394
+
395
+ # 比较结果
396
+ print(f"Output diff: {(out1 - out2).abs().max().item()}")
397
+ print(f"Gradient diff: {(grad1 - grad2).abs().max().item()}")
398
+ print(f"Output allclose: {torch.allclose(out1, out2, atol=1e-6)}")
399
+ print(f"Gradient allclose: {torch.allclose(grad1, grad2, atol=1e-6)}")
Helios-main/helios/modules/helios_kernels/triton_norm.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import triton
3
+ import triton.language as tl
4
+
5
+ from diffusers.models.normalization import FP32LayerNorm, LayerNorm, RMSNorm
6
+
7
+ from .fp32_rmsnorm import FP32RMSNorm
8
+ from .utils import calculate_settings, torch_gpu_device
9
+
10
+
11
+ # ------------------------------- replace funtion -------------------------------
12
+
13
+
14
+ def replace_all_norms_with_flash_norms(model):
15
+ patched_count = {"LayerNorm": 0, "RMSNorm": 0}
16
+
17
+ for name, module in model.named_modules():
18
+ if isinstance(module, (LayerNorm, FP32LayerNorm)):
19
+ if hasattr(module, "elementwise_affine") and module.elementwise_affine:
20
+ module.forward = (lambda self, x: flash_layernorm(self, x)).__get__(module, module.__class__)
21
+ patched_count["LayerNorm"] += 1
22
+
23
+ if isinstance(module, (torch.nn.RMSNorm, RMSNorm, FP32RMSNorm)):
24
+ module.forward = (lambda self, x: flash_rms_layernorm(self, x)).__get__(module, module.__class__)
25
+ patched_count["RMSNorm"] += 1
26
+
27
+ print(f"Patched {patched_count['LayerNorm']} Flash_LayerNorm modules\n")
28
+ print(f"Patched {patched_count['RMSNorm']} Flash_RMSNorm modules\n")
29
+
30
+ return model
31
+
32
+
33
+ # ------------------------------- layer norm -------------------------------
34
+
35
+
36
+ @triton.jit
37
+ def layernorm_forward(
38
+ Y,
39
+ Y_row_stride,
40
+ X,
41
+ X_row_stride,
42
+ W,
43
+ b,
44
+ r,
45
+ mu,
46
+ n_cols: tl.constexpr,
47
+ eps: tl.constexpr,
48
+ BLOCK_SIZE: tl.constexpr,
49
+ ):
50
+ row_idx = tl.program_id(0)
51
+ col_offsets = tl.arange(0, BLOCK_SIZE)
52
+ mask = col_offsets < n_cols
53
+
54
+ Y += row_idx * Y_row_stride
55
+ X += row_idx * X_row_stride
56
+ r += row_idx
57
+ mu += row_idx
58
+
59
+ # According to https://pytorch.org/torchtune/stable/_modules/torchtune/modules/layer_norm.html#Fp32LayerNorm, all modules
60
+ # are in float32!
61
+ X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
62
+ W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
63
+ b_row = tl.load(b + col_offsets, mask=mask, other=0).to(tl.float32)
64
+
65
+ mean_X = tl.sum(X_row, axis=0) / n_cols
66
+ # (X[0] - mean) == -mean so we need to mask it out
67
+ XX = tl.where(mask, X_row - mean_X, 0)
68
+ row_var = tl.sum(XX * XX, axis=0) / n_cols
69
+ inv_var = tl.math.rsqrt(row_var + eps)
70
+ tl.store(r, inv_var)
71
+ tl.store(mu, mean_X)
72
+ output = (XX * inv_var) * W_row + b_row
73
+ tl.store(Y + col_offsets, output, mask=mask)
74
+
75
+
76
+ @triton.jit
77
+ def layernorm_backward(
78
+ dY,
79
+ dY_row_stride,
80
+ X,
81
+ X_row_stride,
82
+ W,
83
+ b,
84
+ r,
85
+ mu,
86
+ n_cols: tl.constexpr,
87
+ eps: tl.constexpr,
88
+ BLOCK_SIZE: tl.constexpr,
89
+ ):
90
+ # Approximately follows https://github.com/karpathy/llm.c/blob/master/doc/layernorm/layernorm.md
91
+ row_idx = tl.program_id(0)
92
+ col_offsets = tl.arange(0, BLOCK_SIZE)
93
+ mask = col_offsets < n_cols
94
+
95
+ dY += row_idx * dY_row_stride
96
+ X += row_idx * X_row_stride
97
+ r += row_idx
98
+ mu += row_idx
99
+
100
+ # According to https://pytorch.org/torchtune/stable/_modules/torchtune/modules/layer_norm.html#Fp32LayerNorm, all modules
101
+ # are in float32!
102
+ dY_row = tl.load(dY + col_offsets, mask=mask, other=0).to(tl.float32)
103
+ X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
104
+ W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
105
+ # b_row = tl.load(b + col_offsets, mask = mask, other = 0).to(tl.float32)
106
+
107
+ inv_var = tl.load(r).to(tl.float32)
108
+ mean = tl.load(mu).to(tl.float32)
109
+ normed = (X_row - mean) * inv_var
110
+ dY_W = dY_row * W_row
111
+ dX_row = dY_W - tl.sum(dY_W, axis=0) / n_cols - normed * tl.sum(dY_W * normed, axis=0) / n_cols
112
+ dX_row = dX_row * inv_var
113
+ tl.store(dY + col_offsets, dX_row, mask=mask)
114
+
115
+
116
+ class Flash_Layernorm(torch.autograd.Function):
117
+ @staticmethod
118
+ def forward(ctx, X, W, b, eps):
119
+ shape = X.shape
120
+ dim = shape[-1]
121
+ X = X.view(-1, dim)
122
+ n_rows, n_cols = X.shape
123
+ BLOCK_SIZE, num_warps = calculate_settings(n_cols)
124
+ device = X.device
125
+ Y = torch.empty((n_rows, n_cols), dtype=X.dtype, device=device)
126
+ r = torch.empty(n_rows, dtype=torch.float32, device=device)
127
+ mu = torch.empty(n_rows, dtype=torch.float32, device=device)
128
+
129
+ with torch_gpu_device(device):
130
+ layernorm_forward[(n_rows,)](
131
+ Y,
132
+ Y.stride(0),
133
+ X,
134
+ X.stride(0),
135
+ W,
136
+ b,
137
+ r,
138
+ mu,
139
+ n_cols,
140
+ eps,
141
+ BLOCK_SIZE=BLOCK_SIZE,
142
+ num_warps=num_warps,
143
+ )
144
+ ctx.eps = eps
145
+ ctx.BLOCK_SIZE = BLOCK_SIZE
146
+ ctx.num_warps = num_warps
147
+ ctx.save_for_backward(X, W, b, r, mu)
148
+ return Y.view(*shape)
149
+
150
+ @staticmethod
151
+ def backward(ctx, dY):
152
+ shape = dY.shape
153
+ dim = shape[-1]
154
+ dY = dY.view(-1, dim)
155
+ X, W, b, r, mu = ctx.saved_tensors
156
+ n_rows, n_cols = dY.shape
157
+
158
+ with torch_gpu_device(dY.device):
159
+ layernorm_backward[(n_rows,)](
160
+ dY,
161
+ dY.stride(0),
162
+ X,
163
+ X.stride(0),
164
+ W,
165
+ b,
166
+ r,
167
+ mu,
168
+ n_cols,
169
+ ctx.eps,
170
+ BLOCK_SIZE=ctx.BLOCK_SIZE,
171
+ num_warps=ctx.num_warps,
172
+ )
173
+ dX = dY.view(*shape)
174
+ return dX, None, None, None, None
175
+
176
+
177
+ def flash_layernorm(layernorm, X):
178
+ assert layernorm.elementwise_affine is True
179
+ W = layernorm.weight
180
+ bias = layernorm.bias
181
+ eps = layernorm.variance_epsilon if hasattr(layernorm, "variance_epsilon") else layernorm.eps
182
+ out = Flash_Layernorm.apply(X, W, bias, eps)
183
+ return out
184
+
185
+
186
+ # ------------------------------- layer norm -------------------------------
187
+
188
+
189
+ # ------------------------------- rms norm -------------------------------
190
+
191
+
192
+ @triton.jit
193
+ def _rms_layernorm_forward(
194
+ Y,
195
+ Y_row_stride: tl.constexpr,
196
+ X,
197
+ X_row_stride: tl.constexpr,
198
+ W,
199
+ W_row_stride: tl.constexpr,
200
+ r,
201
+ r_row_stride: tl.constexpr,
202
+ n_cols: tl.constexpr,
203
+ eps: tl.constexpr,
204
+ BLOCK_SIZE: tl.constexpr,
205
+ ):
206
+ """
207
+ Flash RMS Layernorm kernel
208
+ Inspiration from a Triton tutorial:
209
+ https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
210
+ """
211
+ row_idx = tl.program_id(0)
212
+ col_offsets = tl.arange(0, BLOCK_SIZE)
213
+ mask = col_offsets < n_cols
214
+
215
+ Y += row_idx * Y_row_stride
216
+ X += row_idx * X_row_stride
217
+ r += row_idx * r_row_stride
218
+
219
+ X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
220
+ W_row = tl.load(W + col_offsets, mask=mask, other=0) # .to(tl.float32)
221
+
222
+ row_var = tl.sum(X_row * X_row, axis=0) / n_cols
223
+ inv_var = tl.math.rsqrt(row_var + eps)
224
+ tl.store(r, inv_var)
225
+ normed = X_row * inv_var
226
+ normed = normed.to(W_row.dtype) # Exact copy from HF
227
+ output = normed * W_row
228
+ tl.store(Y + col_offsets, output, mask=mask)
229
+
230
+
231
+ def _rms_layernorm_backward(
232
+ dY,
233
+ dY_row_stride: tl.constexpr,
234
+ dX,
235
+ dX_row_stride: tl.constexpr,
236
+ X,
237
+ X_row_stride: tl.constexpr,
238
+ W,
239
+ W_row_stride: tl.constexpr,
240
+ r,
241
+ r_row_stride: tl.constexpr,
242
+ # dW, dW_row_stride,
243
+ n_cols: tl.constexpr,
244
+ eps: tl.constexpr,
245
+ GEMMA: tl.constexpr,
246
+ BLOCK_SIZE: tl.constexpr,
247
+ ):
248
+ """
249
+ Flash RMS Layernorm kernel for the backward pass
250
+ Inspiration from a Triton tutorial:
251
+ https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
252
+ """
253
+ row_idx = tl.program_id(0)
254
+ col_offsets = tl.arange(0, BLOCK_SIZE)
255
+ mask = col_offsets < n_cols
256
+
257
+ dY += row_idx * dY_row_stride
258
+ X += row_idx * X_row_stride
259
+ r += row_idx * r_row_stride
260
+
261
+ if GEMMA:
262
+ dX += row_idx * dY_row_stride
263
+ else:
264
+ dX = dY
265
+
266
+ dY_row = tl.load(dY + col_offsets, mask=mask, other=0).to(tl.float32)
267
+ X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
268
+ W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
269
+
270
+ # Get saved row variance
271
+ inv_var = tl.load(r).to(tl.float32)
272
+ normed = X_row * inv_var
273
+
274
+ if GEMMA:
275
+ dY_W = dY_row * (W_row + 1.0)
276
+ else:
277
+ dY_W = dY_row * W_row
278
+
279
+ rowsum_dY_normed = tl.sum(dY_W * normed, axis=0)
280
+ output = inv_var / n_cols * (n_cols * dY_W - normed * rowsum_dY_normed)
281
+ tl.store(dX + col_offsets, output, mask=mask)
282
+
283
+
284
+ _rms_layernorm_backward = triton.jit(_rms_layernorm_backward)
285
+ _rms_layernorm_backward = triton.heuristics(
286
+ {
287
+ "GEMMA": lambda args: bool(args["GEMMA"]),
288
+ }
289
+ )(_rms_layernorm_backward)
290
+
291
+
292
+ @triton.jit
293
+ def _gemma_rms_layernorm_forward(
294
+ Y,
295
+ Y_row_stride: tl.constexpr,
296
+ X,
297
+ X_row_stride: tl.constexpr,
298
+ W,
299
+ W_row_stride: tl.constexpr,
300
+ r,
301
+ r_row_stride: tl.constexpr,
302
+ n_cols: tl.constexpr,
303
+ eps: tl.constexpr,
304
+ BLOCK_SIZE: tl.constexpr,
305
+ ):
306
+ # Copies https://github.com/google-deepmind/gemma/blob/main/gemma/layers.py#L31
307
+ # and https://github.com/keras-team/keras-nlp/blob/v0.8.2/keras_nlp/models/gemma/rms_normalization.py#L33
308
+ # exactly. Essentially all in float32!
309
+ row_idx = tl.program_id(0)
310
+ col_offsets = tl.arange(0, BLOCK_SIZE)
311
+ mask = col_offsets < n_cols
312
+
313
+ Y += row_idx * Y_row_stride
314
+ X += row_idx * X_row_stride
315
+ r += row_idx * r_row_stride
316
+
317
+ X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
318
+ W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
319
+
320
+ row_var = tl.sum(X_row * X_row, axis=0) / n_cols
321
+ inv_var = tl.math.rsqrt(row_var + eps)
322
+ tl.store(r, inv_var)
323
+ normed = X_row * inv_var
324
+ output = normed * (W_row + 1.0)
325
+
326
+ tl.store(Y + col_offsets, output, mask=mask)
327
+
328
+
329
+ class Flash_RMS_Layernorm(torch.autograd.Function):
330
+ @staticmethod
331
+ def forward(ctx, X: torch.Tensor, W: torch.Tensor, eps: float, gemma: bool = False):
332
+ shape = X.shape
333
+ dim: int = shape[-1]
334
+ X = X.reshape(-1, dim)
335
+ n_rows: int
336
+ n_cols: int
337
+ n_rows, n_cols = X.shape
338
+ BLOCK_SIZE: int
339
+ num_warps: int
340
+ BLOCK_SIZE, num_warps = calculate_settings(n_cols)
341
+ device = X.device
342
+
343
+ Y = torch.empty((n_rows, n_cols), dtype=X.dtype, device=device)
344
+ r = torch.empty(n_rows, dtype=torch.float32, device=device)
345
+
346
+ fx = _gemma_rms_layernorm_forward if gemma else _rms_layernorm_forward
347
+ with torch_gpu_device(device):
348
+ fx[(n_rows,)](
349
+ Y,
350
+ Y.stride(0),
351
+ X,
352
+ X.stride(0),
353
+ W,
354
+ W.stride(0),
355
+ r,
356
+ r.stride(0),
357
+ n_cols,
358
+ eps,
359
+ BLOCK_SIZE=BLOCK_SIZE,
360
+ num_warps=num_warps,
361
+ )
362
+ ctx.eps = eps
363
+ ctx.BLOCK_SIZE = BLOCK_SIZE
364
+ ctx.num_warps = num_warps
365
+ ctx.GEMMA = gemma
366
+ ctx.save_for_backward(X, W, r)
367
+ return Y.view(*shape)
368
+
369
+ @staticmethod
370
+ def backward(ctx, dY: torch.Tensor):
371
+ shape = dY.shape
372
+ dim: int = shape[-1]
373
+ dY = dY.reshape(-1, dim)
374
+ X, W, r = ctx.saved_tensors
375
+ n_rows: int
376
+ n_cols: int
377
+ n_rows, n_cols = dY.shape
378
+ # dW = X
379
+ dX = torch.empty_like(dY) if ctx.GEMMA else dY
380
+
381
+ with torch_gpu_device(dY.device):
382
+ _rms_layernorm_backward[(n_rows,)](
383
+ dY,
384
+ dY.stride(0),
385
+ dX,
386
+ dX.stride(0),
387
+ X,
388
+ X.stride(0),
389
+ W,
390
+ W.stride(0),
391
+ r,
392
+ r.stride(0),
393
+ # dW, dW.stride(0),
394
+ n_cols,
395
+ ctx.eps,
396
+ GEMMA=ctx.GEMMA,
397
+ BLOCK_SIZE=ctx.BLOCK_SIZE,
398
+ num_warps=ctx.num_warps,
399
+ )
400
+ dX = dX.view(*shape)
401
+ return dX, None, None, None
402
+
403
+
404
+ # [TODO] Unsure why RMS Layernorm is not torch.compiling properly
405
+ @torch.compiler.disable
406
+ def flash_rms_layernorm(layernorm, X: torch.Tensor, gemma: bool = False):
407
+ W: torch.Tensor = layernorm.weight
408
+ eps: float = layernorm.variance_epsilon if hasattr(layernorm, "variance_epsilon") else layernorm.eps
409
+ out = Flash_RMS_Layernorm.apply(X, W, eps, gemma)
410
+ return out
411
+
412
+
413
+ # ------------------------------- rms norm -------------------------------
Helios-main/helios/modules/helios_kernels/utils.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import nullcontext
2
+
3
+ import torch
4
+ import triton
5
+
6
+
7
+ def get_device_type():
8
+ if torch.cuda.is_available():
9
+ try:
10
+ if torch.version.hip is not None:
11
+ return "hip"
12
+ except AttributeError:
13
+ pass
14
+ return "cuda"
15
+
16
+ try:
17
+ if hasattr(torch, "xpu") and torch.xpu.is_available():
18
+ return "xpu"
19
+ except (AttributeError, RuntimeError):
20
+ pass
21
+
22
+ return "cpu"
23
+
24
+
25
+ def get_device_count(device_type):
26
+ if device_type == "cuda" or device_type == "hip":
27
+ return torch.cuda.device_count()
28
+ elif device_type == "xpu":
29
+ try:
30
+ return torch.xpu.device_count()
31
+ except (AttributeError, RuntimeError):
32
+ return 0
33
+ return 0
34
+
35
+
36
+ MAX_FUSED_SIZE: int = 65536
37
+ next_power_of_2 = triton.next_power_of_2
38
+ DEVICE_TYPE = get_device_type()
39
+ DEVICE_COUNT = get_device_count(DEVICE_TYPE)
40
+
41
+ if DEVICE_COUNT > 1:
42
+ if DEVICE_TYPE in ("cuda", "hip"):
43
+ torch_gpu_device = torch.cuda.device
44
+ elif DEVICE_TYPE == "xpu":
45
+ torch_gpu_device = torch.xpu.device
46
+ else:
47
+
48
+ def torch_gpu_device(device):
49
+ return nullcontext()
50
+
51
+
52
+ def calculate_settings(
53
+ n: int,
54
+ ) -> (
55
+ int,
56
+ int,
57
+ ):
58
+ BLOCK_SIZE: int = next_power_of_2(n)
59
+ if BLOCK_SIZE > MAX_FUSED_SIZE:
60
+ raise RuntimeError(
61
+ f"Cannot launch Triton kernel since n = {n} exceeds the maximum CUDA blocksize = {MAX_FUSED_SIZE}."
62
+ )
63
+ num_warps: int = 4
64
+ if BLOCK_SIZE >= 32768:
65
+ num_warps = 32
66
+ elif BLOCK_SIZE >= 8192:
67
+ num_warps = 16
68
+ elif BLOCK_SIZE >= 2048:
69
+ num_warps = 8
70
+ return BLOCK_SIZE, num_warps
Helios-main/scripts/accelerate_configs/multi_node_example_zero2.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ distributed_type: DEEPSPEED
3
+ deepspeed_config:
4
+ deepspeed_config_file: scripts/accelerate_configs/zero2.json
5
+ deepspeed_multinode_launcher: standard
6
+ fsdp_config: {}
7
+ machine_rank: 0
8
+ main_training_function: main
9
+ rdzv_backend: static
10
+ same_network: true
11
+ tpu_env: []
12
+ tpu_use_cluster: false
13
+ tpu_use_sudo: false
14
+ use_cpu: false
Helios-main/scripts/accelerate_configs/multi_node_example_zero3.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ distributed_type: DEEPSPEED
3
+ deepspeed_config:
4
+ deepspeed_config_file: scripts/accelerate_configs/zero3.json
5
+ deepspeed_multinode_launcher: standard
6
+ fsdp_config: {}
7
+ machine_rank: 0
8
+ main_training_function: main
9
+ rdzv_backend: static
10
+ same_network: true
11
+ tpu_env: []
12
+ tpu_use_cluster: false
13
+ tpu_use_sudo: false
14
+ use_cpu: false
Helios-main/scripts/accelerate_configs/scheduler_config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UniPCMultistepScheduler",
3
+ "_diffusers_version": "0.33.0.dev0",
4
+ "beta_end": 0.02,
5
+ "beta_schedule": "linear",
6
+ "beta_start": 0.0001,
7
+ "disable_corrector": [],
8
+ "dynamic_thresholding_ratio": 0.995,
9
+ "final_sigmas_type": "zero",
10
+ "flow_shift": 3.0,
11
+ "lower_order_final": true,
12
+ "num_train_timesteps": 1000,
13
+ "predict_x0": true,
14
+ "prediction_type": "flow_prediction",
15
+ "rescale_betas_zero_snr": false,
16
+ "sample_max_value": 1.0,
17
+ "solver_order": 2,
18
+ "solver_p": null,
19
+ "solver_type": "bh2",
20
+ "steps_offset": 0,
21
+ "thresholding": false,
22
+ "timestep_spacing": "linspace",
23
+ "trained_betas": null,
24
+ "use_beta_sigmas": false,
25
+ "use_exponential_sigmas": false,
26
+ "use_flow_sigmas": true,
27
+ "use_karras_sigmas": false
28
+ }
Helios-main/scripts/accelerate_configs/zero2.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": false,
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "communication_data_type": "fp32",
14
+ "gradient_clipping": 1.0,
15
+ "train_micro_batch_size_per_gpu": "auto",
16
+ "train_batch_size": "auto",
17
+ "gradient_accumulation_steps": "auto",
18
+ "zero_optimization": {
19
+ "stage": 2,
20
+ "overlap_comm": true,
21
+ "contiguous_gradients": true,
22
+ "reduce_bucket_size": 1e9,
23
+ "allgather_bucket_size": 536870912
24
+ }
25
+ }
Helios-main/scripts/accelerate_configs/zero3.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": false,
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "communication_data_type": "fp32",
14
+ "gradient_clipping": 1.0,
15
+ "train_micro_batch_size_per_gpu": "auto",
16
+ "train_batch_size": "auto",
17
+ "gradient_accumulation_steps": "auto",
18
+ "zero_optimization": {
19
+ "stage": 3,
20
+ "overlap_comm": true,
21
+ "contiguous_gradients": true,
22
+ "stage3_gather_16bit_weights_on_model_save": true,
23
+ "sub_group_size": 536870912,
24
+ "reduce_bucket_size": 536870912,
25
+ "stage3_prefetch_bucket_size": 536870912,
26
+ "stage3_param_persistence_threshold": 524288,
27
+ "stage3_max_live_parameters": 536870912,
28
+ "stage3_max_reuse_distance": 536870912
29
+ }
30
+ }
Helios-main/scripts/training/train_ddp.sh ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ export WANDB_MODE="offline"
3
+ export WANDB_API_KEY=""
4
+ export TOKENIZERS_PARALLELISM=true
5
+
6
+ export OMNISTORE_LOAD_STRICT_MODE=0
7
+ export OMNISTORE_LOGGING_LEVEL=ERROR
8
+ #################################################################
9
+ ## Torch
10
+ #################################################################
11
+ export TOKENIZERS_PARALLELISM=false
12
+ export TORCH_LOGS="+dynamo,recompiles,graph_breaks"
13
+ export TORCHDYNAMO_VERBOSE=1
14
+ export TORCH_NCCL_ENABLE_MONITORING=1
15
+ export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9"
16
+ #################################################################
17
+
18
+
19
+ #################################################################
20
+ ## NCCL
21
+ #################################################################
22
+ export NCCL_IB_GID_INDEX=3
23
+ export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE
24
+ export NCCL_SOCKET_IFNAME=eth0
25
+ export NCCL_SOCKET_TIMEOUT=3600000
26
+
27
+ export NCCL_DEBUG=WARN # disable the verbose NCCL logs
28
+ export NCCL_P2P_DISABLE=0
29
+ export NCCL_IB_DISABLE=0 # was 1
30
+ export NCCL_SHM_DISABLE=0 # was 1
31
+ export NCCL_P2P_LEVEL=NVL
32
+
33
+ export NCCL_PXN_DISABLE=0
34
+ export NCCL_NET_GDR_LEVEL=2
35
+ export NCCL_IB_QPS_PER_CONNECTION=4
36
+ export NCCL_IB_TC=160
37
+ export NCCL_IB_TIMEOUT=22
38
+ #################################################################
39
+
40
+ # #################################################################
41
+ # ## DIST
42
+ # #################################################################
43
+ # MASTER_ADDR=$ARNOLD_WORKER_0_HOST
44
+ # ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
45
+ # export MASTER_PORT=${ports[0]}
46
+ # NNODES=$ARNOLD_WORKER_NUM
47
+ # NODE_RANK=$ARNOLD_ID
48
+ # GPUS_PER_NODE=$ARNOLD_WORKER_GPU
49
+ # # GPUS_PER_NODE=1
50
+ # # NNODES=1
51
+ # # NODE_RANK=0
52
+ # WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
53
+
54
+ # DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
55
+ # if [ ! -z $RDZV_BACKEND ]; then
56
+ # DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d"
57
+ # export NCCL_SHM_DISABLE=1
58
+ # fi
59
+
60
+ # echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m"
61
+
62
+ #################################################################
63
+ ## ACCELERATE CONFIG
64
+ #################################################################
65
+ MASTER_ADDR=$ARNOLD_WORKER_0_HOST
66
+ ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
67
+ export MASTER_PORT=${ports[0]}
68
+ NUM_MACHINES=$ARNOLD_WORKER_NUM
69
+ MACHINE_RANK=$ARNOLD_ID
70
+ NUM_PROCESSES_PER_MACHINE=$ARNOLD_WORKER_GPU
71
+
72
+ # export CUDA_VISIBLE_DEVICES=0
73
+ # NUM_PROCESSES_PER_MACHINE=1
74
+ # NUM_MACHINES=1
75
+ # MACHINE_RANK=0
76
+
77
+ ACCELERATE_ARGS="--num_machines $NUM_MACHINES --machine_rank $MACHINE_RANK --num_processes $((NUM_PROCESSES_PER_MACHINE*NUM_MACHINES)) --main_process_ip $MASTER_ADDR --main_process_port $MASTER_PORT"
78
+
79
+ echo -e "\033[31mACCELERATE_ARGS: ${ACCELERATE_ARGS}\033[0m"
80
+
81
+ accelerate launch \
82
+ $ACCELERATE_ARGS \
83
+ train_helios.py \
84
+ --config scripts/training/configs/stage_1_init.yaml \
85
+ 2>&1 | tee ./train.log
86
+
87
+ # accelerate launch \
88
+ # $ACCELERATE_ARGS \
89
+ # --config_file scripts/accelerate_configs/multi_node_example_zero2.yaml \
90
+ # train_helios.py \
91
+ # --config scripts/training/configs/stage_1_init.yaml \
92
+ # 2>&1 | tee ./train.log
Helios-main/scripts/training/train_deepspeed.sh ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ export WANDB_MODE="offline"
3
+ export WANDB_API_KEY=""
4
+ export TOKENIZERS_PARALLELISM=true
5
+
6
+ export OMNISTORE_LOAD_STRICT_MODE=0
7
+ export OMNISTORE_LOGGING_LEVEL=ERROR
8
+ #################################################################
9
+ ## Torch
10
+ #################################################################
11
+ export TOKENIZERS_PARALLELISM=false
12
+ export TORCH_LOGS="+dynamo,recompiles,graph_breaks"
13
+ export TORCHDYNAMO_VERBOSE=1
14
+ export TORCH_NCCL_ENABLE_MONITORING=1
15
+ export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9"
16
+ #################################################################
17
+
18
+
19
+ #################################################################
20
+ ## NCCL
21
+ #################################################################
22
+ export NCCL_IB_GID_INDEX=3
23
+ export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE
24
+ export NCCL_SOCKET_IFNAME=eth0
25
+ export NCCL_SOCKET_TIMEOUT=3600000
26
+
27
+ export NCCL_DEBUG=WARN # disable the verbose NCCL logs
28
+ export NCCL_P2P_DISABLE=0
29
+ export NCCL_IB_DISABLE=0 # was 1
30
+ export NCCL_SHM_DISABLE=0 # was 1
31
+ export NCCL_P2P_LEVEL=NVL
32
+
33
+ export NCCL_PXN_DISABLE=0
34
+ export NCCL_NET_GDR_LEVEL=2
35
+ export NCCL_IB_QPS_PER_CONNECTION=4
36
+ export NCCL_IB_TC=160
37
+ export NCCL_IB_TIMEOUT=22
38
+ #################################################################
39
+
40
+ # #################################################################
41
+ # ## DIST
42
+ # #################################################################
43
+ # MASTER_ADDR=$ARNOLD_WORKER_0_HOST
44
+ # ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
45
+ # export MASTER_PORT=${ports[0]}
46
+ # NNODES=$ARNOLD_WORKER_NUM
47
+ # NODE_RANK=$ARNOLD_ID
48
+ # GPUS_PER_NODE=$ARNOLD_WORKER_GPU
49
+ # # GPUS_PER_NODE=1
50
+ # # NNODES=1
51
+ # # NODE_RANK=0
52
+ # WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
53
+
54
+ # DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
55
+ # if [ ! -z $RDZV_BACKEND ]; then
56
+ # DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d"
57
+ # export NCCL_SHM_DISABLE=1
58
+ # fi
59
+
60
+ # echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m"
61
+
62
+ #################################################################
63
+ ## ACCELERATE CONFIG
64
+ #################################################################
65
+ MASTER_ADDR=$ARNOLD_WORKER_0_HOST
66
+ ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
67
+ export MASTER_PORT=${ports[0]}
68
+ NUM_MACHINES=$ARNOLD_WORKER_NUM
69
+ MACHINE_RANK=$ARNOLD_ID
70
+ NUM_PROCESSES_PER_MACHINE=$ARNOLD_WORKER_GPU
71
+
72
+ # export CUDA_VISIBLE_DEVICES=0
73
+ # NUM_PROCESSES_PER_MACHINE=1
74
+ # NUM_MACHINES=1
75
+ # MACHINE_RANK=0
76
+
77
+ ACCELERATE_ARGS="--num_machines $NUM_MACHINES --machine_rank $MACHINE_RANK --num_processes $((NUM_PROCESSES_PER_MACHINE*NUM_MACHINES)) --main_process_ip $MASTER_ADDR --main_process_port $MASTER_PORT"
78
+
79
+ echo -e "\033[31mACCELERATE_ARGS: ${ACCELERATE_ARGS}\033[0m"
80
+
81
+ # accelerate launch \
82
+ # $ACCELERATE_ARGS \
83
+ # train_helios.py \
84
+ # --config scripts/training/configs/stage_3_post.yaml \
85
+ # 2>&1 | tee ./train.log
86
+
87
+ accelerate launch \
88
+ $ACCELERATE_ARGS \
89
+ --config_file scripts/accelerate_configs/multi_node_example_zero2.yaml \
90
+ train_helios.py \
91
+ --config scripts/training/configs/stage_3_post.yaml \
92
+ 2>&1 | tee ./train.log
LongLive-main/configs/default_config.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ independent_first_frame: false
2
+ warp_denoising_step: false
3
+ weight_decay: 0.01
4
+ same_step_across_blocks: true
5
+ discriminator_lr_multiplier: 1.0
6
+ last_step_only: false
7
+ i2v: false
8
+ num_training_frames: 21
9
+ gc_interval: 100
10
+ context_noise: 0
11
+ causal: true
12
+
13
+ ckpt_step: 0
14
+ prompt_name: MovieGenVideoBench
15
+ prompt_path: prompts/MovieGenVideoBench.txt
16
+ eval_first_n: 64
17
+ num_samples: 1
18
+ height: 480
19
+ width: 832
20
+ num_frames: 81
21
+ max_iters: 10000
LongLive-main/configs/longlive_inference.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ denoising_step_list:
2
+ - 1000
3
+ - 750
4
+ - 500
5
+ - 250
6
+ warp_denoising_step: true # need to remove - 0 in denoising_step_list if warp_denoising_step is true
7
+ num_frame_per_block: 3
8
+ model_name: Wan2.1-T2V-1.3B
9
+ model_kwargs:
10
+ local_attn_size: 12
11
+ timestep_shift: 5.0
12
+ sink_size: 3
13
+
14
+
15
+ # inference
16
+ data_path: longlive_models/prompts/vidprom_filtered_extended.txt
17
+ output_folder: videos/long
18
+ inference_iter: -1
19
+ num_output_frames: 120
20
+ use_ema: false
21
+ seed: 0
22
+ num_samples: 1
23
+ save_with_index: true
24
+ global_sink: true
25
+ context_noise: 0
26
+
27
+ generator_ckpt: longlive_models/models/longlive_base.pt
28
+ lora_ckpt: longlive_models/models/lora.pt
29
+
30
+ adapter:
31
+ type: "lora"
32
+ rank: 256 # LoRA rank (typical values: 8, 16, 32, 64)
33
+ alpha: 256 # LoRA alpha (typically same as rank, but can be different)
34
+ dropout: 0.0 # LoRA dropout rate
35
+ dtype: "bfloat16" # Data type for LoRA parameters: "bfloat16", "float16", "float32"
36
+ verbose: false # Whether to print all target module names
LongLive-main/configs/longlive_inference_infinity.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ denoising_step_list:
2
+ - 1000
3
+ - 750
4
+ - 500
5
+ - 250
6
+ warp_denoising_step: true # need to remove - 0 in denoising_step_list if warp_denoising_step is true
7
+ num_frame_per_block: 3
8
+ model_name: Wan2.1-T2V-1.3B
9
+ model_kwargs:
10
+ local_attn_size: 12
11
+ timestep_shift: 5.0
12
+ sink_size: 3
13
+ use_infinite_attention: true
14
+
15
+ # inference
16
+ data_path: longlive_models/prompts/vidprom_filtered_extended.txt
17
+ output_folder: videos/long_infinity
18
+ inference_iter: -1
19
+ num_output_frames: 1050
20
+ use_ema: false
21
+ seed: 0
22
+ num_samples: 1
23
+ save_with_index: true
24
+ global_sink: true
25
+ context_noise: 0
26
+
27
+ generator_ckpt: longlive_models/models/longlive_base.pt
28
+ lora_ckpt: longlive_models/models/lora.pt
29
+
30
+ adapter:
31
+ type: "lora"
32
+ rank: 256 # LoRA rank (typical values: 8, 16, 32, 64)
33
+ alpha: 256 # LoRA alpha (typically same as rank, but can be different)
34
+ dropout: 0.0 # LoRA dropout rate
35
+ dtype: "bfloat16" # Data type for LoRA parameters: "bfloat16", "float16", "float32"
36
+ verbose: false # Whether to print all target module names
LongLive-main/configs/longlive_interactive_inference.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Architecture
2
+ denoising_step_list:
3
+ - 1000
4
+ - 750
5
+ - 500
6
+ - 250
7
+ warp_denoising_step: true # need to remove - 0 in denoising_step_list if warp_denoising_step is true
8
+ num_frame_per_block: 3
9
+ model_name: Wan2.1-T2V-1.3B
10
+ model_kwargs:
11
+ local_attn_size: 12
12
+ timestep_shift: 5.0
13
+ sink_size: 3
14
+
15
+
16
+ # Inference
17
+ data_path: longlive_models/prompts/interactive_example.jsonl
18
+ output_folder: videos/interactive
19
+ inference_iter: -1
20
+ num_output_frames: 240
21
+ use_ema: false
22
+ seed: 1
23
+ num_samples: 1
24
+ save_with_index: true
25
+ switch_frame_indices: 40, 80, 120, 160, 200
26
+ global_sink: true
27
+ context_noise: 0
28
+
29
+ generator_ckpt: longlive_models/models/longlive_base.pt
30
+ lora_ckpt: longlive_models/models/lora.pt
31
+
32
+ adapter:
33
+ type: "lora"
34
+ rank: 256 # LoRA rank (typical values: 8, 16, 32, 64)
35
+ alpha: 256 # LoRA alpha (typically same as rank, but can be different)
36
+ dropout: 0.0 # LoRA dropout rate
37
+ dtype: "bfloat16" # Data type for LoRA parameters: "bfloat16", "float16", "float32"
38
+ verbose: false # Whether to print all target module names
LongLive-main/configs/longlive_train_init.yaml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ generator_ckpt: checkpoints/ode_init.pt
2
+ generator_fsdp_wrap_strategy: size
3
+ real_score_fsdp_wrap_strategy: size
4
+ fake_score_fsdp_wrap_strategy: size
5
+ # real_name: Wan2.1-T2V-1.3B
6
+ real_name: Wan2.1-T2V-14B
7
+ fake_name: Wan2.1-T2V-1.3B
8
+ text_encoder_fsdp_wrap_strategy: size
9
+ denoising_step_list:
10
+ - 1000
11
+ - 750
12
+ - 500
13
+ - 250
14
+ warp_denoising_step: true # need to remove - 0 in denoising_step_list if warp_denoising_step is true
15
+ ts_schedule: false
16
+ num_train_timestep: 1000
17
+ timestep_shift: 5.0
18
+ guidance_scale: 3.0
19
+ denoising_loss_type: flow
20
+ mixed_precision: true
21
+ seed: 0
22
+ wandb_key: YOUR_WANDB_KEY
23
+ wandb_entity: YOUR_WANDB_ENTITY
24
+ wandb_project: YOUR_WANDB_PROJECT
25
+ sharding_strategy: hybrid_full
26
+ lr: 2.0e-06
27
+ lr_critic: 4.0e-07
28
+ beta1: 0.0
29
+ beta2: 0.999
30
+ beta1_critic: 0.0
31
+ beta2_critic: 0.999
32
+ data_path: prompts/vidprom_filtered_extended.txt
33
+ batch_size: 1
34
+ gradient_accumulation_steps: 1
35
+ ema_weight: 0.99
36
+ ema_start_step: 200
37
+ total_batch_size: 64
38
+ log_iters: 100
39
+ max_checkpoints: 5
40
+ max_iters: 700
41
+
42
+ negative_prompt: '色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走'
43
+ dfake_gen_update_ratio: 5
44
+ image_or_video_shape:
45
+ - 1
46
+ - 21 # unused in sequential training
47
+ - 16
48
+ - 60
49
+ - 104
50
+ distribution_loss: dmd
51
+ trainer: score_distillation
52
+ gradient_checkpointing: true
53
+ num_frame_per_block: 3
54
+ load_raw_video: false
55
+ model_kwargs:
56
+ timestep_shift: 5.0
57
+ local_attn_size: 12
58
+ sink_size: 3
59
+
60
+ # Visualization
61
+ vis_interval: 200
62
+ vis_ema: false
63
+ vis_video_lengths:
64
+ - 21
65
+ val_batch_size: 1
66
+ val_data_path: prompts/vidprom_filtered_extended.txt
67
+
68
+ min_num_training_frames: 21
69
+ num_training_frames: 21
70
+ slice_last_frames: 21
LongLive-main/configs/longlive_train_long.yaml ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ generator_ckpt: checkpoints/longlive_init.pt
2
+ generator_fsdp_wrap_strategy: size
3
+ real_score_fsdp_wrap_strategy: size
4
+ fake_score_fsdp_wrap_strategy: size
5
+ # real_name: Wan2.1-T2V-1.3B
6
+ real_name: Wan2.1-T2V-14B
7
+ fake_name: Wan2.1-T2V-1.3B
8
+ text_encoder_fsdp_wrap_strategy: size
9
+ denoising_step_list:
10
+ - 1000
11
+ - 750
12
+ - 500
13
+ - 250
14
+ warp_denoising_step: true # need to remove - 0 in denoising_step_list if warp_denoising_step is true
15
+ ts_schedule: false
16
+ num_train_timestep: 1000
17
+ timestep_shift: 5.0
18
+ guidance_scale: 3.0
19
+ denoising_loss_type: flow
20
+ mixed_precision: true
21
+ seed: 0
22
+ wandb_key: YOUR_WANDB_KEY
23
+ wandb_entity: YOUR_WANDB_ENTITY
24
+ wandb_project: YOUR_WANDB_PROJECT
25
+ sharding_strategy: hybrid_full
26
+ lr: 1.0e-05
27
+ lr_critic: 2.0e-06
28
+ beta1: 0.0
29
+ beta2: 0.999
30
+ beta1_critic: 0.0
31
+ beta2_critic: 0.999
32
+ data_path: prompts/vidprom_filtered_extended.txt
33
+ switch_prompt_path: prompts/vidprom_filtered_extended_switch.txt
34
+ batch_size: 1
35
+ gradient_accumulation_steps: 1
36
+ ema_weight: 0.99
37
+ ema_start_step: 200
38
+ total_batch_size: 64
39
+ log_iters: 50
40
+ max_checkpoints: 3
41
+ max_iters: 3000
42
+
43
+ negative_prompt: '色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走'
44
+ dfake_gen_update_ratio: 5
45
+ image_or_video_shape:
46
+ - 1
47
+ - 240 # unused in streaming training
48
+ - 16
49
+ - 60
50
+ - 104
51
+ distribution_loss: dmd_switch
52
+ global_sink: false
53
+ trainer: score_distillation
54
+ gradient_checkpointing: true
55
+ num_frame_per_block: 3
56
+ load_raw_video: false
57
+ model_kwargs:
58
+ timestep_shift: 5.0
59
+ local_attn_size: 12
60
+ sink_size: 3
61
+
62
+ # Visualization
63
+ vis_interval: 500
64
+ vis_ema: false
65
+ vis_video_lengths:
66
+ - 240
67
+ val_batch_size: 1
68
+ val_data_path: prompts/vidprom_filtered_extended.txt
69
+ val_switch_prompt_path: prompts/vidprom_filtered_extended_switch.txt
70
+
71
+ slice_last_frames: 21
72
+
73
+ switch_mode: random_choice
74
+ switch_choices:
75
+ - 21
76
+ - 39
77
+ - 57
78
+ - 75
79
+ - 93
80
+ - 111
81
+ - 129
82
+ - 147
83
+ - 165
84
+ - 183
85
+ - 201
86
+
87
+ streaming_training: true
88
+ streaming_chunk_size: 21
89
+ streaming_max_length: 240
90
+
91
+ streaming_min_new_frame: 18
92
+ train_first_chunk: true
93
+
94
+ last_step_only: false
95
+
96
+ ## LoRA Configuration
97
+ adapter:
98
+ type: "lora"
99
+ rank: 256 # LoRA rank (typical values: 8, 16, 32, 64)
100
+ alpha: 256 # LoRA alpha (typically same as rank, but can be different)
101
+ dropout: 0.0 # LoRA dropout rate
102
+ dtype: "bfloat16" # Data type for LoRA parameters: "bfloat16", "float16", "float32"
103
+ apply_to_critic: true # Whether to apply LoRA to critic/fake_score model
104
+ verbose: true # Whether to print all target module names
LongLive-main/docs/FLASH_ATTENTION_3_AND_HOPPER_SUPPORT.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Flash Attention 3 and Hopper GPU Support
2
+
3
+ This document describes the Flash Attention 3 (FA3) integration and extended Hopper GPU support in LongLive.
4
+
5
+ ## Overview
6
+
7
+ LongLive supports both Flash Attention 2 (FA2) and Flash Attention 3 (FA3) for efficient attention computation. FA3 is automatically enabled on Hopper architecture GPUs (Compute Capability 9.0+), providing improved performance.
8
+
9
+ ## Supported Hardware
10
+
11
+ ### Hopper Architecture GPUs (FA3 Enabled)
12
+ - **NVIDIA H100** - Data center GPU
13
+ - **NVIDIA H800** - China-specific variant
14
+ - **NVIDIA H20** - China-specific variant
15
+
16
+ All Hopper GPUs share Compute Capability 9.0, which is the requirement for FA3.
17
+
18
+ ### Other GPUs (FA2 Fallback)
19
+ - **NVIDIA A100** - Ampere architecture (Compute Capability 8.0)
20
+ - **NVIDIA A800** - Ampere architecture (Compute Capability 8.0)
21
+ - Other CUDA-capable GPUs with FA2 support
22
+
23
+ ## Design Choices
24
+
25
+ ### 1. GPU Detection via Compute Capability
26
+
27
+ Instead of relying on device name string matching (which would miss H800/H20), we detect Hopper GPUs using CUDA Compute Capability:
28
+
29
+ ```python
30
+ def is_hopper_gpu():
31
+ if torch.cuda.is_available():
32
+ major, _ = torch.cuda.get_device_capability()
33
+ return major >= 9 # Hopper Compute Capability == 9.0
34
+ return False
35
+ ```
36
+
37
+ **Rationale:**
38
+ - Device names vary across vendors and regions (H100, H800, H20, etc.)
39
+ - Compute Capability is a reliable, standardized way to identify GPU architecture
40
+ - All Hopper GPUs report `major=9` regardless of their marketing name
41
+
42
+ ### 2. FA3 Return Value Handling
43
+
44
+ Flash Attention 3's `flash_attn_varlen_func` has a different return signature than FA2:
45
+
46
+ | Version | Return Value |
47
+ |---------|--------------|
48
+ | FA2 | `(output, softmax_lse, ...)` - tuple, use `[0]` to get output |
49
+ | FA3 | `output` - tensor directly |
50
+
51
+ The code correctly handles this difference:
52
+
53
+ ```python
54
+ # FA3 path - direct tensor return
55
+ x = flash_attn_interface.flash_attn_varlen_func(...).unflatten(0, (b, lq))
56
+
57
+ # FA2 path - tuple return (handled in else branch)
58
+ x = flash_attn.flash_attn_varlen_func(...).unflatten(0, (b, lq))
59
+ ```
60
+
61
+ ### 3. Automatic Fallback
62
+
63
+ The system gracefully falls back to FA2 when FA3 is unavailable:
64
+ - If `flash_attn_interface` module is not installed
65
+ - If running on non-Hopper GPU
66
+ - If user explicitly requests FA2 via `version=2` parameter
67
+
68
+ A warning is issued when FA3 is explicitly requested but unavailable.
69
+
70
+ ## Usage
71
+
72
+ ### Automatic Selection (Recommended)
73
+
74
+ By default, LongLive automatically selects the optimal attention implementation:
75
+
76
+ ```python
77
+ from wan.modules.attention import attention
78
+
79
+ # FA3 will be used on Hopper GPUs, FA2 otherwise
80
+ output = attention(q, k, v)
81
+ ```
82
+
83
+ ### Explicit Version Selection
84
+
85
+ You can force a specific Flash Attention version:
86
+
87
+ ```python
88
+ # Force FA2 (useful for debugging or compatibility)
89
+ output = attention(q, k, v, fa_version=2)
90
+
91
+ # Request FA3 (falls back to FA2 with warning if unavailable)
92
+ output = attention(q, k, v, fa_version=3)
93
+ ```
94
+
95
+ ## Installation
96
+
97
+ ### Flash Attention 3 (Hopper GPUs)
98
+
99
+ ```bash
100
+ git clone https://github.com/Dao-AILab/flash-attention.git
101
+ cd flash-attention/hopper
102
+ python setup.py install
103
+ ```