Ouzhang commited on
Commit
8e29a6e
·
verified ·
1 Parent(s): d441014

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. benchmarks/edit/code/EditBoard/editboard/__init__.py +174 -0
  2. benchmarks/edit/code/EditBoard/editboard/aesthetic_quality.py +63 -0
  3. benchmarks/edit/code/EditBoard/editboard/background_consistency.py +57 -0
  4. benchmarks/edit/code/EditBoard/editboard/clip_similarity.py +75 -0
  5. benchmarks/edit/code/EditBoard/editboard/ff_alpha.py +93 -0
  6. benchmarks/edit/code/EditBoard/editboard/ff_beta.py +43 -0
  7. benchmarks/edit/code/EditBoard/editboard/imaging_quality.py +61 -0
  8. benchmarks/edit/code/EditBoard/editboard/semantic_score.py +49 -0
  9. benchmarks/edit/code/EditBoard/editboard/subject_consistency.py +62 -0
  10. benchmarks/edit/code/EditBoard/editboard/success_rate.py +75 -0
  11. benchmarks/edit/code/EditBoard/editboard/test_optflow.py +121 -0
  12. benchmarks/edit/code/EditBoard/editboard/utils.py +255 -0
  13. benchmarks/edit/code/EditBoard/sample/script.csv +5 -0
  14. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/config.yaml +27 -0
  15. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/diffusion_schedulers/__init__.py +2 -0
  16. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/diffusion_schedulers/scheduling_cosine_ddpm.py +137 -0
  17. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/diffusion_schedulers/scheduling_flow_matching.py +297 -0
  18. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/edit.py +846 -0
  19. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/__init__.py +3 -0
  20. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/__init__.py +3 -0
  21. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_embedding.py +201 -0
  22. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_flux_block.py +1069 -0
  23. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_normalization.py +248 -0
  24. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_pyramid_flux.py +548 -0
  25. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_text_encoder.py +146 -0
  26. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/__init__.py +3 -0
  27. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_embedding.py +390 -0
  28. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_mmdit_block.py +671 -0
  29. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_normalization.py +179 -0
  30. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_pyramid_mmdit.py +497 -0
  31. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_text_encoder.py +140 -0
  32. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/pyramid_dit_for_video_gen_pipeline.py +1283 -0
  33. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/scripts/run_FiVE.sh +8 -0
  34. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/scripts/run_single.sh +13 -0
  35. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/__init__.py +30 -0
  36. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/communicate.py +66 -0
  37. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/fsdp_trainer.py +154 -0
  38. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/sp_utils.py +98 -0
  39. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/utils.py +528 -0
  40. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/vae_ddp_trainer.py +171 -0
  41. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utilities/guidance_utils.py +567 -0
  42. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utilities/initialize_latent.py +28 -0
  43. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utilities/utils.py +53 -0
  44. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utils.py +457 -0
  45. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/__init__.py +3 -0
  46. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/causal_video_vae_wrapper.py +254 -0
  47. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/context_parallel_ops.py +167 -0
  48. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/modeling_block.py +759 -0
  49. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/modeling_causal_conv.py +146 -0
  50. benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/modeling_causal_vae.py +624 -0
benchmarks/edit/code/EditBoard/editboard/__init__.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from .utils import init_submodules, save_json, load_json
4
+ import importlib
5
+ from itertools import chain
6
+ from pathlib import Path
7
+ import shutil
8
+ from PIL import Image
9
+ import pandas as pd
10
+
11
+ def frames2gif(source_folder):
12
+ output_folder = os.path.join(source_folder, "tempt_dir")
13
+
14
+ os.makedirs(output_folder, exist_ok=True)
15
+
16
+ images = []
17
+
18
+ for file_name in sorted(os.listdir(source_folder)):
19
+ file_path = os.path.join(source_folder, file_name)
20
+
21
+ if os.path.isfile(file_path) and file_name.lower().endswith(('.png', '.jpg', '.jpeg')):
22
+ img = Image.open(file_path)
23
+ images.append(img)
24
+ # print(file_name)
25
+
26
+ if images:
27
+ folder_name = os.path.basename(source_folder)
28
+ gif_path = os.path.join(output_folder, f"{folder_name}.gif")
29
+ images[0].save(gif_path, save_all=True, append_images=images[1:], optimize=False, duration=500, loop=0)
30
+
31
+ for img in images:
32
+ img.close()
33
+ else:
34
+ raise Exception("No images found in the source folder.")
35
+
36
+ return output_folder
37
+
38
+ class EditBoard(object):
39
+ def __init__(self, device, output_path):
40
+ self.device = device # cuda or cpu
41
+ self.output_path = output_path # output directory to save EditBoard results
42
+ os.makedirs(self.output_path, exist_ok=True)
43
+
44
+ def build_metadata_json_single(
45
+ self, original_video_path, edited_video_path, semantic_mask_path,
46
+ source_prompt, target_prompt,
47
+ dimension_list, name
48
+ ):
49
+ cur_full_info_list=[]
50
+
51
+ temp = {
52
+ k: v for k, v in {
53
+ "original_video_path": original_video_path,
54
+ "edited_video_path": edited_video_path,
55
+ "semantic_mask_path": semantic_mask_path,
56
+ "source_prompt": source_prompt,
57
+ "target_prompt": target_prompt,
58
+ "dimension": dimension_list,
59
+ }.items() if v is not None
60
+ }
61
+
62
+ cur_full_info_list.append(temp)
63
+
64
+ cur_full_info_path = os.path.join(self.output_path, name+'_metadata.json')
65
+ save_json(cur_full_info_list, cur_full_info_path)
66
+ print(f'Evaluation metadata saved to {cur_full_info_path}')
67
+ return cur_full_info_path
68
+
69
+ def build_metadata_json_multi(self, dimension_list, name, script):
70
+ cur_full_info_list = []
71
+
72
+ if script.split(".")[-1] == 'xlsx':
73
+ df = pd.read_excel(script)
74
+ elif script.split(".")[-1] == 'csv':
75
+ df = pd.read_csv(script)
76
+ else:
77
+ raise Exception("Prompt file must be excel or csv!")
78
+
79
+ available_columns = set(df.columns)
80
+
81
+ expected_columns = {
82
+ "original_video_path": "original_video_path",
83
+ "edited_video_path": "edited_video_path",
84
+ "semantic_mask_path": "semantic_mask_path",
85
+ "source_prompt": "source_prompt",
86
+ "target_prompt": "target_prompt"
87
+ }
88
+
89
+ for index, row in df.iterrows():
90
+ temp = {}
91
+
92
+ for col_key, json_key in expected_columns.items():
93
+ if col_key in available_columns and pd.notna(row[col_key]):
94
+ temp[json_key] = row[col_key]
95
+
96
+ temp["dimension"] = dimension_list
97
+
98
+ cur_full_info_list.append(temp)
99
+
100
+ cur_full_info_path = os.path.join(self.output_path, name + '_metadata.json')
101
+ save_json(cur_full_info_list, cur_full_info_path)
102
+ print(f'Evaluation metadata saved to {cur_full_info_path}')
103
+ return cur_full_info_path
104
+
105
+ def evaluate(
106
+ self, original_video_path, edited_video_path, semantic_mask_path,
107
+ source_prompt, target_prompt,
108
+ dimension_list, name, script
109
+ ):
110
+ read_frame = False
111
+ results_dict = {}
112
+ if dimension_list is None:
113
+ raise Exception("Dimension can't be none!")
114
+ submodules_dict = init_submodules(dimension_list, read_frame=read_frame)
115
+
116
+ if script == None:
117
+ print("Using Normal Command!")
118
+ cur_full_info_path = self.build_metadata_json_single(
119
+ original_video_path, edited_video_path, semantic_mask_path,
120
+ source_prompt, target_prompt,
121
+ dimension_list, name
122
+ )
123
+ else:
124
+ print("Using Script Command!")
125
+ cur_full_info_path = self.build_metadata_json_multi(
126
+ dimension_list, name, script
127
+ )
128
+
129
+
130
+ # Start calculating
131
+ flag = False
132
+ metadata = load_json(cur_full_info_path)
133
+ gif_list = []
134
+ if any(dimension in dimension_list for dimension in ['subject_consistency', 'background_consistency', 'aesthetic_quality', 'imaging_quality']):
135
+ flag = True
136
+ for i in metadata:
137
+ gif_path = frames2gif(i["edited_video_path"])
138
+ gif_list.append(gif_path)
139
+
140
+ for dimension in dimension_list:
141
+ print(f"Calculating {dimension} ...")
142
+ try:
143
+ dimension_module = importlib.import_module(f'editboard.{dimension}')
144
+ evaluate_func = getattr(dimension_module, f'compute_{dimension}')
145
+ except Exception as e:
146
+ raise NotImplementedError(f'UnImplemented dimension {dimension}!, {e}')
147
+ submodules_list = submodules_dict[dimension]
148
+ # print(f'cur_full_info_path: {cur_full_info_path}') # TODO: to delete
149
+ results = evaluate_func(cur_full_info_path, self.device, submodules_list)
150
+ results_dict[dimension] = results
151
+
152
+ if flag:
153
+ for i in gif_list:
154
+ shutil.rmtree(i)
155
+ # Finish calculating
156
+
157
+ for i in metadata:
158
+ i["dimension"] = dict()
159
+ for dimension in dimension_list:
160
+ if dimension in ['subject_consistency', 'background_consistency', 'aesthetic_quality', 'imaging_quality']:
161
+ i["dimension"][dimension] = results_dict[dimension][i["edited_video_path"]]
162
+ elif dimension in ["ff_alpha", "ff_beta"]:
163
+ i["dimension"][dimension] = results_dict[dimension][i["original_video_path"] + i["edited_video_path"]]
164
+ elif dimension in ["clip_similarity", "success_rate"]:
165
+ i["dimension"][dimension] = results_dict[dimension][i["edited_video_path"] + i["source_prompt"] + i["target_prompt"]]
166
+ elif dimension in ["semantic_score"]:
167
+ i["dimension"][dimension] = results_dict[dimension][i["original_video_path"] + i["edited_video_path"] + i["semantic_mask_path"]]
168
+ else:
169
+ raise Exception("Wrong dimension!")
170
+
171
+ output_name = os.path.join(self.output_path, name+'_eval_results.json')
172
+ save_json(metadata, output_name)
173
+ print('All Done!')
174
+ print(f'Evaluation results saved to {output_name}')
benchmarks/edit/code/EditBoard/editboard/aesthetic_quality.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import clip
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import subprocess
7
+ from urllib.request import urlretrieve
8
+ from editboard.utils import load_video, load_dimension_info, clip_transform
9
+ from tqdm import tqdm
10
+
11
+
12
+ def get_aesthetic_model(cache_folder):
13
+ """load the aethetic model"""
14
+ path_to_model = cache_folder + "/sa_0_4_vit_l_14_linear.pth"
15
+ if not os.path.exists(path_to_model):
16
+ os.makedirs(cache_folder, exist_ok=True)
17
+ url_model = (
18
+ "https://github.com/LAION-AI/aesthetic-predictor/blob/main/sa_0_4_vit_l_14_linear.pth?raw=true"
19
+ )
20
+ # download aesthetic predictor
21
+ if not os.path.isfile(path_to_model):
22
+ try:
23
+ print(f'trying urlretrieve to download {url_model} to {path_to_model}')
24
+ urlretrieve(url_model, path_to_model) # unable to download https://github.com/LAION-AI/aesthetic-predictor/blob/main/sa_0_4_vit_l_14_linear.pth?raw=true to pretrained/aesthetic_model/emb_reader/sa_0_4_vit_l_14_linear.pth
25
+ except:
26
+ print(f'unable to download {url_model} to {path_to_model} using urlretrieve, trying wget')
27
+ wget_command = ['wget', url_model, '-P', os.path.dirname(path_to_model)]
28
+ subprocess.run(wget_command)
29
+ m = nn.Linear(768, 1)
30
+ s = torch.load(path_to_model)
31
+ m.load_state_dict(s)
32
+ m.eval()
33
+ return m
34
+
35
+
36
+ def laion_aesthetic(aesthetic_model, clip_model, video_list, device):
37
+ aesthetic_model.eval()
38
+ clip_model.eval()
39
+ num = 0
40
+ video_results = {}
41
+ for video_path in tqdm(video_list):
42
+ images = load_video(video_path)
43
+ image_transform = clip_transform(224)
44
+ images = image_transform(images)
45
+ images = images.to(device)
46
+ image_feats = clip_model.encode_image(images).to(torch.float32)
47
+ image_feats = F.normalize(image_feats, dim=-1, p=2)
48
+ aesthetic_scores = aesthetic_model(image_feats).squeeze()
49
+ normalized_aesthetic_scores = aesthetic_scores/10
50
+ cur_avg = torch.mean(normalized_aesthetic_scores, dim=0, keepdim=True)
51
+ num += 1
52
+ video_results[os.path.dirname(os.path.dirname(video_path))] = cur_avg.item()
53
+ return video_results
54
+
55
+
56
+ def compute_aesthetic_quality(json_dir, device, submodules_list):
57
+ vit_path = submodules_list[0]
58
+ aes_path = submodules_list[1]
59
+ aesthetic_model = get_aesthetic_model(aes_path).to(device)
60
+ clip_model, preprocess = clip.load(vit_path, device=device)
61
+ video_list = load_dimension_info(json_dir, dimension='aesthetic_quality')
62
+ video_results = laion_aesthetic(aesthetic_model, clip_model, video_list, device)
63
+ return video_results
benchmarks/edit/code/EditBoard/editboard/background_consistency.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ import numpy as np
5
+ import clip
6
+ from PIL import Image
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from editboard.utils import load_video, load_dimension_info, clip_transform
11
+ from tqdm import tqdm
12
+
13
+
14
+ def background_consistency(clip_model, preprocess, video_list, device, read_frame):
15
+ sim = 0.0
16
+ cnt = 0
17
+ video_results = {}
18
+ image_transform = clip_transform(224)
19
+ for video_path in tqdm(video_list):
20
+ video_sim = 0.0
21
+ if read_frame:
22
+ video_path = video_path[:-4].replace('videos', 'frames').replace(' ', '_')
23
+ tmp_paths = [os.path.join(video_path, f) for f in sorted(os.listdir(video_path))]
24
+ images = []
25
+ for tmp_path in tmp_paths:
26
+ images.append(preprocess(Image.open(tmp_path)))
27
+ images = torch.stack(images)
28
+ else:
29
+ images = load_video(video_path)
30
+ images = image_transform(images)
31
+ images = images.to(device)
32
+ image_features = clip_model.encode_image(images)
33
+ image_features = F.normalize(image_features, dim=-1, p=2)
34
+ for i in range(len(image_features)):
35
+ image_feature = image_features[i].unsqueeze(0)
36
+ if i == 0:
37
+ first_image_feature = image_feature
38
+ else:
39
+ sim_pre = max(0.0, F.cosine_similarity(former_image_feature, image_feature).item())
40
+ sim_fir = max(0.0, F.cosine_similarity(first_image_feature, image_feature).item())
41
+ cur_sim = (sim_pre + sim_fir) / 2
42
+ video_sim += cur_sim
43
+ cnt += 1
44
+ former_image_feature = image_feature
45
+ sim_per_image = video_sim / (len(image_features) - 1)
46
+ sim += video_sim
47
+ video_results[os.path.dirname(os.path.dirname(video_path))] = sim_per_image
48
+ return video_results
49
+
50
+
51
+ def compute_background_consistency(json_dir, device, submodules_list):
52
+ vit_path, read_frame = submodules_list[0], submodules_list[1]
53
+ clip_model, preprocess = clip.load(vit_path, device=device)
54
+ video_list = load_dimension_info(json_dir, dimension='background_consistency')
55
+ video_results = background_consistency(clip_model, preprocess, video_list, device, read_frame)
56
+ return video_results
57
+
benchmarks/edit/code/EditBoard/editboard/clip_similarity.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import clip
3
+ from PIL import Image
4
+ from glob import glob
5
+ import numpy as np
6
+ import os
7
+ from editboard.utils import load_json
8
+ from tqdm import tqdm
9
+
10
+ def crop_read_image_path(image_path):
11
+ origin_image = Image.open(image_path)
12
+ w, h = origin_image.size
13
+ if h > w:
14
+ origin_image = origin_image.crop((0, h-w, w, h))
15
+ return origin_image
16
+
17
+ def edit_success(image_path, source_prompt,target_prompt, model, preprocess, device):
18
+ image = preprocess(crop_read_image_path(image_path)).unsqueeze(0).to(device)
19
+
20
+ text = clip.tokenize([source_prompt, target_prompt]).to(device)
21
+ target = clip.tokenize(target_prompt).to(device)
22
+
23
+
24
+ with torch.no_grad():
25
+ image_features = model.encode_image(image)
26
+ text_features = model.encode_text(text)
27
+ target_features = model.encode_text(target)
28
+
29
+ logits_per_image, logits_per_text = model(image, text)
30
+ probs = logits_per_image.softmax(dim=-1).cpu().numpy()
31
+
32
+
33
+ image_features = image_features.cpu().numpy()
34
+ target_features = target_features.cpu().numpy()
35
+ image_features_normalized = image_features / np.linalg.norm(image_features)
36
+ text_features_normalized = target_features / np.linalg.norm(target_features)
37
+
38
+ # Compute the cosine similarity
39
+ image_features_normalized = image_features_normalized
40
+ text_features_normalized = text_features_normalized
41
+
42
+ similarity = np.sum(image_features_normalized * text_features_normalized, -1)
43
+
44
+ if probs[0,1] >= probs[0,0]:
45
+ return 1, similarity[0]
46
+
47
+ else:
48
+ return 0, similarity[0]
49
+
50
+ def video_score(edited_video_path, source_prompt, target_prompt, model, preprocess, device):
51
+ count = 0
52
+ score = 0
53
+ file_list = os.listdir(edited_video_path)
54
+ file_list = [img for img in file_list if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
55
+
56
+ for i in file_list:
57
+ image_path = os.path.join(edited_video_path, i)
58
+ count_sub, score_sub = edit_success(image_path, source_prompt, target_prompt, model, preprocess, device)
59
+ count+=count_sub
60
+ score+=score_sub
61
+
62
+ success_rate = count/len(file_list)
63
+ clip_similarity = score/len(file_list)
64
+
65
+ return clip_similarity
66
+
67
+ def compute_clip_similarity(json_dir, device, submodules_list):
68
+ model, preprocess = clip.load("ViT-B/32", device=device)
69
+
70
+ metadata = load_json(json_dir)
71
+ result = {}
72
+ for i in tqdm(metadata):
73
+ score = video_score(i["edited_video_path"], i["source_prompt"], i["target_prompt"], model, preprocess, device)
74
+ result[i["edited_video_path"] + i["source_prompt"] + i["target_prompt"]] = score
75
+ return result
benchmarks/edit/code/EditBoard/editboard/ff_alpha.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from editboard.test_optflow import compute_optical_flow, apply_optical_flow
5
+ from editboard.utils import load_json
6
+ from tqdm import tqdm
7
+
8
+ def get_optical_flow_list(video_path):
9
+ flow_list = []
10
+ frames = os.listdir(video_path)
11
+ frames = [img for img in frames if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
12
+ frames.sort()
13
+ for i in range(0,len(frames)-1):
14
+ img1 = cv2.imread(os.path.join(video_path, frames[i]))
15
+ img2 = cv2.imread(os.path.join(video_path, frames[i+1]))
16
+ flow = compute_optical_flow(img1,img2)
17
+ flow_list.append(flow)
18
+ return flow_list
19
+
20
+ def get_warped_result_list(video_path, flow_list):
21
+ warp_list = []
22
+ frames = os.listdir(video_path)
23
+ frames = [img for img in frames if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
24
+ frames.sort()
25
+ for i in range(0,len(frames)-1):
26
+ pp = os.path.join(video_path, frames[i])
27
+ img1 = cv2.imread(pp)
28
+ flow = flow_list[i]
29
+ warped = apply_optical_flow(img1, flow)
30
+ warp_list.append(warped)
31
+ return warp_list
32
+
33
+ def calculate_ff_alpha(original,ori_warp,edit,edit_warp,threshold=5):
34
+ m,n,_ = original.shape
35
+ mask = np.zeros((m,n))
36
+
37
+ diff = cv2.absdiff(original, ori_warp)
38
+ diff_gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
39
+
40
+ diff_edit = cv2.absdiff(edit, edit_warp)
41
+ # diff_gray_edit = cv2.cvtColor(diff_edit, cv2.COLOR_BGR2GRAY)
42
+ diff_gray_edit = np.max(diff_edit,-1)
43
+ for i in range(m):
44
+ for j in range(n):
45
+ if diff_gray[i][j] <= threshold:
46
+ mask[i][j] = 1
47
+ else:
48
+ mask[i][j] = 0
49
+
50
+ percentage_of_valid_pixel = np.sum(mask==1)/512/512
51
+
52
+ a = np.sum(np.multiply(mask,diff_gray_edit))
53
+ result = a/np.sum(mask==1)
54
+ return result, percentage_of_valid_pixel
55
+
56
+
57
+ def ff_alpha_for_video(original_video_path, edited_video_path, threshold = 5):
58
+ result = []
59
+ valid_percentage = []
60
+ original_frames = os.listdir(original_video_path)
61
+ original_frames = [img for img in original_frames if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
62
+ original_frames.sort()
63
+
64
+ edited_frames = os.listdir(edited_video_path)
65
+ edited_frames = [img for img in edited_frames if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
66
+ edited_frames.sort()
67
+
68
+ flow_list = get_optical_flow_list(original_video_path)
69
+ edit_warp_result = get_warped_result_list(edited_video_path,flow_list)
70
+ original_warp_result = get_warped_result_list(original_video_path,flow_list)
71
+
72
+ for i in range(0, len(edit_warp_result)):
73
+ original = cv2.imread(os.path.join(original_video_path,original_frames[i+1]))
74
+ ori_warp = original_warp_result[i]
75
+ edit = cv2.imread(os.path.join(edited_video_path,edited_frames[i+1]))
76
+ edit_warp = edit_warp_result[i]
77
+ score, valid = calculate_ff_alpha(original, ori_warp, edit, edit_warp,threshold)
78
+ result.append(score)
79
+ valid_percentage.append(valid)
80
+
81
+ if sum(valid_percentage)/len(valid_percentage) >= 0.70:
82
+ return sum(result)/len(edit_warp_result)
83
+ else:
84
+ return 0
85
+
86
+ def compute_ff_alpha(json_dir, device, submodules_list):
87
+ metadata = load_json(json_dir)
88
+ result = {}
89
+ for i in tqdm(metadata):
90
+ score = ff_alpha_for_video(i["original_video_path"], i["edited_video_path"])
91
+ result[i["original_video_path"] + i["edited_video_path"]] = score
92
+ return result
93
+
benchmarks/edit/code/EditBoard/editboard/ff_beta.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from editboard.test_optflow import compute_optical_flow
5
+ from editboard.utils import load_json
6
+ from tqdm import tqdm
7
+
8
+ def get_optical_flow_list(video_path):
9
+ flow_list = []
10
+ frames = os.listdir(video_path)
11
+ frames = [img for img in frames if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
12
+ frames.sort()
13
+ for i in range(0,len(frames)-1):
14
+ img1 = cv2.imread(os.path.join(video_path, frames[i]))
15
+ img2 = cv2.imread(os.path.join(video_path, frames[i+1]))
16
+ flow = compute_optical_flow(img1,img2)
17
+ flow_list.append(flow)
18
+ return flow_list
19
+
20
+ ##check
21
+ def ff_beta_for_one(a, b):
22
+ return np.sum((1 - np.sum(a*b, -1) / ((np.sum(a*a, -1))**0.5 + 1e-7) / ((np.sum(b*b, -1))**0.5 + 1e-7)) ) /(a.shape[0]*a.shape[1])
23
+ # return np.sum((1 - np.sum(a*b, -1) / ((np.sum(a*a, -1))**0.5 + 1e-7) / ((np.sum(b*b, -1))**0.5 + 1e-7)) * np.sum((a-b)**2,-1) ** 0.5) /(a.shape[0]*a.shape[1])
24
+
25
+ def ff_beta_for_video(original_video_path, edited_video_path):
26
+ result = []
27
+
28
+ flow_list_ori = get_optical_flow_list(original_video_path)
29
+ flow_list_edit = get_optical_flow_list(edited_video_path)
30
+
31
+ for i in range(len(flow_list_edit)):
32
+ flow1 = flow_list_ori[i]
33
+ flow2 = flow_list_edit[i]
34
+ result.append(ff_beta_for_one(flow1,flow2))
35
+ return sum(result)/len(flow_list_edit)
36
+
37
+ def compute_ff_beta(json_dir, device, submodules_list):
38
+ metadata = load_json(json_dir)
39
+ result = {}
40
+ for i in tqdm(metadata):
41
+ score = ff_beta_for_video(i["original_video_path"], i["edited_video_path"])
42
+ result[i["original_video_path"] + i["edited_video_path"]] = score
43
+ return result
benchmarks/edit/code/EditBoard/editboard/imaging_quality.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ from tqdm import tqdm
4
+ from torchvision import transforms
5
+ from pyiqa.archs.musiq_arch import MUSIQ
6
+ from editboard.utils import load_video, load_dimension_info
7
+
8
+ def transform(images, preprocess_mode='shorter'):
9
+ """preprocess_mode is for setting preprocessing in imaging_quality
10
+ 1. 'shorter': if the shorter side is more than 512, the image is resized so that the shorter side is 512.
11
+ 2. 'longer': if the longer side is more than 512, the image is resized so that the longer side is 512.
12
+ 3. 'shorter_centercrop': if the shorter side is more than 512, the image is resized so that the shorter side is 512.
13
+ Then the center 512 x 512 after resized is used for evaluation.
14
+ 4. 'None': no preprocessing
15
+ """
16
+ if preprocess_mode.startswith('shorter'):
17
+ _, _, h, w = images.size()
18
+ if min(h,w) > 512:
19
+ scale = 512./min(h,w)
20
+ images = transforms.Resize(size=( int(scale * h), int(scale * w) ))(images)
21
+ if preprocess_mode == 'shorter_centercrop':
22
+ images = transforms.CenterCrop(512)(images)
23
+
24
+ elif preprocess_mode == 'longer':
25
+ _, _, h, w = images.size()
26
+ if max(h,w) > 512:
27
+ scale = 512./max(h,w)
28
+ images = transforms.Resize(size=( int(scale * h), int(scale * w) ))(images)
29
+
30
+ elif preprocess_mode == 'None':
31
+ return images / 255.
32
+
33
+ else:
34
+ raise ValueError("Please recheck imaging_quality_mode")
35
+ return images / 255.
36
+
37
+ def technical_quality(model, video_list, device):
38
+ preprocess_mode = 'longer'
39
+ video_results = {}
40
+ for video_path in tqdm(video_list):
41
+ images = load_video(video_path)
42
+ images = transform(images, preprocess_mode)
43
+ acc_score_video = 0.
44
+ for i in range(len(images)):
45
+ frame = images[i].unsqueeze(0).to(device)
46
+ score = model(frame)
47
+ acc_score_video += float(score)
48
+ video_results[os.path.dirname(os.path.dirname(video_path))] = (acc_score_video/len(images)) / 100
49
+ return video_results
50
+
51
+
52
+ def compute_imaging_quality(json_dir, device, submodules_list):
53
+ model_path = submodules_list['model_path']
54
+
55
+ model = MUSIQ(pretrained_model_path=model_path)
56
+ model.to(device)
57
+ model.training = False
58
+
59
+ video_list = load_dimension_info(json_dir, dimension='imaging_quality')
60
+ video_results = technical_quality(model, video_list, device)
61
+ return video_results
benchmarks/edit/code/EditBoard/editboard/semantic_score.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import numpy as np
4
+ from editboard.utils import load_json
5
+ from tqdm import tqdm
6
+
7
+ def readimagefile(filepath):
8
+ frames = os.listdir(filepath)
9
+ frames = [img for img in frames if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
10
+ frames.sort()
11
+ return frames
12
+
13
+ def semantic_score(original_file, edit_file, mask_file, res=512):
14
+ result = []
15
+ mask_frame = readimagefile(mask_file)
16
+ original_frame = readimagefile(original_file)
17
+ edit_frame = readimagefile(edit_file)
18
+ for i in range(len(mask_frame)):
19
+ mask = cv2.imread(os.path.join(mask_file, mask_frame[i]))
20
+
21
+ original = cv2.imread(os.path.join(original_file, original_frame[i]))
22
+ edit = cv2.imread(os.path.join(edit_file, edit_frame[i]))
23
+
24
+ diff = cv2.absdiff(original, edit)
25
+ diff = np.max(diff, -1)
26
+
27
+ mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
28
+
29
+ mask_0_1 = np.zeros((res,res))
30
+ for i in range(res):
31
+ for j in range(res):
32
+ if mask[i][j] == 0:
33
+ mask_0_1[i][j] = 1
34
+ else:
35
+ mask_0_1[i][j] = 0
36
+
37
+ a = np.sum(np.multiply(mask_0_1,diff))
38
+ result_frame = a/np.sum(mask_0_1==1)
39
+
40
+ result.append(result_frame)
41
+ return sum(result)/len(original_frame)
42
+
43
+ def compute_semantic_score(json_dir, device, submodules_list):
44
+ metadata = load_json(json_dir)
45
+ result = {}
46
+ for i in tqdm(metadata):
47
+ score = semantic_score(i["original_video_path"], i["edited_video_path"], i["semantic_mask_path"])
48
+ result[i["original_video_path"] + i["edited_video_path"] + i["semantic_mask_path"]] = score
49
+ return result
benchmarks/edit/code/EditBoard/editboard/subject_consistency.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import cv2
4
+ import json
5
+ import numpy as np
6
+ from PIL import Image
7
+ from tqdm import tqdm
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import torchvision.transforms as transforms
13
+
14
+ from editboard.utils import load_video, load_dimension_info, dino_transform, dino_transform_Image
15
+
16
+
17
+ def subject_consistency(model, video_list, device, read_frame):
18
+ sim = 0.0
19
+ cnt = 0
20
+ video_results = {}
21
+ if read_frame:
22
+ image_transform = dino_transform_Image(224)
23
+ else:
24
+ image_transform = dino_transform(224)
25
+ for video_path in tqdm(video_list):
26
+ video_sim = 0.0
27
+ if read_frame:
28
+ video_path = video_path[:-4].replace('videos', 'frames').replace(' ', '_')
29
+ tmp_paths = [os.path.join(video_path, f) for f in sorted(os.listdir(video_path))]
30
+ images = []
31
+ for tmp_path in tmp_paths:
32
+ images.append(image_transform(Image.open(tmp_path)))
33
+ else:
34
+ images = load_video(video_path)
35
+ images = image_transform(images)
36
+ for i in range(len(images)):
37
+ with torch.no_grad():
38
+ image = images[i].unsqueeze(0)
39
+ image = image.to(device)
40
+ image_features = model(image)
41
+ image_features = F.normalize(image_features, dim=-1, p=2)
42
+ if i == 0:
43
+ first_image_features = image_features
44
+ else:
45
+ sim_pre = max(0.0, F.cosine_similarity(former_image_features, image_features).item())
46
+ sim_fir = max(0.0, F.cosine_similarity(first_image_features, image_features).item())
47
+ cur_sim = (sim_pre + sim_fir) / 2
48
+ video_sim += cur_sim
49
+ cnt += 1
50
+ former_image_features = image_features
51
+ sim_per_images = video_sim / (len(images) - 1)
52
+ sim += video_sim
53
+ video_results[os.path.dirname(os.path.dirname(video_path))] = sim_per_images
54
+ return video_results
55
+
56
+
57
+ def compute_subject_consistency(json_dir, device, submodules_list):
58
+ dino_model = torch.hub.load(**submodules_list).to(device)
59
+ read_frame = submodules_list['read_frame']
60
+ video_list = load_dimension_info(json_dir, dimension='subject_consistency')
61
+ video_results = subject_consistency(dino_model, video_list, device, read_frame)
62
+ return video_results
benchmarks/edit/code/EditBoard/editboard/success_rate.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import clip
3
+ from PIL import Image
4
+ from glob import glob
5
+ import numpy as np
6
+ import os
7
+ from editboard.utils import load_json
8
+ from tqdm import tqdm
9
+
10
+ def crop_read_image_path(image_path):
11
+ origin_image = Image.open(image_path)
12
+ w, h = origin_image.size
13
+ if h > w:
14
+ origin_image = origin_image.crop((0, h-w, w, h))
15
+ return origin_image
16
+
17
+ def edit_success(image_path, source_prompt,target_prompt, model, preprocess, device):
18
+ image = preprocess(crop_read_image_path(image_path)).unsqueeze(0).to(device)
19
+
20
+ text = clip.tokenize([source_prompt, target_prompt]).to(device)
21
+ target = clip.tokenize(target_prompt).to(device)
22
+
23
+
24
+ with torch.no_grad():
25
+ image_features = model.encode_image(image)
26
+ text_features = model.encode_text(text)
27
+ target_features = model.encode_text(target)
28
+
29
+ logits_per_image, logits_per_text = model(image, text)
30
+ probs = logits_per_image.softmax(dim=-1).cpu().numpy()
31
+
32
+
33
+ image_features = image_features.cpu().numpy()
34
+ target_features = target_features.cpu().numpy()
35
+ image_features_normalized = image_features / np.linalg.norm(image_features)
36
+ text_features_normalized = target_features / np.linalg.norm(target_features)
37
+
38
+ # Compute the cosine similarity
39
+ image_features_normalized = image_features_normalized
40
+ text_features_normalized = text_features_normalized
41
+
42
+ similarity = np.sum(image_features_normalized * text_features_normalized, -1)
43
+
44
+ if probs[0,1] >= probs[0,0]:
45
+ return 1, similarity[0]
46
+
47
+ else:
48
+ return 0, similarity[0]
49
+
50
+ def video_score(edited_video_path, source_prompt, target_prompt, model, preprocess, device):
51
+ count = 0
52
+ score = 0
53
+ file_list = os.listdir(edited_video_path)
54
+ file_list = [img for img in file_list if (img.endswith('.png') or img.endswith('.jpg') or img.endswith('.jpeg'))]
55
+
56
+ for i in file_list:
57
+ image_path = os.path.join(edited_video_path, i)
58
+ count_sub, score_sub = edit_success(image_path, source_prompt, target_prompt, model, preprocess, device)
59
+ count+=count_sub
60
+ score+=score_sub
61
+
62
+ success_rate = count/len(file_list)
63
+ clip_similarity = score/len(file_list)
64
+
65
+ return success_rate
66
+
67
+ def compute_success_rate(json_dir, device, submodules_list):
68
+ model, preprocess = clip.load("ViT-B/32", device=device)
69
+
70
+ metadata = load_json(json_dir)
71
+ result = {}
72
+ for i in tqdm(metadata):
73
+ score = video_score(i["edited_video_path"], i["source_prompt"], i["target_prompt"], model, preprocess, device)
74
+ result[i["edited_video_path"] + i["source_prompt"] + i["target_prompt"]] = score
75
+ return result
benchmarks/edit/code/EditBoard/editboard/test_optflow.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import os
5
+
6
+ def compute_optical_flow(image1, image2):
7
+ """
8
+ Compute the optical flow between two images using Farneback method.
9
+
10
+ Parameters:
11
+ image1 (np.array): The first input image.
12
+ image2 (np.array): The second input image.
13
+
14
+ Returns:
15
+ np.array: The computed optical flow.
16
+ """
17
+ # Convert images to grayscale
18
+ gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
19
+ gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
20
+
21
+ # Compute the optical flow
22
+ flow = cv2.calcOpticalFlowFarneback(gray1, gray2, None, 0.5, 3, 15, 3, 5, 1.2, 0)
23
+
24
+ return flow
25
+
26
+ def apply_optical_flow(image, flow):
27
+ """
28
+ Apply the optical flow to an image.
29
+
30
+ Parameters:
31
+ image (np.array): The input image.
32
+ flow (np.array): The computed optical flow.
33
+
34
+ Returns:
35
+ np.array: The resulting image after applying the optical flow.
36
+ """
37
+ h, w = flow.shape[:2]
38
+ # Generate the grid of coordinates and convert to float32
39
+ flow_map = np.meshgrid(np.arange(w), np.arange(h))
40
+ flow_map = np.stack(flow_map, axis=-1).astype(np.float32)
41
+
42
+ # Add flow to coordinates
43
+ flow_map -= flow
44
+
45
+ # Warp the image using the flow map
46
+ warped_image = cv2.remap(image, flow_map, None, cv2.INTER_LINEAR)
47
+
48
+ return warped_image
49
+
50
+
51
+
52
+
53
+ def draw_flow(img, flow, step=16):
54
+ """
55
+ Draw optical flow vectors on the image.
56
+
57
+ Parameters:
58
+ img (np.array): The input image.
59
+ flow (np.array): The optical flow.
60
+ step (int): The step size for sampling the flow vectors.
61
+
62
+ Returns:
63
+ np.array: The image with flow vectors drawn.
64
+ """
65
+ h, w = img.shape[:2]
66
+ y, x = np.mgrid[step//2:h:step, step//2:w:step].reshape(2,-1).astype(int)
67
+ fx, fy = flow[y,x].T
68
+
69
+ # Create an image with flow vectors
70
+ lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2)
71
+ lines = np.int32(lines + 0.5)
72
+ vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
73
+ cv2.polylines(vis, lines, 0, (0, 255, 0))
74
+
75
+ # Draw end points
76
+ for (x1, y1), (x2, y2) in lines:
77
+ cv2.circle(vis, (x1, y1), 1, (0, 255, 0), -1)
78
+ return vis
79
+
80
+
81
+
82
+
83
+ def visualize_image_difference(image1, image2):
84
+ """
85
+ Visualize the difference between two images.
86
+
87
+ Parameters:
88
+ image1 (np.array): The first input image.
89
+ image2 (np.array): The second input image.
90
+
91
+ Returns:
92
+ np.array: The image showing the differences.
93
+ """
94
+ # Ensure both images have the same shape
95
+ if image1.shape != image2.shape:
96
+ raise ValueError("Input images must have the same dimensions")
97
+
98
+ # Compute the absolute difference between the two images
99
+ diff = cv2.absdiff(image1, image2)
100
+
101
+ # Convert the difference to grayscale
102
+ diff_gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
103
+
104
+ # Apply a color map to the grayscale difference image to visualize it
105
+ diff_colormap = cv2.applyColorMap(diff_gray, cv2.COLORMAP_JET)
106
+
107
+ return diff_colormap
108
+
109
+ def display_image(image, title='Image'):
110
+ """
111
+ Display an image using Matplotlib.
112
+
113
+ Parameters:
114
+ image (np.array): The image to display.
115
+ title (str): The title of the plot.
116
+ """
117
+ plt.figure(figsize=(10, 10))
118
+ plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
119
+ plt.title(title)
120
+ plt.axis('off')
121
+ plt.show()
benchmarks/edit/code/EditBoard/editboard/utils.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
+ import logging
5
+ import subprocess
6
+ import torch
7
+ import re
8
+ from pathlib import Path
9
+ from PIL import Image, ImageSequence
10
+ # from decord import VideoReader # will make cv2.imread NONE!!
11
+ from torchvision import transforms
12
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize, ToPILImage
13
+ try:
14
+ from torchvision.transforms import InterpolationMode
15
+ BICUBIC = InterpolationMode.BICUBIC
16
+ BILINEAR = InterpolationMode.BILINEAR
17
+ except ImportError:
18
+ BICUBIC = Image.BICUBIC
19
+ BILINEAR = Image.BILINEAR
20
+
21
+ CACHE_DIR = os.environ.get('EDITBOARD_CACHE_DIR')
22
+ if CACHE_DIR is None:
23
+ CACHE_DIR = os.path.join(os.path.expanduser('~'), '.cache', 'editboard')
24
+
25
+ logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
26
+ logger = logging.getLogger(__name__)
27
+
28
+ def clip_transform(n_px):
29
+ return Compose([
30
+ Resize(n_px, interpolation=BICUBIC, antialias=False),
31
+ CenterCrop(n_px),
32
+ transforms.Lambda(lambda x: x.float().div(255.0)),
33
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
34
+ ])
35
+
36
+ def clip_transform_Image(n_px):
37
+ return Compose([
38
+ Resize(n_px, interpolation=BICUBIC, antialias=False),
39
+ CenterCrop(n_px),
40
+ ToTensor(),
41
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
42
+ ])
43
+
44
+ def dino_transform(n_px):
45
+ return Compose([
46
+ Resize(size=n_px, antialias=False),
47
+ transforms.Lambda(lambda x: x.float().div(255.0)),
48
+ Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
49
+ ])
50
+
51
+ def dino_transform_Image(n_px):
52
+ return Compose([
53
+ Resize(size=n_px, antialias=False),
54
+ ToTensor(),
55
+ Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
56
+ ])
57
+
58
+ def tag2text_transform(n_px):
59
+ normalize = Normalize(mean=[0.485, 0.456, 0.406],
60
+ std=[0.229, 0.224, 0.225])
61
+ return Compose([ToPILImage(),Resize((n_px, n_px), antialias=False),ToTensor(),normalize])
62
+
63
+ def get_frame_indices(num_frames, vlen, sample='rand', fix_start=None, input_fps=1, max_num_frames=-1):
64
+ if sample in ["rand", "middle"]: # uniform sampling
65
+ acc_samples = min(num_frames, vlen)
66
+ # split the video into `acc_samples` intervals, and sample from each interval.
67
+ intervals = np.linspace(start=0, stop=vlen, num=acc_samples + 1).astype(int)
68
+ ranges = []
69
+ for idx, interv in enumerate(intervals[:-1]):
70
+ ranges.append((interv, intervals[idx + 1] - 1))
71
+ if sample == 'rand':
72
+ try:
73
+ frame_indices = [random.choice(range(x[0], x[1])) for x in ranges]
74
+ except:
75
+ frame_indices = np.random.permutation(vlen)[:acc_samples]
76
+ frame_indices.sort()
77
+ frame_indices = list(frame_indices)
78
+ elif fix_start is not None:
79
+ frame_indices = [x[0] + fix_start for x in ranges]
80
+ elif sample == 'middle':
81
+ frame_indices = [(x[0] + x[1]) // 2 for x in ranges]
82
+ else:
83
+ raise NotImplementedError
84
+
85
+ if len(frame_indices) < num_frames: # padded with last frame
86
+ padded_frame_indices = [frame_indices[-1]] * num_frames
87
+ padded_frame_indices[:len(frame_indices)] = frame_indices
88
+ frame_indices = padded_frame_indices
89
+ elif "fps" in sample: # fps0.5, sequentially sample frames at 0.5 fps
90
+ output_fps = float(sample[3:])
91
+ duration = float(vlen) / input_fps
92
+ delta = 1 / output_fps # gap between frames, this is also the clip length each frame represents
93
+ frame_seconds = np.arange(0 + delta / 2, duration + delta / 2, delta)
94
+ frame_indices = np.around(frame_seconds * input_fps).astype(int)
95
+ frame_indices = [e for e in frame_indices if e < vlen]
96
+ if max_num_frames > 0 and len(frame_indices) > max_num_frames:
97
+ frame_indices = frame_indices[:max_num_frames]
98
+ # frame_indices = np.linspace(0 + delta / 2, duration + delta / 2, endpoint=False, num=max_num_frames)
99
+ else:
100
+ raise ValueError
101
+ return frame_indices
102
+
103
+ def load_video(video_path, data_transform=None, num_frames=None, return_tensor=True, width=None, height=None):
104
+ """
105
+ Load a video from a given path and apply optional data transformations.
106
+
107
+ The function supports loading video in GIF (.gif), PNG (.png), and MP4 (.mp4) formats.
108
+ Depending on the format, it processes and extracts frames accordingly.
109
+
110
+ Parameters:
111
+ - video_path (str): The file path to the video or image to be loaded.
112
+ - data_transform (callable, optional): A function that applies transformations to the video data.
113
+
114
+ Returns:
115
+ - frames (torch.Tensor): A tensor containing the video frames with shape (T, C, H, W),
116
+ where T is the number of frames, C is the number of channels, H is the height, and W is the width.
117
+
118
+ Raises:
119
+ - NotImplementedError: If the video format is not supported.
120
+
121
+ The function first determines the format of the video file by its extension.
122
+ For GIFs, it iterates over each frame and converts them to RGB.
123
+ For PNGs, it reads the single frame, converts it to RGB.
124
+ For MP4s, it reads the frames using the VideoReader class and converts them to NumPy arrays.
125
+ If a data_transform is provided, it is applied to the buffer before converting it to a tensor.
126
+ Finally, the tensor is permuted to match the expected (T, C, H, W) format.
127
+ """
128
+ if video_path.endswith('.gif'):
129
+ frame_ls = []
130
+ img = Image.open(video_path)
131
+ for frame in ImageSequence.Iterator(img):
132
+ frame = frame.convert('RGB')
133
+ frame = np.array(frame).astype(np.uint8)
134
+ frame_ls.append(frame)
135
+ buffer = np.array(frame_ls).astype(np.uint8)
136
+ elif video_path.endswith('.png'):
137
+ frame = Image.open(video_path)
138
+ frame = frame.convert('RGB')
139
+ frame = np.array(frame).astype(np.uint8)
140
+ frame_ls = [frame]
141
+ buffer = np.array(frame_ls)
142
+ # elif video_path.endswith('.mp4'):
143
+ # import decord
144
+ # decord.bridge.set_bridge('native')
145
+ # if width:
146
+ # video_reader = VideoReader(video_path, width=width, height=height, num_threads=1)
147
+ # else:
148
+ # video_reader = VideoReader(video_path, num_threads=1)
149
+ # frame_indices = range(len(video_reader))
150
+ # if num_frames:
151
+ # frame_indices = get_frame_indices(
152
+ # num_frames, len(video_reader), sample="middle"
153
+ # )
154
+ # frames = video_reader.get_batch(frame_indices) # (T, H, W, C), torch.uint8
155
+ # buffer = frames.asnumpy().astype(np.uint8)
156
+ else:
157
+ raise NotImplementedError
158
+
159
+ frames = buffer
160
+ if num_frames and not video_path.endswith('.mp4'):
161
+ frame_indices = get_frame_indices(
162
+ num_frames, len(frames), sample="middle"
163
+ )
164
+ frames = frames[frame_indices]
165
+
166
+ if data_transform:
167
+ frames = data_transform(frames)
168
+ elif return_tensor:
169
+ frames = torch.Tensor(frames)
170
+ frames = frames.permute(0, 3, 1, 2) # (T, C, H, W), torch.uint8
171
+
172
+ return frames
173
+
174
+ def load_dimension_info(json_dir, dimension):
175
+ """
176
+ Load video list and prompt information based on a specified dimension and language from a JSON file.
177
+
178
+ Parameters:
179
+ - json_dir (str): The directory path where the JSON file is located.
180
+ - dimension (str): The dimension for evaluation to filter the video prompts.
181
+
182
+ Returns:
183
+ - video_list (list): A list of video file paths that match the specified dimension.
184
+ - prompt_dict_ls (list): A list of dictionaries, each containing a prompt and its corresponding video list.
185
+
186
+ The function reads the JSON file to extract video information. It filters the prompts based on the specified
187
+ dimension and compiles a list of video paths and associated prompts in the specified language.
188
+
189
+ Notes:
190
+ - The JSON file is expected to contain a list of dictionaries with keys 'dimension', "edited_video_path", and language-based prompts.
191
+ - The function assumes that the "edited_video_path" key in the JSON can either be a list or a single string value.
192
+ """
193
+ video_list = []
194
+ full_prompt_list = load_json(json_dir)
195
+ for each_item in full_prompt_list:
196
+ if dimension in each_item['dimension'] and "edited_video_path" in each_item:
197
+ source_folder = each_item["edited_video_path"]
198
+ output_folder = os.path.join(source_folder, "tempt_dir")
199
+ folder_name = os.path.basename(source_folder)
200
+ gif_path = os.path.join(output_folder, f"{folder_name}.gif")
201
+
202
+ video_list.append(gif_path)
203
+ return video_list
204
+
205
+ def init_submodules(dimension_list, read_frame=False):
206
+ submodules_dict = {}
207
+ for dimension in dimension_list:
208
+ os.makedirs(CACHE_DIR, exist_ok=True)
209
+ if dimension == 'background_consistency':
210
+ # read_frame = False
211
+ vit_b_path = 'ViT-B/32'
212
+
213
+ submodules_dict[dimension] = [vit_b_path, read_frame]
214
+
215
+ # Assign the DINO model path for subject consistency dimension
216
+ elif dimension == 'subject_consistency':
217
+ submodules_dict[dimension] = {
218
+ 'repo_or_dir':'facebookresearch/dino:main',
219
+ 'source':'github',
220
+ 'model': 'dino_vitb16',
221
+ 'read_frame': read_frame
222
+ }
223
+
224
+ elif dimension == 'aesthetic_quality':
225
+ aes_path = f'{CACHE_DIR}/aesthetic_model/emb_reader'
226
+
227
+ vit_l_path = 'ViT-L/14'
228
+ submodules_dict[dimension] = [vit_l_path, aes_path]
229
+ elif dimension == 'imaging_quality':
230
+ musiq_spaq_path = f'{CACHE_DIR}/pyiqa_model/musiq_spaq_ckpt-358bb6af.pth'
231
+ if not os.path.isfile(musiq_spaq_path):
232
+ wget_command = ['wget', 'https://github.com/chaofengc/IQA-PyTorch/releases/download/v0.1-weights/musiq_spaq_ckpt-358bb6af.pth', '-P', os.path.dirname(musiq_spaq_path)]
233
+ subprocess.run(wget_command, check=True)
234
+ submodules_dict[dimension] = {'model_path': musiq_spaq_path}
235
+ else:
236
+ submodules_dict[dimension] = None
237
+ return submodules_dict
238
+
239
+
240
+ def save_json(data, path, indent=4):
241
+ with open(path, 'w', encoding='utf-8') as f:
242
+ json.dump(data, f, indent=indent)
243
+
244
+ def load_json(path):
245
+ """
246
+ Load a JSON file from the given file path.
247
+
248
+ Parameters:
249
+ - file_path (str): The path to the JSON file.
250
+
251
+ Returns:
252
+ - data (dict or list): The data loaded from the JSON file, which could be a dictionary or a list.
253
+ """
254
+ with open(path, 'r', encoding='utf-8') as f:
255
+ return json.load(f)
benchmarks/edit/code/EditBoard/sample/script.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ original_video_path,edited_video_path,semantic_mask_path,source_prompt,target_prompt
2
+ ./sample/bear,./sample/bear_autumn,./sample/bear_mask,a brown bear walks on rocks,a brown bear walks on rocks in the autumn
3
+ ./sample/bear,./sample/bear_grass,./sample/bear_mask,a brown bear walks on rocks,a brown bear walks on grass
4
+ ./sample/bear,./sample/bear_panda,./sample/bear_mask,a brown bear walks on rocks,a brown panda walks on rocks
5
+ ./sample/bear,./sample/bear_white,./sample/bear_mask,a brown bear walks on rocks,a white bear walks on rocks
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/config.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ device: 'cuda'
2
+ dtype: 'bf16'
3
+ seed: null
4
+ model_name: 'pyramid_flux'
5
+ model_path: 'models/pyramid-edit/hf/pyramid-flow-miniflux'
6
+ resolution: '384p'
7
+ dataset_json: 'data/edit_prompt/edit5_FiVE.json'
8
+
9
+ # FiVE-Bench
10
+ output_path: 'outputs/video_name'
11
+ attn_path: 'outputs/video_name/attn_weights'
12
+ data_dir: 'data/images'
13
+ latents_path: 'data/video_name/rf_inv_latents'
14
+ source_prompt: source prompt
15
+ source_obj_prompt: source obj prompt
16
+ target_prompt: target prompt
17
+ target_obj_prompt: target obj prompt
18
+ negative_prompt: worst quality, low quality, blurry, absolute black, absolute white, low res, extra limbs, extra digits, misplaced objects, mutated anatomy, monochrome, horror
19
+ guidance_scale: 7.0
20
+ video_guidance_scale: 5.0
21
+
22
+ max_frames: 41 # (40 // 8 + 1) = 6
23
+ n_timesteps: 20
24
+ guidance_start_timestep_first: 750
25
+ guidance_stop_timestep_first: 100
26
+ guidance_start_timestep: 750
27
+ guidance_stop_timestep: 100
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/diffusion_schedulers/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .scheduling_cosine_ddpm import DDPMCosineScheduler
2
+ from .scheduling_flow_matching import PyramidFlowMatchEulerDiscreteScheduler
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/diffusion_schedulers/scheduling_cosine_ddpm.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ import torch
6
+
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.utils import BaseOutput
9
+ from diffusers.utils.torch_utils import randn_tensor
10
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
11
+
12
+
13
+ @dataclass
14
+ class DDPMSchedulerOutput(BaseOutput):
15
+ """
16
+ Output class for the scheduler's step function output.
17
+
18
+ Args:
19
+ prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
20
+ Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
21
+ denoising loop.
22
+ """
23
+
24
+ prev_sample: torch.Tensor
25
+
26
+
27
+ class DDPMCosineScheduler(SchedulerMixin, ConfigMixin):
28
+
29
+ @register_to_config
30
+ def __init__(
31
+ self,
32
+ scaler: float = 1.0,
33
+ s: float = 0.008,
34
+ ):
35
+ self.scaler = scaler
36
+ self.s = torch.tensor([s])
37
+ self._init_alpha_cumprod = torch.cos(self.s / (1 + self.s) * torch.pi * 0.5) ** 2
38
+
39
+ # standard deviation of the initial noise distribution
40
+ self.init_noise_sigma = 1.0
41
+
42
+ def _alpha_cumprod(self, t, device):
43
+ if self.scaler > 1:
44
+ t = 1 - (1 - t) ** self.scaler
45
+ elif self.scaler < 1:
46
+ t = t**self.scaler
47
+ alpha_cumprod = torch.cos(
48
+ (t + self.s.to(device)) / (1 + self.s.to(device)) * torch.pi * 0.5
49
+ ) ** 2 / self._init_alpha_cumprod.to(device)
50
+ return alpha_cumprod.clamp(0.0001, 0.9999)
51
+
52
+ def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
53
+ """
54
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
55
+ current timestep.
56
+
57
+ Args:
58
+ sample (`torch.Tensor`): input sample
59
+ timestep (`int`, optional): current timestep
60
+
61
+ Returns:
62
+ `torch.Tensor`: scaled input sample
63
+ """
64
+ return sample
65
+
66
+ def set_timesteps(
67
+ self,
68
+ num_inference_steps: int = None,
69
+ timesteps: Optional[List[int]] = None,
70
+ device: Union[str, torch.device] = None,
71
+ ):
72
+ """
73
+ Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
74
+
75
+ Args:
76
+ num_inference_steps (`Dict[float, int]`):
77
+ the number of diffusion steps used when generating samples with a pre-trained model. If passed, then
78
+ `timesteps` must be `None`.
79
+ device (`str` or `torch.device`, optional):
80
+ the device to which the timesteps are moved to. {2 / 3: 20, 0.0: 10}
81
+ """
82
+ if timesteps is None:
83
+ timesteps = torch.linspace(1.0, 0.0, num_inference_steps + 1, device=device)
84
+ if not isinstance(timesteps, torch.Tensor):
85
+ timesteps = torch.Tensor(timesteps).to(device)
86
+ self.timesteps = timesteps
87
+
88
+ def step(
89
+ self,
90
+ model_output: torch.Tensor,
91
+ timestep: int,
92
+ sample: torch.Tensor,
93
+ generator=None,
94
+ return_dict: bool = True,
95
+ ) -> Union[DDPMSchedulerOutput, Tuple]:
96
+ dtype = model_output.dtype
97
+ device = model_output.device
98
+ t = timestep
99
+
100
+ prev_t = self.previous_timestep(t)
101
+
102
+ alpha_cumprod = self._alpha_cumprod(t, device).view(t.size(0), *[1 for _ in sample.shape[1:]])
103
+ alpha_cumprod_prev = self._alpha_cumprod(prev_t, device).view(prev_t.size(0), *[1 for _ in sample.shape[1:]])
104
+ alpha = alpha_cumprod / alpha_cumprod_prev
105
+
106
+ mu = (1.0 / alpha).sqrt() * (sample - (1 - alpha) * model_output / (1 - alpha_cumprod).sqrt())
107
+
108
+ std_noise = randn_tensor(mu.shape, generator=generator, device=model_output.device, dtype=model_output.dtype)
109
+ std = ((1 - alpha) * (1.0 - alpha_cumprod_prev) / (1.0 - alpha_cumprod)).sqrt() * std_noise
110
+ pred = mu + std * (prev_t != 0).float().view(prev_t.size(0), *[1 for _ in sample.shape[1:]])
111
+
112
+ if not return_dict:
113
+ return (pred.to(dtype),)
114
+
115
+ return DDPMSchedulerOutput(prev_sample=pred.to(dtype))
116
+
117
+ def add_noise(
118
+ self,
119
+ original_samples: torch.Tensor,
120
+ noise: torch.Tensor,
121
+ timesteps: torch.Tensor,
122
+ ) -> torch.Tensor:
123
+ device = original_samples.device
124
+ dtype = original_samples.dtype
125
+ alpha_cumprod = self._alpha_cumprod(timesteps, device=device).view(
126
+ timesteps.size(0), *[1 for _ in original_samples.shape[1:]]
127
+ )
128
+ noisy_samples = alpha_cumprod.sqrt() * original_samples + (1 - alpha_cumprod).sqrt() * noise
129
+ return noisy_samples.to(dtype=dtype)
130
+
131
+ def __len__(self):
132
+ return self.config.num_train_timesteps
133
+
134
+ def previous_timestep(self, timestep):
135
+ index = (self.timesteps - timestep[0]).abs().argmin().item()
136
+ prev_t = self.timesteps[index + 1][None].expand(timestep.shape[0])
137
+ return prev_t
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/diffusion_schedulers/scheduling_flow_matching.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Tuple, Union, List
3
+ import math
4
+ import numpy as np
5
+ import torch
6
+
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.utils import BaseOutput, logging
9
+ from diffusers.utils.torch_utils import randn_tensor
10
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
11
+
12
+
13
+ @dataclass
14
+ class FlowMatchEulerDiscreteSchedulerOutput(BaseOutput):
15
+ """
16
+ Output class for the scheduler's `step` function output.
17
+
18
+ Args:
19
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
20
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
21
+ denoising loop.
22
+ """
23
+
24
+ prev_sample: torch.FloatTensor
25
+
26
+
27
+ class PyramidFlowMatchEulerDiscreteScheduler(SchedulerMixin, ConfigMixin):
28
+ """
29
+ Euler scheduler.
30
+
31
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
32
+ methods the library implements for all schedulers such as loading and saving.
33
+
34
+ Args:
35
+ num_train_timesteps (`int`, defaults to 1000):
36
+ The number of diffusion steps to train the model.
37
+ timestep_spacing (`str`, defaults to `"linspace"`):
38
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
39
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
40
+ shift (`float`, defaults to 1.0):
41
+ The shift value for the timestep schedule.
42
+ """
43
+
44
+ _compatibles = []
45
+ order = 1
46
+
47
+ @register_to_config
48
+ def __init__(
49
+ self,
50
+ num_train_timesteps: int = 1000,
51
+ shift: float = 1.0, # Following Stable diffusion 3,
52
+ stages: int = 3,
53
+ stage_range: List = [0, 1/3, 2/3, 1],
54
+ gamma: float = 1/3,
55
+ ):
56
+
57
+ self.timestep_ratios = {} # The timestep ratio for each stage
58
+ self.timesteps_per_stage = {} # The detailed timesteps per stage
59
+ self.sigmas_per_stage = {}
60
+ self.start_sigmas = {}
61
+ self.end_sigmas = {}
62
+ self.ori_start_sigmas = {}
63
+
64
+ # self.init_sigmas()
65
+ self.init_sigmas_for_each_stage()
66
+ self.sigma_min = self.sigmas[-1].item()
67
+ self.sigma_max = self.sigmas[0].item()
68
+ self.gamma = gamma
69
+
70
+ def init_sigmas(self):
71
+ """
72
+ initialize the global timesteps and sigmas
73
+ """
74
+ num_train_timesteps = self.config.num_train_timesteps
75
+ shift = self.config.shift
76
+
77
+ timesteps = np.linspace(1, num_train_timesteps, num_train_timesteps, dtype=np.float32)[::-1].copy()
78
+ timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32)
79
+
80
+ sigmas = timesteps / num_train_timesteps
81
+ sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
82
+
83
+ self.timesteps = sigmas * num_train_timesteps
84
+
85
+ self._step_index = None
86
+ self._begin_index = None
87
+
88
+ self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication
89
+
90
+ def init_sigmas_for_each_stage(self):
91
+ """
92
+ Init the timesteps for each stage
93
+ """
94
+ self.init_sigmas()
95
+
96
+ stage_distance = []
97
+ stages = self.config.stages
98
+ training_steps = self.config.num_train_timesteps
99
+ stage_range = self.config.stage_range
100
+
101
+ # Init the start and end point of each stage
102
+ for i_s in range(stages):
103
+ # To decide the start and ends point
104
+ start_indice = int(stage_range[i_s] * training_steps)
105
+ start_indice = max(start_indice, 0)
106
+ end_indice = int(stage_range[i_s+1] * training_steps)
107
+ end_indice = min(end_indice, training_steps)
108
+ start_sigma = self.sigmas[start_indice].item()
109
+ end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0
110
+ self.ori_start_sigmas[i_s] = start_sigma
111
+
112
+ if i_s != 0:
113
+ ori_sigma = 1 - start_sigma
114
+ gamma = self.config.gamma
115
+ corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma
116
+ # corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma
117
+ start_sigma = 1 - corrected_sigma
118
+
119
+ stage_distance.append(start_sigma - end_sigma)
120
+ self.start_sigmas[i_s] = start_sigma
121
+ self.end_sigmas[i_s] = end_sigma
122
+
123
+ # Determine the ratio of each stage according to flow length
124
+ tot_distance = sum(stage_distance)
125
+ for i_s in range(stages):
126
+ if i_s == 0:
127
+ start_ratio = 0.0
128
+ else:
129
+ start_ratio = sum(stage_distance[:i_s]) / tot_distance
130
+ if i_s == stages - 1:
131
+ end_ratio = 1.0
132
+ else:
133
+ end_ratio = sum(stage_distance[:i_s+1]) / tot_distance
134
+
135
+ self.timestep_ratios[i_s] = (start_ratio, end_ratio)
136
+
137
+ # Determine the timesteps and sigmas for each stage
138
+ for i_s in range(stages):
139
+ timestep_ratio = self.timestep_ratios[i_s]
140
+ timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)]
141
+ timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)]
142
+ timesteps = np.linspace(
143
+ timestep_max, timestep_min, training_steps + 1,
144
+ )
145
+ self.timesteps_per_stage[i_s] = timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1])
146
+ stage_sigmas = np.linspace(
147
+ 1, 0, training_steps + 1,
148
+ )
149
+ self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1])
150
+
151
+ @property
152
+ def step_index(self):
153
+ """
154
+ The index counter for current timestep. It will increase 1 after each scheduler step.
155
+ """
156
+ return self._step_index
157
+
158
+ @property
159
+ def begin_index(self):
160
+ """
161
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
162
+ """
163
+ return self._begin_index
164
+
165
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
166
+ def set_begin_index(self, begin_index: int = 0):
167
+ """
168
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
169
+
170
+ Args:
171
+ begin_index (`int`):
172
+ The begin index for the scheduler.
173
+ """
174
+ self._begin_index = begin_index
175
+
176
+ def _sigma_to_t(self, sigma):
177
+ return sigma * self.config.num_train_timesteps
178
+
179
+ def set_timesteps(self, num_inference_steps: int, stage_index: int, device: Union[str, torch.device] = None):
180
+ """
181
+ Setting the timesteps and sigmas for each stage
182
+ """
183
+ self.num_inference_steps = num_inference_steps
184
+ training_steps = self.config.num_train_timesteps
185
+ self.init_sigmas()
186
+
187
+ stage_timesteps = self.timesteps_per_stage[stage_index]
188
+ timestep_max = stage_timesteps[0].item()
189
+ timestep_min = stage_timesteps[-1].item()
190
+
191
+ timesteps = np.linspace(
192
+ timestep_max, timestep_min, num_inference_steps,
193
+ )
194
+ self.timesteps = torch.from_numpy(timesteps).to(device=device)
195
+
196
+ stage_sigmas = self.sigmas_per_stage[stage_index]
197
+ sigma_max = stage_sigmas[0].item()
198
+ sigma_min = stage_sigmas[-1].item()
199
+
200
+ ratios = np.linspace(
201
+ sigma_max, sigma_min, num_inference_steps
202
+ )
203
+ sigmas = torch.from_numpy(ratios).to(device=device)
204
+ self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
205
+
206
+ self._step_index = None
207
+
208
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
209
+ if schedule_timesteps is None:
210
+ schedule_timesteps = self.timesteps
211
+
212
+ indices = (schedule_timesteps == timestep).nonzero()
213
+
214
+ # The sigma index that is taken for the **very** first `step`
215
+ # is always the second index (or the last index if there is only 1)
216
+ # This way we can ensure we don't accidentally skip a sigma in
217
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
218
+ pos = 1 if len(indices) > 1 else 0
219
+
220
+ return indices[pos].item()
221
+
222
+ def _init_step_index(self, timestep):
223
+ if self.begin_index is None:
224
+ if isinstance(timestep, torch.Tensor):
225
+ timestep = timestep.to(self.timesteps.device)
226
+ self._step_index = self.index_for_timestep(timestep)
227
+ else:
228
+ self._step_index = self._begin_index
229
+
230
+ def step(
231
+ self,
232
+ model_output: torch.FloatTensor,
233
+ timestep: Union[float, torch.FloatTensor],
234
+ sample: torch.FloatTensor,
235
+ generator: Optional[torch.Generator] = None,
236
+ return_dict: bool = True,
237
+ ) -> Union[FlowMatchEulerDiscreteSchedulerOutput, Tuple]:
238
+ """
239
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
240
+ process from the learned model outputs (most often the predicted noise).
241
+
242
+ Args:
243
+ model_output (`torch.FloatTensor`):
244
+ The direct output from learned diffusion model.
245
+ timestep (`float`):
246
+ The current discrete timestep in the diffusion chain.
247
+ sample (`torch.FloatTensor`):
248
+ A current instance of a sample created by the diffusion process.
249
+ generator (`torch.Generator`, *optional*):
250
+ A random number generator.
251
+ return_dict (`bool`):
252
+ Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
253
+ tuple.
254
+
255
+ Returns:
256
+ [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
257
+ If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
258
+ returned, otherwise a tuple is returned where the first element is the sample tensor.
259
+ """
260
+
261
+ if (
262
+ isinstance(timestep, int)
263
+ or isinstance(timestep, torch.IntTensor)
264
+ or isinstance(timestep, torch.LongTensor)
265
+ ):
266
+ raise ValueError(
267
+ (
268
+ "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
269
+ " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
270
+ " one of the `scheduler.timesteps` as a timestep."
271
+ ),
272
+ )
273
+
274
+ if self.step_index is None:
275
+ self._step_index = 0
276
+
277
+ # Upcast to avoid precision issues when computing prev_sample
278
+ sample = sample.to(torch.float32)
279
+
280
+ sigma = self.sigmas[self.step_index]
281
+ sigma_next = self.sigmas[self.step_index + 1]
282
+
283
+ prev_sample = sample + (sigma_next - sigma) * model_output
284
+
285
+ # Cast sample back to model compatible dtype
286
+ prev_sample = prev_sample.to(model_output.dtype)
287
+
288
+ # upon completion increase step index by one
289
+ self._step_index += 1
290
+
291
+ if not return_dict:
292
+ return (prev_sample,)
293
+
294
+ return FlowMatchEulerDiscreteSchedulerOutput(prev_sample=prev_sample)
295
+
296
+ def __len__(self):
297
+ return self.config.num_train_timesteps
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/edit.py ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import copy
3
+ import os, math, cv2
4
+ import random
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from PIL import Image
12
+ from einops import rearrange
13
+ from omegaconf import OmegaConf
14
+ from tqdm import tqdm
15
+ from transformers import logging, T5TokenizerFast
16
+ from torchvision import transforms
17
+ from diffusers.utils import export_to_video
18
+ from typing import List, Union
19
+
20
+ from torchvision.transforms.functional import InterpolationMode
21
+
22
+ from utilities.guidance_utils import register_batch
23
+ from pyramid_dit import PyramidDiTForVideoGeneration
24
+
25
+ # suppress partial model loading warning
26
+ logging.set_verbosity_error()
27
+
28
+
29
+ class T5Tokenizer(torch.nn.Module):
30
+ def __init__(self, model_name, model_path):
31
+ super().__init__()
32
+ if model_name == "pyramid_flux":
33
+ self.tokenizer = T5TokenizerFast.from_pretrained(os.path.join(model_path, 'tokenizer_2'))
34
+ elif model_name == "pyramid_mmdit":
35
+ self.tokenizer = T5TokenizerFast.from_pretrained(os.path.join(model_path, 'tokenizer_3'))
36
+ else:
37
+ raise NotImplementedError(f"Unsupported Text Encoder")
38
+
39
+ def forward(
40
+ self,
41
+ prompt: Union[str, List[str]] = None,
42
+ obj_prompt: Union[str, List[str]] = None,
43
+ ):
44
+
45
+ prompt = [prompt] if isinstance(prompt, str) else prompt
46
+ batch_size = len(prompt)
47
+
48
+ text_inputs = self.tokenizer(
49
+ prompt,
50
+ truncation=True,
51
+ return_length=False,
52
+ return_overflowing_tokens=False,
53
+ return_tensors="pt",
54
+ )
55
+ text_input_ids = text_inputs.input_ids[0]
56
+ print('Prompt len:', len(text_input_ids), text_input_ids)
57
+
58
+ # Tokenize the object phrase
59
+ obj_prompt = [obj_prompt] if isinstance(obj_prompt, str) else obj_prompt
60
+ obj_inputs = self.tokenizer(
61
+ obj_prompt,
62
+ truncation=True,
63
+ return_length=False,
64
+ return_overflowing_tokens=False,
65
+ return_tensors="pt",
66
+ )
67
+ obj_input_ids = obj_inputs.input_ids[0]
68
+ obj_input_ids = obj_input_ids[:-1] # Remove start/end tokens
69
+ print('Obj prompt len:',len(obj_input_ids), obj_input_ids)
70
+
71
+ # Find the start index of the phrase in the sentence
72
+ start_idx = -1
73
+ for i in range(len(text_input_ids) - len(obj_input_ids) + 1):
74
+ if text_input_ids[i:i+len(obj_input_ids)].tolist() == obj_input_ids.tolist():
75
+ start_idx = i
76
+ break
77
+
78
+ # Output results
79
+ # assert start_idx != -1, "Phrase not found in sentence tokens."
80
+ if start_idx == -1:
81
+ print("Phrase not found in sentence tokens.") # Not used
82
+ end_idx = start_idx + len(obj_input_ids)
83
+
84
+ return start_idx, end_idx
85
+
86
+
87
+ class VideoFrameProcessor:
88
+ # load a video and transform
89
+ def __init__(self, resolution=384, num_frames=41, add_normalize=True, sample_fps=24):
90
+
91
+ image_size = resolution
92
+
93
+ transform_list = [
94
+ transforms.Resize(image_size, interpolation=InterpolationMode.BICUBIC, antialias=True),
95
+ transforms.CenterCrop(image_size),
96
+ ]
97
+
98
+ if add_normalize:
99
+ transform_list.append(transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)))
100
+
101
+ print(f"Transform List is {transform_list}")
102
+ self.num_frames = num_frames
103
+ self.transform = transforms.Compose(transform_list)
104
+ self.sample_fps = sample_fps
105
+
106
+ def __call__(self, video_path):
107
+ try:
108
+ video_capture = cv2.VideoCapture(video_path)
109
+ fps = video_capture.get(cv2.CAP_PROP_FPS)
110
+ frames = []
111
+
112
+ while True:
113
+ flag, frame = video_capture.read()
114
+ if not flag:
115
+ break
116
+
117
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
118
+ frame = torch.from_numpy(frame)
119
+ frame = frame.permute(2, 0, 1)
120
+ frames.append(frame)
121
+
122
+ video_capture.release()
123
+ sample_fps = self.sample_fps
124
+
125
+ interval = max(int(fps / sample_fps), 1)
126
+ frames = frames[::interval]
127
+
128
+ if len(frames) < self.num_frames:
129
+ num_frame_to_pack = self.num_frames - len(frames)
130
+ recurrent_num = num_frame_to_pack // len(frames)
131
+ frames = frames + recurrent_num * frames + frames[:(num_frame_to_pack % len(frames))]
132
+ assert len(frames) >= self.num_frames, f'{len(frames)}'
133
+
134
+ frames = torch.stack(frames).float() / 255
135
+ frames = self.transform(frames)
136
+ frames = frames.permute(1, 0, 2, 3)
137
+
138
+ return frames, None
139
+
140
+ except Exception as e:
141
+ print(f"Load video: {video_path} Error, Exception {e}")
142
+ return None, None
143
+
144
+
145
+ class Guidance(nn.Module):
146
+ def __init__(self, config):
147
+ super().__init__()
148
+ self.config = config
149
+ self.device = config["device"]
150
+ model_dtype = config["dtype"]
151
+ assert model_dtype == "bf16", "Pyramid-Flow performs better for bf16!!"
152
+ if model_dtype == "bf16":
153
+ # inference only, "_amp_foreach_non_finite_check_and_unscale_cuda" not implemented for 'BFloat16'
154
+ torch_dtype = torch.bfloat16
155
+ elif model_dtype == "fp16":
156
+ torch_dtype = torch.float16
157
+ else:
158
+ torch_dtype = torch.float32
159
+ self.dtype = torch_dtype
160
+
161
+ self.guidance_start_timestep = config["guidance_start_timestep"]
162
+ self.guidance_stop_timestep = config["guidance_stop_timestep"]
163
+ self.guidance_start_timestep_first = config["guidance_start_timestep_first"]
164
+ self.guidance_stop_timestep_first = config["guidance_stop_timestep_first"]
165
+
166
+ if config['resolution'] == '384p':
167
+ self.resolution = (640, 384) # width, height
168
+ elif config['resolution'] == '768p':
169
+ self.resolution = (1280, 768)
170
+ else:
171
+ raise ValueError
172
+ self.ori_resolution = None
173
+
174
+ print("\n\nLoading video model ...")
175
+
176
+ model_name = config["model_name"] # "pyramid_flux" or "pyramid_mmdit"
177
+ if config['resolution'] == '384p':
178
+ variant='diffusion_transformer_384p' # For low resolution
179
+ else:
180
+ variant='diffusion_transformer_768p' # For high resolution
181
+ model_path = config["model_path"] # The downloaded checkpoint dir
182
+
183
+ self.t5_tokenizer = T5Tokenizer(model_name, model_path)
184
+
185
+ self.video_pipe = PyramidDiTForVideoGeneration(
186
+ model_path,
187
+ model_dtype=self.dtype,
188
+ model_name=model_name,
189
+ model_variant=variant,
190
+ )
191
+
192
+ self.video_pipe.vae.enable_tiling()
193
+ self.video_pipe._guidance_scale = config["guidance_scale"]
194
+ self.vae = self.video_pipe.vae.to("cuda").to(self.dtype)
195
+ self.text_encoder = self.video_pipe.text_encoder.to("cuda")
196
+ self.dit = self.video_pipe.dit.to("cuda")
197
+ self.decode_latent = self.video_pipe.decode_latent
198
+ self.scheduler = copy.deepcopy(self.video_pipe.scheduler)
199
+ self.stages = self.video_pipe.stages
200
+ self.do_classifier_free_guidance = self.video_pipe.do_classifier_free_guidance
201
+ self.device = self.video_pipe.device
202
+ print("video model loaded!\n\n")
203
+
204
+ self.generator = None
205
+
206
+ with torch.no_grad():
207
+ # T5 text embed, T5 text mask, CLIP text pooled embed
208
+ self.src_text_prompt_cond, self.src_prompt_attention_mask, self.src_pooled_prompt_embeds, self.src_all_prompt_embeds = self.get_text_embeds(
209
+ config["source_prompt"], config["negative_prompt"],
210
+ )
211
+ self.tgt_text_prompt_cond, self.tgt_prompt_attention_mask, self.tgt_pooled_prompt_embeds, self.tgt_all_prompt_embeds = self.get_text_embeds(
212
+ config["target_prompt"], config["negative_prompt"],
213
+ )
214
+
215
+ self.video_processor = VideoFrameProcessor(
216
+ (self.resolution[1], self.resolution[0]), num_frames=self.config["max_frames"], add_normalize=True
217
+ )
218
+
219
+ # load images and latents
220
+ self.frame_index = None
221
+ self.input_frames_latent_ms, self.noise_latent_ms = self.get_data()
222
+
223
+ @torch.no_grad()
224
+ def get_text_embeds(self, prompt, negative_prompt, cpu_offloading=False):
225
+ if isinstance(prompt, str):
226
+ if len(prompt) > 0: # except null prompt
227
+ prompt = prompt + ", hyper quality, Ultra HD, 8K" # adding this prompt to improve aesthetics
228
+ else:
229
+ assert isinstance(prompt, list)
230
+ prompt = [p_ + ", hyper quality, Ultra HD, 8K" if len(p_) > 0 else p_ for p_ in prompt]
231
+
232
+ negative_prompt = negative_prompt or ""
233
+
234
+ # Get the text embeddings
235
+ if cpu_offloading:
236
+ self.text_encoder.to("cuda")
237
+ prompt_embeds, prompt_attention_mask, pooled_prompt_embeds, all_prompt_embeds = self.text_encoder(
238
+ prompt, self.device, return_all_prompt_embeds_clip=True)
239
+ negative_prompt_embeds, negative_prompt_attention_mask, negative_pooled_prompt_embeds, negative_all_prompt_embeds = self.text_encoder(
240
+ negative_prompt, self.device, return_all_prompt_embeds_clip=True)
241
+
242
+ if cpu_offloading:
243
+ self.text_encoder.to("cpu")
244
+ self.vae.to("cuda")
245
+ torch.cuda.empty_cache()
246
+
247
+ if self.do_classifier_free_guidance:
248
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
249
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
250
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
251
+ all_prompt_embeds = torch.cat([negative_all_prompt_embeds, all_prompt_embeds], dim=0)
252
+
253
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds, all_prompt_embeds
254
+
255
+
256
+ @torch.autocast(device_type="cuda", dtype=torch.bfloat16)
257
+ def get_data(self):
258
+ # load video frames
259
+ data_path = self.config["data_path"]
260
+
261
+ if os.path.isdir(data_path):
262
+ images = list(Path(data_path).glob("*.png")) + list(Path(data_path).glob("*.jpg"))
263
+ images = sorted(images, key=lambda x: int(x.stem))
264
+ if len(images) > self.config["max_frames"]:
265
+ print('!'*100)
266
+ print(f'Video frames {len(images)} > Max frames {self.config["max_frames"]}! Use the first {self.config["max_frames"]} frames.')
267
+ print('!'*100)
268
+ images = images[:self.config["max_frames"]]
269
+ width, height = Image.open(images[0]).size
270
+ self.ori_resolution = (height, width)
271
+
272
+ image_transform = transforms.Compose([
273
+ transforms.ToTensor(),
274
+ transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)),
275
+ ])
276
+ input_frames_tensor_list = []
277
+ for unit_index in tqdm(range(len(images))):
278
+ image_name = images[unit_index]
279
+ image = Image.open(image_name).convert("RGB")
280
+ image = image.resize(self.resolution)
281
+ input_image_tensor = image_transform(image).unsqueeze(0).unsqueeze(2) # [b c 1 h w]
282
+ input_frames_tensor_list.append(input_image_tensor)
283
+
284
+ input_frames_latent = torch.cat(input_frames_tensor_list, dim=2)
285
+
286
+ else:
287
+
288
+ input_frames_latent, _ = self.video_processor(data_path)
289
+ input_frames_latent = input_frames_latent.unsqueeze(0)
290
+
291
+ self.ori_resolution = (input_frames_latent.shape[-2], input_frames_latent.shape[-1])
292
+
293
+ # 8n + 1
294
+ nf = input_frames_latent.shape[2] // 8
295
+ nf = 8*nf+1 if input_frames_latent.shape[2] % 8 != 0 else 8*(nf-1)+1
296
+ input_frames_latent = input_frames_latent[:,:,:nf]
297
+
298
+ input_frames_latent = self.vae.encode(input_frames_latent.to(self.device).to(self.dtype)).latent_dist.sample()
299
+
300
+ input_frames_latent[:,:,:1] = (input_frames_latent[:,:,:1] - self.video_pipe.vae_shift_factor) * self.video_pipe.vae_scale_factor # [b c 1 h w]
301
+ input_frames_latent[:,:,1:] = (input_frames_latent[:,:,1:] - self.video_pipe.vae_video_shift_factor) * self.video_pipe.vae_video_scale_factor # [b c 1 h w]
302
+ input_frames_latent_ms = self.video_pipe.get_pyramid_latent(input_frames_latent, len(self.stages) - 1)
303
+
304
+ # prepare noisy latent
305
+ if self.config["seed"] is None:
306
+ if os.path.exists(os.path.join(self.config["latents_path"], "seed.txt")):
307
+ with open(os.path.join(self.config["latents_path"], "seed.txt"), "r") as file:
308
+ seed = file.read().strip() # Remove any surrounding whitespace or newline characters
309
+ seed = int(seed)
310
+ else:
311
+ seed = torch.randint(0, 1000000, (1,)).item()
312
+ self.config["seed"] = seed
313
+ else:
314
+ seed = self.config["seed"]
315
+ Path(self.config["output_path"]).mkdir(exist_ok=True)
316
+ with open(Path(self.config["output_path"], "seed.txt"), "w") as f:
317
+ f.write(str(seed))
318
+
319
+ self.generator = torch.Generator()
320
+ self.generator.manual_seed(self.config["seed"])
321
+
322
+ # Create the initial random noise
323
+ batch_size, num_channels_latents = input_frames_latent.shape[:2]
324
+ noise_latent = self.video_pipe.prepare_latents(
325
+ batch_size,
326
+ num_channels_latents,
327
+ input_frames_latent.shape[2],
328
+ self.resolution[1], # height bfe VAE Enc
329
+ self.resolution[0], # width bfe VAE Enc
330
+ self.dtype,
331
+ self.device,
332
+ generator=self.generator,
333
+ )
334
+ noise_latent = noise_latent[:,:,:1].expand(noise_latent.shape)
335
+ height, width = noise_latent.shape[-2:]
336
+ noise_latent_ms = [noise_latent.clone()]
337
+ # by defalut, we needs to start from the block noise
338
+ for _ in range(1, len(self.stages)):
339
+ height //= 2; width //= 2
340
+ noise_latent = rearrange(noise_latent, 'b c t h w -> (b t) c h w')
341
+ noise_latent = F.interpolate(noise_latent, size=(height, width), mode='bilinear') * 2
342
+ noise_latent = rearrange(noise_latent, '(b t) c h w -> b c t h w', b=batch_size)
343
+ noise_latent_ms.append(noise_latent)
344
+ noise_latent_ms = list(reversed(noise_latent_ms)) # make sure from low res to high res
345
+
346
+ return (
347
+ input_frames_latent_ms,
348
+ noise_latent_ms,
349
+ )
350
+
351
+ @torch.no_grad()
352
+ def get_sk_ek_sigma(self, i_s, allocation_type="latent-enhanced"):
353
+ timesteps = self.scheduler.timesteps
354
+ s_k = timesteps[0] / self.scheduler.config.num_train_timesteps
355
+ e_k = timesteps[-1] / self.scheduler.config.num_train_timesteps
356
+
357
+ if allocation_type == "latent-enhanced":
358
+ # elf.scheduler.start_sigmas: {0: 1.0, 1: 0.8002399489209289, 2: 0.5007496155411024}
359
+ # noise precent s_k, e_k: S0 [1, 0.5], S1 [0.67, 0.2], S2 [0.33, 0]
360
+ s_k_sigma = s_k
361
+ e_k_sigma = 1 - self.scheduler.start_sigmas[len(self.stages)-1-i_s]
362
+ elif allocation_type == "equal":
363
+ # s_k, e_k: S0 [1, 0.667], S1[0.667, 0.334], S2 [0.334, 0]
364
+ s_k_sigma = torch.tensor(1 - i_s / len(self.stages)).to(s_k)
365
+ e_k_sigma = torch.tensor(1 - (i_s+1) / len(self.stages)).to(s_k)
366
+ elif allocation_type == "timesteps":
367
+ # s_k, e_k: S0 [1, 0.74], S1[0.74, 0.38], S2 [0.38, 0]
368
+ s_k_sigma, e_k_sigma = s_k, e_k
369
+ else:
370
+ assert ValueError
371
+
372
+ return s_k_sigma, e_k_sigma
373
+
374
+ @torch.no_grad()
375
+ def denoise_step(self, i_s, i, t, past_condition_latent_src, past_condition_latent_tgt,
376
+ y_0_s_k_src, y_0_s_k_tgt, y_0_e_k_src, y_0_e_k_tgt):
377
+ register_batch(self, 4)
378
+ # interpolate the current latent in timestep t
379
+ s_k = self.scheduler.timesteps[0] / self.scheduler.config.num_train_timesteps
380
+ e_k = self.scheduler.timesteps[-1] / self.scheduler.config.num_train_timesteps
381
+ t_01 = t / self.scheduler.config.num_train_timesteps
382
+ t_ = (t_01 - e_k) / (s_k - e_k) # t_ -> 0
383
+
384
+ x_src = t_ * y_0_s_k_src + (1 - t_) * y_0_e_k_src
385
+ x_tgt = y_0_e_k_tgt + x_src - y_0_e_k_src # FlowEdit
386
+
387
+ latent_model_input = torch.cat(
388
+ [x_src] * 2 + [x_tgt] * 2
389
+ ) if self.do_classifier_free_guidance else torch.cat([x_src, x_tgt])
390
+
391
+ latent_model_input = [
392
+ torch.cat([p_src, p_tgt])
393
+ for p_src, p_tgt in zip(past_condition_latent_src[i_s], past_condition_latent_tgt[i_s])
394
+ ] + [latent_model_input]
395
+
396
+ text_prompt_cond = torch.cat([self.src_text_prompt_cond, self.tgt_text_prompt_cond])
397
+ prompt_attention_mask = torch.cat([self.src_prompt_attention_mask, self.tgt_prompt_attention_mask])
398
+ pooled_prompt_embeds = torch.cat([self.src_pooled_prompt_embeds, self.tgt_pooled_prompt_embeds])
399
+
400
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
401
+ timestep = t.expand(latent_model_input[-1].shape[0]).to(x_src.dtype).to(x_src.device)
402
+
403
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
404
+ noise_pred = self.dit(
405
+ sample=[latent_model_input],
406
+ timestep_ratio=timestep,
407
+ encoder_hidden_states=text_prompt_cond,
408
+ encoder_attention_mask=prompt_attention_mask,
409
+ pooled_projections=pooled_prompt_embeds,
410
+ )[0]
411
+
412
+ noise_pred_uncond_src, noise_pred_cond_src, noise_pred_uncond_tgt, noise_pred_cond_tgt = noise_pred.chunk(4)
413
+
414
+ if self.frame_index == 0:
415
+ tgt_guidance_scale = 10.0 + i_s * 2
416
+ noise_pred_src = noise_pred_uncond_src + self.config["guidance_scale"] * (noise_pred_cond_src - noise_pred_uncond_src)
417
+ noise_pred_tgt = noise_pred_uncond_tgt + tgt_guidance_scale * (noise_pred_cond_tgt - noise_pred_uncond_tgt)
418
+ else:
419
+ tgt_guidance_scale = 10.0 + i_s * 2
420
+ noise_pred_src = noise_pred_uncond_src + self.config["video_guidance_scale"] * (noise_pred_cond_src - noise_pred_uncond_src)
421
+ noise_pred_tgt = noise_pred_uncond_tgt + tgt_guidance_scale * (noise_pred_cond_tgt - noise_pred_uncond_tgt)
422
+
423
+ noise_pred_diff = noise_pred_tgt - noise_pred_src
424
+
425
+ self.scheduler._step_index = i
426
+ y_0_e_k_tgt = self.scheduler.step(
427
+ model_output=noise_pred_diff,
428
+ timestep=timestep,
429
+ sample=y_0_e_k_tgt,
430
+ generator=self.generator,
431
+ ).prev_sample
432
+
433
+ return y_0_e_k_tgt
434
+
435
+ @torch.no_grad()
436
+ def sample_block_noise(self, bs, ch, temp, height, width):
437
+ gamma = self.scheduler.config.gamma
438
+ dist = torch.distributions.multivariate_normal.MultivariateNormal(
439
+ torch.zeros(4),
440
+ torch.eye(4) * (1 + gamma) - torch.ones(4, 4) * gamma
441
+ )
442
+ block_number = bs * ch * temp * (height // 2) * (width // 2)
443
+ noise = torch.stack([dist.sample() for _ in range(block_number)]) # [block number, 4]
444
+ noise = rearrange(noise, '(b c t h w) (p q) -> b c t (h p) (w q)',
445
+ b=bs,c=ch,t=temp,h=height//2,w=width//2,p=2,q=2)
446
+ return noise
447
+
448
+ def upsample_with_jump_points(self, i_s, latents_src, latents_tgt, return_latents_bfe_block_noise=False):
449
+ temp = latents_tgt.shape[2]
450
+ height = latents_tgt.shape[-2] * 2
451
+ width = latents_tgt.shape[-1] * 2
452
+ latents_src = rearrange(latents_src, 'b c t h w -> (b t) c h w')
453
+ latents_src = F.interpolate(latents_src, size=(height, width), mode='nearest')
454
+ latents_src = rearrange(latents_src, '(b t) c h w -> b c t h w', t=temp)
455
+ latents_tgt = rearrange(latents_tgt, 'b c t h w -> (b t) c h w')
456
+ latents_tgt = F.interpolate(latents_tgt, size=(height, width), mode='nearest')
457
+ latents_tgt = rearrange(latents_tgt, '(b t) c h w -> b c t h w', t=temp)
458
+
459
+ latents_src_clone, latents_tgt_clone = latents_src.clone(), latents_tgt.clone()
460
+
461
+ # Fix the stage, ori_start_sigmas: {0: 1.0, 1: 0.6669999957084656, 2: 0.33399999141693115}
462
+ # stage 1: alpha=0.599, beta=0.693 => alpha: mean shift, beta: conv shift
463
+ # stage 2: alpha=0.749, beta=0.433
464
+ ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal
465
+ gamma = self.scheduler.config.gamma # 0.333
466
+ alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
467
+ beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
468
+
469
+ # add noise per block
470
+ bs, ch, temp, height, width = latents_tgt.shape
471
+ noise = self.sample_block_noise(bs, ch, temp, height, width)
472
+ noise = noise.to(device=self.device, dtype=self.dtype)
473
+ latents_src = alpha * latents_src + beta * noise # To fix the block artifact
474
+ latents_tgt = alpha * latents_tgt + beta * noise # To fix the block artifact
475
+
476
+ if return_latents_bfe_block_noise:
477
+ return latents_src, latents_tgt, latents_src_clone, latents_tgt_clone
478
+ return latents_src, latents_tgt
479
+
480
+ @torch.no_grad()
481
+ def get_past_condition_latents(self, src_latent_list, tgt_latent_list):
482
+ batch_size = self.input_frames_latent_ms[0].shape[0]
483
+ is_first_frame = self.frame_index == 0
484
+
485
+ if is_first_frame:
486
+ past_condition_latent_src = [[] for _ in range(len(self.stages))]
487
+ past_condition_latent_tgt = [[] for _ in range(len(self.stages))]
488
+ else:
489
+ past_condition_latent_src = []
490
+ clean_latents_list_pyramid = [x[:,:,:self.frame_index] for x in self.input_frames_latent_ms]
491
+
492
+ use_corrupt_noise = False
493
+ for i_s in range(len(self.stages)):
494
+ last_cond_latent = clean_latents_list_pyramid[i_s][:,:,-1:]
495
+ if use_corrupt_noise:
496
+ last_cond_noisy_sigma = torch.rand(size=(batch_size,), device=self.device) * self.video_pipe.corrupt_ratio
497
+ while len(last_cond_noisy_sigma.shape) < last_cond_latent.ndim:
498
+ last_cond_noisy_sigma = last_cond_noisy_sigma.unsqueeze(-1)
499
+ # We adding some noise to corrupt the clean condition
500
+ last_cond_latent = last_cond_noisy_sigma * torch.randn_like(last_cond_latent) + (1 - last_cond_noisy_sigma) * last_cond_latent
501
+
502
+ stage_input = [torch.cat([last_cond_latent] * 2) if self.video_pipe.do_classifier_free_guidance else last_cond_latent]
503
+
504
+ # pad the past clean latents
505
+ cur_unit_num = self.frame_index
506
+ cur_stage = i_s
507
+ cur_unit_ptx = 1
508
+
509
+ while cur_unit_ptx < cur_unit_num:
510
+ cur_stage = max(cur_stage - 1, 0)
511
+ if cur_stage == 0:
512
+ break
513
+ cur_unit_ptx += 1
514
+ cond_latents = clean_latents_list_pyramid[cur_stage][:, :, -cur_unit_ptx : -(cur_unit_ptx - 1)]
515
+ if use_corrupt_noise:
516
+ # We adding some noise to corrupt the clean condition
517
+ cond_latents = last_cond_noisy_sigma * torch.randn_like(cond_latents) + (1 - last_cond_noisy_sigma) * cond_latents
518
+ stage_input.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
519
+
520
+ if cur_stage == 0 and cur_unit_ptx < cur_unit_num:
521
+ cond_latents = clean_latents_list_pyramid[0][:, :, :-cur_unit_ptx]
522
+ if use_corrupt_noise:
523
+ # We adding some noise to corrupt the clean condition
524
+ cond_latents = last_cond_noisy_sigma * torch.randn_like(cond_latents) + (1 - last_cond_noisy_sigma) * cond_latents
525
+ stage_input.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
526
+
527
+ stage_input = list(reversed(stage_input))
528
+ past_condition_latent_src.append(stage_input)
529
+
530
+ past_condition_latent_tgt = []
531
+ reconstructed_latents_list_pyramid = self.video_pipe.get_pyramid_latent(torch.cat(tgt_latent_list, dim=2), len(self.stages) - 1)
532
+ for i_s in range(len(self.stages)):
533
+ last_cond_latent = reconstructed_latents_list_pyramid[i_s][:,:,-1:]
534
+ if use_corrupt_noise:
535
+ last_cond_noisy_sigma = torch.rand(size=(batch_size,), device=self.device) * self.video_pipe.corrupt_ratio
536
+ while len(last_cond_noisy_sigma.shape) < last_cond_latent.ndim:
537
+ last_cond_noisy_sigma = last_cond_noisy_sigma.unsqueeze(-1)
538
+ # We adding some noise to corrupt the clean condition
539
+ last_cond_latent = last_cond_noisy_sigma * torch.randn_like(last_cond_latent) + (1 - last_cond_noisy_sigma) * last_cond_latent
540
+
541
+ stage_input_tgt = [torch.cat([last_cond_latent] * 2) if self.do_classifier_free_guidance else last_cond_latent]
542
+
543
+ # pad the past clean latents
544
+ cur_unit_num = self.frame_index
545
+ cur_stage = i_s
546
+ cur_unit_ptx = 1
547
+
548
+ while cur_unit_ptx < cur_unit_num:
549
+ cur_stage = max(cur_stage - 1, 0)
550
+ if cur_stage == 0:
551
+ break
552
+ cur_unit_ptx += 1
553
+ cond_latents = reconstructed_latents_list_pyramid[cur_stage][:, :, -cur_unit_ptx : -(cur_unit_ptx - 1)]
554
+ if use_corrupt_noise:
555
+ # We adding some noise to corrupt the clean condition
556
+ cond_latents = last_cond_noisy_sigma * torch.randn_like(cond_latents) + (1 - last_cond_noisy_sigma) * cond_latents
557
+ stage_input_tgt.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
558
+
559
+ if cur_stage == 0 and cur_unit_ptx < cur_unit_num:
560
+ cond_latents = reconstructed_latents_list_pyramid[0][:, :, :-cur_unit_ptx]
561
+ if use_corrupt_noise:
562
+ # We adding some noise to corrupt the clean condition
563
+ cond_latents = last_cond_noisy_sigma * torch.randn_like(cond_latents) + (1 - last_cond_noisy_sigma) * cond_latents
564
+ stage_input_tgt.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
565
+
566
+ stage_input_tgt = list(reversed(stage_input_tgt))
567
+ past_condition_latent_tgt.append(stage_input_tgt)
568
+
569
+ return past_condition_latent_src, past_condition_latent_tgt
570
+
571
+ def run_per_unit(self, past_condition_latent_src, past_condition_latent_tgt):
572
+ print("-"*30 + f"frame {self.frame_index} editing" + "-"*30)
573
+ start_timestep_ = self.guidance_start_timestep_first if self.frame_index == 0 \
574
+ else self.guidance_start_timestep
575
+ stop_timestep_ = self.guidance_stop_timestep_first if self.frame_index == 0 \
576
+ else self.guidance_stop_timestep
577
+ print(f"Frame index: {self.frame_index}, Start_timestep: {start_timestep_}, End_timestep: {stop_timestep_}")
578
+
579
+ y_0_e_k_src_ms = [[] for _ in range(len(self.stages))]
580
+ y_0_e_k_tgt_ms = [[] for _ in range(len(self.stages))]
581
+
582
+ for i_s in range(len(self.stages)):
583
+
584
+ self.scheduler.set_timesteps(self.n_timesteps, i_s, device="cuda")
585
+ timesteps = self.scheduler.timesteps
586
+
587
+ s_k_sigma, e_k_sigma = self.get_sk_ek_sigma(i_s) # 0.5/0.2/0.0
588
+ frame_latent = self.input_frames_latent_ms[i_s][:,:,[self.frame_index]].clone()
589
+ noise_latent = self.noise_latent_ms[i_s][:,:,[self.frame_index]].clone()
590
+ y_0_e_k_src = (1 - e_k_sigma) * frame_latent + e_k_sigma * noise_latent.clone()
591
+
592
+ if i_s == 0:
593
+ y_0_s_k_src = noise_latent.clone()
594
+ y_0_s_k_tgt = noise_latent.clone()
595
+ y_0_e_k_tgt = y_0_e_k_src.clone().detach()
596
+
597
+ else:
598
+ y_0_s_k_src = y_0_e_k_src_ms[i_s-1][-1].clone().detach()
599
+ y_0_s_k_tgt = y_0_e_k_tgt_ms[i_s-1][-1].clone().detach()
600
+ y_0_s_k_src, y_0_s_k_tgt, _, _ = self.upsample_with_jump_points(
601
+ i_s, y_0_s_k_src, y_0_s_k_tgt, return_latents_bfe_block_noise=True
602
+ )
603
+ # add the noise diff of src video between start and end points to tgt video
604
+ # (y_0_e_k_src - y_0_s_k_src) contains the info of the source video to be removed
605
+ y_0_e_k_src = y_0_s_k_src + (y_0_e_k_src - y_0_s_k_src)
606
+ y_0_e_k_tgt = y_0_s_k_tgt + (y_0_e_k_src - y_0_s_k_src)
607
+
608
+ for i in tqdm(range(len(timesteps)), desc="Sampling"):
609
+ t = timesteps[i]
610
+
611
+ if not stop_timestep_ <= t <= start_timestep_:
612
+ continue
613
+
614
+ y_0_e_k_tgt = self.denoise_step(
615
+ i_s, i, t,
616
+ past_condition_latent_src, past_condition_latent_tgt,
617
+ y_0_s_k_src, y_0_s_k_tgt, y_0_e_k_src, y_0_e_k_tgt,
618
+ )
619
+
620
+ y_0_e_k_src_ms[i_s].append(y_0_e_k_src.clone().detach())
621
+ y_0_e_k_tgt_ms[i_s].append(y_0_e_k_tgt.clone().detach())
622
+
623
+ return y_0_e_k_src, y_0_e_k_tgt
624
+
625
+
626
+ def run(self):
627
+ src_latent_list, tgt_latent_list = [], []
628
+
629
+ temp = self.input_frames_latent_ms[0].shape[2]
630
+ for unit_index in tqdm(range(temp)):
631
+ self.frame_index = unit_index
632
+ self.n_timesteps = config["n_timesteps"] if unit_index == 0 else config["n_timesteps"] // 2
633
+
634
+ past_condition_latent_src, past_condition_latent_tgt = \
635
+ self.get_past_condition_latents(
636
+ src_latent_list,
637
+ tgt_latent_list
638
+ )
639
+
640
+ # sampling process
641
+ src_latent, tgt_latent = self.run_per_unit(
642
+ past_condition_latent_src,
643
+ past_condition_latent_tgt,
644
+ )
645
+
646
+ src_latent_list.append(src_latent.clone().to(self.dtype))
647
+ tgt_latent_list.append(tgt_latent.clone().to(self.dtype))
648
+
649
+ dir_name_rec = "result_frames_rec"
650
+ reconstructed_frames = self.decode_latent(torch.cat(src_latent_list, dim=2).clone())
651
+ Path(self.config["output_path"], dir_name_rec).mkdir(parents=True, exist_ok=True)
652
+ reconstructed_frame = reconstructed_frames[-1].resize((self.ori_resolution[1], self.ori_resolution[0]))
653
+ reconstructed_frame.save(Path(self.config["output_path"], dir_name_rec, f"frame_{unit_index:04d}.jpg"))
654
+
655
+ # save image
656
+ dir_name = "result_frames"
657
+ reconstructed_frames = self.decode_latent(torch.cat(tgt_latent_list, dim=2).clone())
658
+ Path(self.config["output_path"], dir_name).mkdir(parents=True, exist_ok=True)
659
+ reconstructed_frame = reconstructed_frames[-1].resize((self.ori_resolution[1], self.ori_resolution[0]))
660
+ reconstructed_frame.save(Path(self.config["output_path"], dir_name, f"frame_{unit_index:04d}.jpg"))
661
+
662
+ edited_frames = self.decode_latent(torch.cat(tgt_latent_list, dim=2).clone())
663
+ edited_frames = [
664
+ frame.resize((self.ori_resolution[1], self.ori_resolution[0]))
665
+ for frame in edited_frames
666
+ ]
667
+
668
+ dir_name = "result_all_frames"
669
+ Path(self.config["output_path"], dir_name).mkdir(parents=True, exist_ok=True)
670
+ for idx, edited_frame in enumerate(edited_frames):
671
+ edited_frame.save(Path(self.config["output_path"], dir_name, f"frame_{idx:04d}.jpg"))
672
+
673
+ video_name = "edit.mp4"
674
+ export_to_video(
675
+ edited_frames,
676
+ Path(self.config["output_path"], video_name),
677
+ fps=12
678
+ )
679
+
680
+ # src videos
681
+ reconstructed_frames = self.decode_latent(torch.cat(src_latent_list, dim=2).clone())
682
+ reconstructed_frames = [
683
+ frame.resize((self.ori_resolution[1], self.ori_resolution[0]))
684
+ for frame in reconstructed_frames
685
+ ]
686
+
687
+ dir_name = "result_all_frames_rec"
688
+ Path(self.config["output_path"], dir_name).mkdir(parents=True, exist_ok=True)
689
+ for idx, reconstructed_frame in enumerate(reconstructed_frames):
690
+ reconstructed_frame.save(Path(self.config["output_path"], dir_name, f"frame_{idx:04d}.jpg"))
691
+
692
+ video_name = "rec.mp4"
693
+ export_to_video(
694
+ reconstructed_frames,
695
+ Path(self.config["output_path"], video_name),
696
+ fps=12
697
+ )
698
+
699
+ # combined videos
700
+ combined_latent_list = [
701
+ torch.cat([src, tgt], dim=-1)
702
+ for src, tgt in zip(src_latent_list, tgt_latent_list)
703
+ ]
704
+ combined_frames = self.decode_latent(torch.cat(combined_latent_list, dim=2).clone())
705
+ combined_frames = [
706
+ frame.resize((2*self.ori_resolution[1], self.ori_resolution[0]))
707
+ for frame in combined_frames
708
+ ]
709
+ video_name = "rec_edit.mp4"
710
+ export_to_video(
711
+ combined_frames,
712
+ Path(self.config["output_path"], video_name),
713
+ fps=12
714
+ )
715
+
716
+ return tgt_latent_list
717
+
718
+
719
+ def str2bool(v):
720
+ if isinstance(v, bool):
721
+ return v
722
+ if v.lower() in ('yes', 'true', 't', '1'):
723
+ return True
724
+ elif v.lower() in ('no', 'false', 'f', '0'):
725
+ return False
726
+ else:
727
+ raise argparse.ArgumentTypeError('Boolean value expected.')
728
+
729
+
730
+ if __name__ == "__main__":
731
+ parser = argparse.ArgumentParser()
732
+ parser.add_argument("--max_frames", type=int, default=41)
733
+ parser.add_argument("--data_dir", type=str, default='data/images/')
734
+ parser.add_argument("--config_path", type=str, default="models/pyramid-edit/config.yaml")
735
+ parser.add_argument("--model_name", type=str, default="pyramid_flux", help="pyramid_flux or pyramid_mmdit")
736
+ parser.add_argument("--model_path", type=str, default="models/pyramid-edit/hf/pyramid-flow-miniflux")
737
+ parser.add_argument("--resolution", type=str, default="384p")
738
+ parser.add_argument("--dataset_json", type=str, default=None, help="json file in FiVE-Bench: data/edit_prompt/edit5_FiVE.json")
739
+ parser.add_argument("--guidance_start_timestep_first", type=int, default=850)
740
+ parser.add_argument("--guidance_stop_timestep_first", type=int, default=100)
741
+ parser.add_argument("--guidance_start_timestep", type=int, default=750)
742
+ parser.add_argument("--guidance_stop_timestep", type=int, default=100)
743
+ parser.add_argument("--guidance_scale", type=float, default=None)
744
+ parser.add_argument("--video_guidance_scale", type=float, default=None)
745
+ parser.add_argument("--output_path", type=str, default="outputs/pyramid_edit_results/", help="FiVE dataset json")
746
+ parser.add_argument("--eval_memory_time", action="store_true", help="Enable evaluation of memory time.")
747
+ parser.add_argument("--skip_processed", action="store_true", help="Skip processed videos.")
748
+ # debug
749
+ parser.add_argument("--video_name", type=str, default=None)
750
+ parser.add_argument("--source_prompt", type=str, default=None)
751
+ parser.add_argument("--target_prompt", type=str, default=None)
752
+ parser.add_argument("--negative_prompt", type=str, default=None)
753
+
754
+ opt = parser.parse_args()
755
+
756
+ config = OmegaConf.load(opt.config_path)
757
+ config["max_frames"] = opt.max_frames
758
+ config["data_dir"] = opt.data_dir
759
+ config["model_name"] = opt.model_name
760
+ config["model_path"] = opt.model_path
761
+ config["resolution"] = opt.resolution
762
+ config["dataset_json"] = opt.dataset_json
763
+
764
+ if opt.guidance_start_timestep_first > 0:
765
+ config["guidance_start_timestep_first"] = opt.guidance_start_timestep_first
766
+ if opt.guidance_stop_timestep_first > 0:
767
+ config["guidance_stop_timestep_first"] = opt.guidance_stop_timestep_first
768
+ if opt.guidance_start_timestep > 0:
769
+ config["guidance_start_timestep"] = opt.guidance_start_timestep
770
+ if opt.guidance_stop_timestep > 0:
771
+ config["guidance_stop_timestep"] = opt.guidance_stop_timestep
772
+
773
+ if opt.guidance_scale:
774
+ config["guidance_scale"] = opt.guidance_scale
775
+ if opt.video_guidance_scale:
776
+ config["video_guidance_scale"] = opt.video_guidance_scale
777
+ if opt.output_path:
778
+ config["output_path"] = opt.output_path.rstrip('/')
779
+
780
+ if opt.video_name is not None:
781
+ config["data_path"] = os.path.join(config["data_dir"], opt.video_name)
782
+ if opt.source_prompt:
783
+ config["source_prompt"] = "Photorealistic, high-definition image of " + opt.source_prompt
784
+ if opt.target_prompt:
785
+ config["target_prompt"] = "Photorealistic, high-definition image of " + opt.target_prompt
786
+ if opt.negative_prompt:
787
+ config["negative_prompt"] = opt.negative_prompt
788
+
789
+ output_path = os.path.join(config["output_path"], opt.video_name, opt.target_prompt[:20].replace(' ', '_'))
790
+ config["output_path"] = f"{output_path}_start_{opt.guidance_start_timestep_first}_{opt.guidance_start_timestep}_stop_{opt.guidance_stop_timestep_first}_{opt.guidance_stop_timestep}_guidance_scale_{opt.guidance_scale}_{opt.video_guidance_scale}"
791
+ Path(config["output_path"]).mkdir(parents=True, exist_ok=True)
792
+ OmegaConf.save(config, Path(config["output_path"]) / "config.yaml")
793
+
794
+ guidance = Guidance(config)
795
+ tgt_latent_list = guidance.run()
796
+
797
+ else:
798
+ with open(opt.dataset_json, 'r') as json_file:
799
+ data = json.load(json_file)
800
+
801
+ import psutil, time
802
+ if opt.eval_memory_time:
803
+ data = data[:1] # GPU/Speed
804
+ process = psutil.Process(os.getpid())
805
+ initial_memory = process.memory_info().rss / (1024 ** 2)
806
+ start_time = time.time()
807
+
808
+ num_videos = len(data)
809
+ output_root = config["output_path"]
810
+ for vid, entry in enumerate(data):
811
+ print(f"Processing {vid}/{num_videos} video: {entry['video_name']} ...")
812
+
813
+ config["data_path"] = os.path.join(config["data_dir"], entry['video_name'])
814
+ config["source_prompt"] = entry['source_prompt']
815
+ config["target_prompt"] = entry['target_prompt']
816
+ config["negative_prompt"] = entry['negative_prompt']
817
+
818
+ video_name = entry['video_name']
819
+ config["output_path"] = os.path.join(output_root, video_name, entry["save_dir"])
820
+ if opt.skip_processed and os.path.exists(os.path.join(config["output_path"], "edit.mp4")):
821
+ print(f"Video has been processed! Skip {video_name}")
822
+ continue
823
+
824
+ Path(config["output_path"]).mkdir(parents=True, exist_ok=True)
825
+ OmegaConf.save(config, Path(config["output_path"]) / "config.yaml")
826
+
827
+ guidance = Guidance(config)
828
+ tgt_latent_list = guidance.run()
829
+
830
+ # save GPU Memory / Speed
831
+ running_time = time.time() - start_time
832
+ max_cpu_memory = process.memory_info().rss / (1024 ** 2) # to MB
833
+
834
+ if torch.cuda.is_available():
835
+ peak_gpu_memory = torch.cuda.max_memory_allocated(device="cuda") / (1024 ** 2) # to MB
836
+ else:
837
+ peak_gpu_memory = 0.0
838
+
839
+ with open(f"{output_root}/memory_stats.txt", "a") as f:
840
+ f.write(f"7-Pyramid-Edit: Max CPU Memory Usage: {max_cpu_memory:.2f} MB\n")
841
+ f.write(f"7-Pyramid-Edit: Peak GPU Memory Usage: {peak_gpu_memory:.2f} MB\n")
842
+ f.write(f"7-Pyramid-Edit: Running Time: {running_time:.2f} seconds\n\n")
843
+
844
+ print(f"Max CPU Memory Usage: {max_cpu_memory:.2f} MB")
845
+ print(f"Peak GPU Memory Usage: {peak_gpu_memory:.2f} MB")
846
+ print(f"Running Time: {running_time:.2f} seconds")
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .pyramid_dit_for_video_gen_pipeline import PyramidDiTForVideoGeneration
2
+ from .flux_modules import FluxSingleTransformerBlock, FluxTransformerBlock, FluxTextEncoderWithMask
3
+ from .mmdit_modules import JointTransformerBlock, SD3TextEncoderWithMask
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .modeling_pyramid_flux import PyramidFluxTransformer
2
+ from .modeling_text_encoder import FluxTextEncoderWithMask
3
+ from .modeling_flux_block import FluxSingleTransformerBlock, FluxTransformerBlock
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_embedding.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+ from diffusers.models.activations import get_activation, FP32SiLU
10
+
11
+ def get_timestep_embedding(
12
+ timesteps: torch.Tensor,
13
+ embedding_dim: int,
14
+ flip_sin_to_cos: bool = False,
15
+ downscale_freq_shift: float = 1,
16
+ scale: float = 1,
17
+ max_period: int = 10000,
18
+ ):
19
+ """
20
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
21
+
22
+ Args
23
+ timesteps (torch.Tensor):
24
+ a 1-D Tensor of N indices, one per batch element. These may be fractional.
25
+ embedding_dim (int):
26
+ the dimension of the output.
27
+ flip_sin_to_cos (bool):
28
+ Whether the embedding order should be `cos, sin` (if True) or `sin, cos` (if False)
29
+ downscale_freq_shift (float):
30
+ Controls the delta between frequencies between dimensions
31
+ scale (float):
32
+ Scaling factor applied to the embeddings.
33
+ max_period (int):
34
+ Controls the maximum frequency of the embeddings
35
+ Returns
36
+ torch.Tensor: an [N x dim] Tensor of positional embeddings.
37
+ """
38
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
39
+
40
+ half_dim = embedding_dim // 2
41
+ exponent = -math.log(max_period) * torch.arange(
42
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
43
+ )
44
+ exponent = exponent / (half_dim - downscale_freq_shift)
45
+
46
+ emb = torch.exp(exponent)
47
+ emb = timesteps[:, None].float() * emb[None, :]
48
+
49
+ # scale embeddings
50
+ emb = scale * emb
51
+
52
+ # concat sine and cosine embeddings
53
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
54
+
55
+ # flip sine and cosine embeddings
56
+ if flip_sin_to_cos:
57
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
58
+
59
+ # zero pad
60
+ if embedding_dim % 2 == 1:
61
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
62
+ return emb
63
+
64
+
65
+ class Timesteps(nn.Module):
66
+ def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float, scale: int = 1):
67
+ super().__init__()
68
+ self.num_channels = num_channels
69
+ self.flip_sin_to_cos = flip_sin_to_cos
70
+ self.downscale_freq_shift = downscale_freq_shift
71
+ self.scale = scale
72
+
73
+ def forward(self, timesteps):
74
+ t_emb = get_timestep_embedding(
75
+ timesteps,
76
+ self.num_channels,
77
+ flip_sin_to_cos=self.flip_sin_to_cos,
78
+ downscale_freq_shift=self.downscale_freq_shift,
79
+ scale=self.scale,
80
+ )
81
+ return t_emb
82
+
83
+
84
+ class TimestepEmbedding(nn.Module):
85
+ def __init__(
86
+ self,
87
+ in_channels: int,
88
+ time_embed_dim: int,
89
+ act_fn: str = "silu",
90
+ out_dim: int = None,
91
+ post_act_fn: Optional[str] = None,
92
+ cond_proj_dim=None,
93
+ sample_proj_bias=True,
94
+ ):
95
+ super().__init__()
96
+
97
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, sample_proj_bias)
98
+
99
+ if cond_proj_dim is not None:
100
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
101
+ else:
102
+ self.cond_proj = None
103
+
104
+ self.act = get_activation(act_fn)
105
+
106
+ if out_dim is not None:
107
+ time_embed_dim_out = out_dim
108
+ else:
109
+ time_embed_dim_out = time_embed_dim
110
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out, sample_proj_bias)
111
+
112
+ if post_act_fn is None:
113
+ self.post_act = None
114
+ else:
115
+ self.post_act = get_activation(post_act_fn)
116
+
117
+ def forward(self, sample, condition=None):
118
+ if condition is not None:
119
+ sample = sample + self.cond_proj(condition)
120
+ sample = self.linear_1(sample)
121
+
122
+ if self.act is not None:
123
+ sample = self.act(sample)
124
+
125
+ sample = self.linear_2(sample)
126
+
127
+ if self.post_act is not None:
128
+ sample = self.post_act(sample)
129
+ return sample
130
+
131
+
132
+ class PixArtAlphaTextProjection(nn.Module):
133
+ """
134
+ Projects caption embeddings. Also handles dropout for classifier-free guidance.
135
+
136
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
137
+ """
138
+
139
+ def __init__(self, in_features, hidden_size, out_features=None, act_fn="gelu_tanh"):
140
+ super().__init__()
141
+ if out_features is None:
142
+ out_features = hidden_size
143
+ self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
144
+ if act_fn == "gelu_tanh":
145
+ self.act_1 = nn.GELU(approximate="tanh")
146
+ elif act_fn == "silu":
147
+ self.act_1 = nn.SiLU()
148
+ elif act_fn == "silu_fp32":
149
+ self.act_1 = FP32SiLU()
150
+ else:
151
+ raise ValueError(f"Unknown activation function: {act_fn}")
152
+ self.linear_2 = nn.Linear(in_features=hidden_size, out_features=out_features, bias=True)
153
+
154
+ def forward(self, caption):
155
+ hidden_states = self.linear_1(caption)
156
+ hidden_states = self.act_1(hidden_states)
157
+ hidden_states = self.linear_2(hidden_states)
158
+ return hidden_states
159
+
160
+
161
+ class CombinedTimestepGuidanceTextProjEmbeddings(nn.Module):
162
+ def __init__(self, embedding_dim, pooled_projection_dim):
163
+ super().__init__()
164
+
165
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
166
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
167
+ self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
168
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
169
+
170
+ def forward(self, timestep, guidance, pooled_projection):
171
+ timesteps_proj = self.time_proj(timestep)
172
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
173
+
174
+ guidance_proj = self.time_proj(guidance)
175
+ guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=pooled_projection.dtype)) # (N, D)
176
+
177
+ time_guidance_emb = timesteps_emb + guidance_emb
178
+
179
+ pooled_projections = self.text_embedder(pooled_projection)
180
+ conditioning = time_guidance_emb + pooled_projections
181
+
182
+ return conditioning
183
+
184
+
185
+ class CombinedTimestepTextProjEmbeddings(nn.Module):
186
+ def __init__(self, embedding_dim, pooled_projection_dim):
187
+ super().__init__()
188
+
189
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
190
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
191
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
192
+
193
+ def forward(self, timestep, pooled_projection):
194
+ timesteps_proj = self.time_proj(timestep)
195
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
196
+
197
+ pooled_projections = self.text_embedder(pooled_projection)
198
+
199
+ conditioning = timesteps_emb + pooled_projections
200
+
201
+ return conditioning
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_flux_block.py ADDED
@@ -0,0 +1,1069 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import inspect
7
+ from einops import rearrange
8
+
9
+ from diffusers.utils import deprecate
10
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU, SwiGLU
11
+
12
+ from .modeling_normalization import (
13
+ AdaLayerNormContinuous, AdaLayerNormZero,
14
+ AdaLayerNormZeroSingle, FP32LayerNorm, RMSNorm
15
+ )
16
+
17
+ from trainer_misc import (
18
+ is_sequence_parallel_initialized,
19
+ get_sequence_parallel_group,
20
+ get_sequence_parallel_world_size,
21
+ all_to_all,
22
+ )
23
+
24
+ try:
25
+ from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
26
+ from flash_attn.bert_padding import pad_input, unpad_input, index_first_axis
27
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func
28
+ except:
29
+ flash_attn_func = None
30
+ flash_attn_qkvpacked_func = None
31
+ flash_attn_varlen_func = None
32
+
33
+
34
+ def generate_indices(n, repeat=3, step=6):
35
+ indices = []
36
+ for j in range(0, n, step):
37
+ for _ in range(repeat):
38
+ indices.extend([j, j+1])
39
+ return indices
40
+
41
+
42
+ def apply_rope(xq, xk, freqs_cis):
43
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
44
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
45
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
46
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
47
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
48
+
49
+
50
+ class FeedForward(nn.Module):
51
+ r"""
52
+ A feed-forward layer.
53
+
54
+ Parameters:
55
+ dim (`int`): The number of channels in the input.
56
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
57
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
58
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
59
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
60
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
61
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ dim: int,
67
+ dim_out: Optional[int] = None,
68
+ mult: int = 4,
69
+ dropout: float = 0.0,
70
+ activation_fn: str = "geglu",
71
+ final_dropout: bool = False,
72
+ inner_dim=None,
73
+ bias: bool = True,
74
+ ):
75
+ super().__init__()
76
+ if inner_dim is None:
77
+ inner_dim = int(dim * mult)
78
+ dim_out = dim_out if dim_out is not None else dim
79
+
80
+ if activation_fn == "gelu":
81
+ act_fn = GELU(dim, inner_dim, bias=bias)
82
+ if activation_fn == "gelu-approximate":
83
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
84
+ elif activation_fn == "geglu":
85
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
86
+ elif activation_fn == "geglu-approximate":
87
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
88
+ elif activation_fn == "swiglu":
89
+ act_fn = SwiGLU(dim, inner_dim, bias=bias)
90
+
91
+ self.net = nn.ModuleList([])
92
+ # project in
93
+ self.net.append(act_fn)
94
+ # project dropout
95
+ self.net.append(nn.Dropout(dropout))
96
+ # project out
97
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
98
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
99
+ if final_dropout:
100
+ self.net.append(nn.Dropout(dropout))
101
+
102
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
103
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
104
+ 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`."
105
+ deprecate("scale", "1.0.0", deprecation_message)
106
+ for module in self.net:
107
+ hidden_states = module(hidden_states)
108
+ return hidden_states
109
+
110
+
111
+ class SequenceParallelVarlenFlashSelfAttentionWithT5Mask:
112
+
113
+ def __init__(self):
114
+ pass
115
+
116
+ def __call__(
117
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
118
+ heads, scale, hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
119
+ ):
120
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
121
+
122
+ batch_size = query.shape[0]
123
+ qkv_list = []
124
+ num_stages = len(hidden_length)
125
+
126
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
127
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
128
+
129
+ # To sync the encoder query, key and values
130
+ sp_group = get_sequence_parallel_group()
131
+ sp_group_size = get_sequence_parallel_world_size()
132
+ encoder_qkv = all_to_all(encoder_qkv, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
133
+
134
+ output_hidden = torch.zeros_like(qkv[:,:,0])
135
+ output_encoder_hidden = torch.zeros_like(encoder_qkv[:,:,0])
136
+ encoder_length = encoder_qkv.shape[1]
137
+
138
+ i_sum = 0
139
+ for i_p, length in enumerate(hidden_length):
140
+ # get the query, key, value from padding sequence
141
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
142
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
143
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
144
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, pad_seq, 3, nhead, dim]
145
+
146
+ if image_rotary_emb is not None:
147
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
148
+
149
+ indices = encoder_attention_mask[i_p]['indices']
150
+ qkv_list.append(index_first_axis(rearrange(concat_qkv_tokens, "b s ... -> (b s) ..."), indices))
151
+ i_sum += length
152
+
153
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
154
+ qkv = torch.cat(qkv_list, dim=0)
155
+ query, key, value = qkv.unbind(1)
156
+
157
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
158
+ max_seqlen_q = cu_seqlens.max().item()
159
+ max_seqlen_k = max_seqlen_q
160
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
161
+ cu_seqlens_k = cu_seqlens_q.clone()
162
+
163
+ output = flash_attn_varlen_func(
164
+ query,
165
+ key,
166
+ value,
167
+ cu_seqlens_q=cu_seqlens_q,
168
+ cu_seqlens_k=cu_seqlens_k,
169
+ max_seqlen_q=max_seqlen_q,
170
+ max_seqlen_k=max_seqlen_k,
171
+ dropout_p=0.0,
172
+ causal=False,
173
+ softmax_scale=scale,
174
+ )
175
+
176
+ # To merge the tokens
177
+ i_sum = 0;token_sum = 0
178
+ for i_p, length in enumerate(hidden_length):
179
+ tot_token_num = token_lengths[i_p]
180
+ stage_output = output[token_sum : token_sum + tot_token_num]
181
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, encoder_length + length * sp_group_size)
182
+ stage_encoder_hidden_output = stage_output[:, :encoder_length]
183
+ stage_hidden_output = stage_output[:, encoder_length:]
184
+ stage_hidden_output = all_to_all(stage_hidden_output, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
185
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
186
+ output_encoder_hidden[i_p::num_stages] = stage_encoder_hidden_output
187
+ token_sum += tot_token_num
188
+ i_sum += length
189
+
190
+ output_encoder_hidden = all_to_all(output_encoder_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
191
+ output_hidden = output_hidden.flatten(2, 3)
192
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
193
+
194
+ return output_hidden, output_encoder_hidden
195
+
196
+
197
+ class VarlenFlashSelfAttentionWithT5Mask:
198
+
199
+ def __init__(self):
200
+ pass
201
+
202
+ def __call__(
203
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
204
+ heads, scale, hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
205
+ ):
206
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
207
+
208
+ batch_size = query.shape[0]
209
+ output_hidden = torch.zeros_like(query)
210
+ output_encoder_hidden = torch.zeros_like(encoder_query)
211
+ encoder_length = encoder_query.shape[1]
212
+
213
+ qkv_list = []
214
+ num_stages = len(hidden_length)
215
+
216
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
217
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
218
+
219
+ i_sum = 0
220
+ for i_p, length in enumerate(hidden_length):
221
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
222
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
223
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
224
+
225
+ if image_rotary_emb is not None:
226
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
227
+
228
+ indices = encoder_attention_mask[i_p]['indices']
229
+ qkv_list.append(index_first_axis(rearrange(concat_qkv_tokens, "b s ... -> (b s) ..."), indices))
230
+ i_sum += length
231
+
232
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
233
+ qkv = torch.cat(qkv_list, dim=0)
234
+ query, key, value = qkv.unbind(1)
235
+
236
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
237
+ max_seqlen_q = cu_seqlens.max().item()
238
+ max_seqlen_k = max_seqlen_q
239
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
240
+ cu_seqlens_k = cu_seqlens_q.clone()
241
+
242
+ output = flash_attn_varlen_func(
243
+ query,
244
+ key,
245
+ value,
246
+ cu_seqlens_q=cu_seqlens_q,
247
+ cu_seqlens_k=cu_seqlens_k,
248
+ max_seqlen_q=max_seqlen_q,
249
+ max_seqlen_k=max_seqlen_k,
250
+ dropout_p=0.0,
251
+ causal=False,
252
+ softmax_scale=scale,
253
+ )
254
+
255
+ # To merge the tokens
256
+ i_sum = 0;token_sum = 0
257
+ for i_p, length in enumerate(hidden_length):
258
+ tot_token_num = token_lengths[i_p]
259
+ stage_output = output[token_sum : token_sum + tot_token_num]
260
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, encoder_length + length)
261
+ stage_encoder_hidden_output = stage_output[:, :encoder_length]
262
+ stage_hidden_output = stage_output[:, encoder_length:]
263
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
264
+ output_encoder_hidden[i_p::num_stages] = stage_encoder_hidden_output
265
+ token_sum += tot_token_num
266
+ i_sum += length
267
+
268
+ output_hidden = output_hidden.flatten(2, 3)
269
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
270
+
271
+ return output_hidden, output_encoder_hidden
272
+
273
+
274
+ class SequenceParallelVarlenSelfAttentionWithT5Mask:
275
+
276
+ def __init__(self):
277
+ pass
278
+
279
+ def __call__(
280
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
281
+ heads, scale, hidden_length=None, image_rotary_emb=None, attention_mask=None,
282
+ ):
283
+ assert attention_mask is not None, "The attention mask needed to be set"
284
+
285
+ num_stages = len(hidden_length)
286
+
287
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
288
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
289
+
290
+ # To sync the encoder query, key and values
291
+ sp_group = get_sequence_parallel_group()
292
+ sp_group_size = get_sequence_parallel_world_size()
293
+ encoder_qkv = all_to_all(encoder_qkv, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
294
+ encoder_length = encoder_qkv.shape[1]
295
+
296
+ i_sum = 0
297
+ output_encoder_hidden_list = []
298
+ output_hidden_list = []
299
+
300
+ for i_p, length in enumerate(hidden_length):
301
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
302
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
303
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
304
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
305
+
306
+ if image_rotary_emb is not None:
307
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
308
+
309
+ query, key, value = concat_qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
310
+ query = query.transpose(1, 2)
311
+ key = key.transpose(1, 2)
312
+ value = value.transpose(1, 2)
313
+
314
+ stage_hidden_states = F.scaled_dot_product_attention(
315
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
316
+ )
317
+ stage_hidden_states = stage_hidden_states.transpose(1, 2) # [bs, tot_seq, nhead, dim]
318
+
319
+ output_encoder_hidden_list.append(stage_hidden_states[:, :encoder_length])
320
+
321
+ output_hidden = stage_hidden_states[:, encoder_length:]
322
+ output_hidden = all_to_all(output_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
323
+ output_hidden_list.append(output_hidden)
324
+
325
+ i_sum += length
326
+
327
+ output_encoder_hidden = torch.stack(output_encoder_hidden_list, dim=1) # [b n s nhead d]
328
+ output_encoder_hidden = rearrange(output_encoder_hidden, 'b n s h d -> (b n) s h d')
329
+ output_encoder_hidden = all_to_all(output_encoder_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
330
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
331
+ output_hidden = torch.cat(output_hidden_list, dim=1).flatten(2, 3)
332
+
333
+ return output_hidden, output_encoder_hidden
334
+
335
+
336
+ class VarlenSelfAttentionWithT5Mask:
337
+
338
+ def __init__(self):
339
+ pass
340
+
341
+ def __call__(
342
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
343
+ heads, scale, hidden_length=None, image_rotary_emb=None, attention_mask=None, info=None
344
+ ):
345
+ assert attention_mask is not None, "The attention mask needed to be set"
346
+
347
+ encoder_length = encoder_query.shape[1]
348
+ num_stages = len(hidden_length)
349
+
350
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
351
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
352
+
353
+ i_sum = 0
354
+ output_encoder_hidden_list = []
355
+ output_hidden_list = []
356
+
357
+ for i_p, length in enumerate(hidden_length):
358
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
359
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
360
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
361
+
362
+ if image_rotary_emb is not None:
363
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
364
+
365
+ query, key, value = concat_qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
366
+ query = query.transpose(1, 2)
367
+ key = key.transpose(1, 2)
368
+ value = value.transpose(1, 2)
369
+
370
+ # with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=False, enable_mem_efficient=True):
371
+ stage_hidden_states = F.scaled_dot_product_attention(
372
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
373
+ )
374
+ stage_hidden_states = stage_hidden_states.transpose(1, 2).flatten(2, 3) # [bs, tot_seq, dim]
375
+
376
+ output_encoder_hidden_list.append(stage_hidden_states[:, :encoder_length])
377
+ output_hidden_list.append(stage_hidden_states[:, encoder_length:])
378
+ i_sum += length
379
+
380
+ output_encoder_hidden = torch.stack(output_encoder_hidden_list, dim=1) # [b n s d]
381
+ output_encoder_hidden = rearrange(output_encoder_hidden, 'b n s d -> (b n) s d')
382
+ output_hidden = torch.cat(output_hidden_list, dim=1)
383
+
384
+ return output_hidden, output_encoder_hidden
385
+
386
+
387
+ class SequenceParallelVarlenFlashAttnSingle:
388
+
389
+ def __init__(self):
390
+ pass
391
+
392
+ def __call__(
393
+ self, query, key, value, heads, scale,
394
+ hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
395
+ ):
396
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
397
+
398
+ batch_size = query.shape[0]
399
+ qkv_list = []
400
+ num_stages = len(hidden_length)
401
+
402
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
403
+ output_hidden = torch.zeros_like(qkv[:,:,0])
404
+
405
+ sp_group = get_sequence_parallel_group()
406
+ sp_group_size = get_sequence_parallel_world_size()
407
+
408
+ i_sum = 0
409
+ for i_p, length in enumerate(hidden_length):
410
+ # get the query, key, value from padding sequence
411
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
412
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
413
+
414
+ if image_rotary_emb is not None:
415
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
416
+
417
+ indices = encoder_attention_mask[i_p]['indices']
418
+ qkv_list.append(index_first_axis(rearrange(qkv_tokens, "b s ... -> (b s) ..."), indices))
419
+ i_sum += length
420
+
421
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
422
+ qkv = torch.cat(qkv_list, dim=0)
423
+ query, key, value = qkv.unbind(1)
424
+
425
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
426
+ max_seqlen_q = cu_seqlens.max().item()
427
+ max_seqlen_k = max_seqlen_q
428
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
429
+ cu_seqlens_k = cu_seqlens_q.clone()
430
+
431
+ output = flash_attn_varlen_func(
432
+ query,
433
+ key,
434
+ value,
435
+ cu_seqlens_q=cu_seqlens_q,
436
+ cu_seqlens_k=cu_seqlens_k,
437
+ max_seqlen_q=max_seqlen_q,
438
+ max_seqlen_k=max_seqlen_k,
439
+ dropout_p=0.0,
440
+ causal=False,
441
+ softmax_scale=scale,
442
+ )
443
+
444
+ # To merge the tokens
445
+ i_sum = 0;token_sum = 0
446
+ for i_p, length in enumerate(hidden_length):
447
+ tot_token_num = token_lengths[i_p]
448
+ stage_output = output[token_sum : token_sum + tot_token_num]
449
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, length * sp_group_size)
450
+ stage_hidden_output = all_to_all(stage_output, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
451
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
452
+ token_sum += tot_token_num
453
+ i_sum += length
454
+
455
+ output_hidden = output_hidden.flatten(2, 3)
456
+
457
+ return output_hidden
458
+
459
+
460
+ class VarlenFlashSelfAttnSingle:
461
+
462
+ def __init__(self):
463
+ pass
464
+
465
+ def __call__(
466
+ self, query, key, value, heads, scale,
467
+ hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
468
+ ):
469
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
470
+
471
+ batch_size = query.shape[0]
472
+ output_hidden = torch.zeros_like(query)
473
+
474
+ qkv_list = []
475
+ num_stages = len(hidden_length)
476
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
477
+
478
+ i_sum = 0
479
+ for i_p, length in enumerate(hidden_length):
480
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
481
+
482
+ if image_rotary_emb is not None:
483
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
484
+
485
+ indices = encoder_attention_mask[i_p]['indices']
486
+ qkv_list.append(index_first_axis(rearrange(qkv_tokens, "b s ... -> (b s) ..."), indices))
487
+ i_sum += length
488
+
489
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
490
+ qkv = torch.cat(qkv_list, dim=0)
491
+ query, key, value = qkv.unbind(1)
492
+
493
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
494
+ max_seqlen_q = cu_seqlens.max().item()
495
+ max_seqlen_k = max_seqlen_q
496
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
497
+ cu_seqlens_k = cu_seqlens_q.clone()
498
+
499
+ output = flash_attn_varlen_func(
500
+ query,
501
+ key,
502
+ value,
503
+ cu_seqlens_q=cu_seqlens_q,
504
+ cu_seqlens_k=cu_seqlens_k,
505
+ max_seqlen_q=max_seqlen_q,
506
+ max_seqlen_k=max_seqlen_k,
507
+ dropout_p=0.0,
508
+ causal=False,
509
+ softmax_scale=scale,
510
+ )
511
+
512
+ # To merge the tokens
513
+ i_sum = 0;token_sum = 0
514
+ for i_p, length in enumerate(hidden_length):
515
+ tot_token_num = token_lengths[i_p]
516
+ stage_output = output[token_sum : token_sum + tot_token_num]
517
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, length)
518
+ output_hidden[:, i_sum:i_sum+length] = stage_output
519
+ token_sum += tot_token_num
520
+ i_sum += length
521
+
522
+ output_hidden = output_hidden.flatten(2, 3)
523
+
524
+ return output_hidden
525
+
526
+
527
+ class SequenceParallelVarlenAttnSingle:
528
+
529
+ def __init__(self):
530
+ pass
531
+
532
+ def __call__(
533
+ self, query, key, value, heads, scale,
534
+ hidden_length=None, image_rotary_emb=None, attention_mask=None,
535
+ ):
536
+ assert attention_mask is not None, "The attention mask needed to be set"
537
+
538
+ num_stages = len(hidden_length)
539
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
540
+
541
+ # To sync the encoder query, key and values
542
+ sp_group = get_sequence_parallel_group()
543
+ sp_group_size = get_sequence_parallel_world_size()
544
+
545
+ i_sum = 0
546
+ output_hidden_list = []
547
+
548
+ for i_p, length in enumerate(hidden_length):
549
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
550
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
551
+
552
+ if image_rotary_emb is not None:
553
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
554
+
555
+ query, key, value = qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
556
+ query = query.transpose(1, 2).contiguous()
557
+ key = key.transpose(1, 2).contiguous()
558
+ value = value.transpose(1, 2).contiguous()
559
+
560
+ stage_hidden_states = F.scaled_dot_product_attention(
561
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
562
+ )
563
+ stage_hidden_states = stage_hidden_states.transpose(1, 2) # [bs, tot_seq, nhead, dim]
564
+
565
+ output_hidden = stage_hidden_states
566
+ output_hidden = all_to_all(output_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
567
+ output_hidden_list.append(output_hidden)
568
+
569
+ i_sum += length
570
+
571
+ output_hidden = torch.cat(output_hidden_list, dim=1).flatten(2, 3)
572
+
573
+ return output_hidden
574
+
575
+
576
+ class VarlenSelfAttnSingle:
577
+
578
+ def __init__(self):
579
+ pass
580
+
581
+ def __call__(
582
+ self, query, key, value, heads, scale,
583
+ hidden_length=None, image_rotary_emb=None, attention_mask=None, info=None,
584
+ ):
585
+ assert attention_mask is not None, "The attention mask needed to be set"
586
+
587
+ num_stages = len(hidden_length)
588
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
589
+
590
+ i_sum = 0
591
+ output_hidden_list = []
592
+
593
+ for i_p, length in enumerate(hidden_length):
594
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
595
+
596
+ if image_rotary_emb is not None:
597
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
598
+
599
+ query, key, value = qkv_tokens.unbind(2)
600
+ query = query.transpose(1, 2).contiguous()
601
+ key = key.transpose(1, 2).contiguous()
602
+ value = value.transpose(1, 2).contiguous()
603
+
604
+ stage_hidden_states = F.scaled_dot_product_attention(
605
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p]
606
+ )
607
+
608
+ stage_hidden_states = stage_hidden_states.transpose(1, 2).flatten(2, 3) # [bs, tot_seq, dim]
609
+
610
+ output_hidden_list.append(stage_hidden_states)
611
+ i_sum += length
612
+
613
+ output_hidden = torch.cat(output_hidden_list, dim=1)
614
+
615
+ return output_hidden
616
+
617
+
618
+ class Attention(nn.Module):
619
+
620
+ def __init__(
621
+ self,
622
+ query_dim: int,
623
+ cross_attention_dim: Optional[int] = None,
624
+ heads: int = 8,
625
+ dim_head: int = 64,
626
+ dropout: float = 0.0,
627
+ bias: bool = False,
628
+ qk_norm: Optional[str] = None,
629
+ added_kv_proj_dim: Optional[int] = None,
630
+ added_proj_bias: Optional[bool] = True,
631
+ out_bias: bool = True,
632
+ only_cross_attention: bool = False,
633
+ eps: float = 1e-5,
634
+ processor: Optional["AttnProcessor"] = None,
635
+ out_dim: int = None,
636
+ context_pre_only=None,
637
+ pre_only=False,
638
+ ):
639
+ super().__init__()
640
+
641
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
642
+ self.inner_kv_dim = self.inner_dim
643
+ self.query_dim = query_dim
644
+ self.use_bias = bias
645
+ self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
646
+
647
+ self.dropout = dropout
648
+ self.out_dim = out_dim if out_dim is not None else query_dim
649
+ self.context_pre_only = context_pre_only
650
+ self.pre_only = pre_only
651
+
652
+ self.scale = dim_head**-0.5
653
+ self.heads = out_dim // dim_head if out_dim is not None else heads
654
+
655
+
656
+ self.added_kv_proj_dim = added_kv_proj_dim
657
+ self.only_cross_attention = only_cross_attention
658
+
659
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
660
+ raise ValueError(
661
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
662
+ )
663
+
664
+ if qk_norm is None:
665
+ self.norm_q = None
666
+ self.norm_k = None
667
+ elif qk_norm == "rms_norm":
668
+ self.norm_q = RMSNorm(dim_head, eps=eps)
669
+ self.norm_k = RMSNorm(dim_head, eps=eps)
670
+ else:
671
+ raise ValueError(f"unknown qk_norm: {qk_norm}. Should be None or 'layer_norm'")
672
+
673
+ self.to_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
674
+
675
+ if not self.only_cross_attention:
676
+ # only relevant for the `AddedKVProcessor` classes
677
+ self.to_k = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
678
+ self.to_v = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
679
+ else:
680
+ self.to_k = None
681
+ self.to_v = None
682
+
683
+ self.added_proj_bias = added_proj_bias
684
+ if self.added_kv_proj_dim is not None:
685
+ self.add_k_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
686
+ self.add_v_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
687
+ if self.context_pre_only is not None:
688
+ self.add_q_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
689
+
690
+ if not self.pre_only:
691
+ self.to_out = nn.ModuleList([])
692
+ self.to_out.append(nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
693
+ self.to_out.append(nn.Dropout(dropout))
694
+
695
+ if self.context_pre_only is not None and not self.context_pre_only:
696
+ self.to_add_out = nn.Linear(self.inner_dim, self.out_dim, bias=out_bias)
697
+
698
+ if qk_norm is not None and added_kv_proj_dim is not None:
699
+ if qk_norm == "fp32_layer_norm":
700
+ self.norm_added_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
701
+ self.norm_added_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
702
+ elif qk_norm == "rms_norm":
703
+ self.norm_added_q = RMSNorm(dim_head, eps=eps)
704
+ self.norm_added_k = RMSNorm(dim_head, eps=eps)
705
+ else:
706
+ self.norm_added_q = None
707
+ self.norm_added_k = None
708
+
709
+ # set attention processor
710
+ self.set_processor(processor)
711
+
712
+ def set_processor(self, processor: "AttnProcessor") -> None:
713
+ self.processor = processor
714
+
715
+ def forward(
716
+ self,
717
+ hidden_states: torch.Tensor,
718
+ encoder_hidden_states: Optional[torch.Tensor] = None,
719
+ encoder_attention_mask: Optional[torch.Tensor] = None,
720
+ attention_mask: Optional[torch.Tensor] = None,
721
+ hidden_length: List = None,
722
+ image_rotary_emb: Optional[torch.Tensor] = None,
723
+ info: Optional[Dict] = None,
724
+ ) -> torch.Tensor:
725
+
726
+ return self.processor(
727
+ self,
728
+ hidden_states,
729
+ encoder_hidden_states=encoder_hidden_states,
730
+ encoder_attention_mask=encoder_attention_mask,
731
+ attention_mask=attention_mask,
732
+ hidden_length=hidden_length,
733
+ image_rotary_emb=image_rotary_emb,
734
+ info=info,
735
+ )
736
+
737
+
738
+ class FluxSingleAttnProcessor2_0:
739
+ r"""
740
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
741
+ """
742
+ def __init__(self, use_flash_attn=False):
743
+ self.use_flash_attn = use_flash_attn
744
+
745
+ if self.use_flash_attn:
746
+ if is_sequence_parallel_initialized():
747
+ self.varlen_flash_attn = SequenceParallelVarlenFlashAttnSingle()
748
+ else:
749
+ self.varlen_flash_attn = VarlenFlashSelfAttnSingle()
750
+ else:
751
+ if is_sequence_parallel_initialized():
752
+ self.varlen_attn = SequenceParallelVarlenAttnSingle()
753
+ else:
754
+ self.varlen_attn = VarlenSelfAttnSingle() # used!!
755
+
756
+ def __call__(
757
+ self,
758
+ attn: Attention,
759
+ hidden_states: torch.Tensor,
760
+ encoder_hidden_states: Optional[torch.Tensor] = None,
761
+ encoder_attention_mask: Optional[torch.Tensor] = None,
762
+ attention_mask: Optional[torch.FloatTensor] = None,
763
+ hidden_length: List = None,
764
+ image_rotary_emb: Optional[torch.Tensor] = None,
765
+ info: Optional[dict] = None,
766
+ ) -> torch.Tensor:
767
+
768
+ query = attn.to_q(hidden_states)
769
+ key = attn.to_k(hidden_states)
770
+ value = attn.to_v(hidden_states)
771
+
772
+ inner_dim = key.shape[-1]
773
+ head_dim = inner_dim // attn.heads
774
+
775
+ query = query.view(query.shape[0], -1, attn.heads, head_dim)
776
+ key = key.view(key.shape[0], -1, attn.heads, head_dim)
777
+ value = value.view(value.shape[0], -1, attn.heads, head_dim)
778
+
779
+ if attn.norm_q is not None:
780
+ query = attn.norm_q(query)
781
+ if attn.norm_k is not None:
782
+ key = attn.norm_k(key)
783
+
784
+ if self.use_flash_attn:
785
+ hidden_states = self.varlen_flash_attn(
786
+ query, key, value,
787
+ attn.heads, attn.scale, hidden_length,
788
+ image_rotary_emb, encoder_attention_mask,
789
+ )
790
+ else:
791
+
792
+ hidden_states = self.varlen_attn(
793
+ query, key, value,
794
+ attn.heads, attn.scale, hidden_length,
795
+ image_rotary_emb, attention_mask,
796
+ info=info,
797
+ )
798
+
799
+ return hidden_states
800
+
801
+
802
+ class FluxAttnProcessor2_0:
803
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
804
+
805
+ def __init__(self, use_flash_attn=False):
806
+ self.use_flash_attn = use_flash_attn
807
+
808
+ if self.use_flash_attn:
809
+ if is_sequence_parallel_initialized():
810
+ self.varlen_flash_attn = SequenceParallelVarlenFlashSelfAttentionWithT5Mask()
811
+ else:
812
+ self.varlen_flash_attn = VarlenFlashSelfAttentionWithT5Mask()
813
+ else:
814
+ if is_sequence_parallel_initialized():
815
+ self.varlen_attn = SequenceParallelVarlenSelfAttentionWithT5Mask()
816
+ else:
817
+ self.varlen_attn = VarlenSelfAttentionWithT5Mask() # used!!
818
+
819
+ def __call__(
820
+ self,
821
+ attn: Attention,
822
+ hidden_states: torch.FloatTensor,
823
+ encoder_hidden_states: torch.FloatTensor = None,
824
+ encoder_attention_mask: Optional[torch.Tensor] = None,
825
+ attention_mask: Optional[torch.FloatTensor] = None,
826
+ hidden_length: List = None,
827
+ image_rotary_emb: Optional[torch.Tensor] = None,
828
+ info: Optional[Dict] = None,
829
+ ) -> torch.FloatTensor:
830
+ # `sample` projections.
831
+ query = attn.to_q(hidden_states)
832
+ key = attn.to_k(hidden_states)
833
+ value = attn.to_v(hidden_states)
834
+
835
+ inner_dim = key.shape[-1]
836
+ head_dim = inner_dim // attn.heads
837
+
838
+ query = query.view(query.shape[0], -1, attn.heads, head_dim)
839
+ key = key.view(key.shape[0], -1, attn.heads, head_dim)
840
+ value = value.view(value.shape[0], -1, attn.heads, head_dim)
841
+
842
+ if attn.norm_q is not None:
843
+ query = attn.norm_q(query)
844
+ if attn.norm_k is not None:
845
+ key = attn.norm_k(key)
846
+
847
+ # `context` projections.
848
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
849
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
850
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
851
+
852
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
853
+ encoder_hidden_states_query_proj.shape[0], -1, attn.heads, head_dim
854
+ )
855
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
856
+ encoder_hidden_states_key_proj.shape[0], -1, attn.heads, head_dim
857
+ )
858
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
859
+ encoder_hidden_states_value_proj.shape[0], -1, attn.heads, head_dim
860
+ )
861
+
862
+ if attn.norm_added_q is not None:
863
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
864
+ if attn.norm_added_k is not None:
865
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
866
+
867
+ if self.use_flash_attn:
868
+ hidden_states, encoder_hidden_states = self.varlen_flash_attn(
869
+ query, key, value,
870
+ encoder_hidden_states_query_proj, encoder_hidden_states_key_proj,
871
+ encoder_hidden_states_value_proj, attn.heads, attn.scale, hidden_length,
872
+ image_rotary_emb, encoder_attention_mask,
873
+ )
874
+ else:
875
+ hidden_states, encoder_hidden_states = self.varlen_attn(
876
+ query, key, value,
877
+ encoder_hidden_states_query_proj, encoder_hidden_states_key_proj,
878
+ encoder_hidden_states_value_proj, attn.heads, attn.scale, hidden_length,
879
+ image_rotary_emb, attention_mask,
880
+ info=info,
881
+ )
882
+
883
+ # linear proj
884
+ hidden_states = attn.to_out[0](hidden_states)
885
+ # dropout
886
+ hidden_states = attn.to_out[1](hidden_states)
887
+
888
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
889
+
890
+ return hidden_states, encoder_hidden_states
891
+
892
+
893
+ class FluxSingleTransformerBlock(nn.Module):
894
+ r"""
895
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
896
+
897
+ Reference: https://arxiv.org/abs/2403.03206
898
+
899
+ Parameters:
900
+ dim (`int`): The number of channels in the input and output.
901
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
902
+ attention_head_dim (`int`): The number of channels in each head.
903
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
904
+ processing of `context` conditions.
905
+ """
906
+
907
+ def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0, use_flash_attn=False):
908
+ super().__init__()
909
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
910
+
911
+ self.norm = AdaLayerNormZeroSingle(dim)
912
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
913
+ self.act_mlp = nn.GELU(approximate="tanh")
914
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
915
+
916
+ processor = FluxSingleAttnProcessor2_0(use_flash_attn)
917
+ self.attn = Attention(
918
+ query_dim=dim,
919
+ cross_attention_dim=None,
920
+ dim_head=attention_head_dim,
921
+ heads=num_attention_heads,
922
+ out_dim=dim,
923
+ bias=True,
924
+ processor=processor,
925
+ qk_norm="rms_norm",
926
+ eps=1e-6,
927
+ pre_only=True,
928
+ )
929
+
930
+ def forward(
931
+ self,
932
+ hidden_states: torch.FloatTensor,
933
+ temb: torch.FloatTensor,
934
+ encoder_attention_mask=None,
935
+ attention_mask=None,
936
+ hidden_length=None,
937
+ image_rotary_emb=None,
938
+ info=None,
939
+ ):
940
+ # hidden_states: [bs, 188, 1920], 188 = 128 text tokens + 60 vision tokens
941
+ # temb: [bs, 1920]
942
+ # encoder_attention_mask: [bs, 128]
943
+ # hidden_length: [188]
944
+ residual = hidden_states
945
+
946
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb, hidden_length=hidden_length)
947
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
948
+
949
+ attn_output = self.attn(
950
+ hidden_states=norm_hidden_states,
951
+ encoder_hidden_states=None,
952
+ encoder_attention_mask=encoder_attention_mask,
953
+ attention_mask=attention_mask,
954
+ hidden_length=hidden_length,
955
+ image_rotary_emb=image_rotary_emb,
956
+ info=info,
957
+ )
958
+
959
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
960
+ hidden_states = gate * self.proj_out(hidden_states)
961
+ hidden_states = residual + hidden_states
962
+ if hidden_states.dtype == torch.float16:
963
+ hidden_states = hidden_states.clip(-65504, 65504)
964
+
965
+ return hidden_states
966
+
967
+
968
+ class FluxTransformerBlock(nn.Module):
969
+ r"""
970
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
971
+
972
+ Reference: https://arxiv.org/abs/2403.03206
973
+
974
+ Parameters:
975
+ dim (`int`): The number of channels in the input and output.
976
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
977
+ attention_head_dim (`int`): The number of channels in each head.
978
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
979
+ processing of `context` conditions.
980
+ """
981
+
982
+ def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6, use_flash_attn=False):
983
+ super().__init__()
984
+
985
+ self.norm1 = AdaLayerNormZero(dim)
986
+
987
+ self.norm1_context = AdaLayerNormZero(dim)
988
+
989
+ if hasattr(F, "scaled_dot_product_attention"):
990
+ processor = FluxAttnProcessor2_0(use_flash_attn)
991
+ else:
992
+ raise ValueError(
993
+ "The current PyTorch version does not support the `scaled_dot_product_attention` function."
994
+ )
995
+ self.attn = Attention(
996
+ query_dim=dim,
997
+ cross_attention_dim=None,
998
+ added_kv_proj_dim=dim,
999
+ dim_head=attention_head_dim,
1000
+ heads=num_attention_heads,
1001
+ out_dim=dim,
1002
+ context_pre_only=False,
1003
+ bias=True,
1004
+ processor=processor,
1005
+ qk_norm=qk_norm,
1006
+ eps=eps,
1007
+ )
1008
+
1009
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
1010
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
1011
+
1012
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
1013
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
1014
+
1015
+ def forward(
1016
+ self,
1017
+ hidden_states: torch.FloatTensor, # [bs, 960, 1920]
1018
+ encoder_hidden_states: torch.FloatTensor, # [bs, 128, 1920]
1019
+ encoder_attention_mask: torch.FloatTensor,
1020
+ temb: torch.FloatTensor, # [bs, 1920]
1021
+ attention_mask: torch.FloatTensor = None, # [[bs, 1, 1088, 1088]]
1022
+ hidden_length: List = None,
1023
+ image_rotary_emb=None,
1024
+ info=None,
1025
+ ):
1026
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb, hidden_length=hidden_length)
1027
+
1028
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
1029
+ encoder_hidden_states, emb=temb
1030
+ )
1031
+
1032
+ # Attention.
1033
+ attn_output, context_attn_output = self.attn(
1034
+ hidden_states=norm_hidden_states,
1035
+ encoder_hidden_states=norm_encoder_hidden_states,
1036
+ encoder_attention_mask=encoder_attention_mask,
1037
+ attention_mask=attention_mask,
1038
+ hidden_length=hidden_length,
1039
+ image_rotary_emb=image_rotary_emb,
1040
+ info=info,
1041
+ )
1042
+
1043
+ # Process attention outputs for the `hidden_states`.
1044
+ attn_output = gate_msa * attn_output
1045
+ hidden_states = hidden_states + attn_output
1046
+
1047
+ norm_hidden_states = self.norm2(hidden_states)
1048
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
1049
+
1050
+ ff_output = self.ff(norm_hidden_states)
1051
+ ff_output = gate_mlp * ff_output
1052
+
1053
+ hidden_states = hidden_states + ff_output
1054
+
1055
+ # Process attention outputs for the `encoder_hidden_states`.
1056
+
1057
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
1058
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
1059
+
1060
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
1061
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
1062
+
1063
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
1064
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
1065
+
1066
+ if encoder_hidden_states.dtype == torch.float16:
1067
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
1068
+
1069
+ return encoder_hidden_states, hidden_states
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_normalization.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numbers
2
+ from typing import Dict, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+ from diffusers.utils import is_torch_version
9
+
10
+
11
+ if is_torch_version(">=", "2.1.0"):
12
+ LayerNorm = nn.LayerNorm
13
+ else:
14
+ # Has optional bias parameter compared to torch layer norm
15
+ # TODO: replace with torch layernorm once min required torch version >= 2.1
16
+ class LayerNorm(nn.Module):
17
+ def __init__(self, dim, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True):
18
+ super().__init__()
19
+
20
+ self.eps = eps
21
+
22
+ if isinstance(dim, numbers.Integral):
23
+ dim = (dim,)
24
+
25
+ self.dim = torch.Size(dim)
26
+
27
+ if elementwise_affine:
28
+ self.weight = nn.Parameter(torch.ones(dim))
29
+ self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
30
+ else:
31
+ self.weight = None
32
+ self.bias = None
33
+
34
+ def forward(self, input):
35
+ return F.layer_norm(input, self.dim, self.weight, self.bias, self.eps)
36
+
37
+
38
+ class FP32LayerNorm(nn.LayerNorm):
39
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
40
+ origin_dtype = inputs.dtype
41
+ return F.layer_norm(
42
+ inputs.float(),
43
+ self.normalized_shape,
44
+ self.weight.float() if self.weight is not None else None,
45
+ self.bias.float() if self.bias is not None else None,
46
+ self.eps,
47
+ ).to(origin_dtype)
48
+
49
+
50
+ class RMSNorm(nn.Module):
51
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True):
52
+ super().__init__()
53
+
54
+ self.eps = eps
55
+
56
+ if isinstance(dim, numbers.Integral):
57
+ dim = (dim,)
58
+
59
+ self.dim = torch.Size(dim)
60
+
61
+ if elementwise_affine:
62
+ self.weight = nn.Parameter(torch.ones(dim))
63
+ else:
64
+ self.weight = None
65
+
66
+ def forward(self, hidden_states):
67
+ input_dtype = hidden_states.dtype
68
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
69
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
70
+
71
+ if self.weight is not None:
72
+ # convert into half-precision if necessary
73
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
74
+ hidden_states = hidden_states.to(self.weight.dtype)
75
+ hidden_states = hidden_states * self.weight
76
+ else:
77
+ hidden_states = hidden_states.to(input_dtype)
78
+
79
+ return hidden_states
80
+
81
+
82
+ class AdaLayerNormContinuous(nn.Module):
83
+ def __init__(
84
+ self,
85
+ embedding_dim: int,
86
+ conditioning_embedding_dim: int,
87
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
88
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
89
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
90
+ # However, this is how it was implemented in the original code, and it's rather likely you should
91
+ # set `elementwise_affine` to False.
92
+ elementwise_affine=True,
93
+ eps=1e-5,
94
+ bias=True,
95
+ norm_type="layer_norm",
96
+ ):
97
+ super().__init__()
98
+ self.silu = nn.SiLU()
99
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
100
+ if norm_type == "layer_norm":
101
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
102
+ elif norm_type == "rms_norm":
103
+ self.norm = RMSNorm(embedding_dim, eps, elementwise_affine)
104
+ else:
105
+ raise ValueError(f"unknown norm_type {norm_type}")
106
+
107
+ def forward_with_pad(self, x: torch.Tensor, conditioning_embedding: torch.Tensor, hidden_length=None) -> torch.Tensor:
108
+ assert hidden_length is not None
109
+
110
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
111
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 2)
112
+
113
+ i_sum = 0
114
+ num_stages = len(hidden_length)
115
+ for i_p, length in enumerate(hidden_length):
116
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
117
+ i_sum += length
118
+
119
+ batch_scale, batch_shift = torch.chunk(batch_emb, 2, dim=2)
120
+ x = self.norm(x) * (1 + batch_scale) + batch_shift
121
+ return x
122
+
123
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor, hidden_length=None) -> torch.Tensor:
124
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
125
+ if hidden_length is not None:
126
+ return self.forward_with_pad(x, conditioning_embedding, hidden_length)
127
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
128
+ scale, shift = torch.chunk(emb, 2, dim=1)
129
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
130
+ return x
131
+
132
+
133
+ class AdaLayerNormZero(nn.Module):
134
+ r"""
135
+ Norm layer adaptive layer norm zero (adaLN-Zero).
136
+
137
+ Parameters:
138
+ embedding_dim (`int`): The size of each embedding vector.
139
+ num_embeddings (`int`): The size of the embeddings dictionary.
140
+ """
141
+
142
+ def __init__(self, embedding_dim: int, num_embeddings: Optional[int] = None):
143
+ super().__init__()
144
+ self.emb = None
145
+
146
+ self.silu = nn.SiLU()
147
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
148
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
149
+
150
+ def forward_with_pad(
151
+ self,
152
+ x: torch.Tensor,
153
+ timestep: Optional[torch.Tensor] = None,
154
+ class_labels: Optional[torch.LongTensor] = None,
155
+ hidden_dtype: Optional[torch.dtype] = None,
156
+ emb: Optional[torch.Tensor] = None,
157
+ hidden_length: Optional[torch.Tensor] = None,
158
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
159
+ # hidden_length: [[20, 30], [30, 40], [50, 60]]
160
+ # x: [bs, seq_len, dim]
161
+ if self.emb is not None:
162
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
163
+
164
+ emb = self.linear(self.silu(emb))
165
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 6)
166
+
167
+ i_sum = 0
168
+ num_stages = len(hidden_length)
169
+ for i_p, length in enumerate(hidden_length):
170
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
171
+ i_sum += length
172
+
173
+ batch_shift_msa, batch_scale_msa, batch_gate_msa, batch_shift_mlp, batch_scale_mlp, batch_gate_mlp = batch_emb.chunk(6, dim=2)
174
+ x = self.norm(x) * (1 + batch_scale_msa) + batch_shift_msa
175
+ return x, batch_gate_msa, batch_shift_mlp, batch_scale_mlp, batch_gate_mlp
176
+
177
+ def forward(
178
+ self,
179
+ x: torch.Tensor,
180
+ timestep: Optional[torch.Tensor] = None,
181
+ class_labels: Optional[torch.LongTensor] = None,
182
+ hidden_dtype: Optional[torch.dtype] = None,
183
+ emb: Optional[torch.Tensor] = None,
184
+ hidden_length: Optional[torch.Tensor] = None,
185
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
186
+ if hidden_length is not None:
187
+ return self.forward_with_pad(x, timestep, class_labels, hidden_dtype, emb, hidden_length)
188
+ if self.emb is not None:
189
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
190
+ emb = self.linear(self.silu(emb))
191
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
192
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
193
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
194
+
195
+
196
+ class AdaLayerNormZeroSingle(nn.Module):
197
+ r"""
198
+ Norm layer adaptive layer norm zero (adaLN-Zero).
199
+
200
+ Parameters:
201
+ embedding_dim (`int`): The size of each embedding vector.
202
+ num_embeddings (`int`): The size of the embeddings dictionary.
203
+ """
204
+
205
+ def __init__(self, embedding_dim: int, norm_type="layer_norm", bias=True):
206
+ super().__init__()
207
+
208
+ self.silu = nn.SiLU()
209
+ self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
210
+ if norm_type == "layer_norm":
211
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
212
+ else:
213
+ raise ValueError(
214
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
215
+ )
216
+
217
+ def forward_with_pad(
218
+ self,
219
+ x: torch.Tensor,
220
+ emb: Optional[torch.Tensor] = None,
221
+ hidden_length: Optional[torch.Tensor] = None,
222
+ ):
223
+ emb = self.linear(self.silu(emb))
224
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 3)
225
+
226
+ i_sum = 0
227
+ num_stages = len(hidden_length)
228
+ for i_p, length in enumerate(hidden_length):
229
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
230
+ i_sum += length
231
+
232
+ batch_shift_msa, batch_scale_msa, batch_gate_msa = batch_emb.chunk(3, dim=2)
233
+
234
+ x = self.norm(x) * (1 + batch_scale_msa) + batch_shift_msa
235
+ return x, batch_gate_msa
236
+
237
+ def forward(
238
+ self,
239
+ x: torch.Tensor,
240
+ emb: Optional[torch.Tensor] = None,
241
+ hidden_length: Optional[torch.Tensor] = None,
242
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
243
+ if hidden_length is not None:
244
+ return self.forward_with_pad(x, emb, hidden_length)
245
+ emb = self.linear(self.silu(emb))
246
+ shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
247
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
248
+ return x, gate_msa
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_pyramid_flux.py ADDED
@@ -0,0 +1,548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Union
2
+
3
+ import torch
4
+ import os
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+ from tqdm import tqdm
9
+
10
+ from diffusers.utils.torch_utils import randn_tensor
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.modeling_utils import ModelMixin
13
+ from diffusers.utils import is_torch_version
14
+
15
+ from .modeling_normalization import AdaLayerNormContinuous
16
+ from .modeling_embedding import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings
17
+ from .modeling_flux_block import FluxTransformerBlock, FluxSingleTransformerBlock
18
+
19
+ from trainer_misc import (
20
+ is_sequence_parallel_initialized,
21
+ get_sequence_parallel_group,
22
+ get_sequence_parallel_world_size,
23
+ get_sequence_parallel_rank,
24
+ all_to_all,
25
+ )
26
+
27
+
28
+ def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
29
+ assert dim % 2 == 0, "The dimension must be even."
30
+
31
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
32
+ omega = 1.0 / (theta**scale)
33
+
34
+ batch_size, seq_length = pos.shape
35
+ out = torch.einsum("...n,d->...nd", pos, omega)
36
+ cos_out = torch.cos(out)
37
+ sin_out = torch.sin(out)
38
+
39
+ stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
40
+ out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
41
+ return out.float()
42
+
43
+
44
+ class EmbedND(nn.Module):
45
+ def __init__(self, dim: int, theta: int, axes_dim: List[int]):
46
+ super().__init__()
47
+ self.dim = dim
48
+ self.theta = theta
49
+ self.axes_dim = axes_dim
50
+
51
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
52
+ n_axes = ids.shape[-1]
53
+ emb = torch.cat(
54
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
55
+ dim=-3,
56
+ )
57
+ return emb.unsqueeze(2)
58
+
59
+
60
+ class PyramidFluxTransformer(ModelMixin, ConfigMixin):
61
+ """
62
+ The Transformer model introduced in Flux.
63
+
64
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
65
+
66
+ Parameters:
67
+ patch_size (`int`): Patch size to turn the input data into small patches.
68
+ in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
69
+ num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
70
+ num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
71
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
72
+ num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
73
+ joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
74
+ pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
75
+ """
76
+
77
+ _supports_gradient_checkpointing = True
78
+
79
+ @register_to_config
80
+ def __init__(
81
+ self,
82
+ patch_size: int = 1,
83
+ in_channels: int = 64,
84
+ num_layers: int = 19,
85
+ num_single_layers: int = 38,
86
+ attention_head_dim: int = 64,
87
+ num_attention_heads: int = 24,
88
+ joint_attention_dim: int = 4096,
89
+ pooled_projection_dim: int = 768,
90
+ axes_dims_rope: List[int] = [16, 24, 24],
91
+ use_flash_attn: bool = False,
92
+ use_temporal_causal: bool = True,
93
+ interp_condition_pos: bool = True,
94
+ use_gradient_checkpointing: bool = False,
95
+ gradient_checkpointing_ratio: float = 0.6,
96
+ ):
97
+ super().__init__()
98
+ self.out_channels = in_channels
99
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
100
+
101
+ self.pos_embed = EmbedND(dim=self.inner_dim, theta=10000, axes_dim=axes_dims_rope)
102
+ self.time_text_embed = CombinedTimestepTextProjEmbeddings(
103
+ embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim
104
+ )
105
+
106
+ self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim)
107
+ self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim)
108
+
109
+ self.transformer_blocks = nn.ModuleList(
110
+ [
111
+ FluxTransformerBlock(
112
+ dim=self.inner_dim,
113
+ num_attention_heads=self.config.num_attention_heads,
114
+ attention_head_dim=self.config.attention_head_dim,
115
+ use_flash_attn=use_flash_attn,
116
+ )
117
+ for i in range(self.config.num_layers)
118
+ ]
119
+ )
120
+
121
+ self.single_transformer_blocks = nn.ModuleList(
122
+ [
123
+ FluxSingleTransformerBlock(
124
+ dim=self.inner_dim,
125
+ num_attention_heads=self.config.num_attention_heads,
126
+ attention_head_dim=self.config.attention_head_dim,
127
+ use_flash_attn=use_flash_attn,
128
+ )
129
+ for i in range(self.config.num_single_layers)
130
+ ]
131
+ )
132
+
133
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
134
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
135
+
136
+ self.gradient_checkpointing = use_gradient_checkpointing
137
+ self.gradient_checkpointing_ratio = gradient_checkpointing_ratio
138
+
139
+ self.use_temporal_causal = use_temporal_causal
140
+ if self.use_temporal_causal:
141
+ print("Using temporal causal attention")
142
+
143
+ self.use_flash_attn = use_flash_attn
144
+ if self.use_flash_attn:
145
+ print("Using Flash attention")
146
+
147
+ self.patch_size = 2 # hard-code for now
148
+
149
+ # init weights
150
+ self.initialize_weights()
151
+
152
+ def initialize_weights(self):
153
+ # Initialize transformer layers:
154
+ def _basic_init(module):
155
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.Conv3d)):
156
+ torch.nn.init.xavier_uniform_(module.weight)
157
+ if module.bias is not None:
158
+ nn.init.constant_(module.bias, 0)
159
+ self.apply(_basic_init)
160
+
161
+ # Initialize all the conditioning to normal init
162
+ nn.init.normal_(self.time_text_embed.timestep_embedder.linear_1.weight, std=0.02)
163
+ nn.init.normal_(self.time_text_embed.timestep_embedder.linear_2.weight, std=0.02)
164
+ nn.init.normal_(self.time_text_embed.text_embedder.linear_1.weight, std=0.02)
165
+ nn.init.normal_(self.time_text_embed.text_embedder.linear_2.weight, std=0.02)
166
+ nn.init.normal_(self.context_embedder.weight, std=0.02)
167
+
168
+ # Zero-out adaLN modulation layers in DiT blocks:
169
+ for block in self.transformer_blocks:
170
+ nn.init.constant_(block.norm1.linear.weight, 0)
171
+ nn.init.constant_(block.norm1.linear.bias, 0)
172
+ nn.init.constant_(block.norm1_context.linear.weight, 0)
173
+ nn.init.constant_(block.norm1_context.linear.bias, 0)
174
+
175
+ for block in self.single_transformer_blocks:
176
+ nn.init.constant_(block.norm.linear.weight, 0)
177
+ nn.init.constant_(block.norm.linear.bias, 0)
178
+
179
+ # Zero-out output layers:
180
+ nn.init.constant_(self.norm_out.linear.weight, 0)
181
+ nn.init.constant_(self.norm_out.linear.bias, 0)
182
+ nn.init.constant_(self.proj_out.weight, 0)
183
+ nn.init.constant_(self.proj_out.bias, 0)
184
+
185
+ @torch.no_grad()
186
+ def _prepare_image_ids(self, batch_size, temp, height, width, train_height, train_width, device, start_time_stamp=0):
187
+ latent_image_ids = torch.zeros(temp, height, width, 3)
188
+
189
+ # Temporal Rope
190
+ latent_image_ids[..., 0] = latent_image_ids[..., 0] + torch.arange(start_time_stamp, start_time_stamp + temp)[:, None, None]
191
+
192
+ # height Rope
193
+ if height != train_height:
194
+ height_pos = F.interpolate(torch.arange(train_height)[None, None, :].float(), height, mode='linear').squeeze(0, 1)
195
+ else:
196
+ height_pos = torch.arange(train_height).float()
197
+
198
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + height_pos[None, :, None]
199
+
200
+ # width rope
201
+ if width != train_width:
202
+ width_pos = F.interpolate(torch.arange(train_width)[None, None, :].float(), width, mode='linear').squeeze(0, 1)
203
+ else:
204
+ width_pos = torch.arange(train_width).float()
205
+
206
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + width_pos[None, None, :]
207
+
208
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1, 1)
209
+ latent_image_ids = rearrange(latent_image_ids, 'b t h w c -> b (t h w) c')
210
+
211
+ return latent_image_ids.to(device=device)
212
+
213
+ @torch.no_grad()
214
+ def _prepare_pyramid_image_ids(self, sample, batch_size, device):
215
+ image_ids_list = []
216
+
217
+ for i_b, sample_ in enumerate(sample):
218
+ if not isinstance(sample_, list):
219
+ sample_ = [sample_]
220
+
221
+ cur_image_ids = []
222
+ start_time_stamp = 0
223
+
224
+ train_height = sample_[-1].shape[-2] // self.patch_size
225
+ train_width = sample_[-1].shape[-1] // self.patch_size
226
+
227
+ for clip_ in sample_:
228
+ _, _, temp, height, width = clip_.shape
229
+ height = height // self.patch_size
230
+ width = width // self.patch_size
231
+ cur_image_ids.append(self._prepare_image_ids(batch_size, temp, height, width, train_height, train_width, device, start_time_stamp=start_time_stamp))
232
+ start_time_stamp += temp
233
+
234
+ cur_image_ids = torch.cat(cur_image_ids, dim=1)
235
+ image_ids_list.append(cur_image_ids)
236
+
237
+ return image_ids_list
238
+
239
+ def merge_input(self, sample, encoder_hidden_length, encoder_attention_mask):
240
+ """
241
+ Merge the input video with different resolutions into one sequence
242
+ Sample: From low resolution to high resolution
243
+ """
244
+ if isinstance(sample[0], list):
245
+ device = sample[0][-1].device
246
+ pad_batch_size = sample[0][-1].shape[0]
247
+ else:
248
+ device = sample[0].device
249
+ pad_batch_size = sample[0].shape[0]
250
+
251
+ num_stages = len(sample)
252
+ height_list = [];width_list = [];temp_list = []
253
+ trainable_token_list = []
254
+
255
+ for i_b, sample_ in enumerate(sample):
256
+ if isinstance(sample_, list):
257
+ sample_ = sample_[-1]
258
+ _, _, temp, height, width = sample_.shape
259
+ height = height // self.patch_size
260
+ width = width // self.patch_size
261
+ temp_list.append(temp)
262
+ height_list.append(height)
263
+ width_list.append(width)
264
+ trainable_token_list.append(height * width * temp)
265
+
266
+ # prepare the RoPE IDs,
267
+ image_ids_list = self._prepare_pyramid_image_ids(sample, pad_batch_size, device)
268
+ text_ids = torch.zeros(pad_batch_size, encoder_attention_mask.shape[1], 3).to(device=device)
269
+ input_ids_list = [torch.cat([text_ids, image_ids], dim=1) for image_ids in image_ids_list]
270
+ image_rotary_emb = [self.pos_embed(input_ids) for input_ids in input_ids_list] # [bs, seq_len, 1, head_dim // 2, 2, 2]
271
+
272
+ if is_sequence_parallel_initialized():
273
+ sp_group = get_sequence_parallel_group()
274
+ sp_group_size = get_sequence_parallel_world_size()
275
+ concat_output = True if self.training else False
276
+ image_rotary_emb = [all_to_all(x_.repeat(1, 1, sp_group_size, 1, 1, 1), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output) for x_ in image_rotary_emb]
277
+ input_ids_list = [all_to_all(input_ids.repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output) for input_ids in input_ids_list]
278
+
279
+ hidden_states, hidden_length = [], []
280
+
281
+ for sample_ in sample:
282
+ video_tokens = []
283
+
284
+ for each_latent in sample_:
285
+ each_latent = rearrange(each_latent, 'b c t h w -> b t h w c')
286
+ each_latent = rearrange(each_latent, 'b t (h p1) (w p2) c -> b (t h w) (p1 p2 c)', p1=self.patch_size, p2=self.patch_size)
287
+ video_tokens.append(each_latent)
288
+
289
+ video_tokens = torch.cat(video_tokens, dim=1)
290
+ video_tokens = self.x_embedder(video_tokens)
291
+ hidden_states.append(video_tokens)
292
+ hidden_length.append(video_tokens.shape[1])
293
+
294
+ # prepare the attention mask
295
+ if self.use_flash_attn:
296
+ attention_mask = None
297
+ indices_list = []
298
+ for i_p, length in enumerate(hidden_length):
299
+ pad_attention_mask = torch.ones((pad_batch_size, length), dtype=encoder_attention_mask.dtype).to(device)
300
+ pad_attention_mask = torch.cat([encoder_attention_mask[i_p::num_stages], pad_attention_mask], dim=1)
301
+
302
+ if is_sequence_parallel_initialized():
303
+ sp_group = get_sequence_parallel_group()
304
+ sp_group_size = get_sequence_parallel_world_size()
305
+ pad_attention_mask = all_to_all(pad_attention_mask.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0)
306
+ pad_attention_mask = pad_attention_mask.squeeze(2)
307
+
308
+ seqlens_in_batch = pad_attention_mask.sum(dim=-1, dtype=torch.int32)
309
+ indices = torch.nonzero(pad_attention_mask.flatten(), as_tuple=False).flatten()
310
+
311
+ indices_list.append(
312
+ {
313
+ 'indices': indices,
314
+ 'seqlens_in_batch': seqlens_in_batch,
315
+ }
316
+ )
317
+ encoder_attention_mask = indices_list
318
+ else:
319
+ assert encoder_attention_mask.shape[1] == encoder_hidden_length
320
+ real_batch_size = encoder_attention_mask.shape[0]
321
+
322
+ # prepare text ids
323
+ text_ids = torch.arange(1, real_batch_size + 1, dtype=encoder_attention_mask.dtype).unsqueeze(1).repeat(1, encoder_hidden_length)
324
+ text_ids = text_ids.to(device)
325
+ text_ids[encoder_attention_mask == 0] = 0
326
+
327
+ # prepare image ids
328
+ image_ids = torch.arange(1, real_batch_size + 1, dtype=encoder_attention_mask.dtype).unsqueeze(1).repeat(1, max(hidden_length))
329
+ image_ids = image_ids.to(device)
330
+ image_ids_list = []
331
+ for i_p, length in enumerate(hidden_length):
332
+ image_ids_list.append(image_ids[i_p::num_stages][:, :length])
333
+
334
+ if is_sequence_parallel_initialized():
335
+ sp_group = get_sequence_parallel_group()
336
+ sp_group_size = get_sequence_parallel_world_size()
337
+ concat_output = True if self.training else False
338
+ text_ids = all_to_all(text_ids.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output).squeeze(2)
339
+ image_ids_list = [all_to_all(image_ids_.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output).squeeze(2) for image_ids_ in image_ids_list]
340
+
341
+ attention_mask = []
342
+ for i_p in range(len(hidden_length)):
343
+ image_ids = image_ids_list[i_p]
344
+ token_ids = torch.cat([text_ids[i_p::num_stages], image_ids], dim=1)
345
+ stage_attention_mask = rearrange(token_ids, 'b i -> b 1 i 1') == rearrange(token_ids, 'b j -> b 1 1 j') # [bs, 1, q_len, k_len]
346
+ if self.use_temporal_causal:
347
+ input_order_ids = input_ids_list[i_p][:,:,0]
348
+ temporal_causal_mask = rearrange(input_order_ids, 'b i -> b 1 i 1') >= rearrange(input_order_ids, 'b j -> b 1 1 j')
349
+ stage_attention_mask = stage_attention_mask & temporal_causal_mask
350
+ attention_mask.append(stage_attention_mask)
351
+
352
+ return hidden_states, hidden_length, temp_list, height_list, width_list, trainable_token_list, encoder_attention_mask, attention_mask, image_rotary_emb
353
+
354
+ def split_output(self, batch_hidden_states, hidden_length, temps, heights, widths, trainable_token_list):
355
+ # To split the hidden states
356
+ batch_size = batch_hidden_states.shape[0]
357
+ output_hidden_list = []
358
+ batch_hidden_states = torch.split(batch_hidden_states, hidden_length, dim=1)
359
+
360
+ if is_sequence_parallel_initialized():
361
+ sp_group_size = get_sequence_parallel_world_size()
362
+ if self.training:
363
+ batch_size = batch_size // sp_group_size
364
+
365
+ for i_p, length in enumerate(hidden_length):
366
+ width, height, temp = widths[i_p], heights[i_p], temps[i_p]
367
+ trainable_token_num = trainable_token_list[i_p]
368
+ hidden_states = batch_hidden_states[i_p]
369
+
370
+ if is_sequence_parallel_initialized():
371
+ sp_group = get_sequence_parallel_group()
372
+ sp_group_size = get_sequence_parallel_world_size()
373
+
374
+ if not self.training:
375
+ hidden_states = hidden_states.repeat(sp_group_size, 1, 1)
376
+
377
+ hidden_states = all_to_all(hidden_states, sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
378
+
379
+ # only the trainable token are taking part in loss computation
380
+ hidden_states = hidden_states[:, -trainable_token_num:]
381
+
382
+ # unpatchify
383
+ hidden_states = hidden_states.reshape(
384
+ shape=(batch_size, temp, height, width, self.patch_size, self.patch_size, self.out_channels // 4)
385
+ )
386
+ hidden_states = rearrange(hidden_states, "b t h w p1 p2 c -> b t (h p1) (w p2) c")
387
+ hidden_states = rearrange(hidden_states, "b t h w c -> b c t h w")
388
+ output_hidden_list.append(hidden_states)
389
+
390
+ return output_hidden_list
391
+
392
+ def forward(
393
+ self,
394
+ sample: torch.FloatTensor, # [num_stages]
395
+ encoder_hidden_states: torch.Tensor = None,
396
+ encoder_attention_mask: torch.FloatTensor = None,
397
+ pooled_projections: torch.Tensor = None,
398
+ timestep_ratio: torch.LongTensor = None,
399
+ info: Optional[dict] = None,
400
+ ):
401
+ temb = self.time_text_embed(timestep_ratio, pooled_projections) # CLIP pooled text emb + time emb
402
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
403
+ encoder_hidden_length = encoder_hidden_states.shape[1]
404
+
405
+ # Get the input sequence
406
+ hidden_states, hidden_length, temps, heights, widths, trainable_token_list, encoder_attention_mask, attention_mask, \
407
+ image_rotary_emb = self.merge_input(sample, encoder_hidden_length, encoder_attention_mask)
408
+
409
+ # split the long latents if necessary
410
+ if is_sequence_parallel_initialized():
411
+ sp_group = get_sequence_parallel_group()
412
+ sp_group_size = get_sequence_parallel_world_size()
413
+ concat_output = True if self.training else False
414
+
415
+ # sync the input hidden states
416
+ batch_hidden_states = []
417
+ for i_p, hidden_states_ in enumerate(hidden_states):
418
+ assert hidden_states_.shape[1] % sp_group_size == 0, "The sequence length should be divided by sequence parallel size"
419
+ hidden_states_ = all_to_all(hidden_states_, sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
420
+ hidden_length[i_p] = hidden_length[i_p] // sp_group_size
421
+ batch_hidden_states.append(hidden_states_)
422
+
423
+ # sync the encoder hidden states
424
+ hidden_states = torch.cat(batch_hidden_states, dim=1)
425
+ encoder_hidden_states = all_to_all(encoder_hidden_states, sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
426
+ temb = all_to_all(temb.unsqueeze(1).repeat(1, sp_group_size, 1), sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
427
+ temb = temb.squeeze(1)
428
+ else:
429
+ hidden_states = torch.cat(hidden_states, dim=1)
430
+
431
+ for index_block, block in enumerate(self.transformer_blocks):
432
+ if self.training and self.gradient_checkpointing and (index_block <= int(len(self.transformer_blocks) * self.gradient_checkpointing_ratio)):
433
+
434
+ def create_custom_forward(module):
435
+ def custom_forward(*inputs):
436
+ return module(*inputs)
437
+
438
+ return custom_forward
439
+
440
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
441
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
442
+ create_custom_forward(block),
443
+ hidden_states,
444
+ encoder_hidden_states,
445
+ encoder_attention_mask,
446
+ temb,
447
+ attention_mask,
448
+ hidden_length,
449
+ image_rotary_emb,
450
+ **ckpt_kwargs,
451
+ )
452
+
453
+ else:
454
+
455
+ encoder_hidden_states, hidden_states = block(
456
+ hidden_states=hidden_states,
457
+ encoder_hidden_states=encoder_hidden_states,
458
+ encoder_attention_mask=encoder_attention_mask,
459
+ temb=temb,
460
+ attention_mask=attention_mask,
461
+ hidden_length=hidden_length,
462
+ image_rotary_emb=image_rotary_emb,
463
+ info=info,
464
+ )
465
+
466
+ # remerge for single attention block
467
+ num_stages = len(hidden_length)
468
+ batch_hidden_states = list(torch.split(hidden_states, hidden_length, dim=1))
469
+ concat_hidden_length = []
470
+
471
+ if is_sequence_parallel_initialized():
472
+ sp_group = get_sequence_parallel_group()
473
+ sp_group_size = get_sequence_parallel_world_size()
474
+ encoder_hidden_states = all_to_all(encoder_hidden_states, sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
475
+
476
+ for i_p in range(len(hidden_length)):
477
+
478
+ if is_sequence_parallel_initialized():
479
+ sp_group = get_sequence_parallel_group()
480
+ sp_group_size = get_sequence_parallel_world_size()
481
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
482
+
483
+ batch_hidden_states[i_p] = torch.cat([encoder_hidden_states[i_p::num_stages], batch_hidden_states[i_p]], dim=1)
484
+
485
+ if is_sequence_parallel_initialized():
486
+ sp_group = get_sequence_parallel_group()
487
+ sp_group_size = get_sequence_parallel_world_size()
488
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=1, gather_dim=0)
489
+
490
+ concat_hidden_length.append(batch_hidden_states[i_p].shape[1])
491
+
492
+ hidden_states = torch.cat(batch_hidden_states, dim=1)
493
+
494
+ for index_block, block in enumerate(self.single_transformer_blocks):
495
+ if self.training and self.gradient_checkpointing and (index_block <= int(len(self.single_transformer_blocks) * self.gradient_checkpointing_ratio)):
496
+
497
+ def create_custom_forward(module):
498
+ def custom_forward(*inputs):
499
+ return module(*inputs)
500
+
501
+ return custom_forward
502
+
503
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
504
+ hidden_states = torch.utils.checkpoint.checkpoint(
505
+ create_custom_forward(block),
506
+ hidden_states,
507
+ temb,
508
+ encoder_attention_mask,
509
+ attention_mask,
510
+ concat_hidden_length,
511
+ image_rotary_emb,
512
+ **ckpt_kwargs,
513
+ )
514
+
515
+ else:
516
+
517
+ hidden_states = block(
518
+ hidden_states=hidden_states,
519
+ temb=temb,
520
+ encoder_attention_mask=encoder_attention_mask, # used for
521
+ attention_mask=attention_mask,
522
+ hidden_length=concat_hidden_length,
523
+ image_rotary_emb=image_rotary_emb,
524
+ info=info,
525
+ )
526
+
527
+ batch_hidden_states = list(torch.split(hidden_states, concat_hidden_length, dim=1))
528
+
529
+ for i_p in range(len(concat_hidden_length)):
530
+ if is_sequence_parallel_initialized():
531
+ sp_group = get_sequence_parallel_group()
532
+ sp_group_size = get_sequence_parallel_world_size()
533
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
534
+
535
+ batch_hidden_states[i_p] = batch_hidden_states[i_p][:, encoder_hidden_length :, ...]
536
+
537
+ if is_sequence_parallel_initialized():
538
+ sp_group = get_sequence_parallel_group()
539
+ sp_group_size = get_sequence_parallel_world_size()
540
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=1, gather_dim=0)
541
+
542
+ hidden_states = torch.cat(batch_hidden_states, dim=1)
543
+ hidden_states = self.norm_out(hidden_states, temb, hidden_length=hidden_length)
544
+ hidden_states = self.proj_out(hidden_states)
545
+
546
+ output = self.split_output(hidden_states, hidden_length, temps, heights, widths, trainable_token_list)
547
+
548
+ return output
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/flux_modules/modeling_text_encoder.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import os
4
+
5
+ from transformers import (
6
+ CLIPTextModel,
7
+ CLIPTokenizer,
8
+ T5EncoderModel,
9
+ T5TokenizerFast,
10
+ )
11
+
12
+ from typing import Any, Callable, Dict, List, Optional, Union
13
+
14
+
15
+ class FluxTextEncoderWithMask(nn.Module):
16
+ def __init__(self, model_path, torch_dtype):
17
+ super().__init__()
18
+ # CLIP-G
19
+ self.tokenizer = CLIPTokenizer.from_pretrained(os.path.join(model_path, 'tokenizer'), torch_dtype=torch_dtype)
20
+ self.tokenizer_max_length = (
21
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
22
+ )
23
+ self.text_encoder = CLIPTextModel.from_pretrained(os.path.join(model_path, 'text_encoder'), torch_dtype=torch_dtype)
24
+
25
+ # T5
26
+ self.tokenizer_2 = T5TokenizerFast.from_pretrained(os.path.join(model_path, 'tokenizer_2'))
27
+ self.text_encoder_2 = T5EncoderModel.from_pretrained(os.path.join(model_path, 'text_encoder_2'), torch_dtype=torch_dtype)
28
+
29
+ self._freeze()
30
+
31
+ def _freeze(self):
32
+ for param in self.parameters():
33
+ param.requires_grad = False
34
+
35
+ def _get_t5_prompt_embeds(
36
+ self,
37
+ prompt: Union[str, List[str]] = None,
38
+ num_images_per_prompt: int = 1,
39
+ max_sequence_length: int = 128,
40
+ device: Optional[torch.device] = None,
41
+ ):
42
+
43
+ prompt = [prompt] if isinstance(prompt, str) else prompt
44
+ batch_size = len(prompt)
45
+
46
+ text_inputs = self.tokenizer_2(
47
+ prompt,
48
+ padding="max_length",
49
+ max_length=max_sequence_length,
50
+ truncation=True,
51
+ return_length=False,
52
+ return_overflowing_tokens=False,
53
+ return_tensors="pt",
54
+ )
55
+ text_input_ids = text_inputs.input_ids
56
+ prompt_attention_mask = text_inputs.attention_mask
57
+ prompt_attention_mask = prompt_attention_mask.to(device)
58
+
59
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), attention_mask=prompt_attention_mask, output_hidden_states=False)[0]
60
+
61
+ dtype = self.text_encoder_2.dtype
62
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
63
+
64
+ _, seq_len, _ = prompt_embeds.shape
65
+
66
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
67
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
68
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
69
+ prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
70
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
71
+
72
+ return prompt_embeds, prompt_attention_mask
73
+
74
+ def _get_clip_prompt_embeds(
75
+ self,
76
+ prompt: Union[str, List[str]],
77
+ num_images_per_prompt: int = 1,
78
+ device: Optional[torch.device] = None,
79
+ ):
80
+
81
+ prompt = [prompt] if isinstance(prompt, str) else prompt
82
+ batch_size = len(prompt)
83
+
84
+ text_inputs = self.tokenizer(
85
+ prompt,
86
+ padding="max_length",
87
+ max_length=self.tokenizer_max_length,
88
+ truncation=True,
89
+ return_overflowing_tokens=False,
90
+ return_length=False,
91
+ return_tensors="pt",
92
+ )
93
+
94
+ text_input_ids = text_inputs.input_ids
95
+
96
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
97
+
98
+ all_prompt_embeds = prompt_embeds.last_hidden_state
99
+ all_prompt_embeds = all_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
100
+
101
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
102
+ bs, seq_len, dim = all_prompt_embeds.shape
103
+ all_prompt_embeds = all_prompt_embeds[:, None].repeat(1, 1, 1, num_images_per_prompt)
104
+ all_prompt_embeds = all_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, dim)
105
+
106
+ # Use pooled output of CLIPTextModel
107
+ pooled_prompt_embeds = prompt_embeds.pooler_output
108
+ pooled_prompt_embeds = pooled_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
109
+
110
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
111
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt)
112
+ pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
113
+
114
+ return pooled_prompt_embeds, all_prompt_embeds
115
+
116
+ def encode_prompt(self,
117
+ prompt,
118
+ num_images_per_prompt=1,
119
+ device=None,
120
+ ):
121
+ prompt = [prompt] if isinstance(prompt, str) else prompt
122
+
123
+ batch_size = len(prompt)
124
+
125
+ pooled_prompt_embeds, all_prompt_embeds = self._get_clip_prompt_embeds(
126
+ prompt=prompt,
127
+ device=device,
128
+ num_images_per_prompt=num_images_per_prompt,
129
+ )
130
+
131
+ prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
132
+ prompt=prompt,
133
+ num_images_per_prompt=num_images_per_prompt,
134
+ device=device,
135
+ )
136
+
137
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds, all_prompt_embeds
138
+
139
+ def forward(self, input_prompts, device, return_all_prompt_embeds_clip=False):
140
+ with torch.no_grad():
141
+ prompt_embeds, prompt_attention_mask, pooled_prompt_embeds, all_prompt_embeds = self.encode_prompt(input_prompts, 1, device=device)
142
+
143
+ if return_all_prompt_embeds_clip:
144
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds, all_prompt_embeds
145
+
146
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .modeling_text_encoder import SD3TextEncoderWithMask
2
+ from .modeling_pyramid_mmdit import PyramidDiffusionMMDiT
3
+ from .modeling_mmdit_block import JointTransformerBlock
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_embedding.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ import math
7
+
8
+ from diffusers.models.activations import get_activation
9
+ from einops import rearrange
10
+
11
+
12
+ def get_1d_sincos_pos_embed(
13
+ embed_dim, num_frames, cls_token=False, extra_tokens=0,
14
+ ):
15
+ t = np.arange(num_frames, dtype=np.float32)
16
+ pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, t) # (T, D)
17
+ if cls_token and extra_tokens > 0:
18
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
19
+ return pos_embed
20
+
21
+
22
+ def get_2d_sincos_pos_embed(
23
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16
24
+ ):
25
+ """
26
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
27
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
28
+ """
29
+ if isinstance(grid_size, int):
30
+ grid_size = (grid_size, grid_size)
31
+
32
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size) / interpolation_scale
33
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size) / interpolation_scale
34
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
35
+ grid = np.stack(grid, axis=0)
36
+
37
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
38
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
39
+ if cls_token and extra_tokens > 0:
40
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
41
+ return pos_embed
42
+
43
+
44
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
45
+ if embed_dim % 2 != 0:
46
+ raise ValueError("embed_dim must be divisible by 2")
47
+
48
+ # use half of dimensions to encode grid_h
49
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
50
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
51
+
52
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
53
+ return emb
54
+
55
+
56
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
57
+ """
58
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
59
+ """
60
+ if embed_dim % 2 != 0:
61
+ raise ValueError("embed_dim must be divisible by 2")
62
+
63
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
64
+ omega /= embed_dim / 2.0
65
+ omega = 1.0 / 10000**omega # (D/2,)
66
+
67
+ pos = pos.reshape(-1) # (M,)
68
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
69
+
70
+ emb_sin = np.sin(out) # (M, D/2)
71
+ emb_cos = np.cos(out) # (M, D/2)
72
+
73
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
74
+ return emb
75
+
76
+
77
+ def get_timestep_embedding(
78
+ timesteps: torch.Tensor,
79
+ embedding_dim: int,
80
+ flip_sin_to_cos: bool = False,
81
+ downscale_freq_shift: float = 1,
82
+ scale: float = 1,
83
+ max_period: int = 10000,
84
+ ):
85
+ """
86
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
87
+ :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional.
88
+ :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the
89
+ embeddings. :return: an [N x dim] Tensor of positional embeddings.
90
+ """
91
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
92
+
93
+ half_dim = embedding_dim // 2
94
+ exponent = -math.log(max_period) * torch.arange(
95
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
96
+ )
97
+ exponent = exponent / (half_dim - downscale_freq_shift)
98
+
99
+ emb = torch.exp(exponent)
100
+ emb = timesteps[:, None].float() * emb[None, :]
101
+
102
+ # scale embeddings
103
+ emb = scale * emb
104
+
105
+ # concat sine and cosine embeddings
106
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
107
+
108
+ # flip sine and cosine embeddings
109
+ if flip_sin_to_cos:
110
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
111
+
112
+ # zero pad
113
+ if embedding_dim % 2 == 1:
114
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
115
+ return emb
116
+
117
+
118
+ class Timesteps(nn.Module):
119
+ def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float):
120
+ super().__init__()
121
+ self.num_channels = num_channels
122
+ self.flip_sin_to_cos = flip_sin_to_cos
123
+ self.downscale_freq_shift = downscale_freq_shift
124
+
125
+ def forward(self, timesteps):
126
+ t_emb = get_timestep_embedding(
127
+ timesteps,
128
+ self.num_channels,
129
+ flip_sin_to_cos=self.flip_sin_to_cos,
130
+ downscale_freq_shift=self.downscale_freq_shift,
131
+ )
132
+ return t_emb
133
+
134
+
135
+ class TimestepEmbedding(nn.Module):
136
+ def __init__(
137
+ self,
138
+ in_channels: int,
139
+ time_embed_dim: int,
140
+ act_fn: str = "silu",
141
+ out_dim: int = None,
142
+ post_act_fn: Optional[str] = None,
143
+ sample_proj_bias=True,
144
+ ):
145
+ super().__init__()
146
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, sample_proj_bias)
147
+ self.act = get_activation(act_fn)
148
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim, sample_proj_bias)
149
+
150
+ def forward(self, sample):
151
+ sample = self.linear_1(sample)
152
+ sample = self.act(sample)
153
+ sample = self.linear_2(sample)
154
+ return sample
155
+
156
+
157
+ class TextProjection(nn.Module):
158
+ def __init__(self, in_features, hidden_size, act_fn="silu"):
159
+ super().__init__()
160
+ self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
161
+ self.act_1 = get_activation(act_fn)
162
+ self.linear_2 = nn.Linear(in_features=hidden_size, out_features=hidden_size, bias=True)
163
+
164
+ def forward(self, caption):
165
+ hidden_states = self.linear_1(caption)
166
+ hidden_states = self.act_1(hidden_states)
167
+ hidden_states = self.linear_2(hidden_states)
168
+ return hidden_states
169
+
170
+
171
+ class CombinedTimestepConditionEmbeddings(nn.Module):
172
+ def __init__(self, embedding_dim, pooled_projection_dim):
173
+ super().__init__()
174
+
175
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
176
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
177
+ self.text_embedder = TextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
178
+
179
+ def forward(self, timestep, pooled_projection):
180
+ timesteps_proj = self.time_proj(timestep)
181
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
182
+ pooled_projections = self.text_embedder(pooled_projection)
183
+ conditioning = timesteps_emb + pooled_projections
184
+ return conditioning
185
+
186
+
187
+ class CombinedTimestepEmbeddings(nn.Module):
188
+ def __init__(self, embedding_dim):
189
+ super().__init__()
190
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
191
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
192
+
193
+ def forward(self, timestep):
194
+ timesteps_proj = self.time_proj(timestep)
195
+ timesteps_emb = self.timestep_embedder(timesteps_proj) # (N, D)
196
+ return timesteps_emb
197
+
198
+
199
+ class PatchEmbed3D(nn.Module):
200
+ """Support the 3D Tensor input"""
201
+
202
+ def __init__(
203
+ self,
204
+ height=128,
205
+ width=128,
206
+ patch_size=2,
207
+ in_channels=16,
208
+ embed_dim=1536,
209
+ layer_norm=False,
210
+ bias=True,
211
+ interpolation_scale=1,
212
+ pos_embed_type="sincos",
213
+ temp_pos_embed_type='rope',
214
+ pos_embed_max_size=192, # For SD3 cropping
215
+ max_num_frames=64,
216
+ add_temp_pos_embed=False,
217
+ interp_condition_pos=False,
218
+ ):
219
+ super().__init__()
220
+
221
+ num_patches = (height // patch_size) * (width // patch_size)
222
+ self.layer_norm = layer_norm
223
+ self.pos_embed_max_size = pos_embed_max_size
224
+
225
+ self.proj = nn.Conv2d(
226
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
227
+ )
228
+ if layer_norm:
229
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
230
+ else:
231
+ self.norm = None
232
+
233
+ self.patch_size = patch_size
234
+ self.height, self.width = height // patch_size, width // patch_size
235
+ self.base_size = height // patch_size
236
+ self.interpolation_scale = interpolation_scale
237
+ self.add_temp_pos_embed = add_temp_pos_embed
238
+
239
+ # Calculate positional embeddings based on max size or default
240
+ if pos_embed_max_size:
241
+ grid_size = pos_embed_max_size
242
+ else:
243
+ grid_size = int(num_patches**0.5)
244
+
245
+ if pos_embed_type is None:
246
+ self.pos_embed = None
247
+
248
+ elif pos_embed_type == "sincos":
249
+ pos_embed = get_2d_sincos_pos_embed(
250
+ embed_dim, grid_size, base_size=self.base_size, interpolation_scale=self.interpolation_scale
251
+ )
252
+ persistent = True if pos_embed_max_size else False
253
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=persistent)
254
+
255
+ if add_temp_pos_embed and temp_pos_embed_type == 'sincos':
256
+ time_pos_embed = get_1d_sincos_pos_embed(embed_dim, max_num_frames)
257
+ self.register_buffer("temp_pos_embed", torch.from_numpy(time_pos_embed).float().unsqueeze(0), persistent=True)
258
+
259
+ elif pos_embed_type == "rope":
260
+ print("Using the rotary position embedding")
261
+
262
+ else:
263
+ raise ValueError(f"Unsupported pos_embed_type: {pos_embed_type}")
264
+
265
+ self.pos_embed_type = pos_embed_type
266
+ self.temp_pos_embed_type = temp_pos_embed_type
267
+ self.interp_condition_pos = interp_condition_pos
268
+
269
+ def cropped_pos_embed(self, height, width, ori_height, ori_width):
270
+ """Crops positional embeddings for SD3 compatibility."""
271
+ if self.pos_embed_max_size is None:
272
+ raise ValueError("`pos_embed_max_size` must be set for cropping.")
273
+
274
+ height = height // self.patch_size
275
+ width = width // self.patch_size
276
+ ori_height = ori_height // self.patch_size
277
+ ori_width = ori_width // self.patch_size
278
+
279
+ assert ori_height >= height, "The ori_height needs >= height"
280
+ assert ori_width >= width, "The ori_width needs >= width"
281
+
282
+ if height > self.pos_embed_max_size:
283
+ raise ValueError(
284
+ f"Height ({height}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
285
+ )
286
+ if width > self.pos_embed_max_size:
287
+ raise ValueError(
288
+ f"Width ({width}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
289
+ )
290
+
291
+ if self.interp_condition_pos:
292
+ top = (self.pos_embed_max_size - ori_height) // 2
293
+ left = (self.pos_embed_max_size - ori_width) // 2
294
+ spatial_pos_embed = self.pos_embed.reshape(1, self.pos_embed_max_size, self.pos_embed_max_size, -1)
295
+ spatial_pos_embed = spatial_pos_embed[:, top : top + ori_height, left : left + ori_width, :] # [b h w c]
296
+ if ori_height != height or ori_width != width:
297
+ spatial_pos_embed = spatial_pos_embed.permute(0, 3, 1, 2)
298
+ spatial_pos_embed = torch.nn.functional.interpolate(spatial_pos_embed, size=(height, width), mode='bilinear')
299
+ spatial_pos_embed = spatial_pos_embed.permute(0, 2, 3, 1)
300
+ else:
301
+ top = (self.pos_embed_max_size - height) // 2
302
+ left = (self.pos_embed_max_size - width) // 2
303
+ spatial_pos_embed = self.pos_embed.reshape(1, self.pos_embed_max_size, self.pos_embed_max_size, -1)
304
+ spatial_pos_embed = spatial_pos_embed[:, top : top + height, left : left + width, :]
305
+
306
+ spatial_pos_embed = spatial_pos_embed.reshape(1, -1, spatial_pos_embed.shape[-1])
307
+
308
+ return spatial_pos_embed
309
+
310
+ def forward_func(self, latent, time_index=0, ori_height=None, ori_width=None):
311
+ if self.pos_embed_max_size is not None:
312
+ height, width = latent.shape[-2:]
313
+ else:
314
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
315
+
316
+ bs = latent.shape[0]
317
+ temp = latent.shape[2]
318
+
319
+ latent = rearrange(latent, 'b c t h w -> (b t) c h w')
320
+ latent = self.proj(latent)
321
+ latent = latent.flatten(2).transpose(1, 2) # (BT)CHW -> (BT)NC
322
+
323
+ if self.layer_norm:
324
+ latent = self.norm(latent)
325
+
326
+ if self.pos_embed_type == 'sincos':
327
+ # Spatial position embedding, Interpolate or crop positional embeddings as needed
328
+ if self.pos_embed_max_size:
329
+ pos_embed = self.cropped_pos_embed(height, width, ori_height, ori_width)
330
+ else:
331
+ raise NotImplementedError("Not implemented sincos pos embed without sd3 max pos crop")
332
+ if self.height != height or self.width != width:
333
+ pos_embed = get_2d_sincos_pos_embed(
334
+ embed_dim=self.pos_embed.shape[-1],
335
+ grid_size=(height, width),
336
+ base_size=self.base_size,
337
+ interpolation_scale=self.interpolation_scale,
338
+ )
339
+ pos_embed = torch.from_numpy(pos_embed).float().unsqueeze(0).to(latent.device)
340
+ else:
341
+ pos_embed = self.pos_embed
342
+
343
+ if self.add_temp_pos_embed and self.temp_pos_embed_type == 'sincos':
344
+ latent_dtype = latent.dtype
345
+ latent = latent + pos_embed
346
+ latent = rearrange(latent, '(b t) n c -> (b n) t c', t=temp)
347
+ latent = latent + self.temp_pos_embed[:, time_index:time_index + temp, :]
348
+ latent = latent.to(latent_dtype)
349
+ latent = rearrange(latent, '(b n) t c -> b t n c', b=bs)
350
+ else:
351
+ latent = (latent + pos_embed).to(latent.dtype)
352
+ latent = rearrange(latent, '(b t) n c -> b t n c', b=bs, t=temp)
353
+
354
+ else:
355
+ assert self.pos_embed_type == "rope", "Only supporting the sincos and rope embedding"
356
+ latent = rearrange(latent, '(b t) n c -> b t n c', b=bs, t=temp)
357
+
358
+ return latent
359
+
360
+ def forward(self, latent):
361
+ """
362
+ Arguments:
363
+ past_condition_latents (Torch.FloatTensor): The past latent during the generation
364
+ flatten_input (bool): True indicate flatten the latent into 1D sequence
365
+ """
366
+
367
+ if isinstance(latent, list):
368
+ output_list = []
369
+
370
+ for latent_ in latent:
371
+ if not isinstance(latent_, list):
372
+ latent_ = [latent_]
373
+
374
+ output_latent = []
375
+ time_index = 0
376
+ ori_height, ori_width = latent_[-1].shape[-2:]
377
+ for each_latent in latent_:
378
+ hidden_state = self.forward_func(each_latent, time_index=time_index, ori_height=ori_height, ori_width=ori_width)
379
+ time_index += each_latent.shape[2]
380
+ hidden_state = rearrange(hidden_state, "b t n c -> b (t n) c")
381
+ output_latent.append(hidden_state)
382
+
383
+ output_latent = torch.cat(output_latent, dim=1)
384
+ output_list.append(output_latent)
385
+
386
+ return output_list
387
+ else:
388
+ hidden_states = self.forward_func(latent)
389
+ hidden_states = rearrange(hidden_states, "b t n c -> b (t n) c")
390
+ return hidden_states
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_mmdit_block.py ADDED
@@ -0,0 +1,671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, Tuple, List
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from einops import rearrange
6
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
7
+
8
+ try:
9
+ from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
10
+ from flash_attn.bert_padding import pad_input, unpad_input, index_first_axis
11
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func
12
+ except:
13
+ flash_attn_func = None
14
+ flash_attn_qkvpacked_func = None
15
+ flash_attn_varlen_func = None
16
+
17
+ from trainer_misc import (
18
+ is_sequence_parallel_initialized,
19
+ get_sequence_parallel_group,
20
+ get_sequence_parallel_world_size,
21
+ all_to_all,
22
+ )
23
+
24
+ from .modeling_normalization import AdaLayerNormZero, AdaLayerNormContinuous, RMSNorm
25
+
26
+
27
+ class FeedForward(nn.Module):
28
+ r"""
29
+ A feed-forward layer.
30
+
31
+ Parameters:
32
+ dim (`int`): The number of channels in the input.
33
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
34
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
35
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
36
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
37
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
38
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
39
+ """
40
+ def __init__(
41
+ self,
42
+ dim: int,
43
+ dim_out: Optional[int] = None,
44
+ mult: int = 4,
45
+ dropout: float = 0.0,
46
+ activation_fn: str = "geglu",
47
+ final_dropout: bool = False,
48
+ inner_dim=None,
49
+ bias: bool = True,
50
+ ):
51
+ super().__init__()
52
+ if inner_dim is None:
53
+ inner_dim = int(dim * mult)
54
+ dim_out = dim_out if dim_out is not None else dim
55
+
56
+ if activation_fn == "gelu":
57
+ act_fn = GELU(dim, inner_dim, bias=bias)
58
+ if activation_fn == "gelu-approximate":
59
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
60
+ elif activation_fn == "geglu":
61
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
62
+ elif activation_fn == "geglu-approximate":
63
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
64
+
65
+ self.net = nn.ModuleList([])
66
+ # project in
67
+ self.net.append(act_fn)
68
+ # project dropout
69
+ self.net.append(nn.Dropout(dropout))
70
+ # project out
71
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
72
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
73
+ if final_dropout:
74
+ self.net.append(nn.Dropout(dropout))
75
+
76
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
77
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
78
+ 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`."
79
+ deprecate("scale", "1.0.0", deprecation_message)
80
+ for module in self.net:
81
+ hidden_states = module(hidden_states)
82
+ return hidden_states
83
+
84
+
85
+ class VarlenFlashSelfAttentionWithT5Mask:
86
+
87
+ def __init__(self):
88
+ pass
89
+
90
+ def apply_rope(self, xq, xk, freqs_cis):
91
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
92
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
93
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
94
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
95
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
96
+
97
+ def __call__(
98
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
99
+ heads, scale, hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
100
+ ):
101
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
102
+
103
+ batch_size = query.shape[0]
104
+ output_hidden = torch.zeros_like(query)
105
+ output_encoder_hidden = torch.zeros_like(encoder_query)
106
+ encoder_length = encoder_query.shape[1]
107
+
108
+ qkv_list = []
109
+ num_stages = len(hidden_length)
110
+
111
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
112
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
113
+
114
+ i_sum = 0
115
+ for i_p, length in enumerate(hidden_length):
116
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
117
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
118
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
119
+
120
+ if image_rotary_emb is not None:
121
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = self.apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
122
+
123
+ indices = encoder_attention_mask[i_p]['indices']
124
+ qkv_list.append(index_first_axis(rearrange(concat_qkv_tokens, "b s ... -> (b s) ..."), indices))
125
+ i_sum += length
126
+
127
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
128
+ qkv = torch.cat(qkv_list, dim=0)
129
+ query, key, value = qkv.unbind(1)
130
+
131
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
132
+ max_seqlen_q = cu_seqlens.max().item()
133
+ max_seqlen_k = max_seqlen_q
134
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
135
+ cu_seqlens_k = cu_seqlens_q.clone()
136
+
137
+ output = flash_attn_varlen_func(
138
+ query,
139
+ key,
140
+ value,
141
+ cu_seqlens_q=cu_seqlens_q,
142
+ cu_seqlens_k=cu_seqlens_k,
143
+ max_seqlen_q=max_seqlen_q,
144
+ max_seqlen_k=max_seqlen_k,
145
+ dropout_p=0.0,
146
+ causal=False,
147
+ softmax_scale=scale,
148
+ )
149
+
150
+ # To merge the tokens
151
+ i_sum = 0;token_sum = 0
152
+ for i_p, length in enumerate(hidden_length):
153
+ tot_token_num = token_lengths[i_p]
154
+ stage_output = output[token_sum : token_sum + tot_token_num]
155
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, encoder_length + length)
156
+ stage_encoder_hidden_output = stage_output[:, :encoder_length]
157
+ stage_hidden_output = stage_output[:, encoder_length:]
158
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
159
+ output_encoder_hidden[i_p::num_stages] = stage_encoder_hidden_output
160
+ token_sum += tot_token_num
161
+ i_sum += length
162
+
163
+ output_hidden = output_hidden.flatten(2, 3)
164
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
165
+
166
+ return output_hidden, output_encoder_hidden
167
+
168
+
169
+ class SequenceParallelVarlenFlashSelfAttentionWithT5Mask:
170
+
171
+ def __init__(self):
172
+ pass
173
+
174
+ def apply_rope(self, xq, xk, freqs_cis):
175
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
176
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
177
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
178
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
179
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
180
+
181
+ def __call__(
182
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
183
+ heads, scale, hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
184
+ ):
185
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
186
+
187
+ batch_size = query.shape[0]
188
+ qkv_list = []
189
+ num_stages = len(hidden_length)
190
+
191
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
192
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
193
+
194
+ # To sync the encoder query, key and values
195
+ sp_group = get_sequence_parallel_group()
196
+ sp_group_size = get_sequence_parallel_world_size()
197
+ encoder_qkv = all_to_all(encoder_qkv, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
198
+
199
+ output_hidden = torch.zeros_like(qkv[:,:,0])
200
+ output_encoder_hidden = torch.zeros_like(encoder_qkv[:,:,0])
201
+ encoder_length = encoder_qkv.shape[1]
202
+
203
+ i_sum = 0
204
+ for i_p, length in enumerate(hidden_length):
205
+ # get the query, key, value from padding sequence
206
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
207
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
208
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
209
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, pad_seq, 3, nhead, dim]
210
+
211
+ if image_rotary_emb is not None:
212
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = self.apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
213
+
214
+ indices = encoder_attention_mask[i_p]['indices']
215
+ qkv_list.append(index_first_axis(rearrange(concat_qkv_tokens, "b s ... -> (b s) ..."), indices))
216
+ i_sum += length
217
+
218
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
219
+ qkv = torch.cat(qkv_list, dim=0)
220
+ query, key, value = qkv.unbind(1)
221
+
222
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
223
+ max_seqlen_q = cu_seqlens.max().item()
224
+ max_seqlen_k = max_seqlen_q
225
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
226
+ cu_seqlens_k = cu_seqlens_q.clone()
227
+
228
+ output = flash_attn_varlen_func(
229
+ query,
230
+ key,
231
+ value,
232
+ cu_seqlens_q=cu_seqlens_q,
233
+ cu_seqlens_k=cu_seqlens_k,
234
+ max_seqlen_q=max_seqlen_q,
235
+ max_seqlen_k=max_seqlen_k,
236
+ dropout_p=0.0,
237
+ causal=False,
238
+ softmax_scale=scale,
239
+ )
240
+
241
+ # To merge the tokens
242
+ i_sum = 0;token_sum = 0
243
+ for i_p, length in enumerate(hidden_length):
244
+ tot_token_num = token_lengths[i_p]
245
+ stage_output = output[token_sum : token_sum + tot_token_num]
246
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, encoder_length + length * sp_group_size)
247
+ stage_encoder_hidden_output = stage_output[:, :encoder_length]
248
+ stage_hidden_output = stage_output[:, encoder_length:]
249
+ stage_hidden_output = all_to_all(stage_hidden_output, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
250
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
251
+ output_encoder_hidden[i_p::num_stages] = stage_encoder_hidden_output
252
+ token_sum += tot_token_num
253
+ i_sum += length
254
+
255
+ output_encoder_hidden = all_to_all(output_encoder_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
256
+ output_hidden = output_hidden.flatten(2, 3)
257
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
258
+
259
+ return output_hidden, output_encoder_hidden
260
+
261
+
262
+ class VarlenSelfAttentionWithT5Mask:
263
+
264
+ """
265
+ For chunk stage attention without using flash attention
266
+ """
267
+
268
+ def __init__(self):
269
+ pass
270
+
271
+ def apply_rope(self, xq, xk, freqs_cis):
272
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
273
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
274
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
275
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
276
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
277
+
278
+ def __call__(
279
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
280
+ heads, scale, hidden_length=None, image_rotary_emb=None, attention_mask=None,
281
+ ):
282
+ assert attention_mask is not None, "The attention mask needed to be set"
283
+
284
+ encoder_length = encoder_query.shape[1]
285
+ num_stages = len(hidden_length)
286
+
287
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
288
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
289
+
290
+ i_sum = 0
291
+ output_encoder_hidden_list = []
292
+ output_hidden_list = []
293
+
294
+ for i_p, length in enumerate(hidden_length):
295
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
296
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
297
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
298
+
299
+ if image_rotary_emb is not None:
300
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = self.apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
301
+
302
+ query, key, value = concat_qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
303
+ query = query.transpose(1, 2)
304
+ key = key.transpose(1, 2)
305
+ value = value.transpose(1, 2)
306
+
307
+ # with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=False, enable_mem_efficient=True):
308
+ stage_hidden_states = F.scaled_dot_product_attention(
309
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
310
+ )
311
+ stage_hidden_states = stage_hidden_states.transpose(1, 2).flatten(2, 3) # [bs, tot_seq, dim]
312
+
313
+ output_encoder_hidden_list.append(stage_hidden_states[:, :encoder_length])
314
+ output_hidden_list.append(stage_hidden_states[:, encoder_length:])
315
+ i_sum += length
316
+
317
+ output_encoder_hidden = torch.stack(output_encoder_hidden_list, dim=1) # [b n s d]
318
+ output_encoder_hidden = rearrange(output_encoder_hidden, 'b n s d -> (b n) s d')
319
+ output_hidden = torch.cat(output_hidden_list, dim=1)
320
+
321
+ return output_hidden, output_encoder_hidden
322
+
323
+
324
+ class SequenceParallelVarlenSelfAttentionWithT5Mask:
325
+ """
326
+ For chunk stage attention without using flash attention
327
+ """
328
+
329
+ def __init__(self):
330
+ pass
331
+
332
+ def apply_rope(self, xq, xk, freqs_cis):
333
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
334
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
335
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
336
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
337
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
338
+
339
+ def __call__(
340
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
341
+ heads, scale, hidden_length=None, image_rotary_emb=None, attention_mask=None,
342
+ ):
343
+ assert attention_mask is not None, "The attention mask needed to be set"
344
+
345
+ num_stages = len(hidden_length)
346
+
347
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
348
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
349
+
350
+ # To sync the encoder query, key and values
351
+ sp_group = get_sequence_parallel_group()
352
+ sp_group_size = get_sequence_parallel_world_size()
353
+ encoder_qkv = all_to_all(encoder_qkv, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
354
+ encoder_length = encoder_qkv.shape[1]
355
+
356
+ i_sum = 0
357
+ output_encoder_hidden_list = []
358
+ output_hidden_list = []
359
+
360
+ for i_p, length in enumerate(hidden_length):
361
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
362
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
363
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
364
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
365
+
366
+ if image_rotary_emb is not None:
367
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = self.apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
368
+
369
+ query, key, value = concat_qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
370
+ query = query.transpose(1, 2)
371
+ key = key.transpose(1, 2)
372
+ value = value.transpose(1, 2)
373
+
374
+ stage_hidden_states = F.scaled_dot_product_attention(
375
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
376
+ )
377
+ stage_hidden_states = stage_hidden_states.transpose(1, 2) # [bs, tot_seq, nhead, dim]
378
+
379
+ output_encoder_hidden_list.append(stage_hidden_states[:, :encoder_length])
380
+
381
+ output_hidden = stage_hidden_states[:, encoder_length:]
382
+ output_hidden = all_to_all(output_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
383
+ output_hidden_list.append(output_hidden)
384
+
385
+ i_sum += length
386
+
387
+ output_encoder_hidden = torch.stack(output_encoder_hidden_list, dim=1) # [b n s nhead d]
388
+ output_encoder_hidden = rearrange(output_encoder_hidden, 'b n s h d -> (b n) s h d')
389
+ output_encoder_hidden = all_to_all(output_encoder_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
390
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
391
+ output_hidden = torch.cat(output_hidden_list, dim=1).flatten(2, 3)
392
+
393
+ return output_hidden, output_encoder_hidden
394
+
395
+
396
+ class JointAttention(nn.Module):
397
+
398
+ def __init__(
399
+ self,
400
+ query_dim: int,
401
+ cross_attention_dim: Optional[int] = None,
402
+ heads: int = 8,
403
+ dim_head: int = 64,
404
+ dropout: float = 0.0,
405
+ bias: bool = False,
406
+ qk_norm: Optional[str] = None,
407
+ added_kv_proj_dim: Optional[int] = None,
408
+ out_bias: bool = True,
409
+ eps: float = 1e-5,
410
+ out_dim: int = None,
411
+ context_pre_only=None,
412
+ use_flash_attn=True,
413
+ ):
414
+ """
415
+ Fixing the QKNorm, following the flux, norm the head dimension
416
+ """
417
+ super().__init__()
418
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
419
+ self.query_dim = query_dim
420
+ self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
421
+ self.use_bias = bias
422
+ self.dropout = dropout
423
+
424
+ self.out_dim = out_dim if out_dim is not None else query_dim
425
+ self.context_pre_only = context_pre_only
426
+
427
+ self.scale = dim_head**-0.5
428
+ self.heads = out_dim // dim_head if out_dim is not None else heads
429
+ self.added_kv_proj_dim = added_kv_proj_dim
430
+
431
+ if qk_norm is None:
432
+ self.norm_q = None
433
+ self.norm_k = None
434
+ elif qk_norm == "layer_norm":
435
+ self.norm_q = nn.LayerNorm(dim_head, eps=eps)
436
+ self.norm_k = nn.LayerNorm(dim_head, eps=eps)
437
+ elif qk_norm == 'rms_norm':
438
+ self.norm_q = RMSNorm(dim_head, eps=eps)
439
+ self.norm_k = RMSNorm(dim_head, eps=eps)
440
+ else:
441
+ raise ValueError(f"unknown qk_norm: {qk_norm}. Should be None or 'layer_norm'")
442
+
443
+ self.to_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
444
+ self.to_k = nn.Linear(self.cross_attention_dim, self.inner_dim, bias=bias)
445
+ self.to_v = nn.Linear(self.cross_attention_dim, self.inner_dim, bias=bias)
446
+
447
+ if self.added_kv_proj_dim is not None:
448
+ self.add_k_proj = nn.Linear(added_kv_proj_dim, self.inner_dim)
449
+ self.add_v_proj = nn.Linear(added_kv_proj_dim, self.inner_dim)
450
+ self.add_q_proj = nn.Linear(added_kv_proj_dim, self.inner_dim)
451
+
452
+ if qk_norm is None:
453
+ self.norm_add_q = None
454
+ self.norm_add_k = None
455
+ elif qk_norm == "layer_norm":
456
+ self.norm_add_q = nn.LayerNorm(dim_head, eps=eps)
457
+ self.norm_add_k = nn.LayerNorm(dim_head, eps=eps)
458
+ elif qk_norm == 'rms_norm':
459
+ self.norm_add_q = RMSNorm(dim_head, eps=eps)
460
+ self.norm_add_k = RMSNorm(dim_head, eps=eps)
461
+ else:
462
+ raise ValueError(f"unknown qk_norm: {qk_norm}. Should be None or 'layer_norm'")
463
+
464
+ self.to_out = nn.ModuleList([])
465
+ self.to_out.append(nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
466
+ self.to_out.append(nn.Dropout(dropout))
467
+
468
+ if not self.context_pre_only:
469
+ self.to_add_out = nn.Linear(self.inner_dim, self.out_dim, bias=out_bias)
470
+
471
+ self.use_flash_attn = use_flash_attn
472
+
473
+ if flash_attn_func is None:
474
+ self.use_flash_attn = False
475
+
476
+ # print(f"Using flash-attention: {self.use_flash_attn}")
477
+ if self.use_flash_attn:
478
+ if is_sequence_parallel_initialized():
479
+ self.var_flash_attn = SequenceParallelVarlenFlashSelfAttentionWithT5Mask()
480
+ else:
481
+ self.var_flash_attn = VarlenFlashSelfAttentionWithT5Mask()
482
+ else:
483
+ if is_sequence_parallel_initialized():
484
+ self.var_len_attn = SequenceParallelVarlenSelfAttentionWithT5Mask()
485
+ else:
486
+ self.var_len_attn = VarlenSelfAttentionWithT5Mask()
487
+
488
+
489
+ def forward(
490
+ self,
491
+ hidden_states: torch.FloatTensor,
492
+ encoder_hidden_states: torch.FloatTensor = None,
493
+ encoder_attention_mask: torch.FloatTensor = None,
494
+ attention_mask: torch.FloatTensor = None, # [B, L, S]
495
+ hidden_length: torch.Tensor = None,
496
+ image_rotary_emb: torch.Tensor = None,
497
+ **kwargs,
498
+ ) -> torch.FloatTensor:
499
+ # This function is only used during training
500
+ # `sample` projections.
501
+ query = self.to_q(hidden_states)
502
+ key = self.to_k(hidden_states)
503
+ value = self.to_v(hidden_states)
504
+
505
+ inner_dim = key.shape[-1]
506
+ head_dim = inner_dim // self.heads
507
+
508
+ query = query.view(query.shape[0], -1, self.heads, head_dim)
509
+ key = key.view(key.shape[0], -1, self.heads, head_dim)
510
+ value = value.view(value.shape[0], -1, self.heads, head_dim)
511
+
512
+ if self.norm_q is not None:
513
+ query = self.norm_q(query)
514
+
515
+ if self.norm_k is not None:
516
+ key = self.norm_k(key)
517
+
518
+ # `context` projections.
519
+ encoder_hidden_states_query_proj = self.add_q_proj(encoder_hidden_states)
520
+ encoder_hidden_states_key_proj = self.add_k_proj(encoder_hidden_states)
521
+ encoder_hidden_states_value_proj = self.add_v_proj(encoder_hidden_states)
522
+
523
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
524
+ encoder_hidden_states_query_proj.shape[0], -1, self.heads, head_dim
525
+ )
526
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
527
+ encoder_hidden_states_key_proj.shape[0], -1, self.heads, head_dim
528
+ )
529
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
530
+ encoder_hidden_states_value_proj.shape[0], -1, self.heads, head_dim
531
+ )
532
+
533
+ if self.norm_add_q is not None:
534
+ encoder_hidden_states_query_proj = self.norm_add_q(encoder_hidden_states_query_proj)
535
+
536
+ if self.norm_add_k is not None:
537
+ encoder_hidden_states_key_proj = self.norm_add_k(encoder_hidden_states_key_proj)
538
+
539
+ # To cat the hidden and encoder hidden, perform attention compuataion, and then split
540
+ if self.use_flash_attn:
541
+ hidden_states, encoder_hidden_states = self.var_flash_attn(
542
+ query, key, value,
543
+ encoder_hidden_states_query_proj, encoder_hidden_states_key_proj,
544
+ encoder_hidden_states_value_proj, self.heads, self.scale, hidden_length,
545
+ image_rotary_emb, encoder_attention_mask,
546
+ )
547
+ else:
548
+ hidden_states, encoder_hidden_states = self.var_len_attn(
549
+ query, key, value,
550
+ encoder_hidden_states_query_proj, encoder_hidden_states_key_proj,
551
+ encoder_hidden_states_value_proj, self.heads, self.scale, hidden_length,
552
+ image_rotary_emb, attention_mask,
553
+ )
554
+
555
+ # linear proj
556
+ hidden_states = self.to_out[0](hidden_states)
557
+ # dropout
558
+ hidden_states = self.to_out[1](hidden_states)
559
+ if not self.context_pre_only:
560
+ encoder_hidden_states = self.to_add_out(encoder_hidden_states)
561
+
562
+ return hidden_states, encoder_hidden_states
563
+
564
+
565
+ class JointTransformerBlock(nn.Module):
566
+ r"""
567
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
568
+
569
+ Reference: https://arxiv.org/abs/2403.03206
570
+
571
+ Parameters:
572
+ dim (`int`): The number of channels in the input and output.
573
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
574
+ attention_head_dim (`int`): The number of channels in each head.
575
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
576
+ processing of `context` conditions.
577
+ """
578
+
579
+ def __init__(
580
+ self, dim, num_attention_heads, attention_head_dim, qk_norm=None,
581
+ context_pre_only=False, use_flash_attn=True,
582
+ ):
583
+ super().__init__()
584
+
585
+ self.context_pre_only = context_pre_only
586
+ context_norm_type = "ada_norm_continous" if context_pre_only else "ada_norm_zero"
587
+
588
+ self.norm1 = AdaLayerNormZero(dim)
589
+
590
+ if context_norm_type == "ada_norm_continous":
591
+ self.norm1_context = AdaLayerNormContinuous(
592
+ dim, dim, elementwise_affine=False, eps=1e-6, bias=True, norm_type="layer_norm"
593
+ )
594
+ elif context_norm_type == "ada_norm_zero":
595
+ self.norm1_context = AdaLayerNormZero(dim)
596
+ else:
597
+ raise ValueError(
598
+ f"Unknown context_norm_type: {context_norm_type}, currently only support `ada_norm_continous`, `ada_norm_zero`"
599
+ )
600
+
601
+ self.attn = JointAttention(
602
+ query_dim=dim,
603
+ cross_attention_dim=None,
604
+ added_kv_proj_dim=dim,
605
+ dim_head=attention_head_dim // num_attention_heads,
606
+ heads=num_attention_heads,
607
+ out_dim=attention_head_dim,
608
+ qk_norm=qk_norm,
609
+ context_pre_only=context_pre_only,
610
+ bias=True,
611
+ use_flash_attn=use_flash_attn,
612
+ )
613
+
614
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
615
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
616
+
617
+ if not context_pre_only:
618
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
619
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
620
+ else:
621
+ self.norm2_context = None
622
+ self.ff_context = None
623
+
624
+ def forward(
625
+ self, hidden_states: torch.FloatTensor, encoder_hidden_states: torch.FloatTensor,
626
+ encoder_attention_mask: torch.FloatTensor, temb: torch.FloatTensor,
627
+ attention_mask: torch.FloatTensor = None, hidden_length: List = None,
628
+ image_rotary_emb: torch.FloatTensor = None,
629
+ ):
630
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb, hidden_length=hidden_length)
631
+
632
+ if self.context_pre_only:
633
+ norm_encoder_hidden_states = self.norm1_context(encoder_hidden_states, temb)
634
+ else:
635
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
636
+ encoder_hidden_states, emb=temb,
637
+ )
638
+
639
+ # Attention
640
+ attn_output, context_attn_output = self.attn(
641
+ hidden_states=norm_hidden_states, encoder_hidden_states=norm_encoder_hidden_states,
642
+ encoder_attention_mask=encoder_attention_mask, attention_mask=attention_mask,
643
+ hidden_length=hidden_length, image_rotary_emb=image_rotary_emb,
644
+ )
645
+
646
+ # Process attention outputs for the `hidden_states`.
647
+ attn_output = gate_msa * attn_output
648
+ hidden_states = hidden_states + attn_output
649
+
650
+ norm_hidden_states = self.norm2(hidden_states)
651
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
652
+
653
+ ff_output = self.ff(norm_hidden_states)
654
+ ff_output = gate_mlp * ff_output
655
+
656
+ hidden_states = hidden_states + ff_output
657
+
658
+ # Process attention outputs for the `encoder_hidden_states`.
659
+ if self.context_pre_only:
660
+ encoder_hidden_states = None
661
+ else:
662
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
663
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
664
+
665
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
666
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
667
+
668
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
669
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
670
+
671
+ return encoder_hidden_states, hidden_states
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_normalization.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numbers
2
+ from typing import Dict, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+ from diffusers.utils import is_torch_version
9
+
10
+
11
+ if is_torch_version(">=", "2.1.0"):
12
+ LayerNorm = nn.LayerNorm
13
+ else:
14
+ # Has optional bias parameter compared to torch layer norm
15
+ # TODO: replace with torch layernorm once min required torch version >= 2.1
16
+ class LayerNorm(nn.Module):
17
+ def __init__(self, dim, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True):
18
+ super().__init__()
19
+
20
+ self.eps = eps
21
+
22
+ if isinstance(dim, numbers.Integral):
23
+ dim = (dim,)
24
+
25
+ self.dim = torch.Size(dim)
26
+
27
+ if elementwise_affine:
28
+ self.weight = nn.Parameter(torch.ones(dim))
29
+ self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
30
+ else:
31
+ self.weight = None
32
+ self.bias = None
33
+
34
+ def forward(self, input):
35
+ return F.layer_norm(input, self.dim, self.weight, self.bias, self.eps)
36
+
37
+
38
+ class RMSNorm(nn.Module):
39
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True):
40
+ super().__init__()
41
+
42
+ self.eps = eps
43
+
44
+ if isinstance(dim, numbers.Integral):
45
+ dim = (dim,)
46
+
47
+ self.dim = torch.Size(dim)
48
+
49
+ if elementwise_affine:
50
+ self.weight = nn.Parameter(torch.ones(dim))
51
+ else:
52
+ self.weight = None
53
+
54
+ def forward(self, hidden_states):
55
+ input_dtype = hidden_states.dtype
56
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
57
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
58
+
59
+ if self.weight is not None:
60
+ # convert into half-precision if necessary
61
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
62
+ hidden_states = hidden_states.to(self.weight.dtype)
63
+ hidden_states = hidden_states * self.weight
64
+
65
+ hidden_states = hidden_states.to(input_dtype)
66
+
67
+ return hidden_states
68
+
69
+
70
+ class AdaLayerNormContinuous(nn.Module):
71
+ def __init__(
72
+ self,
73
+ embedding_dim: int,
74
+ conditioning_embedding_dim: int,
75
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
76
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
77
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
78
+ # However, this is how it was implemented in the original code, and it's rather likely you should
79
+ # set `elementwise_affine` to False.
80
+ elementwise_affine=True,
81
+ eps=1e-5,
82
+ bias=True,
83
+ norm_type="layer_norm",
84
+ ):
85
+ super().__init__()
86
+ self.silu = nn.SiLU()
87
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
88
+ if norm_type == "layer_norm":
89
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
90
+ elif norm_type == "rms_norm":
91
+ self.norm = RMSNorm(embedding_dim, eps, elementwise_affine)
92
+ else:
93
+ raise ValueError(f"unknown norm_type {norm_type}")
94
+
95
+ def forward_with_pad(self, x: torch.Tensor, conditioning_embedding: torch.Tensor, hidden_length=None) -> torch.Tensor:
96
+ assert hidden_length is not None
97
+
98
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
99
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 2)
100
+
101
+ i_sum = 0
102
+ num_stages = len(hidden_length)
103
+ for i_p, length in enumerate(hidden_length):
104
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
105
+ i_sum += length
106
+
107
+ batch_scale, batch_shift = torch.chunk(batch_emb, 2, dim=2)
108
+ x = self.norm(x) * (1 + batch_scale) + batch_shift
109
+ return x
110
+
111
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor, hidden_length=None) -> torch.Tensor:
112
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
113
+ if hidden_length is not None:
114
+ return self.forward_with_pad(x, conditioning_embedding, hidden_length)
115
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
116
+ scale, shift = torch.chunk(emb, 2, dim=1)
117
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
118
+ return x
119
+
120
+
121
+ class AdaLayerNormZero(nn.Module):
122
+ r"""
123
+ Norm layer adaptive layer norm zero (adaLN-Zero).
124
+
125
+ Parameters:
126
+ embedding_dim (`int`): The size of each embedding vector.
127
+ num_embeddings (`int`): The size of the embeddings dictionary.
128
+ """
129
+
130
+ def __init__(self, embedding_dim: int, num_embeddings: Optional[int] = None):
131
+ super().__init__()
132
+ self.emb = None
133
+ self.silu = nn.SiLU()
134
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
135
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
136
+
137
+ def forward_with_pad(
138
+ self,
139
+ x: torch.Tensor,
140
+ timestep: Optional[torch.Tensor] = None,
141
+ class_labels: Optional[torch.LongTensor] = None,
142
+ hidden_dtype: Optional[torch.dtype] = None,
143
+ emb: Optional[torch.Tensor] = None,
144
+ hidden_length: Optional[torch.Tensor] = None,
145
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
146
+ # x: [bs, seq_len, dim]
147
+ if self.emb is not None:
148
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
149
+
150
+ emb = self.linear(self.silu(emb))
151
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 6)
152
+
153
+ i_sum = 0
154
+ num_stages = len(hidden_length)
155
+ for i_p, length in enumerate(hidden_length):
156
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
157
+ i_sum += length
158
+
159
+ batch_shift_msa, batch_scale_msa, batch_gate_msa, batch_shift_mlp, batch_scale_mlp, batch_gate_mlp = batch_emb.chunk(6, dim=2)
160
+ x = self.norm(x) * (1 + batch_scale_msa) + batch_shift_msa
161
+ return x, batch_gate_msa, batch_shift_mlp, batch_scale_mlp, batch_gate_mlp
162
+
163
+ def forward(
164
+ self,
165
+ x: torch.Tensor,
166
+ timestep: Optional[torch.Tensor] = None,
167
+ class_labels: Optional[torch.LongTensor] = None,
168
+ hidden_dtype: Optional[torch.dtype] = None,
169
+ emb: Optional[torch.Tensor] = None,
170
+ hidden_length: Optional[torch.Tensor] = None,
171
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
172
+ if hidden_length is not None:
173
+ return self.forward_with_pad(x, timestep, class_labels, hidden_dtype, emb, hidden_length)
174
+ if self.emb is not None:
175
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
176
+ emb = self.linear(self.silu(emb))
177
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
178
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
179
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_pyramid_mmdit.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import os
4
+ import torch.nn.functional as F
5
+
6
+ from einops import rearrange
7
+ from diffusers.utils.torch_utils import randn_tensor
8
+ from diffusers.models.modeling_utils import ModelMixin
9
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
10
+ from diffusers.utils import is_torch_version
11
+ from typing import Any, Callable, Dict, List, Optional, Union
12
+
13
+ from .modeling_embedding import PatchEmbed3D, CombinedTimestepConditionEmbeddings
14
+ from .modeling_normalization import AdaLayerNormContinuous
15
+ from .modeling_mmdit_block import JointTransformerBlock
16
+
17
+ from trainer_misc import (
18
+ is_sequence_parallel_initialized,
19
+ get_sequence_parallel_group,
20
+ get_sequence_parallel_world_size,
21
+ get_sequence_parallel_rank,
22
+ all_to_all,
23
+ )
24
+
25
+ from IPython import embed
26
+
27
+
28
+ def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
29
+ assert dim % 2 == 0, "The dimension must be even."
30
+
31
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
32
+ omega = 1.0 / (theta**scale)
33
+
34
+ batch_size, seq_length = pos.shape
35
+ out = torch.einsum("...n,d->...nd", pos, omega)
36
+ cos_out = torch.cos(out)
37
+ sin_out = torch.sin(out)
38
+
39
+ stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
40
+ out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
41
+ return out.float()
42
+
43
+
44
+ class EmbedNDRoPE(nn.Module):
45
+ def __init__(self, dim: int, theta: int, axes_dim: List[int]):
46
+ super().__init__()
47
+ self.dim = dim
48
+ self.theta = theta
49
+ self.axes_dim = axes_dim
50
+
51
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
52
+ n_axes = ids.shape[-1]
53
+ emb = torch.cat(
54
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
55
+ dim=-3,
56
+ )
57
+ return emb.unsqueeze(2)
58
+
59
+
60
+ class PyramidDiffusionMMDiT(ModelMixin, ConfigMixin):
61
+ _supports_gradient_checkpointing = True
62
+
63
+ @register_to_config
64
+ def __init__(
65
+ self,
66
+ sample_size: int = 128,
67
+ patch_size: int = 2,
68
+ in_channels: int = 16,
69
+ num_layers: int = 24,
70
+ attention_head_dim: int = 64,
71
+ num_attention_heads: int = 24,
72
+ caption_projection_dim: int = 1152,
73
+ pooled_projection_dim: int = 2048,
74
+ pos_embed_max_size: int = 192,
75
+ max_num_frames: int = 200,
76
+ qk_norm: str = 'rms_norm',
77
+ pos_embed_type: str = 'rope',
78
+ temp_pos_embed_type: str = 'sincos',
79
+ joint_attention_dim: int = 4096,
80
+ use_gradient_checkpointing: bool = False,
81
+ use_flash_attn: bool = True,
82
+ use_temporal_causal: bool = False,
83
+ use_t5_mask: bool = False,
84
+ add_temp_pos_embed: bool = False,
85
+ interp_condition_pos: bool = False,
86
+ gradient_checkpointing_ratio: float = 0.6,
87
+ ):
88
+ super().__init__()
89
+
90
+ self.out_channels = in_channels
91
+ self.inner_dim = num_attention_heads * attention_head_dim
92
+ assert temp_pos_embed_type in ['rope', 'sincos']
93
+
94
+ # The input latent embeder, using the name pos_embed to remain the same with SD#
95
+ self.pos_embed = PatchEmbed3D(
96
+ height=sample_size,
97
+ width=sample_size,
98
+ patch_size=patch_size,
99
+ in_channels=in_channels,
100
+ embed_dim=self.inner_dim,
101
+ pos_embed_max_size=pos_embed_max_size, # hard-code for now.
102
+ max_num_frames=max_num_frames,
103
+ pos_embed_type=pos_embed_type,
104
+ temp_pos_embed_type=temp_pos_embed_type,
105
+ add_temp_pos_embed=add_temp_pos_embed,
106
+ interp_condition_pos=interp_condition_pos,
107
+ )
108
+
109
+ # The RoPE EMbedding
110
+ if pos_embed_type == 'rope':
111
+ self.rope_embed = EmbedNDRoPE(self.inner_dim, 10000, axes_dim=[16, 24, 24])
112
+ else:
113
+ self.rope_embed = None
114
+
115
+ if temp_pos_embed_type == 'rope':
116
+ self.temp_rope_embed = EmbedNDRoPE(self.inner_dim, 10000, axes_dim=[attention_head_dim])
117
+ else:
118
+ self.temp_rope_embed = None
119
+
120
+ self.time_text_embed = CombinedTimestepConditionEmbeddings(
121
+ embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim,
122
+ )
123
+ self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.config.caption_projection_dim)
124
+
125
+ self.transformer_blocks = nn.ModuleList(
126
+ [
127
+ JointTransformerBlock(
128
+ dim=self.inner_dim,
129
+ num_attention_heads=num_attention_heads,
130
+ attention_head_dim=self.inner_dim,
131
+ qk_norm=qk_norm,
132
+ context_pre_only=i == num_layers - 1,
133
+ use_flash_attn=use_flash_attn,
134
+ )
135
+ for i in range(num_layers)
136
+ ]
137
+ )
138
+
139
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
140
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
141
+ self.gradient_checkpointing = use_gradient_checkpointing
142
+ self.gradient_checkpointing_ratio = gradient_checkpointing_ratio
143
+
144
+ self.patch_size = patch_size
145
+ self.use_flash_attn = use_flash_attn
146
+ self.use_temporal_causal = use_temporal_causal
147
+ self.pos_embed_type = pos_embed_type
148
+ self.temp_pos_embed_type = temp_pos_embed_type
149
+ self.add_temp_pos_embed = add_temp_pos_embed
150
+
151
+ if self.use_temporal_causal:
152
+ print("Using temporal causal attention")
153
+ assert self.use_flash_attn is False, "The flash attention does not support temporal causal"
154
+
155
+ if interp_condition_pos:
156
+ print("We interp the position embedding of condition latents")
157
+
158
+ # init weights
159
+ self.initialize_weights()
160
+
161
+ def initialize_weights(self):
162
+ # Initialize transformer layers:
163
+ def _basic_init(module):
164
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.Conv3d)):
165
+ torch.nn.init.xavier_uniform_(module.weight)
166
+ if module.bias is not None:
167
+ nn.init.constant_(module.bias, 0)
168
+ self.apply(_basic_init)
169
+
170
+ # Initialize patch_embed like nn.Linear (instead of nn.Conv2d):
171
+ w = self.pos_embed.proj.weight.data
172
+ nn.init.xavier_uniform_(w.view([w.shape[0], -1]))
173
+ nn.init.constant_(self.pos_embed.proj.bias, 0)
174
+
175
+ # Initialize all the conditioning to normal init
176
+ nn.init.normal_(self.time_text_embed.timestep_embedder.linear_1.weight, std=0.02)
177
+ nn.init.normal_(self.time_text_embed.timestep_embedder.linear_2.weight, std=0.02)
178
+ nn.init.normal_(self.time_text_embed.text_embedder.linear_1.weight, std=0.02)
179
+ nn.init.normal_(self.time_text_embed.text_embedder.linear_2.weight, std=0.02)
180
+ nn.init.normal_(self.context_embedder.weight, std=0.02)
181
+
182
+ # Zero-out adaLN modulation layers in DiT blocks:
183
+ for block in self.transformer_blocks:
184
+ nn.init.constant_(block.norm1.linear.weight, 0)
185
+ nn.init.constant_(block.norm1.linear.bias, 0)
186
+ nn.init.constant_(block.norm1_context.linear.weight, 0)
187
+ nn.init.constant_(block.norm1_context.linear.bias, 0)
188
+
189
+ # Zero-out output layers:
190
+ nn.init.constant_(self.norm_out.linear.weight, 0)
191
+ nn.init.constant_(self.norm_out.linear.bias, 0)
192
+ nn.init.constant_(self.proj_out.weight, 0)
193
+ nn.init.constant_(self.proj_out.bias, 0)
194
+
195
+ @torch.no_grad()
196
+ def _prepare_latent_image_ids(self, batch_size, temp, height, width, device):
197
+ latent_image_ids = torch.zeros(temp, height, width, 3)
198
+ latent_image_ids[..., 0] = latent_image_ids[..., 0] + torch.arange(temp)[:, None, None]
199
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[None, :, None]
200
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, None, :]
201
+
202
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1, 1)
203
+ latent_image_ids = rearrange(latent_image_ids, 'b t h w c -> b (t h w) c')
204
+ return latent_image_ids.to(device=device)
205
+
206
+ @torch.no_grad()
207
+ def _prepare_pyramid_latent_image_ids(self, batch_size, temp_list, height_list, width_list, device):
208
+ base_width = width_list[-1]; base_height = height_list[-1]
209
+ assert base_width == max(width_list)
210
+ assert base_height == max(height_list)
211
+
212
+ image_ids_list = []
213
+ for temp, height, width in zip(temp_list, height_list, width_list):
214
+ latent_image_ids = torch.zeros(temp, height, width, 3)
215
+
216
+ if height != base_height:
217
+ height_pos = F.interpolate(torch.arange(base_height)[None, None, :].float(), height, mode='linear').squeeze(0, 1)
218
+ else:
219
+ height_pos = torch.arange(base_height).float()
220
+ if width != base_width:
221
+ width_pos = F.interpolate(torch.arange(base_width)[None, None, :].float(), width, mode='linear').squeeze(0, 1)
222
+ else:
223
+ width_pos = torch.arange(base_width).float()
224
+
225
+ latent_image_ids[..., 0] = latent_image_ids[..., 0] + torch.arange(temp)[:, None, None]
226
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + height_pos[None, :, None]
227
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + width_pos[None, None, :]
228
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1, 1)
229
+ latent_image_ids = rearrange(latent_image_ids, 'b t h w c -> b (t h w) c').to(device)
230
+ image_ids_list.append(latent_image_ids)
231
+
232
+ return image_ids_list
233
+
234
+ @torch.no_grad()
235
+ def _prepare_temporal_rope_ids(self, batch_size, temp, height, width, device, start_time_stamp=0):
236
+ latent_image_ids = torch.zeros(temp, height, width, 1)
237
+ latent_image_ids[..., 0] = latent_image_ids[..., 0] + torch.arange(start_time_stamp, start_time_stamp + temp)[:, None, None]
238
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1, 1)
239
+ latent_image_ids = rearrange(latent_image_ids, 'b t h w c -> b (t h w) c')
240
+ return latent_image_ids.to(device=device)
241
+
242
+ @torch.no_grad()
243
+ def _prepare_pyramid_temporal_rope_ids(self, sample, batch_size, device):
244
+ image_ids_list = []
245
+
246
+ for i_b, sample_ in enumerate(sample):
247
+ if not isinstance(sample_, list):
248
+ sample_ = [sample_]
249
+
250
+ cur_image_ids = []
251
+ start_time_stamp = 0
252
+
253
+ for clip_ in sample_:
254
+ _, _, temp, height, width = clip_.shape
255
+ height = height // self.patch_size
256
+ width = width // self.patch_size
257
+ cur_image_ids.append(self._prepare_temporal_rope_ids(batch_size, temp, height, width, device, start_time_stamp=start_time_stamp))
258
+ start_time_stamp += temp
259
+
260
+ cur_image_ids = torch.cat(cur_image_ids, dim=1)
261
+ image_ids_list.append(cur_image_ids)
262
+
263
+ return image_ids_list
264
+
265
+ def merge_input(self, sample, encoder_hidden_length, encoder_attention_mask):
266
+ """
267
+ Merge the input video with different resolutions into one sequence
268
+ Sample: From low resolution to high resolution
269
+ """
270
+ if isinstance(sample[0], list):
271
+ device = sample[0][-1].device
272
+ pad_batch_size = sample[0][-1].shape[0]
273
+ else:
274
+ device = sample[0].device
275
+ pad_batch_size = sample[0].shape[0]
276
+
277
+ num_stages = len(sample)
278
+ height_list = [];width_list = [];temp_list = []
279
+ trainable_token_list = []
280
+
281
+ for i_b, sample_ in enumerate(sample):
282
+ if isinstance(sample_, list):
283
+ sample_ = sample_[-1]
284
+ _, _, temp, height, width = sample_.shape
285
+ height = height // self.patch_size
286
+ width = width // self.patch_size
287
+ temp_list.append(temp)
288
+ height_list.append(height)
289
+ width_list.append(width)
290
+ trainable_token_list.append(height * width * temp)
291
+
292
+ # prepare the RoPE embedding if needed
293
+ if self.pos_embed_type == 'rope':
294
+ # TODO: support the 3D Rope for video
295
+ raise NotImplementedError("Not compatible with video generation now")
296
+ text_ids = torch.zeros(pad_batch_size, encoder_hidden_length, 3).to(device=device)
297
+ image_ids_list = self._prepare_pyramid_latent_image_ids(pad_batch_size, temp_list, height_list, width_list, device)
298
+ input_ids_list = [torch.cat([text_ids, image_ids], dim=1) for image_ids in image_ids_list]
299
+ image_rotary_emb = [self.rope_embed(input_ids) for input_ids in input_ids_list] # [bs, seq_len, 1, head_dim // 2, 2, 2]
300
+ else:
301
+ if self.temp_pos_embed_type == 'rope' and self.add_temp_pos_embed:
302
+ image_ids_list = self._prepare_pyramid_temporal_rope_ids(sample, pad_batch_size, device)
303
+ text_ids = torch.zeros(pad_batch_size, encoder_attention_mask.shape[1], 1).to(device=device)
304
+ input_ids_list = [torch.cat([text_ids, image_ids], dim=1) for image_ids in image_ids_list]
305
+ image_rotary_emb = [self.temp_rope_embed(input_ids) for input_ids in input_ids_list] # [bs, seq_len, 1, head_dim // 2, 2, 2]
306
+
307
+ if is_sequence_parallel_initialized():
308
+ sp_group = get_sequence_parallel_group()
309
+ sp_group_size = get_sequence_parallel_world_size()
310
+ concat_output = True if self.training else False
311
+ image_rotary_emb = [all_to_all(x_.repeat(1, 1, sp_group_size, 1, 1, 1), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output) for x_ in image_rotary_emb]
312
+ input_ids_list = [all_to_all(input_ids.repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output) for input_ids in input_ids_list]
313
+
314
+ else:
315
+ image_rotary_emb = None
316
+
317
+ hidden_states = self.pos_embed(sample) # hidden states is a list of [b c t h w] b = real_b // num_stages
318
+ hidden_length = []
319
+
320
+ for i_b in range(num_stages):
321
+ hidden_length.append(hidden_states[i_b].shape[1])
322
+
323
+ # prepare the attention mask
324
+ if self.use_flash_attn:
325
+ attention_mask = None
326
+ indices_list = []
327
+ for i_p, length in enumerate(hidden_length):
328
+ pad_attention_mask = torch.ones((pad_batch_size, length), dtype=encoder_attention_mask.dtype).to(device)
329
+ pad_attention_mask = torch.cat([encoder_attention_mask[i_p::num_stages], pad_attention_mask], dim=1)
330
+
331
+ if is_sequence_parallel_initialized():
332
+ sp_group = get_sequence_parallel_group()
333
+ sp_group_size = get_sequence_parallel_world_size()
334
+ pad_attention_mask = all_to_all(pad_attention_mask.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0)
335
+ pad_attention_mask = pad_attention_mask.squeeze(2)
336
+
337
+ seqlens_in_batch = pad_attention_mask.sum(dim=-1, dtype=torch.int32)
338
+ indices = torch.nonzero(pad_attention_mask.flatten(), as_tuple=False).flatten()
339
+
340
+ indices_list.append(
341
+ {
342
+ 'indices': indices,
343
+ 'seqlens_in_batch': seqlens_in_batch,
344
+ }
345
+ )
346
+ encoder_attention_mask = indices_list
347
+ else:
348
+ assert encoder_attention_mask.shape[1] == encoder_hidden_length
349
+ real_batch_size = encoder_attention_mask.shape[0]
350
+ # prepare text ids
351
+ text_ids = torch.arange(1, real_batch_size + 1, dtype=encoder_attention_mask.dtype).unsqueeze(1).repeat(1, encoder_hidden_length)
352
+ text_ids = text_ids.to(device)
353
+ text_ids[encoder_attention_mask == 0] = 0
354
+
355
+ # prepare image ids
356
+ image_ids = torch.arange(1, real_batch_size + 1, dtype=encoder_attention_mask.dtype).unsqueeze(1).repeat(1, max(hidden_length))
357
+ image_ids = image_ids.to(device)
358
+ image_ids_list = []
359
+ for i_p, length in enumerate(hidden_length):
360
+ image_ids_list.append(image_ids[i_p::num_stages][:, :length])
361
+
362
+ if is_sequence_parallel_initialized():
363
+ sp_group = get_sequence_parallel_group()
364
+ sp_group_size = get_sequence_parallel_world_size()
365
+ concat_output = True if self.training else False
366
+ text_ids = all_to_all(text_ids.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output).squeeze(2)
367
+ image_ids_list = [all_to_all(image_ids_.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output).squeeze(2) for image_ids_ in image_ids_list]
368
+
369
+ attention_mask = []
370
+ for i_p in range(len(hidden_length)):
371
+ image_ids = image_ids_list[i_p]
372
+ token_ids = torch.cat([text_ids[i_p::num_stages], image_ids], dim=1)
373
+ stage_attention_mask = rearrange(token_ids, 'b i -> b 1 i 1') == rearrange(token_ids, 'b j -> b 1 1 j') # [bs, 1, q_len, k_len]
374
+ if self.use_temporal_causal:
375
+ input_order_ids = input_ids_list[i_p].squeeze(2)
376
+ temporal_causal_mask = rearrange(input_order_ids, 'b i -> b 1 i 1') >= rearrange(input_order_ids, 'b j -> b 1 1 j')
377
+ stage_attention_mask = stage_attention_mask & temporal_causal_mask
378
+ attention_mask.append(stage_attention_mask)
379
+
380
+ return hidden_states, hidden_length, temp_list, height_list, width_list, trainable_token_list, encoder_attention_mask, attention_mask, image_rotary_emb
381
+
382
+ def split_output(self, batch_hidden_states, hidden_length, temps, heights, widths, trainable_token_list):
383
+ # To split the hidden states
384
+ batch_size = batch_hidden_states.shape[0]
385
+ output_hidden_list = []
386
+ batch_hidden_states = torch.split(batch_hidden_states, hidden_length, dim=1)
387
+
388
+ if is_sequence_parallel_initialized():
389
+ sp_group_size = get_sequence_parallel_world_size()
390
+ if self.training:
391
+ batch_size = batch_size // sp_group_size
392
+
393
+ for i_p, length in enumerate(hidden_length):
394
+ width, height, temp = widths[i_p], heights[i_p], temps[i_p]
395
+ trainable_token_num = trainable_token_list[i_p]
396
+ hidden_states = batch_hidden_states[i_p]
397
+
398
+ if is_sequence_parallel_initialized():
399
+ sp_group = get_sequence_parallel_group()
400
+ sp_group_size = get_sequence_parallel_world_size()
401
+
402
+ if not self.training:
403
+ hidden_states = hidden_states.repeat(sp_group_size, 1, 1)
404
+
405
+ hidden_states = all_to_all(hidden_states, sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
406
+
407
+ # only the trainable token are taking part in loss computation
408
+ hidden_states = hidden_states[:, -trainable_token_num:]
409
+
410
+ # unpatchify
411
+ hidden_states = hidden_states.reshape(
412
+ shape=(batch_size, temp, height, width, self.patch_size, self.patch_size, self.out_channels)
413
+ )
414
+ hidden_states = rearrange(hidden_states, "b t h w p1 p2 c -> b t (h p1) (w p2) c")
415
+ hidden_states = rearrange(hidden_states, "b t h w c -> b c t h w")
416
+ output_hidden_list.append(hidden_states)
417
+
418
+ return output_hidden_list
419
+
420
+ def forward(
421
+ self,
422
+ sample: torch.FloatTensor, # [num_stages]
423
+ encoder_hidden_states: torch.FloatTensor = None,
424
+ encoder_attention_mask: torch.FloatTensor = None,
425
+ pooled_projections: torch.FloatTensor = None,
426
+ timestep_ratio: torch.FloatTensor = None,
427
+ ):
428
+ # Get the timestep embedding
429
+ temb = self.time_text_embed(timestep_ratio, pooled_projections)
430
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
431
+ encoder_hidden_length = encoder_hidden_states.shape[1]
432
+
433
+ # Get the input sequence
434
+ hidden_states, hidden_length, temps, heights, widths, trainable_token_list, encoder_attention_mask, \
435
+ attention_mask, image_rotary_emb = self.merge_input(sample, encoder_hidden_length, encoder_attention_mask)
436
+
437
+ # split the long latents if necessary
438
+ if is_sequence_parallel_initialized():
439
+ sp_group = get_sequence_parallel_group()
440
+ sp_group_size = get_sequence_parallel_world_size()
441
+ concat_output = True if self.training else False
442
+
443
+ # sync the input hidden states
444
+ batch_hidden_states = []
445
+ for i_p, hidden_states_ in enumerate(hidden_states):
446
+ assert hidden_states_.shape[1] % sp_group_size == 0, "The sequence length should be divided by sequence parallel size"
447
+ hidden_states_ = all_to_all(hidden_states_, sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
448
+ hidden_length[i_p] = hidden_length[i_p] // sp_group_size
449
+ batch_hidden_states.append(hidden_states_)
450
+
451
+ # sync the encoder hidden states
452
+ hidden_states = torch.cat(batch_hidden_states, dim=1)
453
+ encoder_hidden_states = all_to_all(encoder_hidden_states, sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
454
+ temb = all_to_all(temb.unsqueeze(1).repeat(1, sp_group_size, 1), sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
455
+ temb = temb.squeeze(1)
456
+ else:
457
+ hidden_states = torch.cat(hidden_states, dim=1)
458
+
459
+ # print(hidden_length)
460
+ for i_b, block in enumerate(self.transformer_blocks):
461
+ if self.training and self.gradient_checkpointing and (i_b >= int(len(self.transformer_blocks) * self.gradient_checkpointing_ratio)):
462
+ def create_custom_forward(module):
463
+ def custom_forward(*inputs):
464
+ return module(*inputs)
465
+
466
+ return custom_forward
467
+
468
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
469
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
470
+ create_custom_forward(block),
471
+ hidden_states,
472
+ encoder_hidden_states,
473
+ encoder_attention_mask,
474
+ temb,
475
+ attention_mask,
476
+ hidden_length,
477
+ image_rotary_emb,
478
+ **ckpt_kwargs,
479
+ )
480
+
481
+ else:
482
+ encoder_hidden_states, hidden_states = block(
483
+ hidden_states=hidden_states,
484
+ encoder_hidden_states=encoder_hidden_states,
485
+ encoder_attention_mask=encoder_attention_mask,
486
+ temb=temb,
487
+ attention_mask=attention_mask,
488
+ hidden_length=hidden_length,
489
+ image_rotary_emb=image_rotary_emb,
490
+ )
491
+
492
+ hidden_states = self.norm_out(hidden_states, temb, hidden_length=hidden_length)
493
+ hidden_states = self.proj_out(hidden_states)
494
+
495
+ output = self.split_output(hidden_states, hidden_length, temps, heights, widths, trainable_token_list)
496
+
497
+ return output
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/mmdit_modules/modeling_text_encoder.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import os
4
+
5
+ from transformers import (
6
+ CLIPTextModelWithProjection,
7
+ CLIPTokenizer,
8
+ T5EncoderModel,
9
+ T5TokenizerFast,
10
+ )
11
+
12
+ from typing import Any, Callable, Dict, List, Optional, Union
13
+
14
+
15
+ class SD3TextEncoderWithMask(nn.Module):
16
+ def __init__(self, model_path, torch_dtype):
17
+ super().__init__()
18
+ # CLIP-L
19
+ self.tokenizer = CLIPTokenizer.from_pretrained(os.path.join(model_path, 'tokenizer'))
20
+ self.tokenizer_max_length = self.tokenizer.model_max_length
21
+ self.text_encoder = CLIPTextModelWithProjection.from_pretrained(os.path.join(model_path, 'text_encoder'), torch_dtype=torch_dtype)
22
+
23
+ # CLIP-G
24
+ self.tokenizer_2 = CLIPTokenizer.from_pretrained(os.path.join(model_path, 'tokenizer_2'))
25
+ self.text_encoder_2 = CLIPTextModelWithProjection.from_pretrained(os.path.join(model_path, 'text_encoder_2'), torch_dtype=torch_dtype)
26
+
27
+ # T5
28
+ self.tokenizer_3 = T5TokenizerFast.from_pretrained(os.path.join(model_path, 'tokenizer_3'))
29
+ self.text_encoder_3 = T5EncoderModel.from_pretrained(os.path.join(model_path, 'text_encoder_3'), torch_dtype=torch_dtype)
30
+
31
+ self._freeze()
32
+
33
+ def _freeze(self):
34
+ for param in self.parameters():
35
+ param.requires_grad = False
36
+
37
+ def _get_t5_prompt_embeds(
38
+ self,
39
+ prompt: Union[str, List[str]] = None,
40
+ num_images_per_prompt: int = 1,
41
+ device: Optional[torch.device] = None,
42
+ max_sequence_length: int = 128,
43
+ ):
44
+ prompt = [prompt] if isinstance(prompt, str) else prompt
45
+ batch_size = len(prompt)
46
+
47
+ text_inputs = self.tokenizer_3(
48
+ prompt,
49
+ padding="max_length",
50
+ max_length=max_sequence_length,
51
+ truncation=True,
52
+ add_special_tokens=True,
53
+ return_tensors="pt",
54
+ )
55
+ text_input_ids = text_inputs.input_ids
56
+ prompt_attention_mask = text_inputs.attention_mask
57
+ prompt_attention_mask = prompt_attention_mask.to(device)
58
+ prompt_embeds = self.text_encoder_3(text_input_ids.to(device), attention_mask=prompt_attention_mask)[0]
59
+ dtype = self.text_encoder_3.dtype
60
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
61
+
62
+ _, seq_len, _ = prompt_embeds.shape
63
+
64
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
65
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
66
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
67
+ prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
68
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
69
+
70
+ return prompt_embeds, prompt_attention_mask
71
+
72
+ def _get_clip_prompt_embeds(
73
+ self,
74
+ prompt: Union[str, List[str]],
75
+ num_images_per_prompt: int = 1,
76
+ device: Optional[torch.device] = None,
77
+ clip_skip: Optional[int] = None,
78
+ clip_model_index: int = 0,
79
+ ):
80
+
81
+ clip_tokenizers = [self.tokenizer, self.tokenizer_2]
82
+ clip_text_encoders = [self.text_encoder, self.text_encoder_2]
83
+
84
+ tokenizer = clip_tokenizers[clip_model_index]
85
+ text_encoder = clip_text_encoders[clip_model_index]
86
+
87
+ batch_size = len(prompt)
88
+
89
+ text_inputs = tokenizer(
90
+ prompt,
91
+ padding="max_length",
92
+ max_length=self.tokenizer_max_length,
93
+ truncation=True,
94
+ return_tensors="pt",
95
+ )
96
+
97
+ text_input_ids = text_inputs.input_ids
98
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
99
+ pooled_prompt_embeds = prompt_embeds[0]
100
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt, 1)
101
+ pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
102
+
103
+ return pooled_prompt_embeds
104
+
105
+ def encode_prompt(self,
106
+ prompt,
107
+ num_images_per_prompt=1,
108
+ clip_skip: Optional[int] = None,
109
+ device=None,
110
+ ):
111
+ prompt = [prompt] if isinstance(prompt, str) else prompt
112
+
113
+ pooled_prompt_embed = self._get_clip_prompt_embeds(
114
+ prompt=prompt,
115
+ device=device,
116
+ num_images_per_prompt=num_images_per_prompt,
117
+ clip_skip=clip_skip,
118
+ clip_model_index=0,
119
+ )
120
+ pooled_prompt_2_embed = self._get_clip_prompt_embeds(
121
+ prompt=prompt,
122
+ device=device,
123
+ num_images_per_prompt=num_images_per_prompt,
124
+ clip_skip=clip_skip,
125
+ clip_model_index=1,
126
+ )
127
+ pooled_prompt_embeds = torch.cat([pooled_prompt_embed, pooled_prompt_2_embed], dim=-1)
128
+
129
+ prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
130
+ prompt=prompt,
131
+ num_images_per_prompt=num_images_per_prompt,
132
+ device=device,
133
+ )
134
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds
135
+
136
+ def forward(self, input_prompts, device):
137
+ with torch.no_grad():
138
+ prompt_embeds, prompt_attention_mask, pooled_prompt_embeds = self.encode_prompt(input_prompts, 1, clip_skip=None, device=device)
139
+
140
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/pyramid_dit/pyramid_dit_for_video_gen_pipeline.py ADDED
@@ -0,0 +1,1283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ import gc
4
+ import sys
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from collections import OrderedDict
9
+ from einops import rearrange
10
+ from diffusers.utils.torch_utils import randn_tensor
11
+ import numpy as np
12
+ import math
13
+ import random
14
+ import PIL
15
+ from PIL import Image
16
+ from tqdm import tqdm
17
+ from torchvision import transforms
18
+ from copy import deepcopy
19
+ from typing import Any, Callable, Dict, List, Optional, Union
20
+ from accelerate import Accelerator, cpu_offload
21
+ from diffusion_schedulers import PyramidFlowMatchEulerDiscreteScheduler
22
+ from video_vae.modeling_causal_vae import CausalVideoVAE
23
+
24
+ from trainer_misc import (
25
+ all_to_all,
26
+ is_sequence_parallel_initialized,
27
+ get_sequence_parallel_group,
28
+ get_sequence_parallel_group_rank,
29
+ get_sequence_parallel_rank,
30
+ get_sequence_parallel_world_size,
31
+ get_rank,
32
+ )
33
+
34
+ from .mmdit_modules import (
35
+ PyramidDiffusionMMDiT,
36
+ SD3TextEncoderWithMask,
37
+ )
38
+
39
+ from .flux_modules import (
40
+ PyramidFluxTransformer,
41
+ FluxTextEncoderWithMask,
42
+ )
43
+
44
+
45
+ def compute_density_for_timestep_sampling(
46
+ weighting_scheme: str, batch_size: int, logit_mean: float = None, logit_std: float = None, mode_scale: float = None
47
+ ):
48
+ if weighting_scheme == "logit_normal":
49
+ # See 3.1 in the SD3 paper ($rf/lognorm(0.00,1.00)$).
50
+ u = torch.normal(mean=logit_mean, std=logit_std, size=(batch_size,), device="cpu")
51
+ u = torch.nn.functional.sigmoid(u)
52
+ elif weighting_scheme == "mode":
53
+ u = torch.rand(size=(batch_size,), device="cpu")
54
+ u = 1 - u - mode_scale * (torch.cos(math.pi * u / 2) ** 2 - 1 + u)
55
+ else:
56
+ u = torch.rand(size=(batch_size,), device="cpu")
57
+ return u
58
+
59
+
60
+ def build_pyramid_dit(
61
+ model_name : str,
62
+ model_path : str,
63
+ torch_dtype,
64
+ use_flash_attn : bool,
65
+ use_mixed_training: bool,
66
+ interp_condition_pos: bool = True,
67
+ use_gradient_checkpointing: bool = False,
68
+ use_temporal_causal: bool = True,
69
+ gradient_checkpointing_ratio: float = 0.6,
70
+ ):
71
+ model_dtype = torch.float32 if use_mixed_training else torch_dtype
72
+ if model_name == "pyramid_flux":
73
+ dit = PyramidFluxTransformer.from_pretrained(
74
+ model_path, torch_dtype=model_dtype,
75
+ use_gradient_checkpointing=use_gradient_checkpointing,
76
+ gradient_checkpointing_ratio=gradient_checkpointing_ratio,
77
+ use_flash_attn=use_flash_attn, use_temporal_causal=use_temporal_causal,
78
+ interp_condition_pos=interp_condition_pos, axes_dims_rope=[16, 24, 24],
79
+ )
80
+ elif model_name == "pyramid_mmdit":
81
+ dit = PyramidDiffusionMMDiT.from_pretrained(
82
+ model_path, torch_dtype=model_dtype, use_gradient_checkpointing=use_gradient_checkpointing,
83
+ gradient_checkpointing_ratio=gradient_checkpointing_ratio,
84
+ use_flash_attn=use_flash_attn, use_t5_mask=True,
85
+ add_temp_pos_embed=True, temp_pos_embed_type='rope',
86
+ use_temporal_causal=use_temporal_causal, interp_condition_pos=interp_condition_pos,
87
+ )
88
+ else:
89
+ raise NotImplementedError(f"Unsupported DiT architecture, please set the model_name to `pyramid_flux` or `pyramid_mmdit`")
90
+
91
+ return dit
92
+
93
+
94
+ def build_text_encoder(
95
+ model_name : str,
96
+ model_path : str,
97
+ torch_dtype,
98
+ load_text_encoder: bool = True,
99
+ ):
100
+ # The text encoder
101
+ if load_text_encoder:
102
+ if model_name == "pyramid_flux":
103
+ text_encoder = FluxTextEncoderWithMask(model_path, torch_dtype=torch_dtype)
104
+ elif model_name == "pyramid_mmdit":
105
+ text_encoder = SD3TextEncoderWithMask(model_path, torch_dtype=torch_dtype)
106
+ else:
107
+ raise NotImplementedError(f"Unsupported Text Encoder architecture, please set the model_name to `pyramid_flux` or `pyramid_mmdit`")
108
+ else:
109
+ text_encoder = None
110
+
111
+ return text_encoder
112
+
113
+
114
+ class PyramidDiTForVideoGeneration:
115
+ """
116
+ The pyramid dit for both image and video generation, The running class wrapper
117
+ This class is mainly for fixed unit implementation: 1 + n + n + n
118
+ """
119
+ def __init__(self, model_path, model_dtype='bf16', model_name='pyramid_mmdit', use_gradient_checkpointing=False,
120
+ return_log=True, model_variant="diffusion_transformer_768p", timestep_shift=1.0, stage_range=[0, 1/3, 2/3, 1],
121
+ sample_ratios=[1, 1, 1], scheduler_gamma=1/3, use_mixed_training=False, use_flash_attn=False,
122
+ load_text_encoder=True, load_vae=True, max_temporal_length=31, frame_per_unit=1, use_temporal_causal=True,
123
+ corrupt_ratio=1/3, interp_condition_pos=True, stages=[1, 2, 4], video_sync_group=8, gradient_checkpointing_ratio=0.6, **kwargs,
124
+ ):
125
+ super().__init__()
126
+
127
+ if model_dtype == 'bf16':
128
+ torch_dtype = torch.bfloat16
129
+ elif model_dtype == 'fp16':
130
+ torch_dtype = torch.float16
131
+ else:
132
+ torch_dtype = torch.float32
133
+
134
+ self.stages = stages
135
+ self.sample_ratios = sample_ratios
136
+ self.corrupt_ratio = corrupt_ratio
137
+
138
+ dit_path = os.path.join(model_path, model_variant)
139
+
140
+ # The dit
141
+ self.dit = build_pyramid_dit(
142
+ model_name, dit_path, torch_dtype,
143
+ use_flash_attn=use_flash_attn, use_mixed_training=use_mixed_training,
144
+ interp_condition_pos=interp_condition_pos, use_gradient_checkpointing=use_gradient_checkpointing,
145
+ use_temporal_causal=use_temporal_causal, gradient_checkpointing_ratio=gradient_checkpointing_ratio,
146
+ )
147
+
148
+ # The text encoder
149
+ self.text_encoder = build_text_encoder(
150
+ model_name, model_path, torch_dtype, load_text_encoder=load_text_encoder,
151
+ )
152
+ self.load_text_encoder = load_text_encoder
153
+
154
+ # The base video vae decoder
155
+ if load_vae:
156
+ self.vae = CausalVideoVAE.from_pretrained(
157
+ os.path.join(model_path, 'causal_video_vae'),
158
+ torch_dtype=torch_dtype,
159
+ interpolate=False
160
+ )
161
+ # Freeze vae
162
+ for parameter in self.vae.parameters():
163
+ parameter.requires_grad = False
164
+ else:
165
+ self.vae = None
166
+ self.load_vae = load_vae
167
+
168
+ # For the image latent
169
+ if model_name == "pyramid_flux":
170
+ self.vae_shift_factor = -0.04
171
+ self.vae_scale_factor = 1 / 1.8726
172
+ elif model_name == "pyramid_mmdit":
173
+ self.vae_shift_factor = 0.1490
174
+ self.vae_scale_factor = 1 / 1.8415
175
+ else:
176
+ raise NotImplementedError(f"Unsupported model name : {model_name}")
177
+
178
+ # For the video latent
179
+ self.vae_video_shift_factor = -0.2343
180
+ self.vae_video_scale_factor = 1 / 3.0986
181
+
182
+ self.downsample = 8
183
+
184
+ # Configure the video training hyper-parameters
185
+ # The video sequence: one frame + N * unit
186
+ self.frame_per_unit = frame_per_unit
187
+ self.max_temporal_length = max_temporal_length
188
+ assert (max_temporal_length - 1) % frame_per_unit == 0, "The frame number should be divided by the frame number per unit"
189
+ self.num_units_per_video = 1 + ((max_temporal_length - 1) // frame_per_unit) + int(sum(sample_ratios))
190
+
191
+ self.scheduler = PyramidFlowMatchEulerDiscreteScheduler(
192
+ shift=timestep_shift, stages=len(self.stages),
193
+ stage_range=stage_range, gamma=scheduler_gamma,
194
+ )
195
+ print(f"The start sigmas and end sigmas of each stage is Start: {self.scheduler.start_sigmas}, End: {self.scheduler.end_sigmas}, Ori_start: {self.scheduler.ori_start_sigmas}")
196
+
197
+ self.cfg_rate = 0.1
198
+ self.return_log = return_log
199
+ self.use_flash_attn = use_flash_attn
200
+ self.model_name = model_name
201
+ self.sequential_offload_enabled = False
202
+ self.accumulate_steps = 0
203
+ self.video_sync_group = video_sync_group
204
+
205
+ def _enable_sequential_cpu_offload(self, model):
206
+ self.sequential_offload_enabled = True
207
+ torch_device = torch.device("cuda")
208
+ device_type = torch_device.type
209
+ device = torch.device(f"{device_type}:0")
210
+ offload_buffers = len(model._parameters) > 0
211
+ cpu_offload(model, device, offload_buffers=offload_buffers)
212
+
213
+ def enable_sequential_cpu_offload(self):
214
+ self._enable_sequential_cpu_offload(self.text_encoder)
215
+ self._enable_sequential_cpu_offload(self.dit)
216
+
217
+ def load_checkpoint(self, checkpoint_path, model_key='model', **kwargs):
218
+ checkpoint = torch.load(checkpoint_path, map_location='cpu')
219
+ dit_checkpoint = OrderedDict()
220
+ for key in checkpoint:
221
+ if key.startswith('vae') or key.startswith('text_encoder'):
222
+ continue
223
+ if key.startswith('dit'):
224
+ new_key = key.split('.')
225
+ new_key = '.'.join(new_key[1:])
226
+ dit_checkpoint[new_key] = checkpoint[key]
227
+ else:
228
+ dit_checkpoint[key] = checkpoint[key]
229
+
230
+ load_result = self.dit.load_state_dict(dit_checkpoint, strict=True)
231
+ print(f"Load checkpoint from {checkpoint_path}, load result: {load_result}")
232
+
233
+ def load_vae_checkpoint(self, vae_checkpoint_path, model_key='model'):
234
+ checkpoint = torch.load(vae_checkpoint_path, map_location='cpu')
235
+ checkpoint = checkpoint[model_key]
236
+ loaded_checkpoint = OrderedDict()
237
+
238
+ for key in checkpoint.keys():
239
+ if key.startswith('vae.'):
240
+ new_key = key.split('.')
241
+ new_key = '.'.join(new_key[1:])
242
+ loaded_checkpoint[new_key] = checkpoint[key]
243
+
244
+ load_result = self.vae.load_state_dict(loaded_checkpoint)
245
+ print(f"Load the VAE from {vae_checkpoint_path}, load result: {load_result}")
246
+
247
+ @torch.no_grad()
248
+ def add_pyramid_noise(
249
+ self,
250
+ latents_list,
251
+ sample_ratios=[1, 1, 1],
252
+ ):
253
+ """
254
+ add the noise for each pyramidal stage
255
+ noting that, this method is a general strategy for pyramid-flow, it
256
+ can be used for both image and video training.
257
+ You can also use this method to train pyramid-flow with full-sequence
258
+ diffusion in video generation (without using temporal pyramid and autoregressive modeling)
259
+
260
+ Params:
261
+ latent_list: [low_res, mid_res, high_res] The vae latents of all stages
262
+ sample_ratios: The proportion of each stage in the training batch
263
+ """
264
+ noise = torch.randn_like(latents_list[-1])
265
+ device = noise.device
266
+ dtype = latents_list[-1].dtype
267
+ t = noise.shape[2]
268
+
269
+ stages = len(self.stages)
270
+ tot_samples = noise.shape[0]
271
+ assert tot_samples % (int(sum(sample_ratios))) == 0
272
+ assert stages == len(sample_ratios)
273
+
274
+ height, width = noise.shape[-2], noise.shape[-1]
275
+ noise_list = [noise]
276
+ cur_noise = noise
277
+ for i_s in range(stages-1):
278
+ height //= 2;width //= 2
279
+ cur_noise = rearrange(cur_noise, 'b c t h w -> (b t) c h w')
280
+ cur_noise = F.interpolate(cur_noise, size=(height, width), mode='bilinear') * 2
281
+ cur_noise = rearrange(cur_noise, '(b t) c h w -> b c t h w', t=t)
282
+ noise_list.append(cur_noise)
283
+
284
+ noise_list = list(reversed(noise_list)) # make sure from low res to high res
285
+
286
+ # To calculate the padding batchsize and column size
287
+ batch_size = tot_samples // int(sum(sample_ratios))
288
+ column_size = int(sum(sample_ratios))
289
+
290
+ column_to_stage = {}
291
+ i_sum = 0
292
+ for i_s, column_num in enumerate(sample_ratios):
293
+ for index in range(i_sum, i_sum + column_num):
294
+ column_to_stage[index] = i_s
295
+ i_sum += column_num
296
+
297
+ noisy_latents_list = []
298
+ ratios_list = []
299
+ targets_list = []
300
+ timesteps_list = []
301
+ training_steps = self.scheduler.config.num_train_timesteps
302
+
303
+ # from low resolution to high resolution
304
+ for index in range(column_size):
305
+ i_s = column_to_stage[index]
306
+ clean_latent = latents_list[i_s][index::column_size] # [bs, c, t, h, w]
307
+ last_clean_latent = None if i_s == 0 else latents_list[i_s-1][index::column_size]
308
+ start_sigma = self.scheduler.start_sigmas[i_s]
309
+ end_sigma = self.scheduler.end_sigmas[i_s]
310
+
311
+ if i_s == 0:
312
+ start_point = noise_list[i_s][index::column_size]
313
+ else:
314
+ # Get the upsampled latent
315
+ last_clean_latent = rearrange(last_clean_latent, 'b c t h w -> (b t) c h w')
316
+ last_clean_latent = F.interpolate(last_clean_latent, size=(last_clean_latent.shape[-2] * 2, last_clean_latent.shape[-1] * 2), mode='nearest')
317
+ last_clean_latent = rearrange(last_clean_latent, '(b t) c h w -> b c t h w', t=t)
318
+ start_point = start_sigma * noise_list[i_s][index::column_size] + (1 - start_sigma) * last_clean_latent
319
+
320
+ if i_s == stages - 1:
321
+ end_point = clean_latent
322
+ else:
323
+ end_point = end_sigma * noise_list[i_s][index::column_size] + (1 - end_sigma) * clean_latent
324
+
325
+ # To sample a timestep
326
+ u = compute_density_for_timestep_sampling(
327
+ weighting_scheme='random',
328
+ batch_size=batch_size,
329
+ logit_mean=0.0,
330
+ logit_std=1.0,
331
+ mode_scale=1.29,
332
+ )
333
+
334
+ indices = (u * training_steps).long() # Totally 1000 training steps per stage
335
+ indices = indices.clamp(0, training_steps-1)
336
+ timesteps = self.scheduler.timesteps_per_stage[i_s][indices].to(device=device)
337
+ ratios = self.scheduler.sigmas_per_stage[i_s][indices].to(device=device)
338
+
339
+ while len(ratios.shape) < start_point.ndim:
340
+ ratios = ratios.unsqueeze(-1)
341
+
342
+ # interpolate the latent
343
+ noisy_latents = ratios * start_point + (1 - ratios) * end_point
344
+
345
+ last_cond_noisy_sigma = torch.rand(size=(batch_size,), device=device) * self.corrupt_ratio
346
+
347
+ # [stage1_latent, stage2_latent, ..., stagen_latent], which will be concat after patching
348
+ noisy_latents_list.append([noisy_latents.to(dtype)])
349
+ ratios_list.append(ratios.to(dtype))
350
+ timesteps_list.append(timesteps.to(dtype))
351
+ targets_list.append(start_point - end_point) # The standard rectified flow matching objective
352
+
353
+ return noisy_latents_list, ratios_list, timesteps_list, targets_list
354
+
355
+ def sample_stage_length(self, num_stages, max_units=None):
356
+ max_units_in_training = 1 + ((self.max_temporal_length - 1) // self.frame_per_unit)
357
+ cur_rank = get_rank()
358
+
359
+ self.accumulate_steps = self.accumulate_steps + 1
360
+ total_turns = max_units_in_training // self.video_sync_group
361
+ update_turn = self.accumulate_steps % total_turns
362
+
363
+ # # uniformly sampling each position
364
+ cur_highres_unit = max(int((cur_rank % self.video_sync_group + 1) + update_turn * self.video_sync_group), 1)
365
+ cur_mid_res_unit = max(1 + max_units_in_training - cur_highres_unit, 1)
366
+ cur_low_res_unit = cur_mid_res_unit
367
+
368
+ if max_units is not None:
369
+ cur_highres_unit = min(cur_highres_unit, max_units)
370
+ cur_mid_res_unit = min(cur_mid_res_unit, max_units)
371
+ cur_low_res_unit = min(cur_low_res_unit, max_units)
372
+
373
+ length_list = [cur_low_res_unit, cur_mid_res_unit, cur_highres_unit]
374
+
375
+ assert len(length_list) == num_stages
376
+
377
+ return length_list
378
+
379
+ @torch.no_grad()
380
+ def add_pyramid_noise_with_temporal_pyramid(
381
+ self,
382
+ latents_list,
383
+ sample_ratios=[1, 1, 1],
384
+ ):
385
+ """
386
+ add the noise for each pyramidal stage, used for AR video training with temporal pyramid
387
+ Params:
388
+ latent_list: [low_res, mid_res, high_res] The vae latents of all stages
389
+ sample_ratios: The proportion of each stage in the training batch
390
+ """
391
+ stages = len(self.stages)
392
+ tot_samples = latents_list[0].shape[0]
393
+ device = latents_list[0].device
394
+ dtype = latents_list[0].dtype
395
+
396
+ assert tot_samples % (int(sum(sample_ratios))) == 0
397
+ assert stages == len(sample_ratios)
398
+
399
+ noise = torch.randn_like(latents_list[-1])
400
+ t = noise.shape[2]
401
+
402
+ # To allocate the temporal length of each stage, ensuring the sum == constant
403
+ max_units = 1 + (t - 1) // self.frame_per_unit
404
+
405
+ if is_sequence_parallel_initialized():
406
+ max_units_per_sample = torch.LongTensor([max_units]).to(device)
407
+ sp_group = get_sequence_parallel_group()
408
+ sp_group_size = get_sequence_parallel_world_size()
409
+ max_units_per_sample = all_to_all(max_units_per_sample.unsqueeze(1).repeat(1, sp_group_size), sp_group, sp_group_size, scatter_dim=1, gather_dim=0).squeeze(1)
410
+ max_units = min(max_units_per_sample.cpu().tolist())
411
+
412
+ num_units_per_stage = self.sample_stage_length(stages, max_units=max_units) # [The unit number of each stage]
413
+
414
+ # we needs to sync the length alloc of each sequence parallel group
415
+ if is_sequence_parallel_initialized():
416
+ num_units_per_stage = torch.LongTensor(num_units_per_stage).to(device)
417
+ sp_group_rank = get_sequence_parallel_group_rank()
418
+ global_src_rank = sp_group_rank * get_sequence_parallel_world_size()
419
+ torch.distributed.broadcast(num_units_per_stage, global_src_rank, group=get_sequence_parallel_group())
420
+ num_units_per_stage = num_units_per_stage.tolist()
421
+
422
+ height, width = noise.shape[-2], noise.shape[-1]
423
+ noise_list = [noise]
424
+ cur_noise = noise
425
+ for i_s in range(stages-1):
426
+ height //= 2;width //= 2
427
+ cur_noise = rearrange(cur_noise, 'b c t h w -> (b t) c h w')
428
+ cur_noise = F.interpolate(cur_noise, size=(height, width), mode='bilinear') * 2
429
+ cur_noise = rearrange(cur_noise, '(b t) c h w -> b c t h w', t=t)
430
+ noise_list.append(cur_noise)
431
+
432
+ noise_list = list(reversed(noise_list)) # make sure from low res to high res
433
+
434
+ # To calculate the batchsize and column size
435
+ batch_size = tot_samples // int(sum(sample_ratios))
436
+ column_size = int(sum(sample_ratios))
437
+
438
+ column_to_stage = {}
439
+ i_sum = 0
440
+ for i_s, column_num in enumerate(sample_ratios):
441
+ for index in range(i_sum, i_sum + column_num):
442
+ column_to_stage[index] = i_s
443
+ i_sum += column_num
444
+
445
+ noisy_latents_list = []
446
+ ratios_list = []
447
+ targets_list = []
448
+ timesteps_list = []
449
+ training_steps = self.scheduler.config.num_train_timesteps
450
+
451
+ # from low resolution to high resolution
452
+ for index in range(column_size):
453
+ # First prepare the trainable latent construction
454
+ i_s = column_to_stage[index]
455
+ clean_latent = latents_list[i_s][index::column_size] # [bs, c, t, h, w]
456
+ last_clean_latent = None if i_s == 0 else latents_list[i_s-1][index::column_size]
457
+ start_sigma = self.scheduler.start_sigmas[i_s]
458
+ end_sigma = self.scheduler.end_sigmas[i_s]
459
+
460
+ if i_s == 0:
461
+ start_point = noise_list[i_s][index::column_size]
462
+ else:
463
+ # Get the upsampled latent
464
+ last_clean_latent = rearrange(last_clean_latent, 'b c t h w -> (b t) c h w')
465
+ last_clean_latent = F.interpolate(last_clean_latent, size=(last_clean_latent.shape[-2] * 2, last_clean_latent.shape[-1] * 2), mode='nearest')
466
+ last_clean_latent = rearrange(last_clean_latent, '(b t) c h w -> b c t h w', t=t)
467
+ start_point = start_sigma * noise_list[i_s][index::column_size] + (1 - start_sigma) * last_clean_latent
468
+
469
+ if i_s == stages - 1:
470
+ end_point = clean_latent
471
+ else:
472
+ end_point = end_sigma * noise_list[i_s][index::column_size] + (1 - end_sigma) * clean_latent
473
+
474
+ # To sample a timestep
475
+ u = compute_density_for_timestep_sampling(
476
+ weighting_scheme='random',
477
+ batch_size=batch_size,
478
+ logit_mean=0.0,
479
+ logit_std=1.0,
480
+ mode_scale=1.29,
481
+ )
482
+
483
+ indices = (u * training_steps).long() # Totally 1000 training steps per stage
484
+ indices = indices.clamp(0, training_steps-1)
485
+ timesteps = self.scheduler.timesteps_per_stage[i_s][indices].to(device=device)
486
+ ratios = self.scheduler.sigmas_per_stage[i_s][indices].to(device=device)
487
+ noise_ratios = ratios * start_sigma + (1 - ratios) * end_sigma
488
+
489
+ while len(ratios.shape) < start_point.ndim:
490
+ ratios = ratios.unsqueeze(-1)
491
+
492
+ # interpolate the latent
493
+ noisy_latents = ratios * start_point + (1 - ratios) * end_point
494
+
495
+ # The flow matching object
496
+ target_latents = start_point - end_point
497
+
498
+ # pad the noisy previous
499
+ num_units = num_units_per_stage[i_s]
500
+ num_units = min(num_units, 1 + (t - 1) // self.frame_per_unit)
501
+ actual_frames = 1 + (num_units - 1) * self.frame_per_unit
502
+
503
+ noisy_latents = noisy_latents[:, :, :actual_frames]
504
+ target_latents = target_latents[:, :, :actual_frames]
505
+
506
+ clean_latent = clean_latent[:, :, :actual_frames]
507
+ stage_noise = noise_list[i_s][index::column_size][:, :, :actual_frames]
508
+
509
+ # only the last latent takes part in training
510
+ noisy_latents = noisy_latents[:, :, -self.frame_per_unit:]
511
+ target_latents = target_latents[:, :, -self.frame_per_unit:]
512
+
513
+ last_cond_noisy_sigma = torch.rand(size=(batch_size,), device=device) * self.corrupt_ratio
514
+
515
+ if num_units == 1:
516
+ stage_input = [noisy_latents.to(dtype)]
517
+ else:
518
+ # add the random noise for the last cond clip
519
+ last_cond_latent = clean_latent[:, :, -(2*self.frame_per_unit):-self.frame_per_unit]
520
+
521
+ while len(last_cond_noisy_sigma.shape) < last_cond_latent.ndim:
522
+ last_cond_noisy_sigma = last_cond_noisy_sigma.unsqueeze(-1)
523
+
524
+ # We adding some noise to corrupt the clean condition
525
+ last_cond_latent = last_cond_noisy_sigma * torch.randn_like(last_cond_latent) + (1 - last_cond_noisy_sigma) * last_cond_latent
526
+
527
+ # concat the corrupted condition and the input noisy latents
528
+ stage_input = [noisy_latents.to(dtype), last_cond_latent.to(dtype)]
529
+
530
+ cur_unit_num = 2
531
+ cur_stage = i_s
532
+
533
+ while cur_unit_num < num_units:
534
+ cur_stage = max(cur_stage - 1, 0)
535
+ if cur_stage == 0:
536
+ break
537
+ cur_unit_num += 1
538
+ cond_latents = latents_list[cur_stage][index::column_size][:, :, :actual_frames]
539
+ cond_latents = cond_latents[:, :, -(cur_unit_num * self.frame_per_unit) : -((cur_unit_num - 1) * self.frame_per_unit)]
540
+ cond_latents = last_cond_noisy_sigma * torch.randn_like(cond_latents) + (1 - last_cond_noisy_sigma) * cond_latents
541
+ stage_input.append(cond_latents.to(dtype))
542
+
543
+ if cur_stage == 0 and cur_unit_num < num_units:
544
+ cond_latents = latents_list[0][index::column_size][:, :, :actual_frames]
545
+ cond_latents = cond_latents[:, :, :-(cur_unit_num * self.frame_per_unit)]
546
+
547
+ cond_latents = last_cond_noisy_sigma * torch.randn_like(cond_latents) + (1 - last_cond_noisy_sigma) * cond_latents
548
+ stage_input.append(cond_latents.to(dtype))
549
+
550
+ stage_input = list(reversed(stage_input))
551
+ noisy_latents_list.append(stage_input)
552
+ ratios_list.append(ratios.to(dtype))
553
+ timesteps_list.append(timesteps.to(dtype))
554
+ targets_list.append(target_latents) # The standard rectified flow matching objective
555
+
556
+ return noisy_latents_list, ratios_list, timesteps_list, targets_list
557
+
558
+ @torch.no_grad()
559
+ def get_pyramid_latent(self, x, stage_num):
560
+ # x is the origin vae latent
561
+ vae_latent_list = []
562
+ vae_latent_list.append(x)
563
+
564
+ temp, height, width = x.shape[-3], x.shape[-2], x.shape[-1]
565
+ for _ in range(stage_num):
566
+ height //= 2
567
+ width //= 2
568
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
569
+ x = torch.nn.functional.interpolate(x, size=(height, width), mode='bilinear')
570
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=temp)
571
+ vae_latent_list.append(x)
572
+
573
+ vae_latent_list = list(reversed(vae_latent_list))
574
+ return vae_latent_list
575
+
576
+ @torch.no_grad()
577
+ def get_vae_latent(self, video, use_temporal_pyramid=True):
578
+ if self.load_vae:
579
+ assert video.shape[1] == 3, "The vae is loaded, the input should be raw pixels"
580
+ video = self.vae.encode(video).latent_dist.sample() # [b c t h w]
581
+
582
+ if video.shape[2] == 1:
583
+ # is image
584
+ video = (video - self.vae_shift_factor) * self.vae_scale_factor
585
+ else:
586
+ # is video
587
+ video[:, :, :1] = (video[:, :, :1] - self.vae_shift_factor) * self.vae_scale_factor
588
+ video[:, :, 1:] = (video[:, :, 1:] - self.vae_video_shift_factor) * self.vae_video_scale_factor
589
+
590
+ # Get the pyramidal stages
591
+ vae_latent_list = self.get_pyramid_latent(video, len(self.stages) - 1)
592
+
593
+ if use_temporal_pyramid:
594
+ noisy_latents_list, ratios_list, timesteps_list, targets_list = self.add_pyramid_noise_with_temporal_pyramid(vae_latent_list, self.sample_ratios)
595
+ else:
596
+ # Only use the spatial pyramidal (without temporal ar)
597
+ noisy_latents_list, ratios_list, timesteps_list, targets_list = self.add_pyramid_noise(vae_latent_list, self.sample_ratios)
598
+
599
+ return noisy_latents_list, ratios_list, timesteps_list, targets_list
600
+
601
+ @torch.no_grad()
602
+ def get_text_embeddings(self, text, rand_idx, device):
603
+ if self.load_text_encoder:
604
+ batch_size = len(text) # Text is a str list
605
+ for idx in range(batch_size):
606
+ if rand_idx[idx].item():
607
+ text[idx] = ''
608
+ return self.text_encoder(text, device) # [b s c]
609
+ else:
610
+ batch_size = len(text['prompt_embeds'])
611
+
612
+ for idx in range(batch_size):
613
+ if rand_idx[idx].item():
614
+ text['prompt_embeds'][idx] = self.null_text_embeds['prompt_embed'].to(device)
615
+ text['prompt_attention_mask'][idx] = self.null_text_embeds['prompt_attention_mask'].to(device)
616
+ text['pooled_prompt_embeds'][idx] = self.null_text_embeds['pooled_prompt_embed'].to(device)
617
+
618
+ return text['prompt_embeds'], text['prompt_attention_mask'], text['pooled_prompt_embeds']
619
+
620
+ def calculate_loss(self, model_preds_list, targets_list):
621
+ loss_list = []
622
+
623
+ for model_pred, target in zip(model_preds_list, targets_list):
624
+ # Compute the loss.
625
+ loss_weight = torch.ones_like(target)
626
+
627
+ loss = torch.mean(
628
+ (loss_weight.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1),
629
+ 1,
630
+ )
631
+ loss_list.append(loss)
632
+
633
+ diffusion_loss = torch.cat(loss_list, dim=0).mean()
634
+
635
+ if self.return_log:
636
+ log = {}
637
+ split="train"
638
+ log[f'{split}/loss'] = diffusion_loss.detach()
639
+ return diffusion_loss, log
640
+ else:
641
+ return diffusion_loss, {}
642
+
643
+ def __call__(self, video, text, identifier=['video'], use_temporal_pyramid=True, accelerator: Accelerator=None):
644
+ xdim = video.ndim
645
+ device = video.device
646
+
647
+ if 'video' in identifier:
648
+ assert 'image' not in identifier
649
+ is_image = False
650
+ else:
651
+ assert 'video' not in identifier
652
+ video = video.unsqueeze(2) # 'b c h w -> b c 1 h w'
653
+ is_image = True
654
+
655
+ # TODO: now have 3 stages, firstly get the vae latents
656
+ with torch.no_grad(), accelerator.autocast():
657
+ # 10% prob drop the text
658
+ batch_size = len(video)
659
+ rand_idx = torch.rand((batch_size,)) <= self.cfg_rate
660
+ prompt_embeds, prompt_attention_mask, pooled_prompt_embeds = self.get_text_embeddings(text, rand_idx, device)
661
+ noisy_latents_list, ratios_list, timesteps_list, targets_list = self.get_vae_latent(video, use_temporal_pyramid=use_temporal_pyramid)
662
+
663
+ timesteps = torch.cat([timestep.unsqueeze(-1) for timestep in timesteps_list], dim=-1)
664
+ timesteps = timesteps.reshape(-1)
665
+
666
+ assert timesteps.shape[0] == prompt_embeds.shape[0]
667
+
668
+ # DiT forward
669
+ model_preds_list = self.dit(
670
+ sample=noisy_latents_list,
671
+ timestep_ratio=timesteps,
672
+ encoder_hidden_states=prompt_embeds,
673
+ encoder_attention_mask=prompt_attention_mask,
674
+ pooled_projections=pooled_prompt_embeds,
675
+ )
676
+
677
+ # calculate the loss
678
+ return self.calculate_loss(model_preds_list, targets_list)
679
+
680
+ def prepare_latents(
681
+ self,
682
+ batch_size,
683
+ num_channels_latents,
684
+ temp,
685
+ height,
686
+ width,
687
+ dtype,
688
+ device,
689
+ generator,
690
+ ):
691
+ shape = (
692
+ batch_size,
693
+ num_channels_latents,
694
+ int(temp),
695
+ int(height) // self.downsample,
696
+ int(width) // self.downsample,
697
+ )
698
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
699
+ return latents
700
+
701
+ def sample_block_noise(self, bs, ch, temp, height, width):
702
+ gamma = self.scheduler.config.gamma
703
+ dist = torch.distributions.multivariate_normal.MultivariateNormal(torch.zeros(4), torch.eye(4) * (1 + gamma) - torch.ones(4, 4) * gamma)
704
+ block_number = bs * ch * temp * (height // 2) * (width // 2)
705
+ noise = torch.stack([dist.sample() for _ in range(block_number)]) # [block number, 4]
706
+ noise = rearrange(noise, '(b c t h w) (p q) -> b c t (h p) (w q)',b=bs,c=ch,t=temp,h=height//2,w=width//2,p=2,q=2)
707
+ return noise
708
+
709
+ @torch.no_grad()
710
+ def generate_one_unit(
711
+ self,
712
+ latents,
713
+ past_conditions, # List of past conditions, contains the conditions of each stage
714
+ prompt_embeds,
715
+ prompt_attention_mask,
716
+ pooled_prompt_embeds,
717
+ num_inference_steps,
718
+ height,
719
+ width,
720
+ temp,
721
+ device,
722
+ dtype,
723
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
724
+ is_first_frame: bool = False,
725
+ ):
726
+ stages = self.stages
727
+ intermed_latents = []
728
+
729
+ for i_s in range(len(stages)):
730
+ self.scheduler.set_timesteps(num_inference_steps[i_s], i_s, device=device)
731
+ timesteps = self.scheduler.timesteps
732
+
733
+ if i_s > 0:
734
+ height *= 2; width *= 2
735
+ latents = rearrange(latents, 'b c t h w -> (b t) c h w')
736
+ latents = F.interpolate(latents, size=(height, width), mode='nearest')
737
+ latents = rearrange(latents, '(b t) c h w -> b c t h w', t=temp)
738
+ # Fix the stage
739
+ ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal
740
+ gamma = self.scheduler.config.gamma
741
+ alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
742
+ beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
743
+
744
+ bs, ch, temp, height, width = latents.shape
745
+ noise = self.sample_block_noise(bs, ch, temp, height, width)
746
+ noise = noise.to(device=device, dtype=dtype)
747
+ latents = alpha * latents + beta * noise # To fix the block artifact
748
+
749
+ for idx, t in enumerate(timesteps):
750
+ # expand the latents if we are doing classifier free guidance
751
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
752
+
753
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
754
+ timestep = t.expand(latent_model_input.shape[0]).to(latent_model_input.dtype)
755
+
756
+ if is_sequence_parallel_initialized():
757
+ # sync the input latent
758
+ sp_group_rank = get_sequence_parallel_group_rank()
759
+ global_src_rank = sp_group_rank * get_sequence_parallel_world_size()
760
+ torch.distributed.broadcast(latent_model_input, global_src_rank, group=get_sequence_parallel_group())
761
+
762
+ latent_model_input = past_conditions[i_s] + [latent_model_input]
763
+
764
+ noise_pred = self.dit(
765
+ sample=[latent_model_input],
766
+ timestep_ratio=timestep,
767
+ encoder_hidden_states=prompt_embeds,
768
+ encoder_attention_mask=prompt_attention_mask,
769
+ pooled_projections=pooled_prompt_embeds,
770
+ )
771
+
772
+ noise_pred = noise_pred[0]
773
+
774
+ # perform guidance
775
+ if self.do_classifier_free_guidance:
776
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
777
+ if is_first_frame:
778
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
779
+ else:
780
+ noise_pred = noise_pred_uncond + self.video_guidance_scale * (noise_pred_text - noise_pred_uncond)
781
+
782
+ # compute the previous noisy sample x_t -> x_t-1
783
+ latents = self.scheduler.step(
784
+ model_output=noise_pred,
785
+ timestep=timestep,
786
+ sample=latents,
787
+ generator=generator,
788
+ ).prev_sample
789
+
790
+ intermed_latents.append(latents)
791
+
792
+ return intermed_latents
793
+
794
+ @torch.no_grad()
795
+ def generate_i2v(
796
+ self,
797
+ prompt: Union[str, List[str]] = '',
798
+ input_image: PIL.Image = None,
799
+ temp: int = 1,
800
+ num_inference_steps: Optional[Union[int, List[int]]] = 28,
801
+ guidance_scale: float = 7.0,
802
+ video_guidance_scale: float = 4.0,
803
+ min_guidance_scale: float = 2.0,
804
+ use_linear_guidance: bool = False,
805
+ alpha: float = 0.5,
806
+ negative_prompt: Optional[Union[str, List[str]]]="cartoon style, worst quality, low quality, blurry, absolute black, absolute white, low res, extra limbs, extra digits, misplaced objects, mutated anatomy, monochrome, horror",
807
+ num_images_per_prompt: Optional[int] = 1,
808
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
809
+ output_type: Optional[str] = "pil",
810
+ save_memory: bool = True,
811
+ cpu_offloading: bool = False, # If true, reload device will be cuda.
812
+ inference_multigpu: bool = False,
813
+ callback: Optional[Callable[[int, int, Dict], None]] = None,
814
+ ):
815
+ if self.sequential_offload_enabled and not cpu_offloading:
816
+ print("Warning: overriding cpu_offloading set to false, as it's needed for sequential cpu offload")
817
+ cpu_offloading=True
818
+ device = self.device if not cpu_offloading else torch.device("cuda")
819
+ dtype = self.dtype
820
+ if cpu_offloading:
821
+ # skip caring about the text encoder here as its about to be used anyways.
822
+ if not self.sequential_offload_enabled:
823
+ if str(self.dit.device) != "cpu":
824
+ print("(dit) Warning: Do not preload pipeline components (i.e. to cuda) with cpu offloading enabled! Otherwise, a second transfer will occur needlessly taking up time.")
825
+ self.dit.to("cpu")
826
+ torch.cuda.empty_cache()
827
+ if str(self.vae.device) != "cpu":
828
+ print("(vae) Warning: Do not preload pipeline components (i.e. to cuda) with cpu offloading enabled! Otherwise, a second transfer will occur needlessly taking up time.")
829
+ self.vae.to("cpu")
830
+ torch.cuda.empty_cache()
831
+
832
+ width = input_image.width
833
+ height = input_image.height
834
+
835
+ assert temp % self.frame_per_unit == 0, "The frames should be divided by frame_per unit"
836
+
837
+ if isinstance(prompt, str):
838
+ batch_size = 1
839
+ prompt = prompt + ", hyper quality, Ultra HD, 8K" # adding this prompt to improve aesthetics
840
+ else:
841
+ assert isinstance(prompt, list)
842
+ batch_size = len(prompt)
843
+ prompt = [_ + ", hyper quality, Ultra HD, 8K" for _ in prompt]
844
+
845
+ if isinstance(num_inference_steps, int):
846
+ num_inference_steps = [num_inference_steps] * len(self.stages)
847
+
848
+ negative_prompt = negative_prompt or ""
849
+
850
+ # Get the text embeddings
851
+ if cpu_offloading and not self.sequential_offload_enabled:
852
+ self.text_encoder.to("cuda")
853
+ prompt_embeds, prompt_attention_mask, pooled_prompt_embeds = self.text_encoder(prompt, device)
854
+ negative_prompt_embeds, negative_prompt_attention_mask, negative_pooled_prompt_embeds = self.text_encoder(negative_prompt, device)
855
+
856
+ if cpu_offloading:
857
+ if not self.sequential_offload_enabled:
858
+ self.text_encoder.to("cpu")
859
+ self.vae.to("cuda")
860
+ torch.cuda.empty_cache()
861
+
862
+ if use_linear_guidance:
863
+ max_guidance_scale = guidance_scale
864
+ guidance_scale_list = [max(max_guidance_scale - alpha * t_, min_guidance_scale) for t_ in range(temp+1)]
865
+ print(guidance_scale_list)
866
+
867
+ self._guidance_scale = guidance_scale
868
+ self._video_guidance_scale = video_guidance_scale
869
+
870
+ if self.do_classifier_free_guidance:
871
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
872
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
873
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
874
+
875
+ if is_sequence_parallel_initialized():
876
+ # sync the prompt embedding across multiple GPUs
877
+ sp_group_rank = get_sequence_parallel_group_rank()
878
+ global_src_rank = sp_group_rank * get_sequence_parallel_world_size()
879
+ torch.distributed.broadcast(prompt_embeds, global_src_rank, group=get_sequence_parallel_group())
880
+ torch.distributed.broadcast(pooled_prompt_embeds, global_src_rank, group=get_sequence_parallel_group())
881
+ torch.distributed.broadcast(prompt_attention_mask, global_src_rank, group=get_sequence_parallel_group())
882
+
883
+ # Create the initial random noise
884
+ num_channels_latents = (self.dit.config.in_channels // 4) if self.model_name == "pyramid_flux" else self.dit.config.in_channels
885
+ latents = self.prepare_latents(
886
+ batch_size * num_images_per_prompt,
887
+ num_channels_latents,
888
+ temp,
889
+ height,
890
+ width,
891
+ prompt_embeds.dtype,
892
+ device,
893
+ generator,
894
+ )
895
+
896
+ temp, height, width = latents.shape[-3], latents.shape[-2], latents.shape[-1]
897
+
898
+ latents = rearrange(latents, 'b c t h w -> (b t) c h w')
899
+ # by defalut, we needs to start from the block noise
900
+ for _ in range(len(self.stages)-1):
901
+ height //= 2;width //= 2
902
+ latents = F.interpolate(latents, size=(height, width), mode='bilinear') * 2
903
+
904
+ latents = rearrange(latents, '(b t) c h w -> b c t h w', t=temp)
905
+
906
+ num_units = temp // self.frame_per_unit
907
+ stages = self.stages
908
+
909
+ # encode the image latents
910
+ image_transform = transforms.Compose([
911
+ transforms.ToTensor(),
912
+ transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)),
913
+ ])
914
+ input_image_tensor = image_transform(input_image).unsqueeze(0).unsqueeze(2) # [b c 1 h w]
915
+ input_image_latent = (self.vae.encode(input_image_tensor.to(self.vae.device, dtype=self.vae.dtype)).latent_dist.sample() - self.vae_shift_factor) * self.vae_scale_factor # [b c 1 h w]
916
+
917
+ if is_sequence_parallel_initialized():
918
+ # sync the image latent across multiple GPUs
919
+ sp_group_rank = get_sequence_parallel_group_rank()
920
+ global_src_rank = sp_group_rank * get_sequence_parallel_world_size()
921
+ torch.distributed.broadcast(input_image_latent, global_src_rank, group=get_sequence_parallel_group())
922
+
923
+ generated_latents_list = [input_image_latent] # The generated results
924
+ last_generated_latents = input_image_latent
925
+
926
+ if cpu_offloading:
927
+ self.vae.to("cpu")
928
+ if not self.sequential_offload_enabled:
929
+ self.dit.to("cuda")
930
+ torch.cuda.empty_cache()
931
+
932
+ for unit_index in tqdm(range(1, num_units)):
933
+ gc.collect()
934
+ torch.cuda.empty_cache()
935
+
936
+ if callback:
937
+ callback(unit_index, num_units)
938
+
939
+ if use_linear_guidance:
940
+ self._guidance_scale = guidance_scale_list[unit_index]
941
+ self._video_guidance_scale = guidance_scale_list[unit_index]
942
+
943
+ # prepare the condition latents
944
+ past_condition_latents = []
945
+ clean_latents_list = self.get_pyramid_latent(torch.cat(generated_latents_list, dim=2), len(stages) - 1)
946
+
947
+ for i_s in range(len(stages)):
948
+ last_cond_latent = clean_latents_list[i_s][:,:,-self.frame_per_unit:]
949
+
950
+ stage_input = [torch.cat([last_cond_latent] * 2) if self.do_classifier_free_guidance else last_cond_latent]
951
+
952
+ # pad the past clean latents
953
+ cur_unit_num = unit_index
954
+ cur_stage = i_s
955
+ cur_unit_ptx = 1
956
+
957
+ while cur_unit_ptx < cur_unit_num:
958
+ cur_stage = max(cur_stage - 1, 0)
959
+ if cur_stage == 0:
960
+ break
961
+ cur_unit_ptx += 1
962
+ cond_latents = clean_latents_list[cur_stage][:, :, -(cur_unit_ptx * self.frame_per_unit) : -((cur_unit_ptx - 1) * self.frame_per_unit)]
963
+ stage_input.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
964
+
965
+ if cur_stage == 0 and cur_unit_ptx < cur_unit_num:
966
+ cond_latents = clean_latents_list[0][:, :, :-(cur_unit_ptx * self.frame_per_unit)]
967
+ stage_input.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
968
+
969
+ stage_input = list(reversed(stage_input))
970
+ past_condition_latents.append(stage_input)
971
+
972
+ intermed_latents = self.generate_one_unit(
973
+ latents[:,:,(unit_index - 1) * self.frame_per_unit:unit_index * self.frame_per_unit],
974
+ past_condition_latents,
975
+ prompt_embeds,
976
+ prompt_attention_mask,
977
+ pooled_prompt_embeds,
978
+ num_inference_steps,
979
+ height,
980
+ width,
981
+ self.frame_per_unit,
982
+ device,
983
+ dtype,
984
+ generator,
985
+ is_first_frame=False,
986
+ )
987
+
988
+ generated_latents_list.append(intermed_latents[-1])
989
+ last_generated_latents = intermed_latents
990
+
991
+ generated_latents = torch.cat(generated_latents_list, dim=2)
992
+
993
+ if output_type == "latent":
994
+ image = generated_latents
995
+ else:
996
+ if cpu_offloading:
997
+ if not self.sequential_offload_enabled:
998
+ self.dit.to("cpu")
999
+ self.vae.to("cuda")
1000
+ torch.cuda.empty_cache()
1001
+ image = self.decode_latent(generated_latents, save_memory=save_memory, inference_multigpu=inference_multigpu)
1002
+ if cpu_offloading:
1003
+ self.vae.to("cpu")
1004
+ torch.cuda.empty_cache()
1005
+ # not technically necessary, but returns the pipeline to its original state
1006
+
1007
+ return image
1008
+
1009
+ @torch.no_grad()
1010
+ def generate(
1011
+ self,
1012
+ prompt: Union[str, List[str]] = None,
1013
+ height: Optional[int] = None,
1014
+ width: Optional[int] = None,
1015
+ temp: int = 1,
1016
+ num_inference_steps: Optional[Union[int, List[int]]] = 28,
1017
+ video_num_inference_steps: Optional[Union[int, List[int]]] = 28,
1018
+ guidance_scale: float = 7.0,
1019
+ video_guidance_scale: float = 7.0,
1020
+ min_guidance_scale: float = 2.0,
1021
+ use_linear_guidance: bool = False,
1022
+ alpha: float = 0.5,
1023
+ negative_prompt: Optional[Union[str, List[str]]]="cartoon style, worst quality, low quality, blurry, absolute black, absolute white, low res, extra limbs, extra digits, misplaced objects, mutated anatomy, monochrome, horror",
1024
+ num_images_per_prompt: Optional[int] = 1,
1025
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1026
+ output_type: Optional[str] = "pil",
1027
+ save_memory: bool = True,
1028
+ cpu_offloading: bool = False, # If true, reload device will be cuda.
1029
+ inference_multigpu: bool = False,
1030
+ callback: Optional[Callable[[int, int, Dict], None]] = None,
1031
+ ):
1032
+ if self.sequential_offload_enabled and not cpu_offloading:
1033
+ print("Warning: overriding cpu_offloading set to false, as it's needed for sequential cpu offload")
1034
+ cpu_offloading=True
1035
+ device = self.device if not cpu_offloading else torch.device("cuda")
1036
+ dtype = self.dtype
1037
+ if cpu_offloading:
1038
+ # skip caring about the text encoder here as its about to be used anyways.
1039
+ if not self.sequential_offload_enabled:
1040
+ if str(self.dit.device) != "cpu":
1041
+ print("(dit) Warning: Do not preload pipeline components (i.e. to cuda) with cpu offloading enabled! Otherwise, a second transfer will occur needlessly taking up time.")
1042
+ self.dit.to("cpu")
1043
+ torch.cuda.empty_cache()
1044
+ if str(self.vae.device) != "cpu":
1045
+ print("(vae) Warning: Do not preload pipeline components (i.e. to cuda) with cpu offloading enabled! Otherwise, a second transfer will occur needlessly taking up time.")
1046
+ self.vae.to("cpu")
1047
+ torch.cuda.empty_cache()
1048
+
1049
+
1050
+ assert (temp - 1) % self.frame_per_unit == 0, "The frames should be divided by frame_per unit"
1051
+
1052
+ if isinstance(prompt, str):
1053
+ batch_size = 1
1054
+ prompt = prompt + ", hyper quality, Ultra HD, 8K" # adding this prompt to improve aesthetics
1055
+ else:
1056
+ assert isinstance(prompt, list)
1057
+ batch_size = len(prompt)
1058
+ prompt = [_ + ", hyper quality, Ultra HD, 8K" for _ in prompt]
1059
+
1060
+ if isinstance(num_inference_steps, int):
1061
+ num_inference_steps = [num_inference_steps] * len(self.stages)
1062
+
1063
+ if isinstance(video_num_inference_steps, int):
1064
+ video_num_inference_steps = [video_num_inference_steps] * len(self.stages)
1065
+
1066
+ negative_prompt = negative_prompt or ""
1067
+
1068
+ # Get the text embeddings
1069
+ if cpu_offloading and not self.sequential_offload_enabled:
1070
+ self.text_encoder.to("cuda")
1071
+ prompt_embeds, prompt_attention_mask, pooled_prompt_embeds = self.text_encoder(prompt, device)
1072
+ negative_prompt_embeds, negative_prompt_attention_mask, negative_pooled_prompt_embeds = self.text_encoder(negative_prompt, device)
1073
+ if cpu_offloading:
1074
+ if not self.sequential_offload_enabled:
1075
+ self.text_encoder.to("cpu")
1076
+ self.dit.to("cuda")
1077
+ torch.cuda.empty_cache()
1078
+
1079
+ if use_linear_guidance:
1080
+ max_guidance_scale = guidance_scale
1081
+ # guidance_scale_list = torch.linspace(max_guidance_scale, min_guidance_scale, temp).tolist()
1082
+ guidance_scale_list = [max(max_guidance_scale - alpha * t_, min_guidance_scale) for t_ in range(temp)]
1083
+ print(guidance_scale_list)
1084
+
1085
+ self._guidance_scale = guidance_scale
1086
+ self._video_guidance_scale = video_guidance_scale
1087
+
1088
+ if self.do_classifier_free_guidance:
1089
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1090
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
1091
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
1092
+
1093
+ if is_sequence_parallel_initialized():
1094
+ # sync the prompt embedding across multiple GPUs
1095
+ sp_group_rank = get_sequence_parallel_group_rank()
1096
+ global_src_rank = sp_group_rank * get_sequence_parallel_world_size()
1097
+ torch.distributed.broadcast(prompt_embeds, global_src_rank, group=get_sequence_parallel_group())
1098
+ torch.distributed.broadcast(pooled_prompt_embeds, global_src_rank, group=get_sequence_parallel_group())
1099
+ torch.distributed.broadcast(prompt_attention_mask, global_src_rank, group=get_sequence_parallel_group())
1100
+
1101
+ # Create the initial random noise
1102
+ num_channels_latents = (self.dit.config.in_channels // 4) if self.model_name == "pyramid_flux" else self.dit.config.in_channels
1103
+ latents = self.prepare_latents(
1104
+ batch_size * num_images_per_prompt,
1105
+ num_channels_latents,
1106
+ temp,
1107
+ height,
1108
+ width,
1109
+ prompt_embeds.dtype,
1110
+ device,
1111
+ generator,
1112
+ )
1113
+
1114
+ temp, height, width = latents.shape[-3], latents.shape[-2], latents.shape[-1]
1115
+
1116
+ latents = rearrange(latents, 'b c t h w -> (b t) c h w')
1117
+ # by default, we needs to start from the block noise
1118
+ for _ in range(len(self.stages)-1):
1119
+ height //= 2;width //= 2
1120
+ latents = F.interpolate(latents, size=(height, width), mode='bilinear') * 2
1121
+
1122
+ latents = rearrange(latents, '(b t) c h w -> b c t h w', t=temp)
1123
+
1124
+ num_units = 1 + (temp - 1) // self.frame_per_unit
1125
+ stages = self.stages
1126
+
1127
+ generated_latents_list = [] # The generated results
1128
+ last_generated_latents = None
1129
+
1130
+ for unit_index in tqdm(range(num_units)):
1131
+ gc.collect()
1132
+ torch.cuda.empty_cache()
1133
+
1134
+ if callback:
1135
+ callback(unit_index, num_units)
1136
+
1137
+ if use_linear_guidance:
1138
+ self._guidance_scale = guidance_scale_list[unit_index]
1139
+ self._video_guidance_scale = guidance_scale_list[unit_index]
1140
+
1141
+ if unit_index == 0:
1142
+ past_condition_latents = [[] for _ in range(len(stages))]
1143
+ intermed_latents = self.generate_one_unit(
1144
+ latents[:,:,:1],
1145
+ past_condition_latents,
1146
+ prompt_embeds,
1147
+ prompt_attention_mask,
1148
+ pooled_prompt_embeds,
1149
+ num_inference_steps,
1150
+ height,
1151
+ width,
1152
+ 1,
1153
+ device,
1154
+ dtype,
1155
+ generator,
1156
+ is_first_frame=True,
1157
+ )
1158
+ else:
1159
+ # prepare the condition latents
1160
+ past_condition_latents = []
1161
+ clean_latents_list = self.get_pyramid_latent(torch.cat(generated_latents_list, dim=2), len(stages) - 1)
1162
+
1163
+ for i_s in range(len(stages)):
1164
+ last_cond_latent = clean_latents_list[i_s][:,:,-(self.frame_per_unit):]
1165
+
1166
+ stage_input = [torch.cat([last_cond_latent] * 2) if self.do_classifier_free_guidance else last_cond_latent]
1167
+
1168
+ # pad the past clean latents
1169
+ cur_unit_num = unit_index
1170
+ cur_stage = i_s
1171
+ cur_unit_ptx = 1
1172
+
1173
+ while cur_unit_ptx < cur_unit_num:
1174
+ cur_stage = max(cur_stage - 1, 0)
1175
+ if cur_stage == 0:
1176
+ break
1177
+ cur_unit_ptx += 1
1178
+ cond_latents = clean_latents_list[cur_stage][:, :, -(cur_unit_ptx * self.frame_per_unit) : -((cur_unit_ptx - 1) * self.frame_per_unit)]
1179
+ stage_input.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
1180
+
1181
+ if cur_stage == 0 and cur_unit_ptx < cur_unit_num:
1182
+ cond_latents = clean_latents_list[0][:, :, :-(cur_unit_ptx * self.frame_per_unit)]
1183
+ stage_input.append(torch.cat([cond_latents] * 2) if self.do_classifier_free_guidance else cond_latents)
1184
+
1185
+ stage_input = list(reversed(stage_input))
1186
+ past_condition_latents.append(stage_input)
1187
+
1188
+ intermed_latents = self.generate_one_unit(
1189
+ latents[:,:, 1 + (unit_index - 1) * self.frame_per_unit:1 + unit_index * self.frame_per_unit],
1190
+ past_condition_latents,
1191
+ prompt_embeds,
1192
+ prompt_attention_mask,
1193
+ pooled_prompt_embeds,
1194
+ video_num_inference_steps,
1195
+ height,
1196
+ width,
1197
+ self.frame_per_unit,
1198
+ device,
1199
+ dtype,
1200
+ generator,
1201
+ is_first_frame=False,
1202
+ )
1203
+
1204
+ generated_latents_list.append(intermed_latents[-1])
1205
+ last_generated_latents = intermed_latents
1206
+
1207
+ generated_latents = torch.cat(generated_latents_list, dim=2)
1208
+
1209
+ if output_type == "latent":
1210
+ image = generated_latents
1211
+ else:
1212
+ if cpu_offloading:
1213
+ if not self.sequential_offload_enabled:
1214
+ self.dit.to("cpu")
1215
+ self.vae.to("cuda")
1216
+ torch.cuda.empty_cache()
1217
+ image = self.decode_latent(generated_latents, save_memory=save_memory, inference_multigpu=inference_multigpu)
1218
+ if cpu_offloading:
1219
+ self.vae.to("cpu")
1220
+ torch.cuda.empty_cache()
1221
+ # not technically necessary, but returns the pipeline to its original state
1222
+
1223
+ return image
1224
+
1225
+ def decode_latent(self, latents, save_memory=True, inference_multigpu=False):
1226
+ # only the main process needs vae decoding
1227
+ if inference_multigpu and get_rank() != 0:
1228
+ return None
1229
+
1230
+ if latents.shape[2] == 1:
1231
+ latents = (latents / self.vae_scale_factor) + self.vae_shift_factor
1232
+ else:
1233
+ latents[:, :, :1] = (latents[:, :, :1] / self.vae_scale_factor) + self.vae_shift_factor
1234
+ latents[:, :, 1:] = (latents[:, :, 1:] / self.vae_video_scale_factor) + self.vae_video_shift_factor
1235
+
1236
+ if save_memory:
1237
+ # reducing the tile size and temporal chunk window size
1238
+ image = self.vae.decode(latents, temporal_chunk=True, window_size=1, tile_sample_min_size=256).sample
1239
+ else:
1240
+ image = self.vae.decode(latents, temporal_chunk=True, window_size=2, tile_sample_min_size=512).sample
1241
+
1242
+ image = image.mul(127.5).add(127.5).clamp(0, 255).byte()
1243
+ image = rearrange(image, "B C T H W -> (B T) H W C")
1244
+ image = image.cpu().numpy()
1245
+ image = self.numpy_to_pil(image)
1246
+
1247
+ return image
1248
+
1249
+ @staticmethod
1250
+ def numpy_to_pil(images):
1251
+ """
1252
+ Convert a numpy image or a batch of images to a PIL image.
1253
+ """
1254
+ if images.ndim == 3:
1255
+ images = images[None, ...]
1256
+
1257
+ if images.shape[-1] == 1:
1258
+ # special case for grayscale (single channel) images
1259
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
1260
+ else:
1261
+ pil_images = [Image.fromarray(image) for image in images]
1262
+
1263
+ return pil_images
1264
+
1265
+ @property
1266
+ def device(self):
1267
+ return next(self.dit.parameters()).device
1268
+
1269
+ @property
1270
+ def dtype(self):
1271
+ return next(self.dit.parameters()).dtype
1272
+
1273
+ @property
1274
+ def guidance_scale(self):
1275
+ return self._guidance_scale
1276
+
1277
+ @property
1278
+ def video_guidance_scale(self):
1279
+ return self._video_guidance_scale
1280
+
1281
+ @property
1282
+ def do_classifier_free_guidance(self):
1283
+ return self._guidance_scale > 0
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/scripts/run_FiVE.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ CUDA_VISIBLE_DEVICES=6 python models/pyramid-edit/edit.py \
2
+ --dataset_json data/edit_prompt/edit5_FiVE.json \
3
+ --guidance_start_timestep_first 750 \
4
+ --guidance_stop_timestep_first 100 \
5
+ --guidance_start_timestep 750 \
6
+ --guidance_stop_timestep 100 \
7
+ --guidance_scale 7.0 \
8
+ --video_guidance_scale 5.0
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/scripts/run_single.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CUDA_VISIBLE_DEVICES=6 python models/pyramid-edit/edit.py \
2
+ --data_dir data/examples \
3
+ --video_name bear \
4
+ --source_prompt "A large brown bear is walking slowly across a rocky terrain in a zoo enclosure, surrounded by stone walls and scattered greenery. The camera remains fixed, capturing the bear's deliberate movements." \
5
+ --target_prompt "A purple bear is walking slowly across a rocky terrain in a zoo enclosure, surrounded by stone walls and scattered greenery. The camera remains fixed, capturing the bear's deliberate movements." \
6
+ --negative_prompt "worst quality, low quality, blurry, absolute black, absolute white, low res, extra limbs, extra digits, misplaced objects, mutated anatomy, monochrome, horror" \
7
+ --guidance_start_timestep_first 750 \
8
+ --guidance_stop_timestep_first 100 \
9
+ --guidance_start_timestep 750 \
10
+ --guidance_stop_timestep 100 \
11
+ --guidance_scale 7 \
12
+ --video_guidance_scale 5 \
13
+ --output_path outputs/pyramid_edit_results/examples
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import (
2
+ create_optimizer,
3
+ get_rank,
4
+ get_world_size,
5
+ is_main_process,
6
+ is_dist_avail_and_initialized,
7
+ init_distributed_mode,
8
+ setup_for_distributed,
9
+ cosine_scheduler,
10
+ constant_scheduler,
11
+ NativeScalerWithGradNormCount,
12
+ auto_load_model,
13
+ save_model,
14
+ )
15
+
16
+ from .sp_utils import (
17
+ is_sequence_parallel_initialized,
18
+ init_sequence_parallel_group,
19
+ get_sequence_parallel_group,
20
+ get_sequence_parallel_world_size,
21
+ get_sequence_parallel_rank,
22
+ get_sequence_parallel_group_rank,
23
+ get_sequence_parallel_proc_num,
24
+ init_sync_input_group,
25
+ get_sync_input_group,
26
+ )
27
+
28
+ from .communicate import all_to_all
29
+ from .fsdp_trainer import train_one_epoch_with_fsdp
30
+ from .vae_ddp_trainer import train_one_epoch
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/communicate.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import math
4
+ import torch.distributed as dist
5
+
6
+
7
+ def _all_to_all(
8
+ input_: torch.Tensor,
9
+ world_size: int,
10
+ group: dist.ProcessGroup,
11
+ scatter_dim: int,
12
+ gather_dim: int,
13
+ concat_output: bool,
14
+ ):
15
+ if world_size == 1:
16
+ return input_
17
+ input_list = [t.contiguous() for t in torch.tensor_split(input_, world_size, scatter_dim)]
18
+ output_list = [torch.empty_like(input_list[0]) for _ in range(world_size)]
19
+ dist.all_to_all(output_list, input_list, group=group)
20
+ if concat_output:
21
+ return torch.cat(output_list, dim=gather_dim).contiguous()
22
+ else:
23
+ # For multi-gpus inference, the latent on each gpu are same, only remain the first one
24
+ return output_list[0]
25
+
26
+
27
+ class _AllToAll(torch.autograd.Function):
28
+
29
+ @staticmethod
30
+ def forward(ctx, input_, process_group, world_size, scatter_dim, gather_dim, concat_output):
31
+ ctx.process_group = process_group
32
+ ctx.scatter_dim = scatter_dim
33
+ ctx.gather_dim = gather_dim
34
+ ctx.world_size = world_size
35
+ ctx.concat_output = concat_output
36
+ output = _all_to_all(input_, ctx.world_size, process_group, scatter_dim, gather_dim, concat_output)
37
+ return output
38
+
39
+ @staticmethod
40
+ def backward(ctx, grad_output):
41
+ grad_output = _all_to_all(
42
+ grad_output,
43
+ ctx.world_size,
44
+ ctx.process_group,
45
+ ctx.gather_dim,
46
+ ctx.scatter_dim,
47
+ ctx.concat_output,
48
+ )
49
+ return (
50
+ grad_output,
51
+ None,
52
+ None,
53
+ None,
54
+ None,
55
+ )
56
+
57
+
58
+ def all_to_all(
59
+ input_: torch.Tensor,
60
+ process_group: dist.ProcessGroup,
61
+ world_size: int = 1,
62
+ scatter_dim: int = 2,
63
+ gather_dim: int = 1,
64
+ concat_output: bool = True,
65
+ ):
66
+ return _AllToAll.apply(input_, process_group, world_size, scatter_dim, gather_dim, concat_output)
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/fsdp_trainer.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ from typing import Iterable
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import accelerate
8
+ from .utils import MetricLogger, SmoothedValue
9
+
10
+
11
+ def update_ema_for_dit(model, model_ema, accelerator, decay):
12
+ """Apply exponential moving average update.
13
+
14
+ The weights are updated in-place as follow:
15
+ w_ema = w_ema * decay + (1 - decay) * w
16
+ Args:
17
+ model: active model that is being optimized
18
+ model_ema: running average model
19
+ decay: exponential decay parameter
20
+ """
21
+ with torch.no_grad():
22
+ msd = accelerator.get_state_dict(model)
23
+ for k, ema_v in model_ema.state_dict().items():
24
+ if k in msd:
25
+ model_v = msd[k].detach().to(ema_v.device, dtype=ema_v.dtype)
26
+ ema_v.copy_(ema_v * decay + (1.0 - decay) * model_v)
27
+
28
+
29
+ def get_decay(optimization_step: int, ema_decay: float) -> float:
30
+ """
31
+ Compute the decay factor for the exponential moving average.
32
+ """
33
+ step = max(0, optimization_step - 1)
34
+
35
+ if step <= 0:
36
+ return 0.0
37
+
38
+ cur_decay_value = (1 + step) / (10 + step)
39
+ cur_decay_value = min(cur_decay_value, ema_decay)
40
+ cur_decay_value = max(cur_decay_value, 0.0)
41
+
42
+ return cur_decay_value
43
+
44
+
45
+ def train_one_epoch_with_fsdp(
46
+ runner,
47
+ model_ema: torch.nn.Module,
48
+ accelerator: accelerate.Accelerator,
49
+ model_dtype: str,
50
+ data_loader: Iterable,
51
+ optimizer: torch.optim.Optimizer,
52
+ lr_schedule_values,
53
+ device: torch.device,
54
+ epoch: int,
55
+ clip_grad: float = 1.0,
56
+ start_steps=None,
57
+ args=None,
58
+ print_freq=20,
59
+ iters_per_epoch=2000,
60
+ ema_decay=0.9999,
61
+ use_temporal_pyramid=True,
62
+ ):
63
+ runner.dit.train()
64
+ metric_logger = MetricLogger(delimiter=" ")
65
+ metric_logger.add_meter('lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
66
+ metric_logger.add_meter('min_lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
67
+ header = 'Epoch: [{}]'.format(epoch)
68
+ train_loss = 0.0
69
+
70
+ print("Start training epoch {}, {} iters per inner epoch. Training dtype {}".format(epoch, iters_per_epoch, model_dtype))
71
+
72
+ for step in metric_logger.log_every(range(iters_per_epoch), print_freq, header):
73
+ if step >= iters_per_epoch:
74
+ break
75
+
76
+ if lr_schedule_values is not None:
77
+ for i, param_group in enumerate(optimizer.param_groups):
78
+ param_group["lr"] = lr_schedule_values[start_steps] * param_group.get("lr_scale", 1.0)
79
+
80
+ for _ in range(args.gradient_accumulation_steps):
81
+
82
+ with accelerator.accumulate(runner.dit):
83
+ # To fetch the data sample and Move the input to device
84
+ samples = next(data_loader)
85
+ video = samples['video'].to(accelerator.device)
86
+ text = samples['text']
87
+ identifier = samples['identifier']
88
+
89
+ # Perform the forward using the accerlate
90
+ loss, log_loss = runner(video, text, identifier,
91
+ use_temporal_pyramid=use_temporal_pyramid, accelerator=accelerator)
92
+
93
+ # Check if the loss is nan
94
+ loss_value = loss.item()
95
+ if not math.isfinite(loss_value):
96
+ print("Loss is {}, stopping training".format(loss_value), force=True)
97
+ sys.exit(1)
98
+
99
+ avg_loss = accelerator.gather(loss.repeat(args.batch_size)).mean()
100
+
101
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
102
+
103
+ accelerator.backward(loss)
104
+
105
+ # clip the gradient
106
+ if accelerator.sync_gradients:
107
+ params_to_clip = runner.dit.parameters()
108
+ grad_norm = accelerator.clip_grad_norm_(params_to_clip, clip_grad)
109
+
110
+ # To deal with the abnormal data point
111
+ if train_loss >= 2.0:
112
+ print(f"The ERROR data sample, finding extreme high loss {train_loss}, skip updating the parameters", force=True)
113
+ # zero out the gradient, do not update
114
+ optimizer.zero_grad()
115
+ train_loss = 0.001 # fix the loss for logging
116
+ else:
117
+ optimizer.step()
118
+ optimizer.zero_grad()
119
+
120
+ if accelerator.sync_gradients:
121
+ # Update every 100 steps
122
+ if model_ema is not None and start_steps % 100 == 0:
123
+ # cur_ema_decay = get_decay(start_steps, ema_decay)
124
+ cur_ema_decay = ema_decay
125
+ update_ema_for_dit(runner.dit, model_ema, accelerator, decay=cur_ema_decay)
126
+
127
+ start_steps += 1
128
+
129
+ # Report to tensorboard
130
+ accelerator.log({"train_loss": train_loss}, step=start_steps)
131
+ metric_logger.update(loss=train_loss)
132
+
133
+ train_loss = 0.0
134
+
135
+ min_lr = 10.
136
+ max_lr = 0.
137
+ for group in optimizer.param_groups:
138
+ min_lr = min(min_lr, group["lr"])
139
+ max_lr = max(max_lr, group["lr"])
140
+
141
+ metric_logger.update(lr=max_lr)
142
+ metric_logger.update(min_lr=min_lr)
143
+ weight_decay_value = None
144
+ for group in optimizer.param_groups:
145
+ if group["weight_decay"] > 0:
146
+ weight_decay_value = group["weight_decay"]
147
+ metric_logger.update(weight_decay=weight_decay_value)
148
+ metric_logger.update(grad_norm=grad_norm)
149
+
150
+ # gather the stats from all processes
151
+ metric_logger.synchronize_between_processes()
152
+ print("Averaged stats:", metric_logger)
153
+
154
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/sp_utils.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.distributed as dist
4
+ from .utils import is_dist_avail_and_initialized, get_rank
5
+
6
+
7
+ SEQ_PARALLEL_GROUP = None
8
+ SEQ_PARALLEL_SIZE = None
9
+ SEQ_PARALLEL_PROC_NUM = None # using how many process for sequence parallel
10
+
11
+ SYNC_INPUT_GROUP = None
12
+ SYNC_INPUT_SIZE = None
13
+
14
+ def is_sequence_parallel_initialized():
15
+ if SEQ_PARALLEL_GROUP is None:
16
+ return False
17
+ else:
18
+ return True
19
+
20
+
21
+ def init_sequence_parallel_group(args):
22
+ global SEQ_PARALLEL_GROUP
23
+ global SEQ_PARALLEL_SIZE
24
+ global SEQ_PARALLEL_PROC_NUM
25
+
26
+ assert SEQ_PARALLEL_GROUP is None, "sequence parallel group is already initialized"
27
+ assert is_dist_avail_and_initialized(), "The pytorch distributed should be initialized"
28
+ SEQ_PARALLEL_SIZE = args.sp_group_size
29
+
30
+ print(f"Setting the Sequence Parallel Size {SEQ_PARALLEL_SIZE}")
31
+
32
+ rank = torch.distributed.get_rank()
33
+ world_size = torch.distributed.get_world_size()
34
+
35
+ if args.sp_proc_num == -1:
36
+ SEQ_PARALLEL_PROC_NUM = world_size
37
+ else:
38
+ SEQ_PARALLEL_PROC_NUM = args.sp_proc_num
39
+
40
+ assert SEQ_PARALLEL_PROC_NUM % SEQ_PARALLEL_SIZE == 0, "The process needs to be evenly divided"
41
+
42
+ for i in range(0, SEQ_PARALLEL_PROC_NUM, SEQ_PARALLEL_SIZE):
43
+ ranks = list(range(i, i + SEQ_PARALLEL_SIZE))
44
+ group = torch.distributed.new_group(ranks)
45
+ if rank in ranks:
46
+ SEQ_PARALLEL_GROUP = group
47
+ break
48
+
49
+
50
+ def init_sync_input_group(args):
51
+ global SYNC_INPUT_GROUP
52
+ global SYNC_INPUT_SIZE
53
+
54
+ assert SYNC_INPUT_GROUP is None, "parallel group is already initialized"
55
+ assert is_dist_avail_and_initialized(), "The pytorch distributed should be initialized"
56
+ SYNC_INPUT_SIZE = args.max_frames
57
+
58
+ rank = torch.distributed.get_rank()
59
+ world_size = torch.distributed.get_world_size()
60
+
61
+ for i in range(0, world_size, SYNC_INPUT_SIZE):
62
+ ranks = list(range(i, i + SYNC_INPUT_SIZE))
63
+ group = torch.distributed.new_group(ranks)
64
+ if rank in ranks:
65
+ SYNC_INPUT_GROUP = group
66
+ break
67
+
68
+
69
+ def get_sequence_parallel_group():
70
+ assert SEQ_PARALLEL_GROUP is not None, "sequence parallel group is not initialized"
71
+ return SEQ_PARALLEL_GROUP
72
+
73
+
74
+ def get_sync_input_group():
75
+ return SYNC_INPUT_GROUP
76
+
77
+
78
+ def get_sequence_parallel_world_size():
79
+ assert SEQ_PARALLEL_SIZE is not None, "sequence parallel size is not initialized"
80
+ return SEQ_PARALLEL_SIZE
81
+
82
+
83
+ def get_sequence_parallel_rank():
84
+ assert SEQ_PARALLEL_SIZE is not None, "sequence parallel size is not initialized"
85
+ rank = get_rank()
86
+ cp_rank = rank % SEQ_PARALLEL_SIZE
87
+ return cp_rank
88
+
89
+
90
+ def get_sequence_parallel_group_rank():
91
+ assert SEQ_PARALLEL_SIZE is not None, "sequence parallel size is not initialized"
92
+ rank = get_rank()
93
+ cp_group_rank = rank // SEQ_PARALLEL_SIZE
94
+ return cp_group_rank
95
+
96
+
97
+ def get_sequence_parallel_proc_num():
98
+ return SEQ_PARALLEL_PROC_NUM
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/utils.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import math
4
+ import time
5
+ import json
6
+ import glob
7
+ from collections import defaultdict, deque, OrderedDict
8
+ import datetime
9
+ import numpy as np
10
+
11
+
12
+ from pathlib import Path
13
+ import argparse
14
+
15
+ import torch
16
+ from torch import optim as optim
17
+ import torch.distributed as dist
18
+
19
+ try:
20
+ from torch._six import inf
21
+ except ImportError:
22
+ from torch import inf
23
+
24
+ from tensorboardX import SummaryWriter
25
+
26
+
27
+ def is_dist_avail_and_initialized():
28
+ if not dist.is_available():
29
+ return False
30
+ if not dist.is_initialized():
31
+ return False
32
+ return True
33
+
34
+
35
+ def get_world_size():
36
+ if not is_dist_avail_and_initialized():
37
+ return 1
38
+ return dist.get_world_size()
39
+
40
+
41
+ def get_rank():
42
+ if not is_dist_avail_and_initialized():
43
+ return 0
44
+ return dist.get_rank()
45
+
46
+
47
+ def is_main_process():
48
+ return get_rank() == 0
49
+
50
+
51
+ def save_on_master(*args, **kwargs):
52
+ if is_main_process():
53
+ torch.save(*args, **kwargs)
54
+
55
+
56
+ def setup_for_distributed(is_master):
57
+ """
58
+ This function disables printing when not in master process
59
+ """
60
+ import builtins as __builtin__
61
+ builtin_print = __builtin__.print
62
+
63
+ def print(*args, **kwargs):
64
+ force = kwargs.pop('force', False)
65
+ if is_master or force:
66
+ builtin_print(*args, **kwargs)
67
+
68
+ __builtin__.print = print
69
+
70
+
71
+ def init_distributed_mode(args, init_pytorch_ddp=True):
72
+ if int(os.getenv('OMPI_COMM_WORLD_SIZE', '0')) > 0:
73
+ rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
74
+ local_rank = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
75
+ world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])
76
+
77
+ os.environ["LOCAL_RANK"] = os.environ['OMPI_COMM_WORLD_LOCAL_RANK']
78
+ os.environ["RANK"] = os.environ['OMPI_COMM_WORLD_RANK']
79
+ os.environ["WORLD_SIZE"] = os.environ['OMPI_COMM_WORLD_SIZE']
80
+
81
+ args.rank = int(os.environ["RANK"])
82
+ args.world_size = int(os.environ["WORLD_SIZE"])
83
+ args.gpu = int(os.environ["LOCAL_RANK"])
84
+
85
+ elif 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
86
+ args.rank = int(os.environ["RANK"])
87
+ args.world_size = int(os.environ['WORLD_SIZE'])
88
+ args.gpu = int(os.environ['LOCAL_RANK'])
89
+
90
+ else:
91
+ print('Not using distributed mode')
92
+ args.distributed = False
93
+ return
94
+
95
+ args.distributed = True
96
+ args.dist_backend = 'nccl'
97
+ args.dist_url = "env://"
98
+ print('| distributed init (rank {}): {}, gpu {}'.format(
99
+ args.rank, args.dist_url, args.gpu), flush=True)
100
+
101
+ if init_pytorch_ddp:
102
+ # Init DDP Group, for script without using accelerate framework
103
+ torch.cuda.set_device(args.gpu)
104
+ torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
105
+ world_size=args.world_size, rank=args.rank, timeout=datetime.timedelta(days=365))
106
+ torch.distributed.barrier()
107
+ setup_for_distributed(args.rank == 0)
108
+
109
+
110
+ def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0,
111
+ start_warmup_value=0, warmup_steps=-1):
112
+ warmup_schedule = np.array([])
113
+ warmup_iters = warmup_epochs * niter_per_ep
114
+ if warmup_steps > 0:
115
+ warmup_iters = warmup_steps
116
+ print("Set warmup steps = %d" % warmup_iters)
117
+ if warmup_epochs > 0:
118
+ warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
119
+
120
+ iters = np.arange(epochs * niter_per_ep - warmup_iters)
121
+ schedule = np.array(
122
+ [final_value + 0.5 * (base_value - final_value) * (1 + math.cos(math.pi * i / (len(iters)))) for i in iters])
123
+
124
+ schedule = np.concatenate((warmup_schedule, schedule))
125
+
126
+ assert len(schedule) == epochs * niter_per_ep
127
+ return schedule
128
+
129
+
130
+ def constant_scheduler(base_value, epochs, niter_per_ep, warmup_epochs=0,
131
+ start_warmup_value=1e-6, warmup_steps=-1):
132
+ warmup_schedule = np.array([])
133
+ warmup_iters = warmup_epochs * niter_per_ep
134
+ if warmup_steps > 0:
135
+ warmup_iters = warmup_steps
136
+ print("Set warmup steps = %d" % warmup_iters)
137
+ if warmup_iters > 0:
138
+ warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
139
+
140
+ iters = epochs * niter_per_ep - warmup_iters
141
+ schedule = np.array([base_value] * iters)
142
+
143
+ schedule = np.concatenate((warmup_schedule, schedule))
144
+
145
+ assert len(schedule) == epochs * niter_per_ep
146
+ return schedule
147
+
148
+
149
+ def get_parameter_groups(model, weight_decay=1e-5, base_lr=1e-4, skip_list=(), get_num_layer=None, get_layer_scale=None, **kwargs):
150
+ parameter_group_names = {}
151
+ parameter_group_vars = {}
152
+
153
+ for name, param in model.named_parameters():
154
+ if not param.requires_grad:
155
+ continue # frozen weights
156
+ if len(kwargs.get('filter_name', [])) > 0:
157
+ flag = False
158
+ for filter_n in kwargs.get('filter_name', []):
159
+ if filter_n in name:
160
+ print(f"filter {name} because of the pattern {filter_n}")
161
+ flag = True
162
+ if flag:
163
+ continue
164
+
165
+ default_scale=1.
166
+
167
+ if param.ndim <= 1 or name.endswith(".bias") or name in skip_list: # param.ndim <= 1 len(param.shape) == 1
168
+ group_name = "no_decay"
169
+ this_weight_decay = 0.
170
+ else:
171
+ group_name = "decay"
172
+ this_weight_decay = weight_decay
173
+
174
+ if get_num_layer is not None:
175
+ layer_id = get_num_layer(name)
176
+ group_name = "layer_%d_%s" % (layer_id, group_name)
177
+ else:
178
+ layer_id = None
179
+
180
+ if group_name not in parameter_group_names:
181
+ if get_layer_scale is not None:
182
+ scale = get_layer_scale(layer_id)
183
+ else:
184
+ scale = default_scale
185
+
186
+ parameter_group_names[group_name] = {
187
+ "weight_decay": this_weight_decay,
188
+ "params": [],
189
+ "lr": base_lr,
190
+ "lr_scale": scale,
191
+ }
192
+
193
+ parameter_group_vars[group_name] = {
194
+ "weight_decay": this_weight_decay,
195
+ "params": [],
196
+ "lr": base_lr,
197
+ "lr_scale": scale,
198
+ }
199
+
200
+ parameter_group_vars[group_name]["params"].append(param)
201
+ parameter_group_names[group_name]["params"].append(name)
202
+
203
+ print("Param groups = %s" % json.dumps(parameter_group_names, indent=2))
204
+ return list(parameter_group_vars.values())
205
+
206
+
207
+ def create_optimizer(args, model, get_num_layer=None, get_layer_scale=None, filter_bias_and_bn=True, skip_list=None, **kwargs):
208
+ opt_lower = args.opt.lower()
209
+ weight_decay = args.weight_decay
210
+
211
+ skip = {}
212
+ if skip_list is not None:
213
+ skip = skip_list
214
+ elif hasattr(model, 'no_weight_decay'):
215
+ skip = model.no_weight_decay()
216
+ print(f"Skip weight decay name marked in model: {skip}")
217
+ parameters = get_parameter_groups(model, weight_decay, args.lr, skip, get_num_layer, get_layer_scale, **kwargs)
218
+ weight_decay = 0.
219
+
220
+ if 'fused' in opt_lower:
221
+ assert has_apex and torch.cuda.is_available(), 'APEX and CUDA required for fused optimizers'
222
+
223
+ opt_args = dict(lr=args.lr, weight_decay=weight_decay)
224
+ if hasattr(args, 'opt_eps') and args.opt_eps is not None:
225
+ opt_args['eps'] = args.opt_eps
226
+ if hasattr(args, 'opt_beta1') and args.opt_beta1 is not None:
227
+ opt_args['betas'] = (args.opt_beta1, args.opt_beta2)
228
+
229
+ print('Optimizer config:', opt_args)
230
+ opt_split = opt_lower.split('_')
231
+ opt_lower = opt_split[-1]
232
+ if opt_lower == 'sgd' or opt_lower == 'nesterov':
233
+ opt_args.pop('eps', None)
234
+ optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=True, **opt_args)
235
+ elif opt_lower == 'momentum':
236
+ opt_args.pop('eps', None)
237
+ optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=False, **opt_args)
238
+ elif opt_lower == 'adam':
239
+ optimizer = optim.Adam(parameters, **opt_args)
240
+ elif opt_lower == 'adamw':
241
+ optimizer = optim.AdamW(parameters, **opt_args)
242
+ elif opt_lower == 'adadelta':
243
+ optimizer = optim.Adadelta(parameters, **opt_args)
244
+ elif opt_lower == 'rmsprop':
245
+ optimizer = optim.RMSprop(parameters, alpha=0.9, momentum=args.momentum, **opt_args)
246
+ else:
247
+ assert False and "Invalid optimizer"
248
+ raise ValueError
249
+
250
+ return optimizer
251
+
252
+
253
+ class SmoothedValue(object):
254
+ """Track a series of values and provide access to smoothed values over a
255
+ window or the global series average.
256
+ """
257
+
258
+ def __init__(self, window_size=20, fmt=None):
259
+ if fmt is None:
260
+ fmt = "{median:.4f} ({global_avg:.4f})"
261
+ self.deque = deque(maxlen=window_size)
262
+ self.total = 0.0
263
+ self.count = 0
264
+ self.fmt = fmt
265
+
266
+ def update(self, value, n=1):
267
+ self.deque.append(value)
268
+ self.count += n
269
+ self.total += value * n
270
+
271
+ def synchronize_between_processes(self):
272
+ """
273
+ Warning: does not synchronize the deque!
274
+ """
275
+ if not is_dist_avail_and_initialized():
276
+ return
277
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
278
+ dist.barrier()
279
+ dist.all_reduce(t)
280
+ t = t.tolist()
281
+ self.count = int(t[0])
282
+ self.total = t[1]
283
+
284
+ @property
285
+ def median(self):
286
+ d = torch.tensor(list(self.deque))
287
+ return d.median().item()
288
+
289
+ @property
290
+ def avg(self):
291
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
292
+ return d.mean().item()
293
+
294
+ @property
295
+ def global_avg(self):
296
+ return self.total / self.count
297
+
298
+ @property
299
+ def max(self):
300
+ return max(self.deque)
301
+
302
+ @property
303
+ def value(self):
304
+ return self.deque[-1]
305
+
306
+ def __str__(self):
307
+ return self.fmt.format(
308
+ median=self.median,
309
+ avg=self.avg,
310
+ global_avg=self.global_avg,
311
+ max=self.max,
312
+ value=self.value)
313
+
314
+
315
+ class MetricLogger(object):
316
+ def __init__(self, delimiter="\t"):
317
+ self.meters = defaultdict(SmoothedValue)
318
+ self.delimiter = delimiter
319
+
320
+ def update(self, **kwargs):
321
+ for k, v in kwargs.items():
322
+ if v is None:
323
+ continue
324
+ if isinstance(v, torch.Tensor):
325
+ v = v.item()
326
+ assert isinstance(v, (float, int))
327
+ self.meters[k].update(v)
328
+
329
+ def __getattr__(self, attr):
330
+ if attr in self.meters:
331
+ return self.meters[attr]
332
+ if attr in self.__dict__:
333
+ return self.__dict__[attr]
334
+ raise AttributeError("'{}' object has no attribute '{}'".format(
335
+ type(self).__name__, attr))
336
+
337
+ def __str__(self):
338
+ loss_str = []
339
+ for name, meter in self.meters.items():
340
+ loss_str.append(
341
+ "{}: {}".format(name, str(meter))
342
+ )
343
+ return self.delimiter.join(loss_str)
344
+
345
+ def synchronize_between_processes(self):
346
+ for meter in self.meters.values():
347
+ meter.synchronize_between_processes()
348
+
349
+ def add_meter(self, name, meter):
350
+ self.meters[name] = meter
351
+
352
+ def log_every(self, iterable, print_freq, header=None):
353
+ i = 0
354
+ if not header:
355
+ header = ''
356
+ start_time = time.time()
357
+ end = time.time()
358
+ iter_time = SmoothedValue(fmt='{avg:.4f}')
359
+ data_time = SmoothedValue(fmt='{avg:.4f}')
360
+ space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
361
+ log_msg = [
362
+ header,
363
+ '[{0' + space_fmt + '}/{1}]',
364
+ 'eta: {eta}',
365
+ '{meters}',
366
+ 'time: {time}',
367
+ 'data: {data}'
368
+ ]
369
+ if torch.cuda.is_available():
370
+ log_msg.append('max mem: {memory:.0f}')
371
+ log_msg = self.delimiter.join(log_msg)
372
+ MB = 1024.0 * 1024.0
373
+ for obj in iterable:
374
+ data_time.update(time.time() - end)
375
+ yield obj
376
+ iter_time.update(time.time() - end)
377
+ if i % print_freq == 0 or i == len(iterable) - 1:
378
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
379
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
380
+ if torch.cuda.is_available():
381
+ print(log_msg.format(
382
+ i, len(iterable), eta=eta_string,
383
+ meters=str(self),
384
+ time=str(iter_time), data=str(data_time),
385
+ memory=torch.cuda.max_memory_allocated() / MB))
386
+ else:
387
+ print(log_msg.format(
388
+ i, len(iterable), eta=eta_string,
389
+ meters=str(self),
390
+ time=str(iter_time), data=str(data_time)))
391
+ i += 1
392
+ end = time.time()
393
+ total_time = time.time() - start_time
394
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
395
+ print('{} Total time: {} ({:.4f} s / it)'.format(
396
+ header, total_time_str, total_time / len(iterable)))
397
+
398
+
399
+ def auto_load_model(args, model, model_without_ddp, optimizer, loss_scaler, model_ema=None, optimizer_disc=None):
400
+ output_dir = Path(args.output_dir)
401
+ if args.auto_resume and len(args.resume) == 0:
402
+ all_checkpoints = glob.glob(os.path.join(output_dir, 'checkpoint.pth'))
403
+ if len(all_checkpoints) > 0:
404
+ args.resume = os.path.join(output_dir, 'checkpoint.pth')
405
+ else:
406
+ all_checkpoints = glob.glob(os.path.join(output_dir, 'checkpoint-*.pth'))
407
+ latest_ckpt = -1
408
+ for ckpt in all_checkpoints:
409
+ t = ckpt.split('-')[-1].split('.')[0]
410
+ if t.isdigit():
411
+ latest_ckpt = max(int(t), latest_ckpt)
412
+ if latest_ckpt >= 0:
413
+ args.resume = os.path.join(output_dir, 'checkpoint-%d.pth' % latest_ckpt)
414
+ print("Auto resume checkpoint: %s" % args.resume)
415
+
416
+ if args.resume:
417
+ if args.resume.startswith('https'):
418
+ checkpoint = torch.hub.load_state_dict_from_url(
419
+ args.resume, map_location='cpu', check_hash=True)
420
+ else:
421
+ checkpoint = torch.load(args.resume, map_location='cpu')
422
+
423
+ model_without_ddp.load_state_dict(checkpoint['model']) # strict: bool=True, , strict=False
424
+ print("Resume checkpoint %s" % args.resume)
425
+
426
+ if ('optimizer' in checkpoint) and ('epoch' in checkpoint) and (optimizer is not None):
427
+ optimizer.load_state_dict(checkpoint['optimizer'])
428
+ print(f"Resume checkpoint at epoch {checkpoint['epoch']}, the global optmization step is {checkpoint['step']}")
429
+ args.start_epoch = checkpoint['epoch'] + 1
430
+ args.global_step = checkpoint['step'] + 1
431
+ if model_ema is not None:
432
+ if 'model_ema' in checkpoint:
433
+ ema_load_res = model_ema.load_state_dict(checkpoint["model_ema"])
434
+ print(f"EMA Model Resume results: {ema_load_res}")
435
+ if 'scaler' in checkpoint:
436
+ loss_scaler.load_state_dict(checkpoint['scaler'])
437
+ print("With optim & sched!")
438
+ if ('optimizer_disc' in checkpoint) and (optimizer_disc is not None):
439
+ optimizer_disc.load_state_dict(checkpoint['optimizer_disc'])
440
+
441
+
442
+ def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, model_ema=None, optimizer_disc=None, save_ckpt_freq=1):
443
+ output_dir = Path(args.output_dir)
444
+ epoch_name = str(epoch)
445
+
446
+ checkpoint_paths = [output_dir / 'checkpoint.pth']
447
+ if epoch == 'best':
448
+ checkpoint_paths = [output_dir / ('checkpoint-%s.pth' % epoch_name),]
449
+ elif (epoch + 1) % save_ckpt_freq == 0:
450
+ checkpoint_paths.append(output_dir / ('checkpoint-%s.pth' % epoch_name))
451
+
452
+ for checkpoint_path in checkpoint_paths:
453
+ to_save = {
454
+ 'model': model_without_ddp.state_dict(),
455
+ 'epoch': epoch,
456
+ 'step' : args.global_step,
457
+ 'args': args,
458
+ }
459
+
460
+ if optimizer is not None:
461
+ to_save['optimizer'] = optimizer.state_dict()
462
+
463
+ if loss_scaler is not None:
464
+ to_save['scaler'] = loss_scaler.state_dict()
465
+
466
+ if model_ema is not None:
467
+ to_save['model_ema'] = model_ema.state_dict()
468
+
469
+ if optimizer_disc is not None:
470
+ to_save['optimizer_disc'] = optimizer_disc.state_dict()
471
+
472
+ save_on_master(to_save, checkpoint_path)
473
+
474
+
475
+ def get_grad_norm_(parameters, norm_type: float = 2.0, layer_names=None) -> torch.Tensor:
476
+ if isinstance(parameters, torch.Tensor):
477
+ parameters = [parameters]
478
+
479
+ parameters = [p for p in parameters if p.grad is not None]
480
+
481
+ norm_type = float(norm_type)
482
+ if len(parameters) == 0:
483
+ return torch.tensor(0.)
484
+ device = parameters[0].grad.device
485
+
486
+ if norm_type == inf:
487
+ total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters)
488
+ else:
489
+ layer_norm = torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters])
490
+ total_norm = torch.norm(layer_norm, norm_type)
491
+
492
+ if layer_names is not None:
493
+ if torch.isnan(total_norm) or torch.isinf(total_norm) or total_norm > 1.0:
494
+ value_top, name_top = torch.topk(layer_norm, k=5)
495
+ print(f"Top norm value: {value_top}")
496
+ print(f"Top norm name: {[layer_names[i][7:] for i in name_top.tolist()]}")
497
+
498
+ return total_norm
499
+
500
+
501
+ class NativeScalerWithGradNormCount:
502
+ state_dict_key = "amp_scaler"
503
+
504
+ def __init__(self, enabled=True):
505
+ print(f"Set the loss scaled to {enabled}")
506
+ self._scaler = torch.cuda.amp.GradScaler(enabled=enabled)
507
+
508
+ def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True, layer_names=None):
509
+ self._scaler.scale(loss).backward(create_graph=create_graph)
510
+ if update_grad:
511
+ if clip_grad is not None:
512
+ assert parameters is not None
513
+ self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place
514
+ norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
515
+ else:
516
+ self._scaler.unscale_(optimizer)
517
+ norm = get_grad_norm_(parameters, layer_names=layer_names)
518
+ self._scaler.step(optimizer)
519
+ self._scaler.update()
520
+ else:
521
+ norm = None
522
+ return norm
523
+
524
+ def state_dict(self):
525
+ return self._scaler.state_dict()
526
+
527
+ def load_state_dict(self, state_dict):
528
+ self._scaler.load_state_dict(state_dict)
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/trainer_misc/vae_ddp_trainer.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import sys
3
+ from typing import Iterable
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from .utils import (
9
+ MetricLogger,
10
+ SmoothedValue,
11
+ )
12
+
13
+
14
+ def train_one_epoch(
15
+ model: torch.nn.Module,
16
+ model_dtype: str,
17
+ data_loader: Iterable,
18
+ optimizer: torch.optim.Optimizer,
19
+ optimizer_disc: torch.optim.Optimizer,
20
+ device: torch.device,
21
+ epoch: int,
22
+ loss_scaler,
23
+ loss_scaler_disc,
24
+ clip_grad: float = 0,
25
+ log_writer=None,
26
+ lr_scheduler=None,
27
+ start_steps=None,
28
+ lr_schedule_values=None,
29
+ lr_schedule_values_disc=None,
30
+ args=None,
31
+ print_freq=20,
32
+ iters_per_epoch=2000,
33
+ ):
34
+ # The trainer for causal video vae
35
+
36
+ model.train()
37
+ metric_logger = MetricLogger(delimiter=" ")
38
+
39
+ if optimizer is not None:
40
+ metric_logger.add_meter('lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
41
+ metric_logger.add_meter('min_lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
42
+
43
+ if optimizer_disc is not None:
44
+ metric_logger.add_meter('disc_lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
45
+ metric_logger.add_meter('disc_min_lr', SmoothedValue(window_size=1, fmt='{value:.6f}'))
46
+
47
+ header = 'Epoch: [{}]'.format(epoch)
48
+
49
+ if model_dtype == 'bf16':
50
+ _dtype = torch.bfloat16
51
+ else:
52
+ _dtype = torch.float16
53
+
54
+ print("Start training epoch {}, {} iters per inner epoch.".format(epoch, iters_per_epoch))
55
+
56
+ for step in metric_logger.log_every(range(iters_per_epoch), print_freq, header):
57
+ if step >= iters_per_epoch:
58
+ break
59
+
60
+ it = start_steps + step # global training iteration
61
+ if lr_schedule_values is not None:
62
+ for i, param_group in enumerate(optimizer.param_groups):
63
+ if lr_schedule_values is not None:
64
+ param_group["lr"] = lr_schedule_values[it] * param_group.get("lr_scale", 1.0)
65
+
66
+ if optimizer_disc is not None:
67
+ for i, param_group in enumerate(optimizer_disc.param_groups):
68
+ if lr_schedule_values_disc is not None:
69
+ param_group["lr"] = lr_schedule_values_disc[it] * param_group.get("lr_scale", 1.0)
70
+
71
+ samples = next(data_loader)
72
+
73
+ samples['video'] = samples['video'].to(device, non_blocking=True)
74
+
75
+ with torch.cuda.amp.autocast(enabled=True, dtype=_dtype):
76
+ rec_loss, gan_loss, log_loss = model(samples['video'], args.global_step, identifier=samples['identifier'])
77
+
78
+ ###################################################################################################
79
+ # The update of rec_loss
80
+ if rec_loss is not None:
81
+ loss_value = rec_loss.item()
82
+
83
+ if not math.isfinite(loss_value):
84
+ print("Loss is {}, stopping training".format(loss_value), force=True)
85
+ sys.exit(1)
86
+
87
+ optimizer.zero_grad()
88
+ is_second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order
89
+ grad_norm = loss_scaler(rec_loss, optimizer, clip_grad=clip_grad,
90
+ parameters=model.module.vae.parameters(), create_graph=is_second_order)
91
+
92
+ if "scale" in loss_scaler.state_dict():
93
+ loss_scale_value = loss_scaler.state_dict()["scale"]
94
+ else:
95
+ loss_scale_value = 1
96
+
97
+ metric_logger.update(vae_loss=loss_value)
98
+ metric_logger.update(loss_scale=loss_scale_value)
99
+
100
+ ###################################################################################################
101
+
102
+ # The updaet of gan_loss
103
+ if gan_loss is not None:
104
+ gan_loss_value = gan_loss.item()
105
+
106
+ if not math.isfinite(gan_loss_value):
107
+ print("The gan discriminator Loss is {}, stopping training".format(gan_loss_value), force=True)
108
+ sys.exit(1)
109
+
110
+ optimizer_disc.zero_grad()
111
+ is_second_order = hasattr(optimizer_disc, 'is_second_order') and optimizer_disc.is_second_order
112
+ disc_grad_norm = loss_scaler_disc(gan_loss, optimizer_disc, clip_grad=clip_grad,
113
+ parameters=model.module.loss.discriminator.parameters(), create_graph=is_second_order)
114
+
115
+ if "scale" in loss_scaler_disc.state_dict():
116
+ disc_loss_scale_value = loss_scaler_disc.state_dict()["scale"]
117
+ else:
118
+ disc_loss_scale_value = 1
119
+
120
+ metric_logger.update(disc_loss=gan_loss_value)
121
+ metric_logger.update(disc_loss_scale=disc_loss_scale_value)
122
+ metric_logger.update(disc_grad_norm=disc_grad_norm)
123
+
124
+ min_lr = 10.
125
+ max_lr = 0.
126
+ for group in optimizer_disc.param_groups:
127
+ min_lr = min(min_lr, group["lr"])
128
+ max_lr = max(max_lr, group["lr"])
129
+
130
+ metric_logger.update(disc_lr=max_lr)
131
+ metric_logger.update(disc_min_lr=min_lr)
132
+
133
+ torch.cuda.synchronize()
134
+ new_log_loss = {k.split('/')[-1]:v for k, v in log_loss.items() if k not in ['total_loss']}
135
+ metric_logger.update(**new_log_loss)
136
+
137
+ if rec_loss is not None:
138
+ min_lr = 10.
139
+ max_lr = 0.
140
+ for group in optimizer.param_groups:
141
+ min_lr = min(min_lr, group["lr"])
142
+ max_lr = max(max_lr, group["lr"])
143
+
144
+ metric_logger.update(lr=max_lr)
145
+ metric_logger.update(min_lr=min_lr)
146
+ weight_decay_value = None
147
+ for group in optimizer.param_groups:
148
+ if group["weight_decay"] > 0:
149
+ weight_decay_value = group["weight_decay"]
150
+ metric_logger.update(weight_decay=weight_decay_value)
151
+ metric_logger.update(grad_norm=grad_norm)
152
+
153
+ if log_writer is not None:
154
+ log_writer.update(**new_log_loss, head="train/loss")
155
+ log_writer.update(lr=max_lr, head="opt")
156
+ log_writer.update(min_lr=min_lr, head="opt")
157
+ log_writer.update(weight_decay=weight_decay_value, head="opt")
158
+ log_writer.update(grad_norm=grad_norm, head="opt")
159
+
160
+ log_writer.set_step()
161
+
162
+ if lr_scheduler is not None:
163
+ lr_scheduler.step_update(start_steps + step)
164
+
165
+ args.global_step = args.global_step + 1
166
+
167
+ # gather the stats from all processes
168
+ metric_logger.synchronize_between_processes()
169
+ print("Averaged stats:", metric_logger)
170
+
171
+ return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utilities/guidance_utils.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ from math import sqrt
4
+ from utilities.utils import isinstance_str
5
+ from pathlib import Path
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from einops import rearrange
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+
13
+ def plot_attention_weight(x, y, timestep=None, save_path=None):
14
+ x = x.clone().detach().cpu().numpy()
15
+ y = y.clone().detach().cpu().numpy()
16
+
17
+ fig, axes = plt.subplots(1, 2, figsize=(10, 5))
18
+ axes[0].imshow(x, cmap='viridis')
19
+ axes[0].set_title('Reconstructed attention weight')
20
+ axes[0].axis('off')
21
+ axes[1].imshow(y, cmap='viridis')
22
+ axes[1].set_title('Editing attention weight')
23
+ axes[1].axis('off')
24
+
25
+ plt.tight_layout()
26
+ assert save_path is not None
27
+ Path(save_path).mkdir(parents=True, exist_ok=True)
28
+ plt.savefig(os.path.join(save_path, f"{int(timestep)}.jpg"))
29
+ plt.clf()
30
+
31
+ @torch.autocast(device_type="cuda", dtype=torch.float32)
32
+ def calculate_losses(orig_features, target_features, config, timestep, groups=32):
33
+ if config["motion_guidance_type"] == "features_diff_dmt":
34
+ return calculate_losses_feature(orig_features, target_features, config, timestep, groups)
35
+ elif config["motion_guidance_type"] == "text_to_obj_activation":
36
+ return calculate_losses_attention(orig_features, target_features, config, timestep, groups)
37
+ else:
38
+ raise NotImplementedError
39
+
40
+ @torch.autocast(device_type="cuda", dtype=torch.float32)
41
+ def calculate_losses_attention(orig_attn_weights, target_attn_weights, config, timestep, groups=32):
42
+ # orig_attn_weights: t, h, w
43
+
44
+ if config["plot_attn_path"]:
45
+ save_path = config["attn_path"]
46
+ plot_attention_weight(orig_attn_weights[0], target_attn_weights[0], timestep, save_path)
47
+
48
+ epsilon = 1e-5
49
+ total_loss = 0
50
+ losses = {}
51
+ if config["attention_l2_weight"] > 0:
52
+ # L1 or L2 loss from mask segmentation
53
+ # loss_fn = nn.SmoothL1Loss()
54
+ loss_fn = nn.MSELoss()
55
+ loss_l2 = loss_fn(orig_attn_weights, target_attn_weights)
56
+ losses["attention_mse_loss"] = loss_l2
57
+ total_loss += loss_l2 * config["attention_l2_weight"]
58
+ print(loss_l2)
59
+
60
+ if config["attention_dice_weight"] > 0:
61
+ # DICE loss from mask segmentation
62
+ intersection = torch.sum(orig_attn_weights * target_attn_weights)
63
+ union = torch.sum(orig_attn_weights) + torch.sum(orig_attn_weights)
64
+ print(intersection, union)
65
+ dice_coeff = (2. * intersection + epsilon) / (union + epsilon)
66
+ loss_dice = 1 - dice_coeff
67
+ losses["attention_dice_loss"] = loss_dice
68
+ total_loss += loss_dice * config["attention_dice_weight"]
69
+
70
+ if config["attention_wass_weight"] > 0:
71
+ loss_wass = energy_based_attention_loss(
72
+ orig_attn_weights,
73
+ target_attn_weights,
74
+ epsilon=epsilon,
75
+ sinkhorn_iter=15
76
+ )
77
+ losses["attention_wass_loss"] = loss_wass
78
+ total_loss += loss_wass * config["attention_wass_weight"]
79
+ print(f'Energy-based attention loss: {loss_wass.item()}')
80
+
81
+ losses["total_loss"] = total_loss
82
+
83
+ return losses
84
+
85
+ def energy_based_attention_loss(attention_weights_x, attention_weights_y, epsilon=1e-5, sinkhorn_iter=20):
86
+ """
87
+ Computes an entropy-regularized Wasserstein distance loss for 2D attention weights.
88
+ Args:
89
+ attention_weights_x (torch.Tensor): 2D attention weights of shape (batch_size, n).
90
+ epsilon (float): Entropy regularization parameter for stability.
91
+ sinkhorn_iter (int): Number of iterations for Sinkhorn-Knopp algorithm.
92
+
93
+ Returns:
94
+ torch.Tensor: Computed Wasserstein distance loss with entropy regularization.
95
+ """
96
+ batch_size, n = attention_weights_x.shape
97
+ loss = 0.0
98
+
99
+ # For simplicity, we will compute pairwise Wasserstein distance between attention weights
100
+ for i in range(batch_size):
101
+ # Get the pairwise cost matrix based on the squared difference
102
+ P = attention_weights_x[i] + epsilon # Add epsilon to avoid log(0)
103
+ Q = attention_weights_x[i] + epsilon
104
+
105
+ # Compute pairwise cost (euclidean distance)
106
+ C = torch.abs(P.unsqueeze(0) - Q.unsqueeze(1)) # Shape: (n, n)
107
+
108
+ # Initialize dual variables (u, v) for Sinkhorn
109
+ u = torch.ones(n, 1, device=attention_weights_x.device)
110
+ v = torch.ones(1, n, device=attention_weights_x.device)
111
+
112
+ # Sinkhorn iterations
113
+ for _ in range(sinkhorn_iter):
114
+ u = 1.0 / (C @ v)
115
+ v = 1.0 / (C.transpose(0, 1) @ u)
116
+
117
+ # Optimal transport plan and the Wasserstein distance
118
+ T = u * C * v
119
+ wasserstein_dist = torch.sum(T * C)
120
+
121
+ # Accumulate the loss
122
+ loss += wasserstein_dist.mean()
123
+
124
+ return loss
125
+
126
+ @torch.autocast(device_type="cuda", dtype=torch.float32)
127
+ def calculate_losses_feature(orig_features, target_features, config, timestep, groups=32):
128
+ orig = orig_features
129
+ target = target_features
130
+
131
+ orig = orig.detach()
132
+
133
+ total_loss = 0
134
+ losses = {}
135
+ if len(orig) == 1:
136
+ config["features_loss_weight"] = 1
137
+ config["features_diff_loss_weight"] = 0
138
+ if config["features_loss_weight"] > 0:
139
+ if config["global_averaging"]:
140
+ orig = orig.mean(dim=(2, 3), keepdim=True)
141
+ target = target.mean(dim=(2, 3), keepdim=True)
142
+
143
+ features_loss = compute_feature_loss(orig, target, groups)
144
+ total_loss += config["features_loss_weight"] * features_loss
145
+ losses["features_mse_loss"] = features_loss
146
+
147
+ if config["features_diff_loss_weight"] > 0 and len(orig) > 1:
148
+ features_diff_loss = 0
149
+ orig = orig.mean(dim=(2, 3), keepdim=True) # t d 1 1
150
+ target = target.mean(dim=(2, 3), keepdim=True)
151
+
152
+ for i in range(len(orig)):
153
+ orig_anchor = orig[i]
154
+ target_anchor = target[i]
155
+ orig_diffs = orig - orig_anchor # t d 1 1
156
+ target_diffs = target - target_anchor # t d 1 1
157
+ t, d, h, w = orig_diffs.shape
158
+ if groups > 0 and (d%groups) == 0:
159
+ orig_diffs = orig_diffs.reshape(t, -1,groups,h,w)
160
+ target_diffs = target_diffs.reshape(t, -1,groups,h,w)
161
+ features_diff_loss += 1 - F.cosine_similarity(target_diffs, orig_diffs.detach(), dim=1).mean()
162
+ features_diff_loss /= len(orig)
163
+
164
+ total_loss += config["features_diff_loss_weight"] * features_diff_loss
165
+ losses["features_diff_loss"] = features_diff_loss
166
+
167
+ losses["total_loss"] = total_loss
168
+ return losses
169
+
170
+
171
+ def compute_feature_loss(orig, target, groups=32):
172
+ features_loss = 0
173
+ for i, (orig_frame, target_frame) in enumerate(zip(orig, target)):
174
+ d, h, w = orig_frame.shape
175
+ if groups > 0 and (d % groups) == 0:
176
+ orig_frame = orig_frame.contiguous().reshape(-1,groups,h,w)
177
+ target_frame = target_frame.contiguous().reshape(-1,groups,h,w)
178
+ features_loss += 1 - F.cosine_similarity(target_frame, orig_frame.detach(), dim=0).mean()
179
+ features_loss /= len(orig)
180
+ return features_loss
181
+
182
+
183
+ def register_time(model, t):
184
+ for _, module in model.dit.named_modules():
185
+ if isinstance_str(module, ["ModuleWithGuidance", "ModuleWithConvGuidance"]):
186
+ setattr(module, "t", t)
187
+
188
+ def register_frame_index(model, frame_index):
189
+ for _, module in model.dit.named_modules():
190
+ if isinstance_str(module, ["ModuleWithGuidance", "ModuleWithConvGuidance"]):
191
+ setattr(module, "frame_index", frame_index)
192
+
193
+ def register_batch(model, b):
194
+ for _, module in model.dit.named_modules():
195
+ if isinstance_str(module, ["ModuleWithGuidance", "ModuleWithConvGuidance"]):
196
+ setattr(module, "b", b)
197
+
198
+ def register_obj_text_start_end_index(model, src_start_index, src_end_index, tgt_start_index, tgt_end_index):
199
+ for _, module in model.dit.named_modules():
200
+ if isinstance_str(module, ["ModuleWithGuidance", "ModuleWithConvGuidance"]):
201
+ setattr(module, "src_obj_text_start_index", src_start_index)
202
+ setattr(module, "src_obj_text_end_index", src_end_index)
203
+ setattr(module, "tgt_obj_text_start_index", tgt_start_index)
204
+ setattr(module, "tgt_obj_text_end_index", tgt_end_index)
205
+
206
+ def register_is_src(model, is_src):
207
+ for _, module in model.dit.named_modules():
208
+ if isinstance_str(module, ["ModuleWithGuidance", "ModuleWithConvGuidance"]):
209
+ setattr(module, "is_src", is_src)
210
+
211
+ def register_opt_step(model, i):
212
+ for _, module in model.dit.named_modules():
213
+ if isinstance_str(module, ["ModuleWithGuidance", "ModuleWithConvGuidance"]):
214
+ setattr(module, "opt_step", i)
215
+
216
+ def register_is_guidance(model, is_guidance):
217
+ for _, module in model.dit.named_modules():
218
+ if isinstance_str(module, ["ModuleWithGuidance", "ModuleWithConvGuidance"]):
219
+ setattr(module, "is_guidance", is_guidance)
220
+
221
+ def register_guidance(model):
222
+ guidance_start_timestep = model.guidance_start_timestep
223
+ guidance_stop_timestep = model.guidance_stop_timestep
224
+ num_frames = model.input_frames_latent_ms[0].shape[-3]
225
+ stages = model.stages
226
+ h_ms = [x_.shape[-2] for x_ in model.input_frames_latent_ms]
227
+ w_ms = [x_.shape[-1] for x_ in model.input_frames_latent_ms]
228
+ len_text_encoder = 128
229
+
230
+ class ModuleWithConvGuidance(torch.nn.Module):
231
+ def __init__(self, module, guidance_start_timestep, guidance_stop_timestep, num_frames, h, w, len_text_encoder, block_name, config, module_type):
232
+ super().__init__()
233
+ self.module = module
234
+ self.guidance_start_timestep = guidance_start_timestep
235
+ self.guidance_stop_timestep = guidance_stop_timestep
236
+ self.num_frames = num_frames
237
+ assert module_type in [
238
+ "spatial_convolution",
239
+ ]
240
+ self.module_type = module_type
241
+ if self.module_type == "spatial_convolution":
242
+ self.starting_shape = "(b t) d h w"
243
+ self.h = h
244
+ self.w = w
245
+ self.len_text_encoder = len_text_encoder
246
+ self.block_name = block_name
247
+ self.config = config
248
+ self.saved_features = None
249
+
250
+ def forward(self, input_tensor, temb):
251
+ hidden_states = input_tensor
252
+
253
+ hidden_states = self.module.norm1(hidden_states)
254
+ hidden_states = self.module.nonlinearity(hidden_states)
255
+
256
+ if self.module.upsample is not None:
257
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
258
+ if hidden_states.shape[0] >= 64:
259
+ input_tensor = input_tensor.contiguous()
260
+ hidden_states = hidden_states.contiguous()
261
+ input_tensor = self.module.upsample(input_tensor)
262
+ hidden_states = self.upsample(hidden_states)
263
+ elif self.module.downsample is not None:
264
+ input_tensor = self.module.downsample(input_tensor)
265
+ hidden_states = self.module.downsample(hidden_states)
266
+
267
+ hidden_states = self.module.conv1(hidden_states)
268
+
269
+ if temb is not None:
270
+ temb = self.module.time_emb_proj(self.module.nonlinearity(temb))[:, :, None, None]
271
+
272
+ if temb is not None and self.module.time_embedding_norm == "default":
273
+ hidden_states = hidden_states + temb
274
+
275
+ hidden_states = self.module.norm2(hidden_states)
276
+
277
+ if temb is not None and self.module.time_embedding_norm == "scale_shift":
278
+ scale, shift = torch.chunk(temb, 2, dim=1)
279
+ hidden_states = hidden_states * (1 + scale) + shift
280
+
281
+ hidden_states = self.module.nonlinearity(hidden_states)
282
+
283
+ hidden_states = self.module.dropout(hidden_states)
284
+ hidden_states = self.module.conv2(hidden_states)
285
+
286
+ if self.config["guidance_before_res"] and (self.guidance_start_timestep <= self.t <= self.guidance_stop_timestep):
287
+ self.saved_features = rearrange(
288
+ hidden_states, f"{self.starting_shape} -> b t d h w", t=self.num_frames
289
+ )
290
+
291
+ if self.module.conv_shortcut is not None:
292
+ input_tensor = self.module.conv_shortcut(input_tensor)
293
+
294
+ output_tensor = (input_tensor + hidden_states) / self.module.output_scale_factor
295
+
296
+ if not self.config["guidance_before_res"] and (self.guidance_start_timestep <= self.t <= self.guidance_stop_timestep):
297
+ self.saved_features = rearrange(
298
+ output_tensor, f"{self.starting_shape} -> b t d h w", t=self.num_frames
299
+ )
300
+
301
+ return output_tensor
302
+
303
+ class ModuleWithGuidance(torch.nn.Module):
304
+ def __init__(self, module, guidance_start_timestep, guidance_stop_timestep, \
305
+ num_frames, h_ms, w_ms, len_text_encoder, stages, block_name, config, module_type):
306
+ super().__init__()
307
+ self.module = module
308
+ self.guidance_start_timestep = guidance_start_timestep
309
+ self.guidance_stop_timestep = guidance_stop_timestep
310
+ self.num_frames = num_frames
311
+ assert module_type in [
312
+ "temporal_attention",
313
+ "spatial_attention",
314
+ "temporal_convolution",
315
+ "upsampler",
316
+ "linear",
317
+ ]
318
+ self.module_type = module_type
319
+ if self.module_type == "temporal_attention":
320
+ self.starting_shape = "(b h w) t d"
321
+ elif self.module_type == "spatial_attention":
322
+ self.starting_shape = "(b t) (h w) d"
323
+ elif self.module_type == "temporal_convolution":
324
+ self.starting_shape = "(b t) d h w"
325
+ elif self.module_type == "upsampler":
326
+ self.starting_shape = "(b t) d h w"
327
+ elif self.module_type == "linear":
328
+ self.starting_shape = "b (t h w) d"
329
+ self.h_ms = h_ms
330
+ self.w_ms = w_ms
331
+ self.len_text_encoder = len_text_encoder
332
+ self.stages = stages
333
+ self.block_name = block_name
334
+ self.config = config
335
+
336
+ def get_attention_weights(self, x, num_groups=4):
337
+ batch_size, sequence_length, dimension = x.shape
338
+ group_dim = dimension // num_groups
339
+
340
+ x_grouped = x.view(batch_size, sequence_length, group_dim, num_groups)
341
+ x_grouped = x_grouped.permute(0, 3, 1, 2).flatten(0, 1)
342
+
343
+ scores = torch.bmm(x_grouped, x_grouped.transpose(1, 2))
344
+ scores = scores / math.sqrt(group_dim)
345
+
346
+ scores = scores.view(batch_size, num_groups, sequence_length, sequence_length)
347
+ scores = scores.mean(dim=1)
348
+
349
+ return scores
350
+
351
+ def plot_attention_weights(self, x_in, shape_frames):
352
+ save_path = os.path.join(
353
+ self.config["attn_path"],
354
+ self.block_name,
355
+ f"frame{self.frame_index}",
356
+ f"timestep{int(self.t)}"
357
+ )
358
+ Path(save_path).mkdir(parents=True, exist_ok=True)
359
+
360
+ x = x_in.clone().detach().float()
361
+ len_frames = [self.len_text_encoder] + [shape_[0]*shape_[1] for shape_ in shape_frames]
362
+ x_frames = torch.split(x, len_frames)
363
+
364
+ t2t = x_frames[0].cpu().numpy()
365
+ plt.figure(figsize=(3, 3))
366
+ plt.imshow(t2t, cmap='viridis')
367
+ plt.title("Attention Map")
368
+ plt.axis("off")
369
+ if self.is_src:
370
+ save_path_ = os.path.join(save_path, f"t2v_src.jpg")
371
+ else:
372
+ save_path_ = os.path.join(save_path, f"t2v_tgt_opt{self.opt_step}.jpg")
373
+ plt.savefig(save_path_, bbox_inches="tight", dpi=300)
374
+ plt.clf()
375
+
376
+ for idx, (frame, hw) in enumerate(zip(x_frames[1:], shape_frames)):
377
+ if self.is_src:
378
+ frame = frame[:,self.src_obj_text_start_index:self.src_obj_text_end_index].mean(-1)
379
+ else:
380
+ frame = frame[:,self.tgt_obj_text_start_index:self.tgt_obj_text_end_index].mean(-1)
381
+ frame = frame.reshape(hw[0], hw[1]).cpu().numpy()
382
+
383
+ plt.figure(figsize=(3, 5))
384
+ plt.imshow(frame, cmap='viridis')
385
+ plt.title("Attention Map")
386
+ plt.axis("off")
387
+
388
+ if self.is_src:
389
+ save_path_ = os.path.join(save_path, f"past_cond{idx}_src.jpg")
390
+ else:
391
+ save_path_ = os.path.join(save_path, f"past_cond{idx}_tgt_opt{self.opt_step}.jpg")
392
+ plt.savefig(save_path_, bbox_inches="tight", dpi=300)
393
+ plt.clf()
394
+
395
+ def plot_attention_weights_all(self, x):
396
+ save_path = os.path.join(
397
+ self.config["attn_path"],
398
+ self.block_name,
399
+ f"frame{self.frame_index}",
400
+ f"timestep{int(self.t)}"
401
+ )
402
+ Path(save_path).mkdir(parents=True, exist_ok=True)
403
+
404
+ x_in = x.clone().detach().float().cpu().numpy()
405
+ plt.figure(figsize=(3, 3))
406
+ plt.imshow(x_in, cmap='viridis')
407
+ plt.title("Attention Map")
408
+ plt.axis("off")
409
+
410
+ if self.is_src:
411
+ save_path_ = os.path.join(save_path, f"all_src.jpg")
412
+ else:
413
+ save_path_ = os.path.join(save_path, f"all_tgt_opt{self.opt_step}.jpg")
414
+ plt.savefig(save_path_, bbox_inches="tight", dpi=300)
415
+ plt.clf()
416
+
417
+ def forward(self, x, *args, **kwargs):
418
+ if not isinstance(args, tuple):
419
+ args = (args,)
420
+ out = self.module(x, *args, **kwargs)
421
+ num_frames = self.num_frames
422
+ if self.module_type == "temporal_attention":
423
+ size = out.shape[0] // self.b
424
+ elif self.module_type == "spatial_attention":
425
+ size = out.shape[1]
426
+ elif self.module_type == "temporal_convolution":
427
+ size = out.shape[2] * out.shape[3]
428
+ elif self.module_type == "upsampler":
429
+ size = out.shape[2] * out.shape[3]
430
+ elif self.module_type == "linear":
431
+ size = out.shape[1]
432
+ num_frames = 1
433
+
434
+ if self.is_guidance and self.guidance_start_timestep <= self.t <= self.guidance_stop_timestep:
435
+ if self.module_type == "linear":
436
+ size = None
437
+
438
+ len_latent_stages = []
439
+ shape_latent_stages = []
440
+ past_frame = min(self.frame_index, len(self.stages)-1)
441
+ for i_s in range(len(self.stages)):
442
+ # low_res * past frames
443
+ len_latent_stage = [
444
+ self.h_ms[0] * self.w_ms[0] // 4
445
+ for _ in range(max(self.frame_index - len(self.stages) + 1, 0))
446
+ ]
447
+ shape_latent_stage = [
448
+ [self.h_ms[0]//2, self.w_ms[0]//2]
449
+ for _ in range(max(self.frame_index - len(self.stages) + 1, 0))
450
+ ]
451
+ len_latent_stage += [self.h_ms[i_s] * self.w_ms[i_s] // 4]
452
+ shape_latent_stage += [[self.h_ms[i_s]//2, self.w_ms[i_s]//2]]
453
+ for f_i in range(past_frame):
454
+ i_s_ = max(i_s-f_i, 0)
455
+ len_latent_stage += [self.h_ms[i_s_] * self.w_ms[i_s_] // 4]
456
+ shape_latent_stage.append([self.h_ms[i_s_]//2, self.w_ms[i_s_]//2])
457
+ len_latent_stages.append(sum(len_latent_stage)) # mmdit [d, h, w] -> [4d, h//2, w//2]
458
+ shape_latent_stages.append(list(reversed(shape_latent_stage)))
459
+
460
+ for i_s, len_latent_stage in enumerate(len_latent_stages):
461
+ if (out.shape[1] - self.len_text_encoder) == len_latent_stage:
462
+ size = self.h_ms[i_s] * self.w_ms[i_s] // 4
463
+ break
464
+ assert size is not None
465
+
466
+ h, w = int(sqrt(size * self.h_ms[i_s] / self.w_ms[i_s])), int(sqrt(size * self.h_ms[i_s] / self.w_ms[i_s]) * self.w_ms[i_s] / self.h_ms[i_s])
467
+ # last frame in autoregressive model
468
+ if self.module_type == "linear":
469
+ if self.config["motion_guidance_type"] == "features_diff_dmt":
470
+ if self.frame_index == 0:
471
+ self.saved_features = rearrange(
472
+ out[:, -size:], f"{self.starting_shape} -> b t d h w", t=num_frames, h=h, w=w
473
+ )
474
+ else:
475
+ self.saved_features = rearrange(
476
+ out[:, -size:] - out[:, -2*size:-size], f"{self.starting_shape} -> b t d h w", t=num_frames, h=h, w=w
477
+ )
478
+ elif self.config["motion_guidance_type"] == "text_to_obj_activation":
479
+ attn_weight = self.get_attention_weights(out) # b, l, l
480
+
481
+ attn_type = 'all' # 'obj_to_vis'
482
+ if attn_type == 'obj_to_vis':
483
+ self.plot_attention_weights(
484
+ attn_weight[0,:,:self.len_text_encoder],
485
+ shape_latent_stages[i_s]
486
+ )
487
+
488
+ attn_weight = attn_weight.softmax(dim=-1) # b, l, l
489
+ attn_weight_v2t = attn_weight[:,:,:self.len_text_encoder]
490
+ if self.is_src:
491
+ src_weight = rearrange(
492
+ attn_weight_v2t[:, -size:, self.src_obj_text_start_index:self.src_obj_text_end_index],
493
+ 'b (h w) l -> b h w l', h=h, w=w,
494
+ ).mean(-1)
495
+ self.saved_features = src_weight.unsqueeze(1) # b, t, h, w
496
+ else:
497
+ tgt_weight = rearrange(
498
+ attn_weight_v2t[:, -size:, self.tgt_obj_text_start_index:self.tgt_obj_text_end_index],
499
+ 'b (h w) l -> b h w l', h=h, w=w,
500
+ ).mean(-1)
501
+ self.saved_features = tgt_weight.unsqueeze(1) # b, t, h, w
502
+ else:
503
+ self.plot_attention_weights_all(attn_weight[0])
504
+
505
+ attn_weight = attn_weight.softmax(dim=-1) # b, l, l
506
+ self.saved_features = attn_weight[:, -size:].unsqueeze(1) # b, t, hw, l
507
+
508
+ else:
509
+ self.saved_features = rearrange(
510
+ out, f"{self.starting_shape} -> b t d h w", t=num_frames, h=h, w=w
511
+ )
512
+
513
+ return out
514
+
515
+ single_transformer_list = model.config["single_transformer_list"]
516
+ assert len(single_transformer_list) == 1
517
+ for key, indexes in single_transformer_list.items():
518
+ for idx in indexes:
519
+ module = model.dit.single_transformer_blocks[idx]
520
+ # FluxSingleTransformerBlock(
521
+ # (norm): AdaLayerNormZeroSingle(
522
+ # (silu): SiLU()
523
+ # (linear): Linear(in_features=1920, out_features=5760, bias=True)
524
+ # (norm): LayerNorm((1920,), eps=1e-06, elementwise_affine=False)
525
+ # )
526
+ # (proj_mlp): Linear(in_features=1920, out_features=7680, bias=True)
527
+ # (act_mlp): GELU(approximate='tanh')
528
+ # (proj_out): Linear(in_features=9600, out_features=1920, bias=True)
529
+ # (attn): Attention(
530
+ # (norm_q): RMSNorm()
531
+ # (norm_k): RMSNorm()
532
+ # (to_q): Linear(in_features=1920, out_features=1920, bias=True)
533
+ # (to_k): Linear(in_features=1920, out_features=1920, bias=True)
534
+ # (to_v): Linear(in_features=1920, out_features=1920, bias=True)
535
+ # )
536
+ # )
537
+ if model.config["use_proj_out_features"]:
538
+ submodule = module.proj_out
539
+ module.proj_out = ModuleWithGuidance(
540
+ submodule,
541
+ guidance_start_timestep,
542
+ guidance_stop_timestep,
543
+ num_frames,
544
+ h_ms,
545
+ w_ms,
546
+ len_text_encoder,
547
+ stages,
548
+ block_name=f"FluxSingleTransformerBlock{idx}_pro_out",
549
+ config=model.config,
550
+ module_type="linear",
551
+ )
552
+
553
+ if model.config["use_proj_mlp_features"]:
554
+ submodule = module.proj_mlp
555
+ module.proj_mlp = ModuleWithGuidance(
556
+ submodule,
557
+ guidance_start_timestep,
558
+ guidance_stop_timestep,
559
+ num_frames,
560
+ h_ms,
561
+ w_ms,
562
+ len_text_encoder,
563
+ stages,
564
+ block_name=f"FluxSingleTransformerBlock{idx}_proj_mlp",
565
+ config=model.config,
566
+ module_type="linear",
567
+ )
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utilities/initialize_latent.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+
4
+
5
+ def load_source_latents_t(i_s, t, latents_path, data_type='stage_end'):
6
+ frames = sorted([d for d in os.listdir(latents_path) if os.path.isdir(os.path.join(latents_path, d))])
7
+
8
+ # latent of all frames in step t
9
+ latents_all = []
10
+ latents_stage_end_all = []
11
+ for frame in frames:
12
+ if data_type != 'stage_end' and not frame.endswith("_reverted_latent_stage_end"):
13
+ latents_t_path = os.path.join(latents_path, f"{frame}/noisy_latents_stage{i_s}_timestep{t+1}.pt")
14
+ print(latents_t_path)
15
+ assert os.path.exists(latents_t_path), f"Missing latents at stage {i_s} t {t} path {latents_t_path}"
16
+ latents = torch.load(latents_t_path).float()
17
+ latents_all.append(latents)
18
+
19
+ if data_type == 'stage_end' and frame.endswith("_reverted_latent_stage_end"):
20
+ latents_t_path = os.path.join(latents_path, f"{frame}/noisy_latents_stage{i_s}.pt")
21
+ assert os.path.exists(latents_t_path), f"Missing latents at stage {i_s} path {latents_t_path}"
22
+ latents = torch.load(latents_t_path).float()
23
+ latents_stage_end_all.append(latents)
24
+
25
+ if data_type != 'stage_end':
26
+ return latents_all
27
+ else:
28
+ return latents_stage_end_all
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utilities/utils.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import random
3
+
4
+ import numpy as np
5
+ import torch
6
+ from typing import Union, List
7
+ from torchvision.io import write_video
8
+
9
+ video_codec = "libx264"
10
+ video_options = {
11
+ "crf": "17", # Constant Rate Factor (lower value = higher quality, 18 is a good balance)
12
+ "preset": "slow", # Encoding preset (e.g., ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow)
13
+ }
14
+
15
+ def save_video(video, path):
16
+ write_video(
17
+ path,
18
+ video,
19
+ fps=10,
20
+ video_codec=video_codec,
21
+ options=video_options,
22
+ )
23
+
24
+ def seed_everything(seed):
25
+ torch.manual_seed(seed)
26
+ torch.cuda.manual_seed(seed)
27
+ random.seed(seed)
28
+ np.random.seed(seed)
29
+
30
+
31
+ def clean_memory():
32
+ torch.cuda.empty_cache()
33
+ gc.collect()
34
+ torch.cuda.empty_cache()
35
+ gc.collect()
36
+
37
+
38
+ def isinstance_str(x: object, cls_name: Union[str, List[str]]):
39
+ """
40
+ Checks whether x has any class *named* cls_name in its ancestry.
41
+ Doesn't require access to the class's implementation.
42
+
43
+ Useful for patching!
44
+ """
45
+ if type(cls_name) == str:
46
+ for _cls in x.__class__.__mro__:
47
+ if _cls.__name__ == cls_name:
48
+ return True
49
+ else:
50
+ for _cls in x.__class__.__mro__:
51
+ if _cls.__name__ in cls_name:
52
+ return True
53
+ return False
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/utils.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import PIL.Image
4
+ import numpy as np
5
+ from torch import nn
6
+ import torch.distributed as dist
7
+ import timm.models.hub as timm_hub
8
+
9
+ """Modified from https://github.com/CompVis/taming-transformers.git"""
10
+
11
+ import hashlib
12
+ import requests
13
+ from tqdm import tqdm
14
+ try:
15
+ import piq
16
+ except:
17
+ pass
18
+
19
+ _CONTEXT_PARALLEL_GROUP = None
20
+ _CONTEXT_PARALLEL_SIZE = None
21
+
22
+
23
+ def is_dist_avail_and_initialized():
24
+ if not dist.is_available():
25
+ return False
26
+ if not dist.is_initialized():
27
+ return False
28
+ return True
29
+
30
+
31
+ def get_world_size():
32
+ if not is_dist_avail_and_initialized():
33
+ return 1
34
+ return dist.get_world_size()
35
+
36
+
37
+ def get_rank():
38
+ if not is_dist_avail_and_initialized():
39
+ return 0
40
+ return dist.get_rank()
41
+
42
+
43
+ def is_main_process():
44
+ return get_rank() == 0
45
+
46
+
47
+ def is_context_parallel_initialized():
48
+ if _CONTEXT_PARALLEL_GROUP is None:
49
+ return False
50
+ else:
51
+ return True
52
+
53
+
54
+ def set_context_parallel_group(size, group):
55
+ global _CONTEXT_PARALLEL_GROUP
56
+ global _CONTEXT_PARALLEL_SIZE
57
+ _CONTEXT_PARALLEL_GROUP = group
58
+ _CONTEXT_PARALLEL_SIZE = size
59
+
60
+
61
+ def initialize_context_parallel(context_parallel_size):
62
+ global _CONTEXT_PARALLEL_GROUP
63
+ global _CONTEXT_PARALLEL_SIZE
64
+
65
+ assert _CONTEXT_PARALLEL_GROUP is None, "context parallel group is already initialized"
66
+ _CONTEXT_PARALLEL_SIZE = context_parallel_size
67
+
68
+ rank = torch.distributed.get_rank()
69
+ world_size = torch.distributed.get_world_size()
70
+
71
+ for i in range(0, world_size, context_parallel_size):
72
+ ranks = range(i, i + context_parallel_size)
73
+ group = torch.distributed.new_group(ranks)
74
+ if rank in ranks:
75
+ _CONTEXT_PARALLEL_GROUP = group
76
+ break
77
+
78
+
79
+ def get_context_parallel_group():
80
+ assert _CONTEXT_PARALLEL_GROUP is not None, "context parallel group is not initialized"
81
+
82
+ return _CONTEXT_PARALLEL_GROUP
83
+
84
+
85
+ def get_context_parallel_world_size():
86
+ assert _CONTEXT_PARALLEL_SIZE is not None, "context parallel size is not initialized"
87
+
88
+ return _CONTEXT_PARALLEL_SIZE
89
+
90
+
91
+ def get_context_parallel_rank():
92
+ assert _CONTEXT_PARALLEL_SIZE is not None, "context parallel size is not initialized"
93
+
94
+ rank = get_rank()
95
+ cp_rank = rank % _CONTEXT_PARALLEL_SIZE
96
+ return cp_rank
97
+
98
+
99
+ def get_context_parallel_group_rank():
100
+ assert _CONTEXT_PARALLEL_SIZE is not None, "context parallel size is not initialized"
101
+
102
+ rank = get_rank()
103
+ cp_group_rank = rank // _CONTEXT_PARALLEL_SIZE
104
+
105
+ return cp_group_rank
106
+
107
+
108
+ def download_cached_file(url, check_hash=True, progress=False):
109
+ """
110
+ Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again.
111
+ If distributed, only the main process downloads the file, and the other processes wait for the file to be downloaded.
112
+ """
113
+
114
+ def get_cached_file_path():
115
+ # a hack to sync the file path across processes
116
+ parts = torch.hub.urlparse(url)
117
+ filename = os.path.basename(parts.path)
118
+ cached_file = os.path.join(timm_hub.get_cache_dir(), filename)
119
+
120
+ return cached_file
121
+
122
+ if is_main_process():
123
+ timm_hub.download_cached_file(url, check_hash, progress)
124
+
125
+ if is_dist_avail_and_initialized():
126
+ dist.barrier()
127
+
128
+ return get_cached_file_path()
129
+
130
+
131
+ def convert_weights_to_fp16(model: nn.Module):
132
+ """Convert applicable model parameters to fp16"""
133
+
134
+ def _convert_weights_to_fp16(l):
135
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d, nn.Linear)):
136
+ l.weight.data = l.weight.data.to(torch.float16)
137
+ if l.bias is not None:
138
+ l.bias.data = l.bias.data.to(torch.float16)
139
+
140
+ model.apply(_convert_weights_to_fp16)
141
+
142
+
143
+ def convert_weights_to_bf16(model: nn.Module):
144
+ """Convert applicable model parameters to fp16"""
145
+
146
+ def _convert_weights_to_bf16(l):
147
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d, nn.Linear)):
148
+ l.weight.data = l.weight.data.to(torch.bfloat16)
149
+ if l.bias is not None:
150
+ l.bias.data = l.bias.data.to(torch.bfloat16)
151
+
152
+ model.apply(_convert_weights_to_bf16)
153
+
154
+
155
+ def save_result(result, result_dir, filename, remove_duplicate="", save_format='json'):
156
+ import json
157
+ import jsonlines
158
+ print("Dump result")
159
+
160
+ # Make the temp dir for saving results
161
+ if not os.path.exists(result_dir):
162
+ if is_main_process():
163
+ os.makedirs(result_dir)
164
+ if is_dist_avail_and_initialized():
165
+ torch.distributed.barrier()
166
+
167
+ result_file = os.path.join(
168
+ result_dir, "%s_rank%d.json" % (filename, get_rank())
169
+ )
170
+
171
+ final_result_file = os.path.join(result_dir, f"{filename}.{save_format}")
172
+
173
+ json.dump(result, open(result_file, "w"))
174
+
175
+ if is_dist_avail_and_initialized():
176
+ torch.distributed.barrier()
177
+
178
+ if is_main_process():
179
+ # print("rank %d starts merging results." % get_rank())
180
+ # combine results from all processes
181
+ result = []
182
+
183
+ for rank in range(get_world_size()):
184
+ result_file = os.path.join(result_dir, "%s_rank%d.json" % (filename, rank))
185
+ res = json.load(open(result_file, "r"))
186
+ result += res
187
+
188
+ # print("Remove duplicate")
189
+ if remove_duplicate:
190
+ result_new = []
191
+ id_set = set()
192
+ for res in result:
193
+ if res[remove_duplicate] not in id_set:
194
+ id_set.add(res[remove_duplicate])
195
+ result_new.append(res)
196
+ result = result_new
197
+
198
+ if save_format == 'json':
199
+ json.dump(result, open(final_result_file, "w"))
200
+ else:
201
+ assert save_format == 'jsonl', "Only support json adn jsonl format"
202
+ with jsonlines.open(final_result_file, "w") as writer:
203
+ writer.write_all(result)
204
+
205
+ # print("result file saved to %s" % final_result_file)
206
+
207
+ return final_result_file
208
+
209
+
210
+ # resizing utils
211
+ # TODO: clean up later
212
+ def _resize_with_antialiasing(input, size, interpolation="bicubic", align_corners=True):
213
+ h, w = input.shape[-2:]
214
+ factors = (h / size[0], w / size[1])
215
+
216
+ # First, we have to determine sigma
217
+ # Taken from skimage: https://github.com/scikit-image/scikit-image/blob/v0.19.2/skimage/transform/_warps.py#L171
218
+ sigmas = (
219
+ max((factors[0] - 1.0) / 2.0, 0.001),
220
+ max((factors[1] - 1.0) / 2.0, 0.001),
221
+ )
222
+
223
+ # Now kernel size. Good results are for 3 sigma, but that is kind of slow. Pillow uses 1 sigma
224
+ # https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206
225
+ # But they do it in the 2 passes, which gives better results. Let's try 2 sigmas for now
226
+ ks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3))
227
+
228
+ # Make sure it is odd
229
+ if (ks[0] % 2) == 0:
230
+ ks = ks[0] + 1, ks[1]
231
+
232
+ if (ks[1] % 2) == 0:
233
+ ks = ks[0], ks[1] + 1
234
+
235
+ input = _gaussian_blur2d(input, ks, sigmas)
236
+
237
+ output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)
238
+ return output
239
+
240
+
241
+ def _compute_padding(kernel_size):
242
+ """Compute padding tuple."""
243
+ # 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)
244
+ # https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad
245
+ if len(kernel_size) < 2:
246
+ raise AssertionError(kernel_size)
247
+ computed = [k - 1 for k in kernel_size]
248
+
249
+ # for even kernels we need to do asymmetric padding :(
250
+ out_padding = 2 * len(kernel_size) * [0]
251
+
252
+ for i in range(len(kernel_size)):
253
+ computed_tmp = computed[-(i + 1)]
254
+
255
+ pad_front = computed_tmp // 2
256
+ pad_rear = computed_tmp - pad_front
257
+
258
+ out_padding[2 * i + 0] = pad_front
259
+ out_padding[2 * i + 1] = pad_rear
260
+
261
+ return out_padding
262
+
263
+
264
+ def _filter2d(input, kernel):
265
+ # prepare kernel
266
+ b, c, h, w = input.shape
267
+ tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
268
+
269
+ tmp_kernel = tmp_kernel.expand(-1, c, -1, -1)
270
+
271
+ height, width = tmp_kernel.shape[-2:]
272
+
273
+ padding_shape: list[int] = _compute_padding([height, width])
274
+ input = torch.nn.functional.pad(input, padding_shape, mode="reflect")
275
+
276
+ # kernel and input tensor reshape to align element-wise or batch-wise params
277
+ tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)
278
+ input = input.view(-1, tmp_kernel.size(0), input.size(-2), input.size(-1))
279
+
280
+ # convolve the tensor with the kernel.
281
+ output = torch.nn.functional.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
282
+
283
+ out = output.view(b, c, h, w)
284
+ return out
285
+
286
+
287
+ def _gaussian(window_size: int, sigma):
288
+ if isinstance(sigma, float):
289
+ sigma = torch.tensor([[sigma]])
290
+
291
+ batch_size = sigma.shape[0]
292
+
293
+ x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)
294
+
295
+ if window_size % 2 == 0:
296
+ x = x + 0.5
297
+
298
+ gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0)))
299
+
300
+ return gauss / gauss.sum(-1, keepdim=True)
301
+
302
+
303
+ def _gaussian_blur2d(input, kernel_size, sigma):
304
+ if isinstance(sigma, tuple):
305
+ sigma = torch.tensor([sigma], dtype=input.dtype)
306
+ else:
307
+ sigma = sigma.to(dtype=input.dtype)
308
+
309
+ ky, kx = int(kernel_size[0]), int(kernel_size[1])
310
+ bs = sigma.shape[0]
311
+ kernel_x = _gaussian(kx, sigma[:, 1].view(bs, 1))
312
+ kernel_y = _gaussian(ky, sigma[:, 0].view(bs, 1))
313
+ out_x = _filter2d(input, kernel_x[..., None, :])
314
+ out = _filter2d(out_x, kernel_y[..., None])
315
+
316
+ return out
317
+
318
+
319
+ URL_MAP = {
320
+ "vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"
321
+ }
322
+
323
+ CKPT_MAP = {
324
+ "vgg_lpips": "vgg.pth"
325
+ }
326
+
327
+ MD5_MAP = {
328
+ "vgg_lpips": "d507d7349b931f0638a25a48a722f98a"
329
+ }
330
+
331
+
332
+ def download(url, local_path, chunk_size=1024):
333
+ os.makedirs(os.path.split(local_path)[0], exist_ok=True)
334
+ with requests.get(url, stream=True) as r:
335
+ total_size = int(r.headers.get("content-length", 0))
336
+ with tqdm(total=total_size, unit="B", unit_scale=True) as pbar:
337
+ with open(local_path, "wb") as f:
338
+ for data in r.iter_content(chunk_size=chunk_size):
339
+ if data:
340
+ f.write(data)
341
+ pbar.update(chunk_size)
342
+
343
+
344
+ def md5_hash(path):
345
+ with open(path, "rb") as f:
346
+ content = f.read()
347
+ return hashlib.md5(content).hexdigest()
348
+
349
+
350
+ def get_ckpt_path(name, root, check=False):
351
+ assert name in URL_MAP
352
+ path = os.path.join(root, CKPT_MAP[name])
353
+ print(md5_hash(path))
354
+ if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):
355
+ print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path))
356
+ download(URL_MAP[name], path)
357
+ md5 = md5_hash(path)
358
+ assert md5 == MD5_MAP[name], md5
359
+ return path
360
+
361
+
362
+ class KeyNotFoundError(Exception):
363
+ def __init__(self, cause, keys=None, visited=None):
364
+ self.cause = cause
365
+ self.keys = keys
366
+ self.visited = visited
367
+ messages = list()
368
+ if keys is not None:
369
+ messages.append("Key not found: {}".format(keys))
370
+ if visited is not None:
371
+ messages.append("Visited: {}".format(visited))
372
+ messages.append("Cause:\n{}".format(cause))
373
+ message = "\n".join(messages)
374
+ super().__init__(message)
375
+
376
+
377
+ def retrieve(
378
+ list_or_dict, key, splitval="/", default=None, expand=True, pass_success=False
379
+ ):
380
+ """Given a nested list or dict return the desired value at key expanding
381
+ callable nodes if necessary and :attr:`expand` is ``True``. The expansion
382
+ is done in-place.
383
+
384
+ Parameters
385
+ ----------
386
+ list_or_dict : list or dict
387
+ Possibly nested list or dictionary.
388
+ key : str
389
+ key/to/value, path like string describing all keys necessary to
390
+ consider to get to the desired value. List indices can also be
391
+ passed here.
392
+ splitval : str
393
+ String that defines the delimiter between keys of the
394
+ different depth levels in `key`.
395
+ default : obj
396
+ Value returned if :attr:`key` is not found.
397
+ expand : bool
398
+ Whether to expand callable nodes on the path or not.
399
+
400
+ Returns
401
+ -------
402
+ The desired value or if :attr:`default` is not ``None`` and the
403
+ :attr:`key` is not found returns ``default``.
404
+
405
+ Raises
406
+ ------
407
+ Exception if ``key`` not in ``list_or_dict`` and :attr:`default` is
408
+ ``None``.
409
+ """
410
+
411
+ keys = key.split(splitval)
412
+
413
+ success = True
414
+ try:
415
+ visited = []
416
+ parent = None
417
+ last_key = None
418
+ for key in keys:
419
+ if callable(list_or_dict):
420
+ if not expand:
421
+ raise KeyNotFoundError(
422
+ ValueError(
423
+ "Trying to get past callable node with expand=False."
424
+ ),
425
+ keys=keys,
426
+ visited=visited,
427
+ )
428
+ list_or_dict = list_or_dict()
429
+ parent[last_key] = list_or_dict
430
+
431
+ last_key = key
432
+ parent = list_or_dict
433
+
434
+ try:
435
+ if isinstance(list_or_dict, dict):
436
+ list_or_dict = list_or_dict[key]
437
+ else:
438
+ list_or_dict = list_or_dict[int(key)]
439
+ except (KeyError, IndexError, ValueError) as e:
440
+ raise KeyNotFoundError(e, keys=keys, visited=visited)
441
+
442
+ visited += [key]
443
+ # final expansion of retrieved value
444
+ if expand and callable(list_or_dict):
445
+ list_or_dict = list_or_dict()
446
+ parent[last_key] = list_or_dict
447
+ except KeyNotFoundError as e:
448
+ if default is None:
449
+ raise e
450
+ else:
451
+ list_or_dict = default
452
+ success = False
453
+
454
+ if not pass_success:
455
+ return list_or_dict
456
+ else:
457
+ return list_or_dict, success
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .modeling_loss import LPIPSWithDiscriminator
2
+ from .modeling_causal_vae import CausalVideoVAE
3
+ from .causal_video_vae_wrapper import CausalVideoVAELossWrapper
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/causal_video_vae_wrapper.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ import torch.nn as nn
4
+ from collections import OrderedDict
5
+ from .modeling_causal_vae import CausalVideoVAE
6
+ from .modeling_loss import LPIPSWithDiscriminator
7
+ from einops import rearrange
8
+ from PIL import Image
9
+ from IPython import embed
10
+
11
+ from utils import (
12
+ is_context_parallel_initialized,
13
+ get_context_parallel_group,
14
+ get_context_parallel_world_size,
15
+ get_context_parallel_rank,
16
+ get_context_parallel_group_rank,
17
+ )
18
+
19
+ from .context_parallel_ops import (
20
+ conv_scatter_to_context_parallel_region,
21
+ conv_gather_from_context_parallel_region,
22
+ )
23
+
24
+
25
+ class CausalVideoVAELossWrapper(nn.Module):
26
+ """
27
+ The causal video vae training and inference running wrapper
28
+ """
29
+ def __init__(self, model_path, model_dtype='fp32', disc_start=0, logvar_init=0.0, kl_weight=1.0,
30
+ pixelloss_weight=1.0, perceptual_weight=1.0, disc_weight=0.5, interpolate=True,
31
+ add_discriminator=True, freeze_encoder=False, load_loss_module=False, lpips_ckpt=None, **kwargs,
32
+ ):
33
+ super().__init__()
34
+
35
+ if model_dtype == 'bf16':
36
+ torch_dtype = torch.bfloat16
37
+ elif model_dtype == 'fp16':
38
+ torch_dtype = torch.float16
39
+ else:
40
+ torch_dtype = torch.float32
41
+
42
+ self.vae = CausalVideoVAE.from_pretrained(model_path, torch_dtype=torch_dtype, interpolate=False)
43
+ self.vae_scale_factor = self.vae.config.scaling_factor
44
+
45
+ if freeze_encoder:
46
+ print("Freeze the parameters of vae encoder")
47
+ for parameter in self.vae.encoder.parameters():
48
+ parameter.requires_grad = False
49
+ for parameter in self.vae.quant_conv.parameters():
50
+ parameter.requires_grad = False
51
+
52
+ self.add_discriminator = add_discriminator
53
+ self.freeze_encoder = freeze_encoder
54
+
55
+ # Used for training
56
+ if load_loss_module:
57
+ self.loss = LPIPSWithDiscriminator(disc_start, logvar_init=logvar_init, kl_weight=kl_weight,
58
+ pixelloss_weight=pixelloss_weight, perceptual_weight=perceptual_weight, disc_weight=disc_weight,
59
+ add_discriminator=add_discriminator, using_3d_discriminator=False, disc_num_layers=4, lpips_ckpt=lpips_ckpt)
60
+ else:
61
+ self.loss = None
62
+
63
+ self.disc_start = disc_start
64
+
65
+ def load_checkpoint(self, checkpoint_path, **kwargs):
66
+ checkpoint = torch.load(checkpoint_path, map_location='cpu')
67
+ if 'model' in checkpoint:
68
+ checkpoint = checkpoint['model']
69
+
70
+ vae_checkpoint = OrderedDict()
71
+ disc_checkpoint = OrderedDict()
72
+
73
+ for key in checkpoint.keys():
74
+ if key.startswith('vae.'):
75
+ new_key = key.split('.')
76
+ new_key = '.'.join(new_key[1:])
77
+ vae_checkpoint[new_key] = checkpoint[key]
78
+ if key.startswith('loss.discriminator'):
79
+ new_key = key.split('.')
80
+ new_key = '.'.join(new_key[2:])
81
+ disc_checkpoint[new_key] = checkpoint[key]
82
+
83
+ vae_ckpt_load_result = self.vae.load_state_dict(vae_checkpoint, strict=False)
84
+ print(f"Load vae checkpoint from {checkpoint_path}, load result: {vae_ckpt_load_result}")
85
+
86
+ if self.add_discriminator:
87
+ disc_ckpt_load_result = self.loss.discriminator.load_state_dict(disc_checkpoint, strict=False)
88
+ print(f"Load disc checkpoint from {checkpoint_path}, load result: {disc_ckpt_load_result}")
89
+
90
+ def forward(self, x, step, identifier=['video']):
91
+ xdim = x.ndim
92
+ if xdim == 4:
93
+ x = x.unsqueeze(2) # (B, C, H, W) -> (B, C, 1, H , W)
94
+
95
+ if 'video' in identifier:
96
+ # The input is video
97
+ assert 'image' not in identifier
98
+ else:
99
+ # The input is image
100
+ assert 'video' not in identifier
101
+ # We arrange multiple images to a 5D Tensor for compatibility with video input
102
+ # So we needs to reformulate images into 1-frame video tensor
103
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
104
+ x = x.unsqueeze(2) # [(b t) c 1 h w]
105
+
106
+ if is_context_parallel_initialized():
107
+ assert self.training, "Only supports during training now"
108
+ cp_world_size = get_context_parallel_world_size()
109
+ global_src_rank = get_context_parallel_group_rank() * cp_world_size
110
+ # sync the input and split
111
+ torch.distributed.broadcast(x, src=global_src_rank, group=get_context_parallel_group())
112
+ batch_x = conv_scatter_to_context_parallel_region(x, dim=2, kernel_size=1)
113
+ else:
114
+ batch_x = x
115
+
116
+ posterior, reconstruct = self.vae(batch_x, freeze_encoder=self.freeze_encoder,
117
+ is_init_image=True, temporal_chunk=False,)
118
+
119
+ # The reconstruct loss
120
+ reconstruct_loss, rec_log = self.loss(
121
+ batch_x, reconstruct, posterior,
122
+ optimizer_idx=0, global_step=step, last_layer=self.vae.get_last_layer(),
123
+ )
124
+
125
+ if step < self.disc_start:
126
+ return reconstruct_loss, None, rec_log
127
+
128
+ # The loss to train the discriminator
129
+ gan_loss, gan_log = self.loss(batch_x, reconstruct, posterior, optimizer_idx=1,
130
+ global_step=step, last_layer=self.vae.get_last_layer(),
131
+ )
132
+
133
+ loss_log = {**rec_log, **gan_log}
134
+
135
+ return reconstruct_loss, gan_loss, loss_log
136
+
137
+ def encode(self, x, sample=False, is_init_image=True,
138
+ temporal_chunk=False, window_size=16, tile_sample_min_size=256,):
139
+ # x: (B, C, T, H, W) or (B, C, H, W)
140
+ B = x.shape[0]
141
+ xdim = x.ndim
142
+
143
+ if xdim == 4:
144
+ # The input is an image
145
+ x = x.unsqueeze(2)
146
+
147
+ if sample:
148
+ x = self.vae.encode(
149
+ x, is_init_image=is_init_image, temporal_chunk=temporal_chunk,
150
+ window_size=window_size, tile_sample_min_size=tile_sample_min_size,
151
+ ).latent_dist.sample()
152
+ else:
153
+ x = self.vae.encode(
154
+ x, is_init_image=is_init_image, temporal_chunk=temporal_chunk,
155
+ window_size=window_size, tile_sample_min_size=tile_sample_min_size,
156
+ ).latent_dist.mode()
157
+
158
+ return x
159
+
160
+ def decode(self, x, is_init_image=True, temporal_chunk=False,
161
+ window_size=2, tile_sample_min_size=256,):
162
+ # x: (B, C, T, H, W) or (B, C, H, W)
163
+ B = x.shape[0]
164
+ xdim = x.ndim
165
+
166
+ if xdim == 4:
167
+ # The input is an image
168
+ x = x.unsqueeze(2)
169
+
170
+ x = self.vae.decode(
171
+ x, is_init_image=is_init_image, temporal_chunk=temporal_chunk,
172
+ window_size=window_size, tile_sample_min_size=tile_sample_min_size,
173
+ ).sample
174
+
175
+ return x
176
+
177
+ @staticmethod
178
+ def numpy_to_pil(images):
179
+ """
180
+ Convert a numpy image or a batch of images to a PIL image.
181
+ """
182
+ if images.ndim == 3:
183
+ images = images[None, ...]
184
+ images = (images * 255).round().astype("uint8")
185
+ if images.shape[-1] == 1:
186
+ # special case for grayscale (single channel) images
187
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
188
+ else:
189
+ pil_images = [Image.fromarray(image) for image in images]
190
+
191
+ return pil_images
192
+
193
+ def reconstruct(
194
+ self, x, sample=False, return_latent=False, is_init_image=True,
195
+ temporal_chunk=False, window_size=16, tile_sample_min_size=256, **kwargs
196
+ ):
197
+ assert x.shape[0] == 1
198
+ xdim = x.ndim
199
+ encode_window_size = window_size
200
+ decode_window_size = window_size // self.vae.downsample_scale
201
+
202
+ # Encode
203
+ x = self.encode(
204
+ x, sample, is_init_image, temporal_chunk, encode_window_size, tile_sample_min_size,
205
+ )
206
+ encode_latent = x
207
+
208
+ # Decode
209
+ x = self.decode(
210
+ x, is_init_image, temporal_chunk, decode_window_size, tile_sample_min_size
211
+ )
212
+ output_image = x.float()
213
+ output_image = (output_image / 2 + 0.5).clamp(0, 1)
214
+
215
+ # Convert to PIL images
216
+ output_image = rearrange(output_image, "B C T H W -> (B T) C H W")
217
+ output_image = output_image.cpu().permute(0, 2, 3, 1).numpy()
218
+ output_images = self.numpy_to_pil(output_image)
219
+
220
+ if return_latent:
221
+ return output_images, encode_latent
222
+
223
+ return output_images
224
+
225
+ # encode vae latent
226
+ def encode_latent(self, x, sample=False, is_init_image=True,
227
+ temporal_chunk=False, window_size=16, tile_sample_min_size=256,):
228
+ # Encode
229
+ latent = self.encode(
230
+ x, sample, is_init_image, temporal_chunk, window_size, tile_sample_min_size,
231
+ )
232
+ return latent
233
+
234
+ # decode vae latent
235
+ def decode_latent(self, latent, is_init_image=True,
236
+ temporal_chunk=False, window_size=2, tile_sample_min_size=256,):
237
+ x = self.decode(
238
+ latent, is_init_image, temporal_chunk, window_size, tile_sample_min_size
239
+ )
240
+ output_image = x.float()
241
+ output_image = (output_image / 2 + 0.5).clamp(0, 1)
242
+ # Convert to PIL images
243
+ output_image = rearrange(output_image, "B C T H W -> (B T) C H W")
244
+ output_image = output_image.cpu().permute(0, 2, 3, 1).numpy()
245
+ output_images = self.numpy_to_pil(output_image)
246
+ return output_images
247
+
248
+ @property
249
+ def device(self):
250
+ return next(self.parameters()).device
251
+
252
+ @property
253
+ def dtype(self):
254
+ return next(self.parameters()).dtype
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/context_parallel_ops.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from cogvideoX
2
+ import torch
3
+ import torch.nn as nn
4
+ import math
5
+
6
+ from utils import (
7
+ get_context_parallel_group,
8
+ get_context_parallel_rank,
9
+ get_context_parallel_world_size,
10
+ get_context_parallel_group_rank,
11
+ )
12
+
13
+
14
+ def _conv_split(input_, dim=2, kernel_size=1):
15
+ cp_world_size = get_context_parallel_world_size()
16
+
17
+ # Bypass the function if context parallel is 1
18
+ if cp_world_size == 1:
19
+ return input_
20
+
21
+ # print('in _conv_split, cp_rank:', cp_rank, 'input_size:', input_.shape)
22
+
23
+ cp_rank = get_context_parallel_rank()
24
+
25
+ dim_size = (input_.size()[dim] - kernel_size) // cp_world_size
26
+
27
+ if cp_rank == 0:
28
+ output = input_.transpose(dim, 0)[: dim_size + kernel_size].transpose(dim, 0)
29
+ else:
30
+ # output = input_.transpose(dim, 0)[cp_rank * dim_size + 1:(cp_rank + 1) * dim_size + kernel_size].transpose(dim, 0)
31
+ output = input_.transpose(dim, 0)[
32
+ cp_rank * dim_size + kernel_size : (cp_rank + 1) * dim_size + kernel_size
33
+ ].transpose(dim, 0)
34
+ output = output.contiguous()
35
+
36
+ # print('out _conv_split, cp_rank:', cp_rank, 'input_size:', output.shape)
37
+
38
+ return output
39
+
40
+
41
+ def _conv_gather(input_, dim=2, kernel_size=1):
42
+ cp_world_size = get_context_parallel_world_size()
43
+
44
+ # Bypass the function if context parallel is 1
45
+ if cp_world_size == 1:
46
+ return input_
47
+
48
+ group = get_context_parallel_group()
49
+ cp_rank = get_context_parallel_rank()
50
+
51
+ # print('in _conv_gather, cp_rank:', cp_rank, 'input_size:', input_.shape)
52
+
53
+ input_first_kernel_ = input_.transpose(0, dim)[:kernel_size].transpose(0, dim).contiguous()
54
+ if cp_rank == 0:
55
+ input_ = input_.transpose(0, dim)[kernel_size:].transpose(0, dim).contiguous()
56
+ else:
57
+ input_ = input_.transpose(0, dim)[max(kernel_size - 1, 0) :].transpose(0, dim).contiguous()
58
+
59
+ tensor_list = [torch.empty_like(torch.cat([input_first_kernel_, input_], dim=dim))] + [
60
+ torch.empty_like(input_) for _ in range(cp_world_size - 1)
61
+ ]
62
+ if cp_rank == 0:
63
+ input_ = torch.cat([input_first_kernel_, input_], dim=dim)
64
+
65
+ tensor_list[cp_rank] = input_
66
+ torch.distributed.all_gather(tensor_list, input_, group=group)
67
+
68
+ # Note: torch.cat already creates a contiguous tensor.
69
+ output = torch.cat(tensor_list, dim=dim).contiguous()
70
+
71
+ # print('out _conv_gather, cp_rank:', cp_rank, 'input_size:', output.shape)
72
+
73
+ return output
74
+
75
+
76
+ def _cp_pass_from_previous_rank(input_, dim, kernel_size):
77
+ # Bypass the function if kernel size is 1
78
+ if kernel_size == 1:
79
+ return input_
80
+
81
+ group = get_context_parallel_group()
82
+ cp_rank = get_context_parallel_rank()
83
+ cp_group_rank = get_context_parallel_group_rank()
84
+ cp_world_size = get_context_parallel_world_size()
85
+
86
+ # print('in _pass_from_previous_rank, cp_rank:', cp_rank, 'input_size:', input_.shape)
87
+
88
+ global_rank = torch.distributed.get_rank()
89
+ global_world_size = torch.distributed.get_world_size()
90
+
91
+ input_ = input_.transpose(0, dim)
92
+
93
+ # pass from last rank
94
+ send_rank = global_rank + 1
95
+ recv_rank = global_rank - 1
96
+ if send_rank % cp_world_size == 0:
97
+ send_rank -= cp_world_size
98
+ if recv_rank % cp_world_size == cp_world_size - 1:
99
+ recv_rank += cp_world_size
100
+
101
+ recv_buffer = torch.empty_like(input_[-kernel_size + 1 :]).contiguous()
102
+ if cp_rank < cp_world_size - 1:
103
+ req_send = torch.distributed.isend(input_[-kernel_size + 1 :].contiguous(), send_rank, group=group)
104
+ if cp_rank > 0:
105
+ req_recv = torch.distributed.irecv(recv_buffer, recv_rank, group=group)
106
+
107
+ if cp_rank == 0:
108
+ input_ = torch.cat([torch.zeros_like(input_[:1])] * (kernel_size - 1) + [input_], dim=0)
109
+ else:
110
+ req_recv.wait()
111
+ input_ = torch.cat([recv_buffer, input_], dim=0)
112
+
113
+ input_ = input_.transpose(0, dim).contiguous()
114
+ return input_
115
+
116
+
117
+ def _drop_from_previous_rank(input_, dim, kernel_size):
118
+ input_ = input_.transpose(0, dim)[kernel_size - 1 :].transpose(0, dim)
119
+ return input_
120
+
121
+
122
+ class _ConvolutionScatterToContextParallelRegion(torch.autograd.Function):
123
+ @staticmethod
124
+ def forward(ctx, input_, dim, kernel_size):
125
+ ctx.dim = dim
126
+ ctx.kernel_size = kernel_size
127
+ return _conv_split(input_, dim, kernel_size)
128
+
129
+ @staticmethod
130
+ def backward(ctx, grad_output):
131
+ return _conv_gather(grad_output, ctx.dim, ctx.kernel_size), None, None
132
+
133
+
134
+ class _ConvolutionGatherFromContextParallelRegion(torch.autograd.Function):
135
+ @staticmethod
136
+ def forward(ctx, input_, dim, kernel_size):
137
+ ctx.dim = dim
138
+ ctx.kernel_size = kernel_size
139
+ return _conv_gather(input_, dim, kernel_size)
140
+
141
+ @staticmethod
142
+ def backward(ctx, grad_output):
143
+ return _conv_split(grad_output, ctx.dim, ctx.kernel_size), None, None
144
+
145
+
146
+ class _CPConvolutionPassFromPreviousRank(torch.autograd.Function):
147
+ @staticmethod
148
+ def forward(ctx, input_, dim, kernel_size):
149
+ ctx.dim = dim
150
+ ctx.kernel_size = kernel_size
151
+ return _cp_pass_from_previous_rank(input_, dim, kernel_size)
152
+
153
+ @staticmethod
154
+ def backward(ctx, grad_output):
155
+ return _drop_from_previous_rank(grad_output, ctx.dim, ctx.kernel_size), None, None
156
+
157
+
158
+ def conv_scatter_to_context_parallel_region(input_, dim, kernel_size):
159
+ return _ConvolutionScatterToContextParallelRegion.apply(input_, dim, kernel_size)
160
+
161
+
162
+ def conv_gather_from_context_parallel_region(input_, dim, kernel_size):
163
+ return _ConvolutionGatherFromContextParallelRegion.apply(input_, dim, kernel_size)
164
+
165
+
166
+ def cp_pass_from_previous_rank(input_, dim, kernel_size):
167
+ return _CPConvolutionPassFromPreviousRank.apply(input_, dim, kernel_size)
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/modeling_block.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Dict, Optional, Tuple, Union
15
+
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+ from einops import rearrange
21
+
22
+ from diffusers.utils import logging
23
+ from diffusers.models.attention_processor import Attention
24
+ from .modeling_resnet import (
25
+ Downsample2D, ResnetBlock2D, CausalResnetBlock3D, Upsample2D,
26
+ TemporalDownsample2x, TemporalUpsample2x,
27
+ CausalDownsample2x, CausalTemporalDownsample2x,
28
+ CausalUpsample2x, CausalTemporalUpsample2x,
29
+ )
30
+
31
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
32
+
33
+
34
+ def get_input_layer(
35
+ in_channels: int,
36
+ out_channels: int,
37
+ norm_num_groups: int,
38
+ layer_type: str,
39
+ norm_type: str = 'group',
40
+ affine: bool = True,
41
+ ):
42
+ if layer_type == 'conv':
43
+ input_layer = nn.Conv3d(
44
+ in_channels,
45
+ out_channels,
46
+ kernel_size=3,
47
+ stride=1,
48
+ padding=1,
49
+ )
50
+
51
+ elif layer_type == 'pixel_shuffle':
52
+ input_layer = nn.Sequential(
53
+ nn.PixelUnshuffle(2),
54
+ nn.Conv2d(in_channels * 4, out_channels, kernel_size=1),
55
+ )
56
+ else:
57
+ raise NotImplementedError(f"Not support input layer {layer_type}")
58
+
59
+ return input_layer
60
+
61
+
62
+ def get_output_layer(
63
+ in_channels: int,
64
+ out_channels: int,
65
+ norm_num_groups: int,
66
+ layer_type: str,
67
+ norm_type: str = 'group',
68
+ affine: bool = True,
69
+ ):
70
+ if layer_type == 'norm_act_conv':
71
+ output_layer = nn.Sequential(
72
+ nn.GroupNorm(num_channels=in_channels, num_groups=norm_num_groups, eps=1e-6, affine=affine),
73
+ nn.SiLU(),
74
+ nn.Conv3d(in_channels, out_channels, 3, stride=1, padding=1),
75
+ )
76
+
77
+ elif layer_type == 'pixel_shuffle':
78
+ output_layer = nn.Sequential(
79
+ nn.Conv2d(in_channels, out_channels * 4, kernel_size=1),
80
+ nn.PixelShuffle(2),
81
+ )
82
+
83
+ else:
84
+ raise NotImplementedError(f"Not support output layer {layer_type}")
85
+
86
+ return output_layer
87
+
88
+
89
+ def get_down_block(
90
+ down_block_type: str,
91
+ num_layers: int,
92
+ in_channels: int,
93
+ out_channels: int = None,
94
+ temb_channels: int = None,
95
+ add_spatial_downsample: bool = None,
96
+ add_temporal_downsample: bool = None,
97
+ resnet_eps: float = 1e-6,
98
+ resnet_act_fn: str = 'silu',
99
+ resnet_groups: Optional[int] = None,
100
+ downsample_padding: Optional[int] = None,
101
+ resnet_time_scale_shift: str = "default",
102
+ attention_head_dim: Optional[int] = None,
103
+ dropout: float = 0.0,
104
+ norm_affline: bool = True,
105
+ norm_layer: str = 'layer',
106
+ ):
107
+
108
+ if down_block_type == "DownEncoderBlock2D":
109
+ return DownEncoderBlock2D(
110
+ num_layers=num_layers,
111
+ in_channels=in_channels,
112
+ out_channels=out_channels,
113
+ dropout=dropout,
114
+ add_spatial_downsample=add_spatial_downsample,
115
+ add_temporal_downsample=add_temporal_downsample,
116
+ resnet_eps=resnet_eps,
117
+ resnet_act_fn=resnet_act_fn,
118
+ resnet_groups=resnet_groups,
119
+ downsample_padding=downsample_padding,
120
+ resnet_time_scale_shift=resnet_time_scale_shift,
121
+ )
122
+
123
+ elif down_block_type == "DownEncoderBlockCausal3D":
124
+ return DownEncoderBlockCausal3D(
125
+ num_layers=num_layers,
126
+ in_channels=in_channels,
127
+ out_channels=out_channels,
128
+ dropout=dropout,
129
+ add_spatial_downsample=add_spatial_downsample,
130
+ add_temporal_downsample=add_temporal_downsample,
131
+ resnet_eps=resnet_eps,
132
+ resnet_act_fn=resnet_act_fn,
133
+ resnet_groups=resnet_groups,
134
+ downsample_padding=downsample_padding,
135
+ resnet_time_scale_shift=resnet_time_scale_shift,
136
+ )
137
+
138
+ raise ValueError(f"{down_block_type} does not exist.")
139
+
140
+
141
+ def get_up_block(
142
+ up_block_type: str,
143
+ num_layers: int,
144
+ in_channels: int,
145
+ out_channels: int,
146
+ prev_output_channel: int = None,
147
+ temb_channels: int = None,
148
+ add_spatial_upsample: bool = None,
149
+ add_temporal_upsample: bool = None,
150
+ resnet_eps: float = 1e-6,
151
+ resnet_act_fn: str = 'silu',
152
+ resolution_idx: Optional[int] = None,
153
+ resnet_groups: Optional[int] = None,
154
+ resnet_time_scale_shift: str = "default",
155
+ attention_head_dim: Optional[int] = None,
156
+ dropout: float = 0.0,
157
+ interpolate: bool = True,
158
+ norm_affline: bool = True,
159
+ norm_layer: str = 'layer',
160
+ ) -> nn.Module:
161
+
162
+ if up_block_type == "UpDecoderBlock2D":
163
+ return UpDecoderBlock2D(
164
+ num_layers=num_layers,
165
+ in_channels=in_channels,
166
+ out_channels=out_channels,
167
+ resolution_idx=resolution_idx,
168
+ dropout=dropout,
169
+ add_spatial_upsample=add_spatial_upsample,
170
+ add_temporal_upsample=add_temporal_upsample,
171
+ resnet_eps=resnet_eps,
172
+ resnet_act_fn=resnet_act_fn,
173
+ resnet_groups=resnet_groups,
174
+ resnet_time_scale_shift=resnet_time_scale_shift,
175
+ temb_channels=temb_channels,
176
+ interpolate=interpolate,
177
+ )
178
+
179
+ elif up_block_type == "UpDecoderBlockCausal3D":
180
+ return UpDecoderBlockCausal3D(
181
+ num_layers=num_layers,
182
+ in_channels=in_channels,
183
+ out_channels=out_channels,
184
+ resolution_idx=resolution_idx,
185
+ dropout=dropout,
186
+ add_spatial_upsample=add_spatial_upsample,
187
+ add_temporal_upsample=add_temporal_upsample,
188
+ resnet_eps=resnet_eps,
189
+ resnet_act_fn=resnet_act_fn,
190
+ resnet_groups=resnet_groups,
191
+ resnet_time_scale_shift=resnet_time_scale_shift,
192
+ temb_channels=temb_channels,
193
+ interpolate=interpolate,
194
+ )
195
+
196
+ raise ValueError(f"{up_block_type} does not exist.")
197
+
198
+
199
+
200
+ class UNetMidBlock2D(nn.Module):
201
+ """
202
+ A 2D UNet mid-block [`UNetMidBlock2D`] with multiple residual blocks and optional attention blocks.
203
+
204
+ Args:
205
+ in_channels (`int`): The number of input channels.
206
+ temb_channels (`int`): The number of temporal embedding channels.
207
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
208
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
209
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
210
+ resnet_time_scale_shift (`str`, *optional*, defaults to `default`):
211
+ The type of normalization to apply to the time embeddings. This can help to improve the performance of the
212
+ model on tasks with long-range temporal dependencies.
213
+ resnet_act_fn (`str`, *optional*, defaults to `swish`): The activation function for the resnet blocks.
214
+ resnet_groups (`int`, *optional*, defaults to 32):
215
+ The number of groups to use in the group normalization layers of the resnet blocks.
216
+ attn_groups (`Optional[int]`, *optional*, defaults to None): The number of groups for the attention blocks.
217
+ resnet_pre_norm (`bool`, *optional*, defaults to `True`):
218
+ Whether to use pre-normalization for the resnet blocks.
219
+ add_attention (`bool`, *optional*, defaults to `True`): Whether to add attention blocks.
220
+ attention_head_dim (`int`, *optional*, defaults to 1):
221
+ Dimension of a single attention head. The number of attention heads is determined based on this value and
222
+ the number of input channels.
223
+ output_scale_factor (`float`, *optional*, defaults to 1.0): The output scale factor.
224
+
225
+ Returns:
226
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
227
+ in_channels, height, width)`.
228
+
229
+ """
230
+
231
+ def __init__(
232
+ self,
233
+ in_channels: int,
234
+ temb_channels: int,
235
+ dropout: float = 0.0,
236
+ num_layers: int = 1,
237
+ resnet_eps: float = 1e-6,
238
+ resnet_time_scale_shift: str = "default", # default, spatial
239
+ resnet_act_fn: str = "swish",
240
+ resnet_groups: int = 32,
241
+ attn_groups: Optional[int] = None,
242
+ resnet_pre_norm: bool = True,
243
+ add_attention: bool = True,
244
+ attention_head_dim: int = 1,
245
+ output_scale_factor: float = 1.0,
246
+ ):
247
+ super().__init__()
248
+ resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
249
+ self.add_attention = add_attention
250
+
251
+ if attn_groups is None:
252
+ attn_groups = resnet_groups if resnet_time_scale_shift == "default" else None
253
+
254
+ # there is always at least one resnet
255
+ resnets = [
256
+ ResnetBlock2D(
257
+ in_channels=in_channels,
258
+ out_channels=in_channels,
259
+ temb_channels=temb_channels,
260
+ eps=resnet_eps,
261
+ groups=resnet_groups,
262
+ dropout=dropout,
263
+ time_embedding_norm=resnet_time_scale_shift,
264
+ non_linearity=resnet_act_fn,
265
+ output_scale_factor=output_scale_factor,
266
+ pre_norm=resnet_pre_norm,
267
+ )
268
+ ]
269
+ attentions = []
270
+
271
+ if attention_head_dim is None:
272
+ logger.warn(
273
+ f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}."
274
+ )
275
+ attention_head_dim = in_channels
276
+
277
+ for _ in range(num_layers):
278
+ if self.add_attention:
279
+ # Spatial attention
280
+ attentions.append(
281
+ Attention(
282
+ in_channels,
283
+ heads=in_channels // attention_head_dim,
284
+ dim_head=attention_head_dim,
285
+ rescale_output_factor=output_scale_factor,
286
+ eps=resnet_eps,
287
+ norm_num_groups=attn_groups,
288
+ spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
289
+ residual_connection=True,
290
+ bias=True,
291
+ upcast_softmax=True,
292
+ _from_deprecated_attn_block=True,
293
+ )
294
+ )
295
+ else:
296
+ attentions.append(None)
297
+
298
+ resnets.append(
299
+ ResnetBlock2D(
300
+ in_channels=in_channels,
301
+ out_channels=in_channels,
302
+ temb_channels=temb_channels,
303
+ eps=resnet_eps,
304
+ groups=resnet_groups,
305
+ dropout=dropout,
306
+ time_embedding_norm=resnet_time_scale_shift,
307
+ non_linearity=resnet_act_fn,
308
+ output_scale_factor=output_scale_factor,
309
+ pre_norm=resnet_pre_norm,
310
+ )
311
+ )
312
+
313
+ self.attentions = nn.ModuleList(attentions)
314
+ self.resnets = nn.ModuleList(resnets)
315
+
316
+ def forward(self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None) -> torch.FloatTensor:
317
+ hidden_states = self.resnets[0](hidden_states, temb)
318
+ t = hidden_states.shape[2]
319
+
320
+ for attn, resnet in zip(self.attentions, self.resnets[1:]):
321
+ if attn is not None:
322
+ hidden_states = rearrange(hidden_states, 'b c t h w -> b t c h w')
323
+ hidden_states = rearrange(hidden_states, 'b t c h w -> (b t) c h w')
324
+ hidden_states = attn(hidden_states, temb=temb)
325
+ hidden_states = rearrange(hidden_states, '(b t) c h w -> b t c h w', t=t)
326
+ hidden_states = rearrange(hidden_states, 'b t c h w -> b c t h w')
327
+
328
+ hidden_states = resnet(hidden_states, temb)
329
+
330
+ return hidden_states
331
+
332
+
333
+ class CausalUNetMidBlock2D(nn.Module):
334
+ """
335
+ A 2D UNet mid-block [`UNetMidBlock2D`] with multiple residual blocks and optional attention blocks.
336
+
337
+ Args:
338
+ in_channels (`int`): The number of input channels.
339
+ temb_channels (`int`): The number of temporal embedding channels.
340
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
341
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
342
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
343
+ resnet_time_scale_shift (`str`, *optional*, defaults to `default`):
344
+ The type of normalization to apply to the time embeddings. This can help to improve the performance of the
345
+ model on tasks with long-range temporal dependencies.
346
+ resnet_act_fn (`str`, *optional*, defaults to `swish`): The activation function for the resnet blocks.
347
+ resnet_groups (`int`, *optional*, defaults to 32):
348
+ The number of groups to use in the group normalization layers of the resnet blocks.
349
+ attn_groups (`Optional[int]`, *optional*, defaults to None): The number of groups for the attention blocks.
350
+ resnet_pre_norm (`bool`, *optional*, defaults to `True`):
351
+ Whether to use pre-normalization for the resnet blocks.
352
+ add_attention (`bool`, *optional*, defaults to `True`): Whether to add attention blocks.
353
+ attention_head_dim (`int`, *optional*, defaults to 1):
354
+ Dimension of a single attention head. The number of attention heads is determined based on this value and
355
+ the number of input channels.
356
+ output_scale_factor (`float`, *optional*, defaults to 1.0): The output scale factor.
357
+
358
+ Returns:
359
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
360
+ in_channels, height, width)`.
361
+
362
+ """
363
+
364
+ def __init__(
365
+ self,
366
+ in_channels: int,
367
+ temb_channels: int,
368
+ dropout: float = 0.0,
369
+ num_layers: int = 1,
370
+ resnet_eps: float = 1e-6,
371
+ resnet_time_scale_shift: str = "default", # default, spatial
372
+ resnet_act_fn: str = "swish",
373
+ resnet_groups: int = 32,
374
+ attn_groups: Optional[int] = None,
375
+ resnet_pre_norm: bool = True,
376
+ add_attention: bool = True,
377
+ attention_head_dim: int = 1,
378
+ output_scale_factor: float = 1.0,
379
+ ):
380
+ super().__init__()
381
+ resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
382
+ self.add_attention = add_attention
383
+
384
+ if attn_groups is None:
385
+ attn_groups = resnet_groups if resnet_time_scale_shift == "default" else None
386
+
387
+ # there is always at least one resnet
388
+ resnets = [
389
+ CausalResnetBlock3D(
390
+ in_channels=in_channels,
391
+ out_channels=in_channels,
392
+ temb_channels=temb_channels,
393
+ eps=resnet_eps,
394
+ groups=resnet_groups,
395
+ dropout=dropout,
396
+ time_embedding_norm=resnet_time_scale_shift,
397
+ non_linearity=resnet_act_fn,
398
+ output_scale_factor=output_scale_factor,
399
+ pre_norm=resnet_pre_norm,
400
+ )
401
+ ]
402
+ attentions = []
403
+
404
+ if attention_head_dim is None:
405
+ logger.warn(
406
+ f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}."
407
+ )
408
+ attention_head_dim = in_channels
409
+
410
+ for _ in range(num_layers):
411
+ if self.add_attention:
412
+ # Spatial attention
413
+ attentions.append(
414
+ Attention(
415
+ in_channels,
416
+ heads=in_channels // attention_head_dim,
417
+ dim_head=attention_head_dim,
418
+ rescale_output_factor=output_scale_factor,
419
+ eps=resnet_eps,
420
+ norm_num_groups=attn_groups,
421
+ spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
422
+ residual_connection=True,
423
+ bias=True,
424
+ upcast_softmax=True,
425
+ _from_deprecated_attn_block=True,
426
+ )
427
+ )
428
+ else:
429
+ attentions.append(None)
430
+
431
+ resnets.append(
432
+ CausalResnetBlock3D(
433
+ in_channels=in_channels,
434
+ out_channels=in_channels,
435
+ temb_channels=temb_channels,
436
+ eps=resnet_eps,
437
+ groups=resnet_groups,
438
+ dropout=dropout,
439
+ time_embedding_norm=resnet_time_scale_shift,
440
+ non_linearity=resnet_act_fn,
441
+ output_scale_factor=output_scale_factor,
442
+ pre_norm=resnet_pre_norm,
443
+ )
444
+ )
445
+
446
+ self.attentions = nn.ModuleList(attentions)
447
+ self.resnets = nn.ModuleList(resnets)
448
+
449
+ def forward(self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None,
450
+ is_init_image=True, temporal_chunk=False) -> torch.FloatTensor:
451
+ hidden_states = self.resnets[0](hidden_states, temb, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
452
+ t = hidden_states.shape[2]
453
+
454
+ for attn, resnet in zip(self.attentions, self.resnets[1:]):
455
+ if attn is not None:
456
+ hidden_states = rearrange(hidden_states, 'b c t h w -> b t c h w')
457
+ hidden_states = rearrange(hidden_states, 'b t c h w -> (b t) c h w')
458
+ hidden_states = attn(hidden_states, temb=temb)
459
+ hidden_states = rearrange(hidden_states, '(b t) c h w -> b t c h w', t=t)
460
+ hidden_states = rearrange(hidden_states, 'b t c h w -> b c t h w')
461
+
462
+ hidden_states = resnet(hidden_states, temb, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
463
+
464
+ return hidden_states
465
+
466
+
467
+ class DownEncoderBlockCausal3D(nn.Module):
468
+ def __init__(
469
+ self,
470
+ in_channels: int,
471
+ out_channels: int,
472
+ dropout: float = 0.0,
473
+ num_layers: int = 1,
474
+ resnet_eps: float = 1e-6,
475
+ resnet_time_scale_shift: str = "default",
476
+ resnet_act_fn: str = "swish",
477
+ resnet_groups: int = 32,
478
+ resnet_pre_norm: bool = True,
479
+ output_scale_factor: float = 1.0,
480
+ add_spatial_downsample: bool = True,
481
+ add_temporal_downsample: bool = False,
482
+ downsample_padding: int = 1,
483
+ ):
484
+ super().__init__()
485
+ resnets = []
486
+
487
+ for i in range(num_layers):
488
+ in_channels = in_channels if i == 0 else out_channels
489
+ resnets.append(
490
+ CausalResnetBlock3D(
491
+ in_channels=in_channels,
492
+ out_channels=out_channels,
493
+ temb_channels=None,
494
+ eps=resnet_eps,
495
+ groups=resnet_groups,
496
+ dropout=dropout,
497
+ time_embedding_norm=resnet_time_scale_shift,
498
+ non_linearity=resnet_act_fn,
499
+ output_scale_factor=output_scale_factor,
500
+ pre_norm=resnet_pre_norm,
501
+ )
502
+ )
503
+
504
+ self.resnets = nn.ModuleList(resnets)
505
+
506
+ if add_spatial_downsample:
507
+ self.downsamplers = nn.ModuleList(
508
+ [
509
+ CausalDownsample2x(
510
+ out_channels, use_conv=True, out_channels=out_channels,
511
+ )
512
+ ]
513
+ )
514
+ else:
515
+ self.downsamplers = None
516
+
517
+ if add_temporal_downsample:
518
+ self.temporal_downsamplers = nn.ModuleList(
519
+ [
520
+ CausalTemporalDownsample2x(
521
+ out_channels, use_conv=True, out_channels=out_channels,
522
+ )
523
+ ]
524
+ )
525
+ else:
526
+ self.temporal_downsamplers = None
527
+
528
+ def forward(self, hidden_states: torch.FloatTensor, is_init_image=True, temporal_chunk=False) -> torch.FloatTensor:
529
+ for resnet in self.resnets:
530
+ hidden_states = resnet(hidden_states, temb=None, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
531
+
532
+ if self.downsamplers is not None:
533
+ for downsampler in self.downsamplers:
534
+ hidden_states = downsampler(hidden_states, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
535
+
536
+ if self.temporal_downsamplers is not None:
537
+ for temporal_downsampler in self.temporal_downsamplers:
538
+ hidden_states = temporal_downsampler(hidden_states, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
539
+
540
+ return hidden_states
541
+
542
+
543
+ class DownEncoderBlock2D(nn.Module):
544
+ def __init__(
545
+ self,
546
+ in_channels: int,
547
+ out_channels: int,
548
+ dropout: float = 0.0,
549
+ num_layers: int = 1,
550
+ resnet_eps: float = 1e-6,
551
+ resnet_time_scale_shift: str = "default",
552
+ resnet_act_fn: str = "swish",
553
+ resnet_groups: int = 32,
554
+ resnet_pre_norm: bool = True,
555
+ output_scale_factor: float = 1.0,
556
+ add_spatial_downsample: bool = True,
557
+ add_temporal_downsample: bool = False,
558
+ downsample_padding: int = 1,
559
+ ):
560
+ super().__init__()
561
+ resnets = []
562
+
563
+ for i in range(num_layers):
564
+ in_channels = in_channels if i == 0 else out_channels
565
+ resnets.append(
566
+ ResnetBlock2D(
567
+ in_channels=in_channels,
568
+ out_channels=out_channels,
569
+ temb_channels=None,
570
+ eps=resnet_eps,
571
+ groups=resnet_groups,
572
+ dropout=dropout,
573
+ time_embedding_norm=resnet_time_scale_shift,
574
+ non_linearity=resnet_act_fn,
575
+ output_scale_factor=output_scale_factor,
576
+ pre_norm=resnet_pre_norm,
577
+ )
578
+ )
579
+
580
+ self.resnets = nn.ModuleList(resnets)
581
+
582
+ if add_spatial_downsample:
583
+ self.downsamplers = nn.ModuleList(
584
+ [
585
+ Downsample2D(
586
+ out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
587
+ )
588
+ ]
589
+ )
590
+ else:
591
+ self.downsamplers = None
592
+
593
+ if add_temporal_downsample:
594
+ self.temporal_downsamplers = nn.ModuleList(
595
+ [
596
+ TemporalDownsample2x(
597
+ out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding,
598
+ )
599
+ ]
600
+ )
601
+ else:
602
+ self.temporal_downsamplers = None
603
+
604
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
605
+ for resnet in self.resnets:
606
+ hidden_states = resnet(hidden_states, temb=None)
607
+
608
+ if self.downsamplers is not None:
609
+ for downsampler in self.downsamplers:
610
+ hidden_states = downsampler(hidden_states)
611
+
612
+ if self.temporal_downsamplers is not None:
613
+ for temporal_downsampler in self.temporal_downsamplers:
614
+ hidden_states = temporal_downsampler(hidden_states)
615
+
616
+ return hidden_states
617
+
618
+
619
+ class UpDecoderBlock2D(nn.Module):
620
+ def __init__(
621
+ self,
622
+ in_channels: int,
623
+ out_channels: int,
624
+ resolution_idx: Optional[int] = None,
625
+ dropout: float = 0.0,
626
+ num_layers: int = 1,
627
+ resnet_eps: float = 1e-6,
628
+ resnet_time_scale_shift: str = "default", # default, spatial
629
+ resnet_act_fn: str = "swish",
630
+ resnet_groups: int = 32,
631
+ resnet_pre_norm: bool = True,
632
+ output_scale_factor: float = 1.0,
633
+ add_spatial_upsample: bool = True,
634
+ add_temporal_upsample: bool = False,
635
+ temb_channels: Optional[int] = None,
636
+ interpolate: bool = True,
637
+ ):
638
+ super().__init__()
639
+ resnets = []
640
+
641
+ for i in range(num_layers):
642
+ input_channels = in_channels if i == 0 else out_channels
643
+
644
+ resnets.append(
645
+ ResnetBlock2D(
646
+ in_channels=input_channels,
647
+ out_channels=out_channels,
648
+ temb_channels=temb_channels,
649
+ eps=resnet_eps,
650
+ groups=resnet_groups,
651
+ dropout=dropout,
652
+ time_embedding_norm=resnet_time_scale_shift,
653
+ non_linearity=resnet_act_fn,
654
+ output_scale_factor=output_scale_factor,
655
+ pre_norm=resnet_pre_norm,
656
+ )
657
+ )
658
+
659
+ self.resnets = nn.ModuleList(resnets)
660
+
661
+ if add_spatial_upsample:
662
+ self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels, interpolate=interpolate)])
663
+ else:
664
+ self.upsamplers = None
665
+
666
+ if add_temporal_upsample:
667
+ self.temporal_upsamplers = nn.ModuleList([TemporalUpsample2x(out_channels, use_conv=True, out_channels=out_channels, interpolate=interpolate)])
668
+ else:
669
+ self.temporal_upsamplers = None
670
+
671
+ self.resolution_idx = resolution_idx
672
+
673
+ def forward(
674
+ self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0, is_image: bool = False,
675
+ ) -> torch.FloatTensor:
676
+ for resnet in self.resnets:
677
+ hidden_states = resnet(hidden_states, temb=temb, scale=scale)
678
+
679
+ if self.upsamplers is not None:
680
+ for upsampler in self.upsamplers:
681
+ hidden_states = upsampler(hidden_states)
682
+
683
+ if self.temporal_upsamplers is not None:
684
+ for temporal_upsampler in self.temporal_upsamplers:
685
+ hidden_states = temporal_upsampler(hidden_states, is_image=is_image)
686
+
687
+ return hidden_states
688
+
689
+
690
+ class UpDecoderBlockCausal3D(nn.Module):
691
+ def __init__(
692
+ self,
693
+ in_channels: int,
694
+ out_channels: int,
695
+ resolution_idx: Optional[int] = None,
696
+ dropout: float = 0.0,
697
+ num_layers: int = 1,
698
+ resnet_eps: float = 1e-6,
699
+ resnet_time_scale_shift: str = "default", # default, spatial
700
+ resnet_act_fn: str = "swish",
701
+ resnet_groups: int = 32,
702
+ resnet_pre_norm: bool = True,
703
+ output_scale_factor: float = 1.0,
704
+ add_spatial_upsample: bool = True,
705
+ add_temporal_upsample: bool = False,
706
+ temb_channels: Optional[int] = None,
707
+ interpolate: bool = True,
708
+ ):
709
+ super().__init__()
710
+ resnets = []
711
+
712
+ for i in range(num_layers):
713
+ input_channels = in_channels if i == 0 else out_channels
714
+
715
+ resnets.append(
716
+ CausalResnetBlock3D(
717
+ in_channels=input_channels,
718
+ out_channels=out_channels,
719
+ temb_channels=temb_channels,
720
+ eps=resnet_eps,
721
+ groups=resnet_groups,
722
+ dropout=dropout,
723
+ time_embedding_norm=resnet_time_scale_shift,
724
+ non_linearity=resnet_act_fn,
725
+ output_scale_factor=output_scale_factor,
726
+ pre_norm=resnet_pre_norm,
727
+ )
728
+ )
729
+
730
+ self.resnets = nn.ModuleList(resnets)
731
+
732
+ if add_spatial_upsample:
733
+ self.upsamplers = nn.ModuleList([CausalUpsample2x(out_channels, use_conv=True, out_channels=out_channels, interpolate=interpolate)])
734
+ else:
735
+ self.upsamplers = None
736
+
737
+ if add_temporal_upsample:
738
+ self.temporal_upsamplers = nn.ModuleList([CausalTemporalUpsample2x(out_channels, use_conv=True, out_channels=out_channels, interpolate=interpolate)])
739
+ else:
740
+ self.temporal_upsamplers = None
741
+
742
+ self.resolution_idx = resolution_idx
743
+
744
+ def forward(
745
+ self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None,
746
+ is_init_image=True, temporal_chunk=False,
747
+ ) -> torch.FloatTensor:
748
+ for resnet in self.resnets:
749
+ hidden_states = resnet(hidden_states, temb=temb, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
750
+
751
+ if self.upsamplers is not None:
752
+ for upsampler in self.upsamplers:
753
+ hidden_states = upsampler(hidden_states, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
754
+
755
+ if self.temporal_upsamplers is not None:
756
+ for temporal_upsampler in self.temporal_upsamplers:
757
+ hidden_states = temporal_upsampler(hidden_states, is_init_image=is_init_image, temporal_chunk=temporal_chunk)
758
+
759
+ return hidden_states
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/modeling_causal_conv.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, Union
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.utils.checkpoint import checkpoint
5
+ import torch.nn.functional as F
6
+ from collections import deque
7
+ from einops import rearrange
8
+ from timm.models.layers import trunc_normal_
9
+ from torch import Tensor
10
+
11
+ from utils import (
12
+ is_context_parallel_initialized,
13
+ get_context_parallel_group,
14
+ get_context_parallel_world_size,
15
+ get_context_parallel_rank,
16
+ get_context_parallel_group_rank,
17
+ )
18
+
19
+ from .context_parallel_ops import (
20
+ conv_scatter_to_context_parallel_region,
21
+ conv_gather_from_context_parallel_region,
22
+ cp_pass_from_previous_rank,
23
+ )
24
+
25
+
26
+ def divisible_by(num, den):
27
+ return (num % den) == 0
28
+
29
+ def cast_tuple(t, length = 1):
30
+ return t if isinstance(t, tuple) else ((t,) * length)
31
+
32
+ def is_odd(n):
33
+ return not divisible_by(n, 2)
34
+
35
+
36
+ class CausalGroupNorm(nn.GroupNorm):
37
+
38
+ def forward(self, x: Tensor) -> Tensor:
39
+ t = x.shape[2]
40
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
41
+ x = super().forward(x)
42
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=t)
43
+ return x
44
+
45
+
46
+ class CausalConv3d(nn.Module):
47
+
48
+ def __init__(
49
+ self,
50
+ in_channels,
51
+ out_channels,
52
+ kernel_size: Union[int, Tuple[int, int, int]],
53
+ stride: Union[int, Tuple[int, int, int]] = 1,
54
+ pad_mode: str ='constant',
55
+ **kwargs
56
+ ):
57
+ super().__init__()
58
+ if isinstance(kernel_size, int):
59
+ kernel_size = cast_tuple(kernel_size, 3)
60
+
61
+ time_kernel_size, height_kernel_size, width_kernel_size = kernel_size
62
+ self.time_kernel_size = time_kernel_size
63
+ assert is_odd(height_kernel_size) and is_odd(width_kernel_size)
64
+ dilation = kwargs.pop('dilation', 1)
65
+ self.pad_mode = pad_mode
66
+
67
+ if isinstance(stride, int):
68
+ stride = (stride, 1, 1)
69
+
70
+ time_pad = dilation * (time_kernel_size - 1)
71
+ height_pad = height_kernel_size // 2
72
+ width_pad = width_kernel_size // 2
73
+
74
+ self.temporal_stride = stride[0]
75
+ self.time_pad = time_pad
76
+ self.time_causal_padding = (width_pad, width_pad, height_pad, height_pad, time_pad, 0)
77
+ self.time_uncausal_padding = (width_pad, width_pad, height_pad, height_pad, 0, 0)
78
+
79
+ self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=0, dilation=dilation, **kwargs)
80
+ self.cache_front_feat = deque()
81
+
82
+ def _clear_context_parallel_cache(self):
83
+ del self.cache_front_feat
84
+ self.cache_front_feat = deque()
85
+
86
+ def _init_weights(self, m):
87
+ if isinstance(m, (nn.Linear, nn.Conv2d, nn.Conv3d)):
88
+ trunc_normal_(m.weight, std=.02)
89
+ if m.bias is not None:
90
+ nn.init.constant_(m.bias, 0)
91
+ elif isinstance(m, (nn.LayerNorm, nn.GroupNorm)):
92
+ nn.init.constant_(m.bias, 0)
93
+ nn.init.constant_(m.weight, 1.0)
94
+
95
+ def context_parallel_forward(self, x):
96
+ cp_rank = get_context_parallel_rank()
97
+ if self.time_kernel_size == 3 and ((cp_rank == 0 and x.shape[2] <= 2) or (cp_rank != 0 and x.shape[2] <= 1)):
98
+ # This code is only for training 8 frames per GPU (except for cp_rank=0, 9 frames) with context parallel
99
+ # If you do not have enough GPU memory, you can set the total frames = 8 * CONTEXT_SIZE + 1, enable each GPU
100
+ # only forward 8 frames during training
101
+ x = cp_pass_from_previous_rank(x, dim=2, kernel_size=2) # pass one latent
102
+ trans_x = cp_pass_from_previous_rank(x[:, :, :-1], dim=2, kernel_size=2) # pass one latent
103
+ x = torch.cat([trans_x, x[:, :,-1:]], dim=2)
104
+ else:
105
+ x = cp_pass_from_previous_rank(x, dim=2, kernel_size=self.time_kernel_size)
106
+
107
+ x = F.pad(x, self.time_uncausal_padding, mode='constant')
108
+
109
+ if cp_rank != 0:
110
+ if self.temporal_stride == 2 and self.time_kernel_size == 3:
111
+ x = x[:,:,1:]
112
+
113
+ x = self.conv(x)
114
+ return x
115
+
116
+ def forward(self, x, is_init_image=True, temporal_chunk=False):
117
+ # temporal_chunk: whether to use the temporal chunk
118
+
119
+ if is_context_parallel_initialized():
120
+ return self.context_parallel_forward(x)
121
+
122
+ pad_mode = self.pad_mode if self.time_pad < x.shape[2] else 'constant'
123
+
124
+ if not temporal_chunk:
125
+ x = F.pad(x, self.time_causal_padding, mode=pad_mode)
126
+ else:
127
+ assert not self.training, "The feature cache should not be used in training"
128
+ if is_init_image:
129
+ # Encode the first chunk
130
+ x = F.pad(x, self.time_causal_padding, mode=pad_mode)
131
+ self._clear_context_parallel_cache()
132
+ self.cache_front_feat.append(x[:, :, -2:].clone().detach())
133
+ else:
134
+ x = F.pad(x, self.time_uncausal_padding, mode=pad_mode)
135
+ video_front_context = self.cache_front_feat.pop()
136
+ self._clear_context_parallel_cache()
137
+
138
+ if self.temporal_stride == 1 and self.time_kernel_size == 3:
139
+ x = torch.cat([video_front_context, x], dim=2)
140
+ elif self.temporal_stride == 2 and self.time_kernel_size == 3:
141
+ x = torch.cat([video_front_context[:,:,-1:], x], dim=2)
142
+
143
+ self.cache_front_feat.append(x[:, :, -2:].clone().detach())
144
+
145
+ x = self.conv(x)
146
+ return x
benchmarks/edit/code/FiVE-Bench/models/pyramid-edit/video_vae/modeling_causal_vae.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, Tuple, Union
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
6
+ from diffusers.models.attention_processor import (
7
+ ADDED_KV_ATTENTION_PROCESSORS,
8
+ CROSS_ATTENTION_PROCESSORS,
9
+ Attention,
10
+ AttentionProcessor,
11
+ AttnAddedKVProcessor,
12
+ AttnProcessor,
13
+ )
14
+
15
+ from diffusers.models.modeling_outputs import AutoencoderKLOutput
16
+ from diffusers.models.modeling_utils import ModelMixin
17
+
18
+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_
19
+ from .modeling_enc_dec import (
20
+ DecoderOutput, DiagonalGaussianDistribution,
21
+ CausalVaeDecoder, CausalVaeEncoder,
22
+ )
23
+ from .modeling_causal_conv import CausalConv3d
24
+
25
+ from utils import (
26
+ is_context_parallel_initialized,
27
+ get_context_parallel_group,
28
+ get_context_parallel_world_size,
29
+ get_context_parallel_rank,
30
+ get_context_parallel_group_rank,
31
+ )
32
+
33
+ from .context_parallel_ops import (
34
+ conv_scatter_to_context_parallel_region,
35
+ conv_gather_from_context_parallel_region,
36
+ )
37
+
38
+
39
+ class CausalVideoVAE(ModelMixin, ConfigMixin):
40
+ r"""
41
+ A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
42
+
43
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
44
+ for all models (such as downloading or saving).
45
+
46
+ Parameters:
47
+ in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
48
+ out_channels (int, *optional*, defaults to 3): Number of channels in the output.
49
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
50
+ Tuple of downsample block types.
51
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
52
+ Tuple of upsample block types.
53
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
54
+ Tuple of block output channels.
55
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
56
+ latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
57
+ sample_size (`int`, *optional*, defaults to `32`): Sample input size.
58
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
59
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
60
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
61
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
62
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
63
+ / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
64
+ Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
65
+ force_upcast (`bool`, *optional*, default to `True`):
66
+ If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
67
+ can be fine-tuned / trained to a lower range without loosing too much precision in which case
68
+ `force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
69
+ """
70
+
71
+ _supports_gradient_checkpointing = True
72
+
73
+ @register_to_config
74
+ def __init__(
75
+ self,
76
+ # encoder related parameters
77
+ encoder_in_channels: int = 3,
78
+ encoder_out_channels: int = 4,
79
+ encoder_layers_per_block: Tuple[int, ...] = (2, 2, 2, 2),
80
+ encoder_down_block_types: Tuple[str, ...] = (
81
+ "DownEncoderBlockCausal3D",
82
+ "DownEncoderBlockCausal3D",
83
+ "DownEncoderBlockCausal3D",
84
+ "DownEncoderBlockCausal3D",
85
+ ),
86
+ encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
87
+ encoder_spatial_down_sample: Tuple[bool, ...] = (True, True, True, False),
88
+ encoder_temporal_down_sample: Tuple[bool, ...] = (True, True, True, False),
89
+ encoder_block_dropout: Tuple[int, ...] = (0.0, 0.0, 0.0, 0.0),
90
+ encoder_act_fn: str = "silu",
91
+ encoder_norm_num_groups: int = 32,
92
+ encoder_double_z: bool = True,
93
+ encoder_type: str = 'causal_vae_conv',
94
+ # decoder related
95
+ decoder_in_channels: int = 4,
96
+ decoder_out_channels: int = 3,
97
+ decoder_layers_per_block: Tuple[int, ...] = (3, 3, 3, 3),
98
+ decoder_up_block_types: Tuple[str, ...] = (
99
+ "UpDecoderBlockCausal3D",
100
+ "UpDecoderBlockCausal3D",
101
+ "UpDecoderBlockCausal3D",
102
+ "UpDecoderBlockCausal3D",
103
+ ),
104
+ decoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
105
+ decoder_spatial_up_sample: Tuple[bool, ...] = (True, True, True, False),
106
+ decoder_temporal_up_sample: Tuple[bool, ...] = (True, True, True, False),
107
+ decoder_block_dropout: Tuple[int, ...] = (0.0, 0.0, 0.0, 0.0),
108
+ decoder_act_fn: str = "silu",
109
+ decoder_norm_num_groups: int = 32,
110
+ decoder_type: str = 'causal_vae_conv',
111
+ sample_size: int = 256,
112
+ scaling_factor: float = 0.18215,
113
+ add_post_quant_conv: bool = True,
114
+ interpolate: bool = False,
115
+ downsample_scale: int = 8,
116
+ ):
117
+ super().__init__()
118
+
119
+ print(f"The latent dimmension channes is {encoder_out_channels}")
120
+ # pass init params to Encoder
121
+
122
+ self.encoder = CausalVaeEncoder(
123
+ in_channels=encoder_in_channels,
124
+ out_channels=encoder_out_channels,
125
+ down_block_types=encoder_down_block_types,
126
+ spatial_down_sample=encoder_spatial_down_sample,
127
+ temporal_down_sample=encoder_temporal_down_sample,
128
+ block_out_channels=encoder_block_out_channels,
129
+ layers_per_block=encoder_layers_per_block,
130
+ act_fn=encoder_act_fn,
131
+ norm_num_groups=encoder_norm_num_groups,
132
+ double_z=True,
133
+ block_dropout=encoder_block_dropout,
134
+ )
135
+
136
+ # pass init params to Decoder
137
+ self.decoder = CausalVaeDecoder(
138
+ in_channels=decoder_in_channels,
139
+ out_channels=decoder_out_channels,
140
+ up_block_types=decoder_up_block_types,
141
+ spatial_up_sample=decoder_spatial_up_sample,
142
+ temporal_up_sample=decoder_temporal_up_sample,
143
+ block_out_channels=decoder_block_out_channels,
144
+ layers_per_block=decoder_layers_per_block,
145
+ norm_num_groups=decoder_norm_num_groups,
146
+ act_fn=decoder_act_fn,
147
+ interpolate=interpolate,
148
+ block_dropout=decoder_block_dropout,
149
+ )
150
+
151
+ self.quant_conv = CausalConv3d(2 * encoder_out_channels, 2 * encoder_out_channels, kernel_size=1, stride=1)
152
+ self.post_quant_conv = CausalConv3d(encoder_out_channels, encoder_out_channels, kernel_size=1, stride=1)
153
+ self.use_tiling = False
154
+
155
+ # only relevant if vae tiling is enabled
156
+ self.tile_sample_min_size = self.config.sample_size
157
+
158
+ sample_size = (
159
+ self.config.sample_size[0]
160
+ if isinstance(self.config.sample_size, (list, tuple))
161
+ else self.config.sample_size
162
+ )
163
+ self.tile_latent_min_size = int(sample_size / downsample_scale)
164
+ self.encode_tile_overlap_factor = 1 / 4
165
+ self.decode_tile_overlap_factor = 1 / 4
166
+ self.downsample_scale = downsample_scale
167
+
168
+ self.apply(self._init_weights)
169
+
170
+ def _init_weights(self, m):
171
+ if isinstance(m, (nn.Linear, nn.Conv2d, nn.Conv3d)):
172
+ trunc_normal_(m.weight, std=.02)
173
+ if m.bias is not None:
174
+ nn.init.constant_(m.bias, 0)
175
+ elif isinstance(m, (nn.LayerNorm, nn.GroupNorm)):
176
+ nn.init.constant_(m.bias, 0)
177
+ nn.init.constant_(m.weight, 1.0)
178
+
179
+ def _set_gradient_checkpointing(self, module, value=False):
180
+ if isinstance(module, (Encoder, Decoder)):
181
+ module.gradient_checkpointing = value
182
+
183
+ def enable_tiling(self, use_tiling: bool = True):
184
+ r"""
185
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
186
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
187
+ processing larger images.
188
+ """
189
+ self.use_tiling = use_tiling
190
+
191
+ def disable_tiling(self):
192
+ r"""
193
+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
194
+ decoding in one step.
195
+ """
196
+ self.enable_tiling(False)
197
+
198
+ @property
199
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
200
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
201
+ r"""
202
+ Returns:
203
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
204
+ indexed by its weight name.
205
+ """
206
+ # set recursively
207
+ processors = {}
208
+
209
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
210
+ if hasattr(module, "get_processor"):
211
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
212
+
213
+ for sub_name, child in module.named_children():
214
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
215
+
216
+ return processors
217
+
218
+ for name, module in self.named_children():
219
+ fn_recursive_add_processors(name, module, processors)
220
+
221
+ return processors
222
+
223
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
224
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
225
+ r"""
226
+ Sets the attention processor to use to compute attention.
227
+
228
+ Parameters:
229
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
230
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
231
+ for **all** `Attention` layers.
232
+
233
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
234
+ processor. This is strongly recommended when setting trainable attention processors.
235
+
236
+ """
237
+ count = len(self.attn_processors.keys())
238
+
239
+ if isinstance(processor, dict) and len(processor) != count:
240
+ raise ValueError(
241
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
242
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
243
+ )
244
+
245
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
246
+ if hasattr(module, "set_processor"):
247
+ if not isinstance(processor, dict):
248
+ module.set_processor(processor)
249
+ else:
250
+ module.set_processor(processor.pop(f"{name}.processor"))
251
+
252
+ for sub_name, child in module.named_children():
253
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
254
+
255
+ for name, module in self.named_children():
256
+ fn_recursive_attn_processor(name, module, processor)
257
+
258
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
259
+ def set_default_attn_processor(self):
260
+ """
261
+ Disables custom attention processors and sets the default attention implementation.
262
+ """
263
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
264
+ processor = AttnAddedKVProcessor()
265
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
266
+ processor = AttnProcessor()
267
+ else:
268
+ raise ValueError(
269
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
270
+ )
271
+
272
+ self.set_attn_processor(processor)
273
+
274
+ def encode(
275
+ self, x: torch.FloatTensor, return_dict: bool = True,
276
+ is_init_image=True, temporal_chunk=False, window_size=16, tile_sample_min_size=256,
277
+ ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
278
+ """
279
+ Encode a batch of images into latents.
280
+
281
+ Args:
282
+ x (`torch.FloatTensor`): Input batch of images.
283
+ return_dict (`bool`, *optional*, defaults to `True`):
284
+ Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
285
+
286
+ Returns:
287
+ The latent representations of the encoded images. If `return_dict` is True, a
288
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
289
+ """
290
+ self.tile_sample_min_size = tile_sample_min_size
291
+ self.tile_latent_min_size = int(tile_sample_min_size / self.downsample_scale)
292
+
293
+ if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
294
+ return self.tiled_encode(x, return_dict=return_dict, is_init_image=is_init_image,
295
+ temporal_chunk=temporal_chunk, window_size=window_size)
296
+
297
+ if temporal_chunk:
298
+ moments = self.chunk_encode(x, window_size=window_size)
299
+ else:
300
+ h = self.encoder(x, is_init_image=is_init_image, temporal_chunk=False)
301
+ moments = self.quant_conv(h, is_init_image=is_init_image, temporal_chunk=False)
302
+
303
+ posterior = DiagonalGaussianDistribution(moments)
304
+
305
+ if not return_dict:
306
+ return (posterior,)
307
+
308
+ return AutoencoderKLOutput(latent_dist=posterior)
309
+
310
+ @torch.no_grad()
311
+ def chunk_encode(self, x: torch.FloatTensor, window_size=16):
312
+ # Only used during inference
313
+ # Encode a long video clips through sliding window
314
+ num_frames = x.shape[2]
315
+ assert (num_frames - 1) % self.downsample_scale == 0
316
+ init_window_size = window_size + 1
317
+ frame_list = [x[:,:,:init_window_size]]
318
+
319
+ # To chunk the long video
320
+ full_chunk_size = (num_frames - init_window_size) // window_size
321
+ fid = init_window_size
322
+ for idx in range(full_chunk_size):
323
+ frame_list.append(x[:, :, fid:fid+window_size])
324
+ fid += window_size
325
+
326
+ if fid < num_frames:
327
+ frame_list.append(x[:, :, fid:])
328
+
329
+ latent_list = []
330
+ for idx, frames in enumerate(frame_list):
331
+ if idx == 0:
332
+ h = self.encoder(frames, is_init_image=True, temporal_chunk=True)
333
+ moments = self.quant_conv(h, is_init_image=True, temporal_chunk=True)
334
+ else:
335
+ h = self.encoder(frames, is_init_image=False, temporal_chunk=True)
336
+ moments = self.quant_conv(h, is_init_image=False, temporal_chunk=True)
337
+
338
+ latent_list.append(moments)
339
+
340
+ latent = torch.cat(latent_list, dim=2)
341
+ return latent
342
+
343
+ def get_last_layer(self):
344
+ return self.decoder.conv_out.conv.weight
345
+
346
+ @torch.no_grad()
347
+ def chunk_decode(self, z: torch.FloatTensor, window_size=2):
348
+ num_frames = z.shape[2]
349
+ init_window_size = window_size + 1
350
+ frame_list = [z[:,:,:init_window_size]]
351
+
352
+ # To chunk the long video
353
+ full_chunk_size = (num_frames - init_window_size) // window_size
354
+ fid = init_window_size
355
+ for idx in range(full_chunk_size):
356
+ frame_list.append(z[:, :, fid:fid+window_size])
357
+ fid += window_size
358
+
359
+ if fid < num_frames:
360
+ frame_list.append(z[:, :, fid:])
361
+
362
+ dec_list = []
363
+ for idx, frames in enumerate(frame_list):
364
+ if idx == 0:
365
+ z_h = self.post_quant_conv(frames, is_init_image=True, temporal_chunk=True)
366
+ dec = self.decoder(z_h, is_init_image=True, temporal_chunk=True)
367
+ else:
368
+ z_h = self.post_quant_conv(frames, is_init_image=False, temporal_chunk=True)
369
+ dec = self.decoder(z_h, is_init_image=False, temporal_chunk=True)
370
+
371
+ dec_list.append(dec)
372
+
373
+ dec = torch.cat(dec_list, dim=2)
374
+ return dec
375
+
376
+ def decode(self, z: torch.FloatTensor, is_init_image=True, temporal_chunk=False,
377
+ return_dict: bool = True, window_size: int = 2, tile_sample_min_size: int = 256,) -> Union[DecoderOutput, torch.FloatTensor]:
378
+
379
+ self.tile_sample_min_size = tile_sample_min_size
380
+ self.tile_latent_min_size = int(tile_sample_min_size / self.downsample_scale)
381
+
382
+ if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
383
+ return self.tiled_decode(z, is_init_image=is_init_image,
384
+ temporal_chunk=temporal_chunk, window_size=window_size, return_dict=return_dict)
385
+
386
+ if temporal_chunk:
387
+ dec = self.chunk_decode(z, window_size=window_size)
388
+ else:
389
+ z = self.post_quant_conv(z, is_init_image=is_init_image, temporal_chunk=False)
390
+ dec = self.decoder(z, is_init_image=is_init_image, temporal_chunk=False)
391
+
392
+ if not return_dict:
393
+ return (dec,)
394
+
395
+ return DecoderOutput(sample=dec)
396
+
397
+ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
398
+ blend_extent = min(a.shape[3], b.shape[3], blend_extent)
399
+ for y in range(blend_extent):
400
+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (y / blend_extent)
401
+ return b
402
+
403
+ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
404
+ blend_extent = min(a.shape[4], b.shape[4], blend_extent)
405
+ for x in range(blend_extent):
406
+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (x / blend_extent)
407
+ return b
408
+
409
+ def tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True,
410
+ is_init_image=True, temporal_chunk=False, window_size=16,) -> AutoencoderKLOutput:
411
+ r"""Encode a batch of images using a tiled encoder.
412
+
413
+ When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
414
+ steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
415
+ different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
416
+ tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
417
+ output, but they should be much less noticeable.
418
+
419
+ Args:
420
+ x (`torch.FloatTensor`): Input batch of images.
421
+ return_dict (`bool`, *optional*, defaults to `True`):
422
+ Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
423
+
424
+ Returns:
425
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`:
426
+ If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain
427
+ `tuple` is returned.
428
+ """
429
+ overlap_size = int(self.tile_sample_min_size * (1 - self.encode_tile_overlap_factor))
430
+ blend_extent = int(self.tile_latent_min_size * self.encode_tile_overlap_factor)
431
+ row_limit = self.tile_latent_min_size - blend_extent
432
+
433
+ # Split the image into 512x512 tiles and encode them separately.
434
+ rows = []
435
+ for i in range(0, x.shape[3], overlap_size):
436
+ row = []
437
+ for j in range(0, x.shape[4], overlap_size):
438
+ tile = x[:, :, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
439
+ if temporal_chunk:
440
+ tile = self.chunk_encode(tile, window_size=window_size)
441
+ else:
442
+ tile = self.encoder(tile, is_init_image=True, temporal_chunk=False)
443
+ tile = self.quant_conv(tile, is_init_image=True, temporal_chunk=False)
444
+ row.append(tile)
445
+ rows.append(row)
446
+ result_rows = []
447
+ for i, row in enumerate(rows):
448
+ result_row = []
449
+ for j, tile in enumerate(row):
450
+ # blend the above tile and the left tile
451
+ # to the current tile and add the current tile to the result row
452
+ if i > 0:
453
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
454
+ if j > 0:
455
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
456
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
457
+ result_rows.append(torch.cat(result_row, dim=4))
458
+
459
+ moments = torch.cat(result_rows, dim=3)
460
+
461
+ posterior = DiagonalGaussianDistribution(moments)
462
+
463
+ if not return_dict:
464
+ return (posterior,)
465
+
466
+ return AutoencoderKLOutput(latent_dist=posterior)
467
+
468
+ def tiled_decode(self, z: torch.FloatTensor, is_init_image=True,
469
+ temporal_chunk=False, window_size=2, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
470
+ r"""
471
+ Decode a batch of images using a tiled decoder.
472
+
473
+ Args:
474
+ z (`torch.FloatTensor`): Input batch of latent vectors.
475
+ return_dict (`bool`, *optional*, defaults to `True`):
476
+ Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
477
+
478
+ Returns:
479
+ [`~models.vae.DecoderOutput`] or `tuple`:
480
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
481
+ returned.
482
+ """
483
+ overlap_size = int(self.tile_latent_min_size * (1 - self.decode_tile_overlap_factor))
484
+ blend_extent = int(self.tile_sample_min_size * self.decode_tile_overlap_factor)
485
+ row_limit = self.tile_sample_min_size - blend_extent
486
+
487
+ # Split z into overlapping 64x64 tiles and decode them separately.
488
+ # The tiles have an overlap to avoid seams between tiles.
489
+ rows = []
490
+ for i in range(0, z.shape[3], overlap_size):
491
+ row = []
492
+ for j in range(0, z.shape[4], overlap_size):
493
+ tile = z[:, :, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
494
+ if temporal_chunk:
495
+ decoded = self.chunk_decode(tile, window_size=window_size)
496
+ else:
497
+ tile = self.post_quant_conv(tile, is_init_image=True, temporal_chunk=False)
498
+ decoded = self.decoder(tile, is_init_image=True, temporal_chunk=False)
499
+ row.append(decoded)
500
+ rows.append(row)
501
+ result_rows = []
502
+
503
+ for i, row in enumerate(rows):
504
+ result_row = []
505
+ for j, tile in enumerate(row):
506
+ # blend the above tile and the left tile
507
+ # to the current tile and add the current tile to the result row
508
+ if i > 0:
509
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
510
+ if j > 0:
511
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
512
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
513
+ result_rows.append(torch.cat(result_row, dim=4))
514
+
515
+ dec = torch.cat(result_rows, dim=3)
516
+ if not return_dict:
517
+ return (dec,)
518
+
519
+ return DecoderOutput(sample=dec)
520
+
521
+ def forward(
522
+ self,
523
+ sample: torch.FloatTensor,
524
+ sample_posterior: bool = True,
525
+ generator: Optional[torch.Generator] = None,
526
+ freeze_encoder: bool = False,
527
+ is_init_image=True,
528
+ temporal_chunk=False,
529
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
530
+ r"""
531
+ Args:
532
+ sample (`torch.FloatTensor`): Input sample.
533
+ sample_posterior (`bool`, *optional*, defaults to `False`):
534
+ Whether to sample from the posterior.
535
+ return_dict (`bool`, *optional*, defaults to `True`):
536
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
537
+ """
538
+ x = sample
539
+
540
+ if is_context_parallel_initialized():
541
+ assert self.training, "Only supports during training now"
542
+
543
+ if freeze_encoder:
544
+ with torch.no_grad():
545
+ h = self.encoder(x, is_init_image=True, temporal_chunk=False)
546
+ moments = self.quant_conv(h, is_init_image=True, temporal_chunk=False)
547
+ posterior = DiagonalGaussianDistribution(moments)
548
+ global_posterior = posterior
549
+ else:
550
+ h = self.encoder(x, is_init_image=True, temporal_chunk=False)
551
+ moments = self.quant_conv(h, is_init_image=True, temporal_chunk=False)
552
+ posterior = DiagonalGaussianDistribution(moments)
553
+ global_moments = conv_gather_from_context_parallel_region(moments, dim=2, kernel_size=1)
554
+ global_posterior = DiagonalGaussianDistribution(global_moments)
555
+
556
+ if sample_posterior:
557
+ z = posterior.sample(generator=generator)
558
+ else:
559
+ z = posterior.mode()
560
+
561
+ if get_context_parallel_rank() == 0:
562
+ dec = self.decode(z, is_init_image=True).sample
563
+ else:
564
+ # Do not drop the first upsampled frame
565
+ dec = self.decode(z, is_init_image=False).sample
566
+
567
+ return global_posterior, dec
568
+
569
+ else:
570
+ # The normal training
571
+ if freeze_encoder:
572
+ with torch.no_grad():
573
+ posterior = self.encode(x, is_init_image=is_init_image,
574
+ temporal_chunk=temporal_chunk).latent_dist
575
+ else:
576
+ posterior = self.encode(x, is_init_image=is_init_image,
577
+ temporal_chunk=temporal_chunk).latent_dist
578
+
579
+ if sample_posterior:
580
+ z = posterior.sample(generator=generator)
581
+ else:
582
+ z = posterior.mode()
583
+
584
+ dec = self.decode(z, is_init_image=is_init_image, temporal_chunk=temporal_chunk).sample
585
+
586
+ return posterior, dec
587
+
588
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
589
+ def fuse_qkv_projections(self):
590
+ """
591
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
592
+ key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
593
+
594
+ <Tip warning={true}>
595
+
596
+ This API is 🧪 experimental.
597
+
598
+ </Tip>
599
+ """
600
+ self.original_attn_processors = None
601
+
602
+ for _, attn_processor in self.attn_processors.items():
603
+ if "Added" in str(attn_processor.__class__.__name__):
604
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
605
+
606
+ self.original_attn_processors = self.attn_processors
607
+
608
+ for module in self.modules():
609
+ if isinstance(module, Attention):
610
+ module.fuse_projections(fuse=True)
611
+
612
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
613
+ def unfuse_qkv_projections(self):
614
+ """Disables the fused QKV projection if enabled.
615
+
616
+ <Tip warning={true}>
617
+
618
+ This API is 🧪 experimental.
619
+
620
+ </Tip>
621
+
622
+ """
623
+ if self.original_attn_processors is not None:
624
+ self.set_attn_processor(self.original_attn_processors)