Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Helios/_DEV/tools/gradio/comparison/gradio_compare_diff-ckpt.py +547 -0
- Helios/_DEV/tools/gradio/comparison/gradio_compare_diff-video.py +450 -0
- Helios/_DEV/tools/others/benchmark/benchmark_compile_performance.py +234 -0
- Helios/_DEV/tools/others/benchmark/benchmark_compile_results.txt +269 -0
- Helios/_DEV/tools/others/benchmark/benchmark_patchification_performance.py +381 -0
- Helios/_DEV/tools/others/benchmark/benchmark_patchification_results.json +309 -0
- Helios/_DEV/tools/others/benchmark/benchmark_triton_performance.py +659 -0
- Helios/_DEV/tools/others/benchmark/benchmark_triton_results_helios.json +111 -0
- Helios/_DEV/tools/others/benchmark/benchmark_triton_results_wan.json +111 -0
- Helios/_DEV2/__pycache__/infer_helios.cpython-312.pyc +0 -0
- Helios/_DEV2/demo_data/MovieGenVideoBench_extended.txt +0 -0
- Helios/_DEV2/demo_data/VBench_extended.txt +0 -0
- Helios/_DEV2/example/prompt.txt +11 -0
- Helios/_DEV2/example/prompt_interactive_helios.csv +54 -0
- Helios/_DEV2/example/toy_data/toy_filter.json +46 -0
- Helios/_DEV2/helios/__init__.py +0 -0
- Helios/_DEV2/helios/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/__pycache__/__init__.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/dataset/__init__.py +0 -0
- Helios/_DEV2/helios/dataset/dataloader_dmd.py +531 -0
- Helios/_DEV2/helios/dataset/dataloader_history_latents_dist.py +685 -0
- Helios/_DEV2/helios/dataset/dataloader_mp4_dist.py +854 -0
- Helios/_DEV2/helios/diffusers_version/__init__.py +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/__init__.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/scheduling_helios_diffusers.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/scheduling_helios_diffusers.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/transformer_helios_diffusers.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/__pycache__/transformer_helios_diffusers.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/diffusers_version/pipeline_helios_diffusers.py +1460 -0
- Helios/_DEV2/helios/diffusers_version/scheduling_helios_diffusers.py +947 -0
- Helios/_DEV2/helios/diffusers_version/transformer_helios_diffusers.py +1005 -0
- Helios/_DEV2/helios/modules/__init__.py +0 -0
- Helios/_DEV2/helios/modules/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/modules/__pycache__/__init__.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/modules/__pycache__/transformer_helios.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__init__.py +5 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/__init__.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/attention_dispatch.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/attention_dispatch.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/fp32_rmsnorm.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/fp32_rmsnorm.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/tiled_linear.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/tiled_linear.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/triton_norm.cpython-311.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/triton_norm.cpython-312.pyc +0 -0
- Helios/_DEV2/helios/modules/helios_kernels/__pycache__/triton_rope.cpython-311.pyc +0 -0
Helios/_DEV/tools/gradio/comparison/gradio_compare_diff-ckpt.py
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_video_name(filename):
|
| 8 |
+
"""Parse video filename to extract step and index"""
|
| 9 |
+
# Match checkpoint-{step}_{idx}.mp4 format
|
| 10 |
+
match = re.match(r"checkpoint-(\d+)_(\d+)\.mp4$", filename)
|
| 11 |
+
if match:
|
| 12 |
+
step = int(match.group(1))
|
| 13 |
+
idx = int(match.group(2))
|
| 14 |
+
return step, idx
|
| 15 |
+
return None, None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_video_list(folder_path):
|
| 19 |
+
"""Get all mp4 videos from folder"""
|
| 20 |
+
if not os.path.exists(folder_path):
|
| 21 |
+
return []
|
| 22 |
+
|
| 23 |
+
videos = []
|
| 24 |
+
for file in os.listdir(folder_path):
|
| 25 |
+
if file.endswith(".mp4"):
|
| 26 |
+
step, idx = parse_video_name(file)
|
| 27 |
+
if step is not None:
|
| 28 |
+
videos.append({"filename": file, "step": step, "idx": idx, "path": os.path.join(folder_path, file)})
|
| 29 |
+
|
| 30 |
+
# Sort by step and idx
|
| 31 |
+
videos.sort(key=lambda x: (x["step"], x["idx"]))
|
| 32 |
+
return videos
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def create_video_mapping(videos):
|
| 36 |
+
"""Create (step, idx) -> filename mapping"""
|
| 37 |
+
mapping = {}
|
| 38 |
+
for video in videos:
|
| 39 |
+
key = (video["step"], video["idx"])
|
| 40 |
+
mapping[key] = video["filename"]
|
| 41 |
+
return mapping
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_step_idx_mapping(common_keys):
|
| 45 |
+
"""Extract step and idx mapping from common (step, idx) keys"""
|
| 46 |
+
step_idx_map = {} # {step: [idx1, idx2, ...]}
|
| 47 |
+
all_steps = set()
|
| 48 |
+
all_indices = set()
|
| 49 |
+
|
| 50 |
+
for step, idx in common_keys:
|
| 51 |
+
all_steps.add(step)
|
| 52 |
+
all_indices.add(idx)
|
| 53 |
+
if step not in step_idx_map:
|
| 54 |
+
step_idx_map[step] = []
|
| 55 |
+
step_idx_map[step].append(idx)
|
| 56 |
+
|
| 57 |
+
# Sort
|
| 58 |
+
for step in step_idx_map:
|
| 59 |
+
step_idx_map[step].sort()
|
| 60 |
+
|
| 61 |
+
return sorted(all_steps), sorted(all_indices), step_idx_map
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_videos(folder1, folder2):
|
| 65 |
+
"""Load videos from both folders and match them"""
|
| 66 |
+
if not folder1 or not folder2:
|
| 67 |
+
return (
|
| 68 |
+
None,
|
| 69 |
+
None,
|
| 70 |
+
"Please enter both folder paths",
|
| 71 |
+
gr.update(choices=[], value=None),
|
| 72 |
+
gr.update(choices=[], value=None),
|
| 73 |
+
gr.update(interactive=False),
|
| 74 |
+
gr.update(interactive=False),
|
| 75 |
+
gr.update(interactive=False),
|
| 76 |
+
gr.update(interactive=False),
|
| 77 |
+
"0 / 0",
|
| 78 |
+
{},
|
| 79 |
+
{},
|
| 80 |
+
{},
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
videos1 = get_video_list(folder1)
|
| 84 |
+
videos2 = get_video_list(folder2)
|
| 85 |
+
|
| 86 |
+
if not videos1:
|
| 87 |
+
return (
|
| 88 |
+
None,
|
| 89 |
+
None,
|
| 90 |
+
f"No video files found in folder 1 (total {len(os.listdir(folder1)) if os.path.exists(folder1) else 0} files)",
|
| 91 |
+
gr.update(choices=[], value=None),
|
| 92 |
+
gr.update(choices=[], value=None),
|
| 93 |
+
gr.update(interactive=False),
|
| 94 |
+
gr.update(interactive=False),
|
| 95 |
+
gr.update(interactive=False),
|
| 96 |
+
gr.update(interactive=False),
|
| 97 |
+
"0 / 0",
|
| 98 |
+
{},
|
| 99 |
+
{},
|
| 100 |
+
{},
|
| 101 |
+
)
|
| 102 |
+
if not videos2:
|
| 103 |
+
return (
|
| 104 |
+
None,
|
| 105 |
+
None,
|
| 106 |
+
f"No video files found in folder 2 (total {len(os.listdir(folder2)) if os.path.exists(folder2) else 0} files)",
|
| 107 |
+
gr.update(choices=[], value=None),
|
| 108 |
+
gr.update(choices=[], value=None),
|
| 109 |
+
gr.update(interactive=False),
|
| 110 |
+
gr.update(interactive=False),
|
| 111 |
+
gr.update(interactive=False),
|
| 112 |
+
gr.update(interactive=False),
|
| 113 |
+
"0 / 0",
|
| 114 |
+
{},
|
| 115 |
+
{},
|
| 116 |
+
{},
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# Create (step, idx) to filename mapping
|
| 120 |
+
video_map1 = create_video_mapping(videos1)
|
| 121 |
+
video_map2 = create_video_mapping(videos2)
|
| 122 |
+
|
| 123 |
+
# Find common (step, idx) combinations
|
| 124 |
+
common_keys = sorted(set(video_map1.keys()) & set(video_map2.keys()))
|
| 125 |
+
|
| 126 |
+
if not common_keys:
|
| 127 |
+
# Show detailed information for debugging
|
| 128 |
+
steps1 = {v["step"] for v in videos1}
|
| 129 |
+
steps2 = {v["step"] for v in videos2}
|
| 130 |
+
info = "No matching videos found in both folders\n"
|
| 131 |
+
info += f"Folder 1: {len(videos1)} videos found\n"
|
| 132 |
+
info += f"Folder 2: {len(videos2)} videos found\n"
|
| 133 |
+
info += f"Folder 1 steps: {sorted(steps1)}\n"
|
| 134 |
+
info += f"Folder 2 steps: {sorted(steps2)}\n"
|
| 135 |
+
info += f"Common steps: {sorted(steps1 & steps2)}"
|
| 136 |
+
return (
|
| 137 |
+
None,
|
| 138 |
+
None,
|
| 139 |
+
info,
|
| 140 |
+
gr.update(choices=[], value=None),
|
| 141 |
+
gr.update(choices=[], value=None),
|
| 142 |
+
gr.update(interactive=False),
|
| 143 |
+
gr.update(interactive=False),
|
| 144 |
+
gr.update(interactive=False),
|
| 145 |
+
gr.update(interactive=False),
|
| 146 |
+
"0 / 0",
|
| 147 |
+
{},
|
| 148 |
+
{},
|
| 149 |
+
{},
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Get all steps and indices
|
| 153 |
+
all_steps, all_indices, step_idx_map = get_step_idx_mapping(common_keys)
|
| 154 |
+
|
| 155 |
+
# Load first video
|
| 156 |
+
first_key = common_keys[0]
|
| 157 |
+
first_step, first_idx = first_key
|
| 158 |
+
|
| 159 |
+
filename1 = video_map1[first_key]
|
| 160 |
+
filename2 = video_map2[first_key]
|
| 161 |
+
|
| 162 |
+
video1_path = os.path.join(folder1, filename1)
|
| 163 |
+
video2_path = os.path.join(folder2, filename2)
|
| 164 |
+
|
| 165 |
+
info = f"Found {len(common_keys)} matching video pairs\n"
|
| 166 |
+
info += f"Folder 1: {len(videos1)} videos\n"
|
| 167 |
+
info += f"Folder 2: {len(videos2)} videos\n"
|
| 168 |
+
info += f"Current: Step {first_step}, Index {first_idx}\n"
|
| 169 |
+
info += f"File 1: {filename1}\n"
|
| 170 |
+
info += f"File 2: {filename2}"
|
| 171 |
+
|
| 172 |
+
# Get available indices for current step
|
| 173 |
+
available_indices = step_idx_map.get(first_step, [])
|
| 174 |
+
|
| 175 |
+
progress = f"1 / {len(common_keys)}"
|
| 176 |
+
|
| 177 |
+
return (
|
| 178 |
+
video1_path,
|
| 179 |
+
video2_path,
|
| 180 |
+
info,
|
| 181 |
+
gr.update(choices=all_steps, value=first_step),
|
| 182 |
+
gr.update(choices=available_indices, value=first_idx),
|
| 183 |
+
gr.update(interactive=first_step > all_steps[0]),
|
| 184 |
+
gr.update(interactive=first_step < all_steps[-1]),
|
| 185 |
+
gr.update(interactive=first_idx > available_indices[0] if available_indices else False),
|
| 186 |
+
gr.update(interactive=first_idx < available_indices[-1] if available_indices else False),
|
| 187 |
+
progress,
|
| 188 |
+
video_map1,
|
| 189 |
+
video_map2,
|
| 190 |
+
step_idx_map,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def update_available_indices(selected_step, step_idx_map):
|
| 195 |
+
"""Update available index list"""
|
| 196 |
+
if not step_idx_map or selected_step is None:
|
| 197 |
+
return gr.update(choices=[], value=None)
|
| 198 |
+
|
| 199 |
+
available_indices = step_idx_map.get(selected_step, [])
|
| 200 |
+
first_idx = available_indices[0] if available_indices else None
|
| 201 |
+
|
| 202 |
+
return gr.update(choices=available_indices, value=first_idx)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def update_videos_from_selectors(folder1, folder2, selected_step, selected_idx, video_map1, video_map2, step_idx_map):
|
| 206 |
+
"""Update videos based on selected step and idx"""
|
| 207 |
+
if selected_step is None or selected_idx is None:
|
| 208 |
+
return None, None, "Please select step and index", gr.update(), gr.update(), gr.update(), gr.update(), ""
|
| 209 |
+
|
| 210 |
+
key = (selected_step, selected_idx)
|
| 211 |
+
|
| 212 |
+
if key not in video_map1 or key not in video_map2:
|
| 213 |
+
return (
|
| 214 |
+
None,
|
| 215 |
+
None,
|
| 216 |
+
f"Video not found for Step {selected_step}, Index {selected_idx}",
|
| 217 |
+
gr.update(),
|
| 218 |
+
gr.update(),
|
| 219 |
+
gr.update(),
|
| 220 |
+
gr.update(),
|
| 221 |
+
"",
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
filename1 = video_map1[key]
|
| 225 |
+
filename2 = video_map2[key]
|
| 226 |
+
|
| 227 |
+
video1_path = os.path.join(folder1, filename1)
|
| 228 |
+
video2_path = os.path.join(folder2, filename2)
|
| 229 |
+
|
| 230 |
+
info = f"Current: Step {selected_step}, Index {selected_idx}\n"
|
| 231 |
+
info += f"File 1: {filename1}\n"
|
| 232 |
+
info += f"File 2: {filename2}"
|
| 233 |
+
|
| 234 |
+
# Get all steps and indices for current step
|
| 235 |
+
all_steps = sorted(step_idx_map.keys())
|
| 236 |
+
available_indices = step_idx_map.get(selected_step, [])
|
| 237 |
+
|
| 238 |
+
# Update button states
|
| 239 |
+
prev_step_interactive = selected_step > all_steps[0]
|
| 240 |
+
next_step_interactive = selected_step < all_steps[-1]
|
| 241 |
+
prev_idx_interactive = selected_idx > available_indices[0] if available_indices else False
|
| 242 |
+
next_idx_interactive = selected_idx < available_indices[-1] if available_indices else False
|
| 243 |
+
|
| 244 |
+
# Calculate current video position
|
| 245 |
+
all_keys = sorted(set(video_map1.keys()) & set(video_map2.keys()))
|
| 246 |
+
current_idx = all_keys.index(key) + 1
|
| 247 |
+
progress = f"{current_idx} / {len(all_keys)}"
|
| 248 |
+
|
| 249 |
+
return (
|
| 250 |
+
video1_path,
|
| 251 |
+
video2_path,
|
| 252 |
+
info,
|
| 253 |
+
gr.update(interactive=prev_step_interactive),
|
| 254 |
+
gr.update(interactive=next_step_interactive),
|
| 255 |
+
gr.update(interactive=prev_idx_interactive),
|
| 256 |
+
gr.update(interactive=next_idx_interactive),
|
| 257 |
+
progress,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def navigate_step(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction):
|
| 262 |
+
"""Navigate to previous or next step"""
|
| 263 |
+
if not step_idx_map or current_step is None:
|
| 264 |
+
return (
|
| 265 |
+
None,
|
| 266 |
+
None,
|
| 267 |
+
"Please load videos first",
|
| 268 |
+
current_step,
|
| 269 |
+
current_idx,
|
| 270 |
+
gr.update(),
|
| 271 |
+
gr.update(),
|
| 272 |
+
gr.update(),
|
| 273 |
+
gr.update(),
|
| 274 |
+
"",
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
all_steps = sorted(step_idx_map.keys())
|
| 278 |
+
current_step_idx = all_steps.index(current_step)
|
| 279 |
+
|
| 280 |
+
if direction == "prev":
|
| 281 |
+
new_step_idx = max(0, current_step_idx - 1)
|
| 282 |
+
else: # next
|
| 283 |
+
new_step_idx = min(len(all_steps) - 1, current_step_idx + 1)
|
| 284 |
+
|
| 285 |
+
new_step = all_steps[new_step_idx]
|
| 286 |
+
|
| 287 |
+
# Get first available index for new step
|
| 288 |
+
available_indices = step_idx_map.get(new_step, [])
|
| 289 |
+
new_idx = available_indices[0] if available_indices else current_idx
|
| 290 |
+
|
| 291 |
+
return update_videos_from_selectors(folder1, folder2, new_step, new_idx, video_map1, video_map2, step_idx_map) + (
|
| 292 |
+
new_step,
|
| 293 |
+
new_idx,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def navigate_idx(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction):
|
| 298 |
+
"""Navigate to previous or next index"""
|
| 299 |
+
if not step_idx_map or current_step is None or current_idx is None:
|
| 300 |
+
return (
|
| 301 |
+
None,
|
| 302 |
+
None,
|
| 303 |
+
"Please load videos first",
|
| 304 |
+
current_step,
|
| 305 |
+
current_idx,
|
| 306 |
+
gr.update(),
|
| 307 |
+
gr.update(),
|
| 308 |
+
gr.update(),
|
| 309 |
+
gr.update(),
|
| 310 |
+
"",
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
available_indices = step_idx_map.get(current_step, [])
|
| 314 |
+
if not available_indices or current_idx not in available_indices:
|
| 315 |
+
return (
|
| 316 |
+
None,
|
| 317 |
+
None,
|
| 318 |
+
"Index not in list",
|
| 319 |
+
current_step,
|
| 320 |
+
current_idx,
|
| 321 |
+
gr.update(),
|
| 322 |
+
gr.update(),
|
| 323 |
+
gr.update(),
|
| 324 |
+
gr.update(),
|
| 325 |
+
"",
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
current_idx_pos = available_indices.index(current_idx)
|
| 329 |
+
|
| 330 |
+
if direction == "prev":
|
| 331 |
+
new_idx_pos = max(0, current_idx_pos - 1)
|
| 332 |
+
else: # next
|
| 333 |
+
new_idx_pos = min(len(available_indices) - 1, current_idx_pos + 1)
|
| 334 |
+
|
| 335 |
+
new_idx = available_indices[new_idx_pos]
|
| 336 |
+
|
| 337 |
+
return update_videos_from_selectors(
|
| 338 |
+
folder1, folder2, current_step, new_idx, video_map1, video_map2, step_idx_map
|
| 339 |
+
) + (current_step, new_idx)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# Create Gradio interface
|
| 343 |
+
with gr.Blocks(title="Video Comparison Tool") as demo:
|
| 344 |
+
gr.Markdown("# Video Comparison Tool")
|
| 345 |
+
gr.Markdown(
|
| 346 |
+
"Enter two folder paths to automatically match and compare checkpoint-{step}_{idx}.mp4 format video files"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Store state
|
| 350 |
+
video_map1_state = gr.State({})
|
| 351 |
+
video_map2_state = gr.State({})
|
| 352 |
+
step_idx_map_state = gr.State({})
|
| 353 |
+
|
| 354 |
+
with gr.Row():
|
| 355 |
+
folder1_input = gr.Textbox(label="Folder 1 Path", placeholder="/path/to/folder1", scale=2)
|
| 356 |
+
folder2_input = gr.Textbox(label="Folder 2 Path", placeholder="/path/to/folder2", scale=2)
|
| 357 |
+
|
| 358 |
+
load_btn = gr.Button("Load Videos", variant="primary")
|
| 359 |
+
|
| 360 |
+
info_text = gr.Textbox(label="Information", interactive=False, lines=6)
|
| 361 |
+
|
| 362 |
+
# Step navigation controls
|
| 363 |
+
with gr.Row():
|
| 364 |
+
prev_step_btn = gr.Button("⬅️ Previous Step", interactive=False, scale=1)
|
| 365 |
+
step_selector = gr.Dropdown(label="Select Step", choices=[], interactive=True, scale=2)
|
| 366 |
+
next_step_btn = gr.Button("Next Step ➡️", interactive=False, scale=1)
|
| 367 |
+
|
| 368 |
+
# Index navigation controls
|
| 369 |
+
with gr.Row():
|
| 370 |
+
prev_idx_btn = gr.Button("⬅️ Previous Index", interactive=False, scale=1)
|
| 371 |
+
idx_selector = gr.Dropdown(label="Select Index", choices=[], interactive=True, scale=2)
|
| 372 |
+
next_idx_btn = gr.Button("Next Index ➡️", interactive=False, scale=1)
|
| 373 |
+
|
| 374 |
+
progress_text = gr.Textbox(label="Progress", value="0 / 0", interactive=False)
|
| 375 |
+
|
| 376 |
+
with gr.Row():
|
| 377 |
+
with gr.Column():
|
| 378 |
+
gr.Markdown("### Folder 1")
|
| 379 |
+
video1 = gr.Video(label="Video 1", autoplay=True, loop=True)
|
| 380 |
+
|
| 381 |
+
with gr.Column():
|
| 382 |
+
gr.Markdown("### Folder 2")
|
| 383 |
+
video2 = gr.Video(label="Video 2", autoplay=True, loop=True)
|
| 384 |
+
|
| 385 |
+
# Event bindings
|
| 386 |
+
load_btn.click(
|
| 387 |
+
fn=load_videos,
|
| 388 |
+
inputs=[folder1_input, folder2_input],
|
| 389 |
+
outputs=[
|
| 390 |
+
video1,
|
| 391 |
+
video2,
|
| 392 |
+
info_text,
|
| 393 |
+
step_selector,
|
| 394 |
+
idx_selector,
|
| 395 |
+
prev_step_btn,
|
| 396 |
+
next_step_btn,
|
| 397 |
+
prev_idx_btn,
|
| 398 |
+
next_idx_btn,
|
| 399 |
+
progress_text,
|
| 400 |
+
video_map1_state,
|
| 401 |
+
video_map2_state,
|
| 402 |
+
step_idx_map_state,
|
| 403 |
+
],
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
# When step changes, update available indices
|
| 407 |
+
step_selector.change(
|
| 408 |
+
fn=update_available_indices, inputs=[step_selector, step_idx_map_state], outputs=[idx_selector]
|
| 409 |
+
).then(
|
| 410 |
+
fn=update_videos_from_selectors,
|
| 411 |
+
inputs=[
|
| 412 |
+
folder1_input,
|
| 413 |
+
folder2_input,
|
| 414 |
+
step_selector,
|
| 415 |
+
idx_selector,
|
| 416 |
+
video_map1_state,
|
| 417 |
+
video_map2_state,
|
| 418 |
+
step_idx_map_state,
|
| 419 |
+
],
|
| 420 |
+
outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text],
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
# When index changes, update videos
|
| 424 |
+
idx_selector.change(
|
| 425 |
+
fn=update_videos_from_selectors,
|
| 426 |
+
inputs=[
|
| 427 |
+
folder1_input,
|
| 428 |
+
folder2_input,
|
| 429 |
+
step_selector,
|
| 430 |
+
idx_selector,
|
| 431 |
+
video_map1_state,
|
| 432 |
+
video_map2_state,
|
| 433 |
+
step_idx_map_state,
|
| 434 |
+
],
|
| 435 |
+
outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text],
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
# Step navigation buttons
|
| 439 |
+
prev_step_btn.click(
|
| 440 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "prev"),
|
| 441 |
+
inputs=[
|
| 442 |
+
folder1_input,
|
| 443 |
+
folder2_input,
|
| 444 |
+
step_selector,
|
| 445 |
+
idx_selector,
|
| 446 |
+
video_map1_state,
|
| 447 |
+
video_map2_state,
|
| 448 |
+
step_idx_map_state,
|
| 449 |
+
],
|
| 450 |
+
outputs=[
|
| 451 |
+
video1,
|
| 452 |
+
video2,
|
| 453 |
+
info_text,
|
| 454 |
+
prev_step_btn,
|
| 455 |
+
next_step_btn,
|
| 456 |
+
prev_idx_btn,
|
| 457 |
+
next_idx_btn,
|
| 458 |
+
progress_text,
|
| 459 |
+
step_selector,
|
| 460 |
+
idx_selector,
|
| 461 |
+
],
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
next_step_btn.click(
|
| 465 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "next"),
|
| 466 |
+
inputs=[
|
| 467 |
+
folder1_input,
|
| 468 |
+
folder2_input,
|
| 469 |
+
step_selector,
|
| 470 |
+
idx_selector,
|
| 471 |
+
video_map1_state,
|
| 472 |
+
video_map2_state,
|
| 473 |
+
step_idx_map_state,
|
| 474 |
+
],
|
| 475 |
+
outputs=[
|
| 476 |
+
video1,
|
| 477 |
+
video2,
|
| 478 |
+
info_text,
|
| 479 |
+
prev_step_btn,
|
| 480 |
+
next_step_btn,
|
| 481 |
+
prev_idx_btn,
|
| 482 |
+
next_idx_btn,
|
| 483 |
+
progress_text,
|
| 484 |
+
step_selector,
|
| 485 |
+
idx_selector,
|
| 486 |
+
],
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
# Index navigation buttons
|
| 490 |
+
prev_idx_btn.click(
|
| 491 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "prev"),
|
| 492 |
+
inputs=[
|
| 493 |
+
folder1_input,
|
| 494 |
+
folder2_input,
|
| 495 |
+
step_selector,
|
| 496 |
+
idx_selector,
|
| 497 |
+
video_map1_state,
|
| 498 |
+
video_map2_state,
|
| 499 |
+
step_idx_map_state,
|
| 500 |
+
],
|
| 501 |
+
outputs=[
|
| 502 |
+
video1,
|
| 503 |
+
video2,
|
| 504 |
+
info_text,
|
| 505 |
+
prev_step_btn,
|
| 506 |
+
next_step_btn,
|
| 507 |
+
prev_idx_btn,
|
| 508 |
+
next_idx_btn,
|
| 509 |
+
progress_text,
|
| 510 |
+
step_selector,
|
| 511 |
+
idx_selector,
|
| 512 |
+
],
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
+
next_idx_btn.click(
|
| 516 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "next"),
|
| 517 |
+
inputs=[
|
| 518 |
+
folder1_input,
|
| 519 |
+
folder2_input,
|
| 520 |
+
step_selector,
|
| 521 |
+
idx_selector,
|
| 522 |
+
video_map1_state,
|
| 523 |
+
video_map2_state,
|
| 524 |
+
step_idx_map_state,
|
| 525 |
+
],
|
| 526 |
+
outputs=[
|
| 527 |
+
video1,
|
| 528 |
+
video2,
|
| 529 |
+
info_text,
|
| 530 |
+
prev_step_btn,
|
| 531 |
+
next_step_btn,
|
| 532 |
+
prev_idx_btn,
|
| 533 |
+
next_idx_btn,
|
| 534 |
+
progress_text,
|
| 535 |
+
step_selector,
|
| 536 |
+
idx_selector,
|
| 537 |
+
],
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
if __name__ == "__main__":
|
| 541 |
+
demo.launch(
|
| 542 |
+
share=True,
|
| 543 |
+
allowed_paths=[
|
| 544 |
+
"0_ablation_videos",
|
| 545 |
+
"ablation_stage3_1_warmup",
|
| 546 |
+
],
|
| 547 |
+
)
|
Helios/_DEV/tools/gradio/comparison/gradio_compare_diff-video.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parse_video_name(filename):
|
| 8 |
+
"""Parse video filename to extract step and index"""
|
| 9 |
+
# Match checkpoint-{step}_{idx}.mp4 format
|
| 10 |
+
match = re.match(r"checkpoint-(\d+)_(\d+)\.mp4$", filename)
|
| 11 |
+
if match:
|
| 12 |
+
step = int(match.group(1))
|
| 13 |
+
idx = int(match.group(2))
|
| 14 |
+
return step, idx
|
| 15 |
+
return None, None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_video_list(folder_path):
|
| 19 |
+
"""Get all mp4 videos from folder"""
|
| 20 |
+
if not os.path.exists(folder_path):
|
| 21 |
+
return []
|
| 22 |
+
|
| 23 |
+
videos = []
|
| 24 |
+
for file in os.listdir(folder_path):
|
| 25 |
+
if file.endswith(".mp4"):
|
| 26 |
+
step, idx = parse_video_name(file)
|
| 27 |
+
if step is not None:
|
| 28 |
+
videos.append({"filename": file, "step": step, "idx": idx, "path": os.path.join(folder_path, file)})
|
| 29 |
+
|
| 30 |
+
# Sort by step and idx
|
| 31 |
+
videos.sort(key=lambda x: (x["step"], x["idx"]))
|
| 32 |
+
return videos
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def create_video_mapping(videos):
|
| 36 |
+
"""Create (step, idx) -> filename mapping"""
|
| 37 |
+
mapping = {}
|
| 38 |
+
for video in videos:
|
| 39 |
+
key = (video["step"], video["idx"])
|
| 40 |
+
mapping[key] = video["filename"]
|
| 41 |
+
return mapping
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_step_idx_info(video_map):
|
| 45 |
+
"""Extract step and idx information from video mapping"""
|
| 46 |
+
all_steps = set()
|
| 47 |
+
all_indices = set()
|
| 48 |
+
idx_step_map = {} # {idx: [step1, step2, ...]}
|
| 49 |
+
|
| 50 |
+
for step, idx in video_map.keys():
|
| 51 |
+
all_steps.add(step)
|
| 52 |
+
all_indices.add(idx)
|
| 53 |
+
if idx not in idx_step_map:
|
| 54 |
+
idx_step_map[idx] = []
|
| 55 |
+
idx_step_map[idx].append(step)
|
| 56 |
+
|
| 57 |
+
# Sort
|
| 58 |
+
for idx in idx_step_map:
|
| 59 |
+
idx_step_map[idx].sort()
|
| 60 |
+
|
| 61 |
+
return sorted(all_steps), sorted(all_indices), idx_step_map
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_videos(folder_path):
|
| 65 |
+
"""Load videos from folder"""
|
| 66 |
+
if not folder_path:
|
| 67 |
+
return (
|
| 68 |
+
None,
|
| 69 |
+
None,
|
| 70 |
+
"Please enter folder path",
|
| 71 |
+
gr.update(choices=[], value=None),
|
| 72 |
+
gr.update(choices=[], value=None),
|
| 73 |
+
gr.update(choices=[], value=None),
|
| 74 |
+
gr.update(interactive=False),
|
| 75 |
+
gr.update(interactive=False),
|
| 76 |
+
gr.update(interactive=False),
|
| 77 |
+
gr.update(interactive=False),
|
| 78 |
+
"0 / 0",
|
| 79 |
+
{},
|
| 80 |
+
{},
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
videos = get_video_list(folder_path)
|
| 84 |
+
|
| 85 |
+
if not videos:
|
| 86 |
+
return (
|
| 87 |
+
None,
|
| 88 |
+
None,
|
| 89 |
+
f"No video files found in folder ({len(os.listdir(folder_path)) if os.path.exists(folder_path) else 0} files total)",
|
| 90 |
+
gr.update(choices=[], value=None),
|
| 91 |
+
gr.update(choices=[], value=None),
|
| 92 |
+
gr.update(choices=[], value=None),
|
| 93 |
+
gr.update(interactive=False),
|
| 94 |
+
gr.update(interactive=False),
|
| 95 |
+
gr.update(interactive=False),
|
| 96 |
+
gr.update(interactive=False),
|
| 97 |
+
"0 / 0",
|
| 98 |
+
{},
|
| 99 |
+
{},
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Create (step, idx) to filename mapping
|
| 103 |
+
video_map = create_video_mapping(videos)
|
| 104 |
+
|
| 105 |
+
# Get all step and index information
|
| 106 |
+
all_steps, all_indices, idx_step_map = get_step_idx_info(video_map)
|
| 107 |
+
|
| 108 |
+
# Filter indices with at least 2 steps
|
| 109 |
+
valid_indices = [idx for idx in all_indices if len(idx_step_map[idx]) >= 2]
|
| 110 |
+
|
| 111 |
+
if not valid_indices:
|
| 112 |
+
info = (
|
| 113 |
+
f"Found {len(videos)} videos, but no comparable videos (need at least 2 different steps for same index)\n"
|
| 114 |
+
)
|
| 115 |
+
info += f"Steps: {all_steps}\n"
|
| 116 |
+
info += f"Indices: {all_indices}"
|
| 117 |
+
return (
|
| 118 |
+
None,
|
| 119 |
+
None,
|
| 120 |
+
info,
|
| 121 |
+
gr.update(choices=[], value=None),
|
| 122 |
+
gr.update(choices=[], value=None),
|
| 123 |
+
gr.update(choices=[], value=None),
|
| 124 |
+
gr.update(interactive=False),
|
| 125 |
+
gr.update(interactive=False),
|
| 126 |
+
gr.update(interactive=False),
|
| 127 |
+
gr.update(interactive=False),
|
| 128 |
+
"0 / 0",
|
| 129 |
+
{},
|
| 130 |
+
{},
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# Select first valid index and its first two steps
|
| 134 |
+
first_idx = valid_indices[0]
|
| 135 |
+
available_steps = idx_step_map[first_idx]
|
| 136 |
+
step1 = available_steps[0]
|
| 137 |
+
step2 = available_steps[1] if len(available_steps) > 1 else available_steps[0]
|
| 138 |
+
|
| 139 |
+
# Load videos
|
| 140 |
+
filename1 = video_map.get((step1, first_idx))
|
| 141 |
+
filename2 = video_map.get((step2, first_idx))
|
| 142 |
+
|
| 143 |
+
video1_path = os.path.join(folder_path, filename1) if filename1 else None
|
| 144 |
+
video2_path = os.path.join(folder_path, filename2) if filename2 else None
|
| 145 |
+
|
| 146 |
+
info = f"Found {len(videos)} videos, {len(valid_indices)} comparable indices\n"
|
| 147 |
+
info += f"Current Index: {first_idx}\n"
|
| 148 |
+
info += f"Step1: {step1} - {filename1}\n"
|
| 149 |
+
info += f"Step2: {step2} - {filename2}"
|
| 150 |
+
|
| 151 |
+
progress = f"1 / {len(valid_indices)}"
|
| 152 |
+
|
| 153 |
+
return (
|
| 154 |
+
video1_path,
|
| 155 |
+
video2_path,
|
| 156 |
+
info,
|
| 157 |
+
gr.update(choices=valid_indices, value=first_idx),
|
| 158 |
+
gr.update(choices=available_steps, value=step1),
|
| 159 |
+
gr.update(choices=available_steps, value=step2),
|
| 160 |
+
gr.update(interactive=first_idx > valid_indices[0]),
|
| 161 |
+
gr.update(interactive=first_idx < valid_indices[-1]),
|
| 162 |
+
gr.update(interactive=True),
|
| 163 |
+
gr.update(interactive=True),
|
| 164 |
+
progress,
|
| 165 |
+
video_map,
|
| 166 |
+
idx_step_map,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def update_videos(folder_path, selected_idx, selected_step1, selected_step2, video_map, idx_step_map):
|
| 171 |
+
"""Update videos based on selected idx and two steps"""
|
| 172 |
+
if selected_idx is None or selected_step1 is None or selected_step2 is None:
|
| 173 |
+
return None, None, "Please select index and steps", gr.update(), gr.update(), gr.update(), gr.update(), ""
|
| 174 |
+
|
| 175 |
+
key1 = (selected_step1, selected_idx)
|
| 176 |
+
key2 = (selected_step2, selected_idx)
|
| 177 |
+
|
| 178 |
+
filename1 = video_map.get(key1)
|
| 179 |
+
filename2 = video_map.get(key2)
|
| 180 |
+
|
| 181 |
+
if not filename1 or not filename2:
|
| 182 |
+
return (
|
| 183 |
+
None,
|
| 184 |
+
None,
|
| 185 |
+
f"Complete video pair not found: Index {selected_idx}, Step1 {selected_step1}, Step2 {selected_step2}",
|
| 186 |
+
gr.update(),
|
| 187 |
+
gr.update(),
|
| 188 |
+
gr.update(),
|
| 189 |
+
gr.update(),
|
| 190 |
+
"",
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
video1_path = os.path.join(folder_path, filename1)
|
| 194 |
+
video2_path = os.path.join(folder_path, filename2)
|
| 195 |
+
|
| 196 |
+
info = f"Current Index: {selected_idx}\n"
|
| 197 |
+
info += f"Step1: {selected_step1} - {filename1}\n"
|
| 198 |
+
info += f"Step2: {selected_step2} - {filename2}"
|
| 199 |
+
|
| 200 |
+
# Get all valid indices
|
| 201 |
+
all_indices = [idx for idx in idx_step_map.keys() if len(idx_step_map[idx]) >= 2]
|
| 202 |
+
all_indices.sort()
|
| 203 |
+
|
| 204 |
+
# Update button states
|
| 205 |
+
prev_idx_interactive = selected_idx > all_indices[0] if all_indices else False
|
| 206 |
+
next_idx_interactive = selected_idx < all_indices[-1] if all_indices else False
|
| 207 |
+
|
| 208 |
+
# Calculate progress
|
| 209 |
+
current_pos = all_indices.index(selected_idx) + 1 if selected_idx in all_indices else 0
|
| 210 |
+
progress = f"{current_pos} / {len(all_indices)}"
|
| 211 |
+
|
| 212 |
+
return (
|
| 213 |
+
video1_path,
|
| 214 |
+
video2_path,
|
| 215 |
+
info,
|
| 216 |
+
gr.update(interactive=prev_idx_interactive),
|
| 217 |
+
gr.update(interactive=next_idx_interactive),
|
| 218 |
+
gr.update(),
|
| 219 |
+
gr.update(),
|
| 220 |
+
progress,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def update_available_steps(selected_idx, idx_step_map):
|
| 225 |
+
"""Update available steps list for current index"""
|
| 226 |
+
if not idx_step_map or selected_idx is None:
|
| 227 |
+
return gr.update(choices=[], value=None), gr.update(choices=[], value=None)
|
| 228 |
+
|
| 229 |
+
available_steps = idx_step_map.get(selected_idx, [])
|
| 230 |
+
first_step = available_steps[0] if available_steps else None
|
| 231 |
+
second_step = available_steps[1] if len(available_steps) > 1 else first_step
|
| 232 |
+
|
| 233 |
+
return (
|
| 234 |
+
gr.update(choices=available_steps, value=first_step),
|
| 235 |
+
gr.update(choices=available_steps, value=second_step),
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def navigate_idx(folder_path, current_idx, step1, step2, video_map, idx_step_map, direction):
|
| 240 |
+
"""Navigate to previous or next index"""
|
| 241 |
+
if not idx_step_map or current_idx is None:
|
| 242 |
+
return (
|
| 243 |
+
None,
|
| 244 |
+
None,
|
| 245 |
+
"Please load videos first",
|
| 246 |
+
current_idx,
|
| 247 |
+
step1,
|
| 248 |
+
step2,
|
| 249 |
+
gr.update(),
|
| 250 |
+
gr.update(),
|
| 251 |
+
gr.update(),
|
| 252 |
+
gr.update(),
|
| 253 |
+
"",
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
# Get all valid indices
|
| 257 |
+
all_indices = [idx for idx in idx_step_map.keys() if len(idx_step_map[idx]) >= 2]
|
| 258 |
+
all_indices.sort()
|
| 259 |
+
|
| 260 |
+
if current_idx not in all_indices:
|
| 261 |
+
return (
|
| 262 |
+
None,
|
| 263 |
+
None,
|
| 264 |
+
"Current Index invalid",
|
| 265 |
+
current_idx,
|
| 266 |
+
step1,
|
| 267 |
+
step2,
|
| 268 |
+
gr.update(),
|
| 269 |
+
gr.update(),
|
| 270 |
+
gr.update(),
|
| 271 |
+
gr.update(),
|
| 272 |
+
"",
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
current_idx_pos = all_indices.index(current_idx)
|
| 276 |
+
|
| 277 |
+
if direction == "prev":
|
| 278 |
+
new_idx_pos = max(0, current_idx_pos - 1)
|
| 279 |
+
else: # next
|
| 280 |
+
new_idx_pos = min(len(all_indices) - 1, current_idx_pos + 1)
|
| 281 |
+
|
| 282 |
+
new_idx = all_indices[new_idx_pos]
|
| 283 |
+
|
| 284 |
+
# Get available steps for new index
|
| 285 |
+
available_steps = idx_step_map.get(new_idx, [])
|
| 286 |
+
new_step1 = available_steps[0] if available_steps else step1
|
| 287 |
+
new_step2 = available_steps[1] if len(available_steps) > 1 else available_steps[0]
|
| 288 |
+
|
| 289 |
+
result = update_videos(folder_path, new_idx, new_step1, new_step2, video_map, idx_step_map)
|
| 290 |
+
return result + (new_idx, new_step1, new_step2)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# Create Gradio interface
|
| 294 |
+
with gr.Blocks(title="Video Comparison Tool - Different Step Comparison") as demo:
|
| 295 |
+
gr.Markdown("# Video Comparison Tool - Different Step Comparison")
|
| 296 |
+
gr.Markdown(
|
| 297 |
+
"Enter folder path to compare videos of same index at different steps (checkpoint-{step}_{idx}.mp4 format)"
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
# Store state
|
| 301 |
+
video_map_state = gr.State({})
|
| 302 |
+
idx_step_map_state = gr.State({})
|
| 303 |
+
|
| 304 |
+
folder_input = gr.Textbox(label="Folder Path", placeholder="/path/to/folder", scale=2)
|
| 305 |
+
|
| 306 |
+
load_btn = gr.Button("Load Videos", variant="primary")
|
| 307 |
+
|
| 308 |
+
info_text = gr.Textbox(label="Information", interactive=False, lines=5)
|
| 309 |
+
|
| 310 |
+
# Index navigation controls
|
| 311 |
+
with gr.Row():
|
| 312 |
+
prev_idx_btn = gr.Button("⬅️ Previous Index", interactive=False, scale=1)
|
| 313 |
+
idx_selector = gr.Dropdown(label="Select Index", choices=[], interactive=True, scale=2)
|
| 314 |
+
next_idx_btn = gr.Button("Next Index ➡️", interactive=False, scale=1)
|
| 315 |
+
|
| 316 |
+
# Step selectors
|
| 317 |
+
with gr.Row():
|
| 318 |
+
step1_selector = gr.Dropdown(label="Select Step1 (Left)", choices=[], interactive=True, scale=1)
|
| 319 |
+
step2_selector = gr.Dropdown(label="Select Step2 (Right)", choices=[], interactive=True, scale=1)
|
| 320 |
+
|
| 321 |
+
progress_text = gr.Textbox(label="Progress", value="0 / 0", interactive=False)
|
| 322 |
+
|
| 323 |
+
with gr.Row():
|
| 324 |
+
with gr.Column():
|
| 325 |
+
gr.Markdown("### Step 1")
|
| 326 |
+
video1 = gr.Video(label="Video 1", autoplay=True, loop=True)
|
| 327 |
+
|
| 328 |
+
with gr.Column():
|
| 329 |
+
gr.Markdown("### Step 2")
|
| 330 |
+
video2 = gr.Video(label="Video 2", autoplay=True, loop=True)
|
| 331 |
+
|
| 332 |
+
# Event binding
|
| 333 |
+
load_btn.click(
|
| 334 |
+
fn=load_videos,
|
| 335 |
+
inputs=[folder_input],
|
| 336 |
+
outputs=[
|
| 337 |
+
video1,
|
| 338 |
+
video2,
|
| 339 |
+
info_text,
|
| 340 |
+
idx_selector,
|
| 341 |
+
step1_selector,
|
| 342 |
+
step2_selector,
|
| 343 |
+
prev_idx_btn,
|
| 344 |
+
next_idx_btn,
|
| 345 |
+
gr.State(),
|
| 346 |
+
gr.State(),
|
| 347 |
+
progress_text,
|
| 348 |
+
video_map_state,
|
| 349 |
+
idx_step_map_state,
|
| 350 |
+
],
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
# When index changes, update available steps and videos
|
| 354 |
+
def handle_idx_change(folder_path, selected_idx, video_map, idx_step_map):
|
| 355 |
+
"""Handle index change - update steps and videos together"""
|
| 356 |
+
if not idx_step_map or selected_idx is None:
|
| 357 |
+
return (
|
| 358 |
+
None,
|
| 359 |
+
None,
|
| 360 |
+
"Please select index",
|
| 361 |
+
gr.update(choices=[], value=None),
|
| 362 |
+
gr.update(choices=[], value=None),
|
| 363 |
+
gr.update(),
|
| 364 |
+
gr.update(),
|
| 365 |
+
"",
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
# Get available steps for new index
|
| 369 |
+
available_steps = idx_step_map.get(selected_idx, [])
|
| 370 |
+
new_step1 = available_steps[0] if available_steps else None
|
| 371 |
+
new_step2 = available_steps[1] if len(available_steps) > 1 else available_steps[0]
|
| 372 |
+
|
| 373 |
+
# Update videos with new steps
|
| 374 |
+
result = update_videos(folder_path, selected_idx, new_step1, new_step2, video_map, idx_step_map)
|
| 375 |
+
|
| 376 |
+
return (
|
| 377 |
+
result[0], # video1
|
| 378 |
+
result[1], # video2
|
| 379 |
+
result[2], # info
|
| 380 |
+
gr.update(choices=available_steps, value=new_step1), # step1_selector
|
| 381 |
+
gr.update(choices=available_steps, value=new_step2), # step2_selector
|
| 382 |
+
result[3], # prev_idx_btn
|
| 383 |
+
result[4], # next_idx_btn
|
| 384 |
+
result[7], # progress
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
idx_selector.change(
|
| 388 |
+
fn=handle_idx_change,
|
| 389 |
+
inputs=[folder_input, idx_selector, video_map_state, idx_step_map_state],
|
| 390 |
+
outputs=[video1, video2, info_text, step1_selector, step2_selector, prev_idx_btn, next_idx_btn, progress_text],
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
step1_selector.select(
|
| 394 |
+
fn=update_videos,
|
| 395 |
+
inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state],
|
| 396 |
+
outputs=[video1, video2, info_text, prev_idx_btn, next_idx_btn, gr.State(), gr.State(), progress_text],
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
step2_selector.select(
|
| 400 |
+
fn=update_videos,
|
| 401 |
+
inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state],
|
| 402 |
+
outputs=[video1, video2, info_text, prev_idx_btn, next_idx_btn, gr.State(), gr.State(), progress_text],
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# Index navigation buttons
|
| 406 |
+
prev_idx_btn.click(
|
| 407 |
+
fn=lambda f, i, s1, s2, vm, ism: navigate_idx(f, i, s1, s2, vm, ism, "prev"),
|
| 408 |
+
inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state],
|
| 409 |
+
outputs=[
|
| 410 |
+
video1,
|
| 411 |
+
video2,
|
| 412 |
+
info_text,
|
| 413 |
+
prev_idx_btn,
|
| 414 |
+
next_idx_btn,
|
| 415 |
+
gr.State(),
|
| 416 |
+
gr.State(),
|
| 417 |
+
progress_text,
|
| 418 |
+
idx_selector,
|
| 419 |
+
step1_selector,
|
| 420 |
+
step2_selector,
|
| 421 |
+
],
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
next_idx_btn.click(
|
| 425 |
+
fn=lambda f, i, s1, s2, vm, ism: navigate_idx(f, i, s1, s2, vm, ism, "next"),
|
| 426 |
+
inputs=[folder_input, idx_selector, step1_selector, step2_selector, video_map_state, idx_step_map_state],
|
| 427 |
+
outputs=[
|
| 428 |
+
video1,
|
| 429 |
+
video2,
|
| 430 |
+
info_text,
|
| 431 |
+
prev_idx_btn,
|
| 432 |
+
next_idx_btn,
|
| 433 |
+
gr.State(),
|
| 434 |
+
gr.State(),
|
| 435 |
+
progress_text,
|
| 436 |
+
idx_selector,
|
| 437 |
+
step1_selector,
|
| 438 |
+
step2_selector,
|
| 439 |
+
],
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
if __name__ == "__main__":
|
| 444 |
+
demo.launch(
|
| 445 |
+
share=True,
|
| 446 |
+
allowed_paths=[
|
| 447 |
+
"0_ablation_videos",
|
| 448 |
+
"ablation_stage3_1_warmup",
|
| 449 |
+
],
|
| 450 |
+
)
|
Helios/_DEV/tools/others/benchmark/benchmark_compile_performance.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 3 |
+
import time
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
|
| 10 |
+
os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes"
|
| 11 |
+
|
| 12 |
+
from helios.modules.kernels import (
|
| 13 |
+
replace_all_norms_with_flash_norms,
|
| 14 |
+
replace_rmsnorm_with_fp32,
|
| 15 |
+
replace_rope_with_flash_rope,
|
| 16 |
+
)
|
| 17 |
+
from helios.modules.transformer_helios import HeliosTransformer3DModel
|
| 18 |
+
from helios.pipelines.pipeline_wan import WanPipeline
|
| 19 |
+
|
| 20 |
+
from diffusers import AutoencoderKLWan
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DualLogger:
|
| 24 |
+
"""同时输出到控制台和文件的日志器"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, filename):
|
| 27 |
+
self.file = open(filename, "w", encoding="utf-8")
|
| 28 |
+
self.stdout = sys.stdout
|
| 29 |
+
|
| 30 |
+
def write(self, message):
|
| 31 |
+
self.stdout.write(message) # 输出到控制台
|
| 32 |
+
self.file.write(message) # 写入文件
|
| 33 |
+
self.file.flush() # 实时刷新
|
| 34 |
+
|
| 35 |
+
def flush(self):
|
| 36 |
+
self.stdout.flush()
|
| 37 |
+
self.file.flush()
|
| 38 |
+
|
| 39 |
+
def close(self):
|
| 40 |
+
self.file.close()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def setup_pipeline(model_id, compile_config=None):
|
| 44 |
+
"""设置pipeline"""
|
| 45 |
+
print(f"\n{'=' * 60}")
|
| 46 |
+
print(f"设置 Pipeline: {compile_config['name'] if compile_config else 'No Compile'}")
|
| 47 |
+
print(f"{'=' * 60}")
|
| 48 |
+
|
| 49 |
+
# 加载模型
|
| 50 |
+
transformer = HeliosTransformer3DModel.from_pretrained(
|
| 51 |
+
model_id, subfolder="transformer", torch_dtype=torch.bfloat16, use_default_loader=True
|
| 52 |
+
)
|
| 53 |
+
transformer = replace_rmsnorm_with_fp32(transformer)
|
| 54 |
+
transformer = replace_all_norms_with_flash_norms(transformer)
|
| 55 |
+
replace_rope_with_flash_rope()
|
| 56 |
+
|
| 57 |
+
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 58 |
+
pipe = WanPipeline.from_pretrained(model_id, vae=vae, transformer=transformer, torch_dtype=torch.bfloat16)
|
| 59 |
+
|
| 60 |
+
pipe.transformer.set_attention_backend("_flash_3_hub")
|
| 61 |
+
pipe.to("cuda")
|
| 62 |
+
|
| 63 |
+
# 应用compile配置
|
| 64 |
+
if compile_config:
|
| 65 |
+
print(f"应用编译配置: {compile_config['kwargs']}")
|
| 66 |
+
pipe.transformer.compile(**compile_config["kwargs"])
|
| 67 |
+
|
| 68 |
+
return pipe
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def run_benchmark(pipe, prompt, negative_prompt, num_runs=3, warmup=1):
|
| 72 |
+
"""运行基准测试"""
|
| 73 |
+
times = []
|
| 74 |
+
|
| 75 |
+
# Warmup
|
| 76 |
+
print(f"\n预热运行 {warmup} 次...")
|
| 77 |
+
for i in range(warmup):
|
| 78 |
+
print(f" 预热 {i + 1}/{warmup}")
|
| 79 |
+
_ = pipe(
|
| 80 |
+
prompt=prompt,
|
| 81 |
+
negative_prompt=negative_prompt,
|
| 82 |
+
height=384,
|
| 83 |
+
width=640,
|
| 84 |
+
num_frames=45,
|
| 85 |
+
guidance_scale=5.0,
|
| 86 |
+
num_inference_steps=50,
|
| 87 |
+
generator=torch.Generator(device="cuda").manual_seed(42),
|
| 88 |
+
).frames[0]
|
| 89 |
+
torch.cuda.empty_cache()
|
| 90 |
+
|
| 91 |
+
# 实际测试
|
| 92 |
+
print(f"\n开始基准测试 {num_runs} 次...")
|
| 93 |
+
for i in range(num_runs):
|
| 94 |
+
print(f" 运行 {i + 1}/{num_runs}")
|
| 95 |
+
start = time.time()
|
| 96 |
+
torch.cuda.synchronize()
|
| 97 |
+
|
| 98 |
+
_ = pipe(
|
| 99 |
+
prompt=prompt,
|
| 100 |
+
negative_prompt=negative_prompt,
|
| 101 |
+
height=384,
|
| 102 |
+
width=640,
|
| 103 |
+
num_frames=45,
|
| 104 |
+
guidance_scale=5.0,
|
| 105 |
+
num_inference_steps=50,
|
| 106 |
+
generator=torch.Generator(device="cuda").manual_seed(42),
|
| 107 |
+
).frames[0]
|
| 108 |
+
|
| 109 |
+
torch.cuda.synchronize()
|
| 110 |
+
elapsed = time.time() - start
|
| 111 |
+
times.append(elapsed)
|
| 112 |
+
print(f" 耗时: {elapsed:.2f}秒")
|
| 113 |
+
torch.cuda.empty_cache()
|
| 114 |
+
|
| 115 |
+
return times
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def main():
|
| 119 |
+
# 创建日志文件
|
| 120 |
+
# timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 121 |
+
log_filename = "benchmark_compile_results.txt"
|
| 122 |
+
|
| 123 |
+
# 创建双输出日志器
|
| 124 |
+
logger = DualLogger(log_filename)
|
| 125 |
+
original_stdout = sys.stdout
|
| 126 |
+
sys.stdout = logger
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
# 打印测试信息
|
| 130 |
+
print("=" * 80)
|
| 131 |
+
print("PyTorch Compile 模式基准测试")
|
| 132 |
+
print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 133 |
+
print(f"PyTorch 版本: {torch.__version__}")
|
| 134 |
+
print(f"CUDA 版本: {torch.version.cuda}")
|
| 135 |
+
print(f"GPU: {torch.cuda.get_device_name(0)}")
|
| 136 |
+
print("=" * 80)
|
| 137 |
+
|
| 138 |
+
model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
|
| 139 |
+
|
| 140 |
+
prompt = "A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about."
|
| 141 |
+
negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 142 |
+
|
| 143 |
+
# 定义不同的compile配置
|
| 144 |
+
compile_configs = [
|
| 145 |
+
{"name": "No Compile (Baseline)", "kwargs": None},
|
| 146 |
+
{"name": "Default Compile", "kwargs": {}},
|
| 147 |
+
{"name": "Fullgraph Only", "kwargs": {"fullgraph": True}},
|
| 148 |
+
{
|
| 149 |
+
"name": "Max-Autotune-No-Cudagraphs + Dynamic",
|
| 150 |
+
"kwargs": {"mode": "max-autotune-no-cudagraphs", "dynamic": True},
|
| 151 |
+
},
|
| 152 |
+
{"name": "Max-Autotune + Fullgraph", "kwargs": {"mode": "max-autotune", "fullgraph": True}},
|
| 153 |
+
{"name": "Max-Autotune", "kwargs": {"mode": "max-autotune"}},
|
| 154 |
+
{"name": "Reduce-Overhead", "kwargs": {"mode": "reduce-overhead"}},
|
| 155 |
+
{"name": "Default Mode", "kwargs": {"mode": "default"}},
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
results = {}
|
| 159 |
+
|
| 160 |
+
# 测试每个配置
|
| 161 |
+
for config in compile_configs:
|
| 162 |
+
try:
|
| 163 |
+
# 清理GPU内存
|
| 164 |
+
torch.cuda.empty_cache()
|
| 165 |
+
|
| 166 |
+
# 设置pipeline
|
| 167 |
+
if config["kwargs"] is None:
|
| 168 |
+
pipe = setup_pipeline(model_id, None)
|
| 169 |
+
else:
|
| 170 |
+
pipe = setup_pipeline(model_id, config)
|
| 171 |
+
|
| 172 |
+
# 运行基准测试
|
| 173 |
+
times = run_benchmark(pipe, prompt, negative_prompt, num_runs=3, warmup=1)
|
| 174 |
+
results[config["name"]] = times
|
| 175 |
+
|
| 176 |
+
# 删除pipeline释放内存
|
| 177 |
+
del pipe
|
| 178 |
+
torch.cuda.empty_cache()
|
| 179 |
+
|
| 180 |
+
except Exception as e:
|
| 181 |
+
print(f"\n❌ 配置 '{config['name']}' 失败: {str(e)}")
|
| 182 |
+
results[config["name"]] = None
|
| 183 |
+
|
| 184 |
+
# 打印结果摘要
|
| 185 |
+
print("\n" + "=" * 80)
|
| 186 |
+
print("基准测试结果摘要")
|
| 187 |
+
print("=" * 80)
|
| 188 |
+
print(f"{'配置':<45} {'平均时间(秒)':<15} {'最小时间(秒)':<15} {'最大时间(秒)':<15}")
|
| 189 |
+
print("-" * 80)
|
| 190 |
+
|
| 191 |
+
sorted_results = []
|
| 192 |
+
for name, times in results.items():
|
| 193 |
+
if times:
|
| 194 |
+
avg_time = sum(times) / len(times)
|
| 195 |
+
min_time = min(times)
|
| 196 |
+
max_time = max(times)
|
| 197 |
+
sorted_results.append((name, avg_time, min_time, max_time, times))
|
| 198 |
+
print(f"{name:<45} {avg_time:<15.2f} {min_time:<15.2f} {max_time:<15.2f}")
|
| 199 |
+
else:
|
| 200 |
+
print(f"{name:<45} {'FAILED':<15} {'FAILED':<15} {'FAILED':<15}")
|
| 201 |
+
|
| 202 |
+
# 按平均时间排序
|
| 203 |
+
if sorted_results:
|
| 204 |
+
sorted_results.sort(key=lambda x: x[1])
|
| 205 |
+
print("\n" + "=" * 80)
|
| 206 |
+
print("速度排名 (从快到慢)")
|
| 207 |
+
print("=" * 80)
|
| 208 |
+
baseline_time = sorted_results[-1][1]
|
| 209 |
+
for rank, (name, avg_time, min_time, max_time, times) in enumerate(sorted_results, 1):
|
| 210 |
+
speedup = baseline_time / avg_time if avg_time > 0 else 0
|
| 211 |
+
print(f"\n{rank}. {name}")
|
| 212 |
+
print(f" 平均时间: {avg_time:.2f}秒")
|
| 213 |
+
print(f" 相对最慢提速: {speedup:.2f}x")
|
| 214 |
+
print(f" 详细时间: {[f'{t:.2f}s' for t in times]}")
|
| 215 |
+
|
| 216 |
+
print("\n" + "=" * 80)
|
| 217 |
+
print(f"测试完成! 结果已保存到: {log_filename}")
|
| 218 |
+
print("=" * 80)
|
| 219 |
+
|
| 220 |
+
except Exception as e:
|
| 221 |
+
print(f"\n❌ 测试过程出错: {str(e)}")
|
| 222 |
+
import traceback
|
| 223 |
+
|
| 224 |
+
traceback.print_exc()
|
| 225 |
+
|
| 226 |
+
finally:
|
| 227 |
+
# 恢复标准输出并关闭文件
|
| 228 |
+
sys.stdout = original_stdout
|
| 229 |
+
logger.close()
|
| 230 |
+
print(f"\n✅ 测试完成! 结果已保存到: {log_filename}")
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
if __name__ == "__main__":
|
| 234 |
+
main()
|
Helios/_DEV/tools/others/benchmark/benchmark_compile_results.txt
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
================================================================================
|
| 2 |
+
PyTorch Compile 模式基准测试
|
| 3 |
+
测试时间: 2026-01-25 16:09:44
|
| 4 |
+
PyTorch 版本: 2.7.1+cu126
|
| 5 |
+
CUDA 版本: 12.6
|
| 6 |
+
GPU: NVIDIA H100 80GB HBM3
|
| 7 |
+
================================================================================
|
| 8 |
+
|
| 9 |
+
============================================================
|
| 10 |
+
设置 Pipeline: No Compile
|
| 11 |
+
============================================================
|
| 12 |
+
Patched 120 FP32_RMSNorm modules
|
| 13 |
+
|
| 14 |
+
Patched 30 Flash_LayerNorm modules
|
| 15 |
+
|
| 16 |
+
Patched 120 Flash_RMSNorm modules
|
| 17 |
+
|
| 18 |
+
Patched Flash_RoPE globally
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
预热运行 1 次...
|
| 22 |
+
预热 1/1
|
| 23 |
+
|
| 24 |
+
开始基准测试 3 次...
|
| 25 |
+
运行 1/3
|
| 26 |
+
耗时: 17.15秒
|
| 27 |
+
运行 2/3
|
| 28 |
+
耗时: 17.14秒
|
| 29 |
+
运行 3/3
|
| 30 |
+
耗时: 17.19秒
|
| 31 |
+
|
| 32 |
+
============================================================
|
| 33 |
+
设置 Pipeline: Default Compile
|
| 34 |
+
============================================================
|
| 35 |
+
Patched 120 FP32_RMSNorm modules
|
| 36 |
+
|
| 37 |
+
Patched 30 Flash_LayerNorm modules
|
| 38 |
+
|
| 39 |
+
Patched 120 Flash_RMSNorm modules
|
| 40 |
+
|
| 41 |
+
Patched Flash_RoPE globally
|
| 42 |
+
|
| 43 |
+
应用编译配置: {}
|
| 44 |
+
|
| 45 |
+
预热运行 1 次...
|
| 46 |
+
预热 1/1
|
| 47 |
+
|
| 48 |
+
开始基准测试 3 次...
|
| 49 |
+
运行 1/3
|
| 50 |
+
耗时: 12.80秒
|
| 51 |
+
运行 2/3
|
| 52 |
+
耗时: 12.79秒
|
| 53 |
+
运行 3/3
|
| 54 |
+
耗时: 12.79秒
|
| 55 |
+
|
| 56 |
+
============================================================
|
| 57 |
+
设置 Pipeline: Fullgraph Only
|
| 58 |
+
============================================================
|
| 59 |
+
Patched 120 FP32_RMSNorm modules
|
| 60 |
+
|
| 61 |
+
Patched 30 Flash_LayerNorm modules
|
| 62 |
+
|
| 63 |
+
Patched 120 Flash_RMSNorm modules
|
| 64 |
+
|
| 65 |
+
Patched Flash_RoPE globally
|
| 66 |
+
|
| 67 |
+
应用编译配置: {'fullgraph': True}
|
| 68 |
+
|
| 69 |
+
预热运行 1 次...
|
| 70 |
+
预热 1/1
|
| 71 |
+
|
| 72 |
+
开始基准测试 3 次...
|
| 73 |
+
运行 1/3
|
| 74 |
+
耗时: 12.79秒
|
| 75 |
+
运行 2/3
|
| 76 |
+
耗时: 12.80秒
|
| 77 |
+
运行 3/3
|
| 78 |
+
耗时: 12.80秒
|
| 79 |
+
|
| 80 |
+
============================================================
|
| 81 |
+
设置 Pipeline: Max-Autotune-No-Cudagraphs + Dynamic
|
| 82 |
+
============================================================
|
| 83 |
+
Patched 120 FP32_RMSNorm modules
|
| 84 |
+
|
| 85 |
+
Patched 30 Flash_LayerNorm modules
|
| 86 |
+
|
| 87 |
+
Patched 120 Flash_RMSNorm modules
|
| 88 |
+
|
| 89 |
+
Patched Flash_RoPE globally
|
| 90 |
+
|
| 91 |
+
应用编译配置: {'mode': 'max-autotune-no-cudagraphs', 'dynamic': True}
|
| 92 |
+
|
| 93 |
+
预热运行 1 次...
|
| 94 |
+
预热 1/1
|
| 95 |
+
|
| 96 |
+
开始基准测试 3 次...
|
| 97 |
+
运行 1/3
|
| 98 |
+
耗时: 12.61秒
|
| 99 |
+
运行 2/3
|
| 100 |
+
耗时: 12.63秒
|
| 101 |
+
运行 3/3
|
| 102 |
+
耗时: 12.63秒
|
| 103 |
+
|
| 104 |
+
============================================================
|
| 105 |
+
设置 Pipeline: Max-Autotune + Fullgraph
|
| 106 |
+
============================================================
|
| 107 |
+
Patched 120 FP32_RMSNorm modules
|
| 108 |
+
|
| 109 |
+
Patched 30 Flash_LayerNorm modules
|
| 110 |
+
|
| 111 |
+
Patched 120 Flash_RMSNorm modules
|
| 112 |
+
|
| 113 |
+
Patched Flash_RoPE globally
|
| 114 |
+
|
| 115 |
+
应用编译配置: {'mode': 'max-autotune', 'fullgraph': True}
|
| 116 |
+
|
| 117 |
+
预热运行 1 次...
|
| 118 |
+
预热 1/1
|
| 119 |
+
|
| 120 |
+
❌ 配置 'Max-Autotune + Fullgraph' 失败: Skip calling `torch.compiler.disable()`d function
|
| 121 |
+
Explanation: Skip calling function `<function flash_rms_layernorm at 0x7fe108a128e0>` since it was wrapped with `torch.compiler.disable`
|
| 122 |
+
Hint: Remove the `torch.compiler.disable` call
|
| 123 |
+
|
| 124 |
+
Developer debug context: <function flash_rms_layernorm at 0x7fe108a128e0>
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
from user code:
|
| 128 |
+
File "transformer_helios.py", line 999, in forward
|
| 129 |
+
attn_output = self.attn1(
|
| 130 |
+
File "transformer_helios.py", line 737, in forward
|
| 131 |
+
return self.processor(
|
| 132 |
+
File "transformer_helios.py", line 360, in __call__
|
| 133 |
+
query = attn.norm_q(query)
|
| 134 |
+
File "/usr/local/lib/python3.11/dist-packages/torch/nn/modules/module.py", line 1762, in _call_impl
|
| 135 |
+
return forward_call(*args, **kwargs)
|
| 136 |
+
File "kernels/triton_norm.py", line 29, in <lambda>
|
| 137 |
+
module.forward = (lambda self, x: flash_rms_layernorm(self, x)).__get__(module, module.__class__)
|
| 138 |
+
|
| 139 |
+
Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
============================================================
|
| 143 |
+
设置 Pipeline: Max-Autotune
|
| 144 |
+
============================================================
|
| 145 |
+
Patched 120 FP32_RMSNorm modules
|
| 146 |
+
|
| 147 |
+
Patched 30 Flash_LayerNorm modules
|
| 148 |
+
|
| 149 |
+
Patched 120 Flash_RMSNorm modules
|
| 150 |
+
|
| 151 |
+
Patched Flash_RoPE globally
|
| 152 |
+
|
| 153 |
+
应用编译配置: {'mode': 'max-autotune'}
|
| 154 |
+
|
| 155 |
+
预热运行 1 次...
|
| 156 |
+
预热 1/1
|
| 157 |
+
|
| 158 |
+
开始基准测试 3 次...
|
| 159 |
+
运行 1/3
|
| 160 |
+
耗时: 13.02秒
|
| 161 |
+
运行 2/3
|
| 162 |
+
耗时: 13.02秒
|
| 163 |
+
运行 3/3
|
| 164 |
+
耗时: 13.03秒
|
| 165 |
+
|
| 166 |
+
============================================================
|
| 167 |
+
设置 Pipeline: Reduce-Overhead
|
| 168 |
+
============================================================
|
| 169 |
+
Patched 120 FP32_RMSNorm modules
|
| 170 |
+
|
| 171 |
+
Patched 30 Flash_LayerNorm modules
|
| 172 |
+
|
| 173 |
+
Patched 120 Flash_RMSNorm modules
|
| 174 |
+
|
| 175 |
+
Patched Flash_RoPE globally
|
| 176 |
+
|
| 177 |
+
应用编译配置: {'mode': 'reduce-overhead'}
|
| 178 |
+
|
| 179 |
+
预热运行 1 次...
|
| 180 |
+
预热 1/1
|
| 181 |
+
|
| 182 |
+
开始基准测试 3 次...
|
| 183 |
+
运行 1/3
|
| 184 |
+
耗时: 13.24秒
|
| 185 |
+
运行 2/3
|
| 186 |
+
耗时: 13.24秒
|
| 187 |
+
运行 3/3
|
| 188 |
+
耗时: 13.26秒
|
| 189 |
+
|
| 190 |
+
============================================================
|
| 191 |
+
设置 Pipeline: Default Mode
|
| 192 |
+
============================================================
|
| 193 |
+
Patched 120 FP32_RMSNorm modules
|
| 194 |
+
|
| 195 |
+
Patched 30 Flash_LayerNorm modules
|
| 196 |
+
|
| 197 |
+
Patched 120 Flash_RMSNorm modules
|
| 198 |
+
|
| 199 |
+
Patched Flash_RoPE globally
|
| 200 |
+
|
| 201 |
+
应用编译配置: {'mode': 'default'}
|
| 202 |
+
|
| 203 |
+
预热运行 1 次...
|
| 204 |
+
预热 1/1
|
| 205 |
+
|
| 206 |
+
开始基准测试 3 次...
|
| 207 |
+
运行 1/3
|
| 208 |
+
耗时: 12.74秒
|
| 209 |
+
运行 2/3
|
| 210 |
+
耗时: 12.68秒
|
| 211 |
+
运行 3/3
|
| 212 |
+
耗时: 12.75秒
|
| 213 |
+
|
| 214 |
+
================================================================================
|
| 215 |
+
基准测试结果摘要
|
| 216 |
+
================================================================================
|
| 217 |
+
配置 平均时间(秒) 最小时间(秒) 最大时间(秒)
|
| 218 |
+
--------------------------------------------------------------------------------
|
| 219 |
+
No Compile (Baseline) 17.16 17.14 17.19
|
| 220 |
+
Default Compile 12.79 12.79 12.80
|
| 221 |
+
Fullgraph Only 12.80 12.79 12.80
|
| 222 |
+
Max-Autotune-No-Cudagraphs + Dynamic 12.62 12.61 12.63
|
| 223 |
+
Max-Autotune + Fullgraph FAILED FAILED FAILED
|
| 224 |
+
Max-Autotune 13.02 13.02 13.03
|
| 225 |
+
Reduce-Overhead 13.25 13.24 13.26
|
| 226 |
+
Default Mode 12.72 12.68 12.75
|
| 227 |
+
|
| 228 |
+
================================================================================
|
| 229 |
+
速度排名 (从快到慢)
|
| 230 |
+
================================================================================
|
| 231 |
+
|
| 232 |
+
1. Max-Autotune-No-Cudagraphs + Dynamic
|
| 233 |
+
平均时间: 12.62秒
|
| 234 |
+
相对最慢提速: 1.36x
|
| 235 |
+
详细时间: ['12.61s', '12.63s', '12.63s']
|
| 236 |
+
|
| 237 |
+
2. Default Mode
|
| 238 |
+
平均时间: 12.72秒
|
| 239 |
+
相对最慢提速: 1.35x
|
| 240 |
+
详细时间: ['12.74s', '12.68s', '12.75s']
|
| 241 |
+
|
| 242 |
+
3. Default Compile
|
| 243 |
+
平均时间: 12.79秒
|
| 244 |
+
相对最慢提速: 1.34x
|
| 245 |
+
详细时间: ['12.80s', '12.79s', '12.79s']
|
| 246 |
+
|
| 247 |
+
4. Fullgraph Only
|
| 248 |
+
平均时间: 12.80秒
|
| 249 |
+
相对最慢提速: 1.34x
|
| 250 |
+
详细时间: ['12.79s', '12.80s', '12.80s']
|
| 251 |
+
|
| 252 |
+
5. Max-Autotune
|
| 253 |
+
平均时间: 13.02秒
|
| 254 |
+
相对最慢提速: 1.32x
|
| 255 |
+
详细时间: ['13.02s', '13.02s', '13.03s']
|
| 256 |
+
|
| 257 |
+
6. Reduce-Overhead
|
| 258 |
+
平均时间: 13.25秒
|
| 259 |
+
相对最慢提速: 1.30x
|
| 260 |
+
详细时间: ['13.24s', '13.24s', '13.26s']
|
| 261 |
+
|
| 262 |
+
7. No Compile (Baseline)
|
| 263 |
+
平均时间: 17.16秒
|
| 264 |
+
相对最慢提速: 1.00x
|
| 265 |
+
详细时间: ['17.15s', '17.14s', '17.19s']
|
| 266 |
+
|
| 267 |
+
================================================================================
|
| 268 |
+
测试完成! 结果已保存到: compile_benchmark_results_20260125_160944.txt
|
| 269 |
+
================================================================================
|
Helios/_DEV/tools/others/benchmark/benchmark_patchification_performance.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 15 |
+
# 加载transformer
|
| 16 |
+
model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
|
| 17 |
+
transformer = WanTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.bfloat16)
|
| 18 |
+
transformer.enable_gradient_checkpointing()
|
| 19 |
+
transformer.set_attention_backend("_flash_3_hub")
|
| 20 |
+
transformer.to("cuda")
|
| 21 |
+
|
| 22 |
+
noise_per_token = 960
|
| 23 |
+
noise_total_token = noise_per_token * 9
|
| 24 |
+
|
| 25 |
+
his_tokens = [960, 1920, 3840, 5760, 7680, 9600, 11520, 13440, 15360, 17280]
|
| 26 |
+
his_tokens_naive = [960, 1920, 2160, 2190, 2220, 2250, 2280, 2310, 2340, 2370]
|
| 27 |
+
|
| 28 |
+
benchmark_results = {
|
| 29 |
+
"timestamp": datetime.now().isoformat(),
|
| 30 |
+
"noise_total_token": noise_total_token,
|
| 31 |
+
"experiments": [],
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def create_dummy_inputs(transformer, num_frames, height=384, width=640, requires_grad=False):
|
| 36 |
+
"""创建transformer的dummy输入"""
|
| 37 |
+
batch_size = 1
|
| 38 |
+
device = transformer.device
|
| 39 |
+
dtype = transformer.dtype
|
| 40 |
+
|
| 41 |
+
# hidden_states: [B, C, F, H, W]
|
| 42 |
+
in_channels = transformer.config.in_channels
|
| 43 |
+
latent_h = height // 8
|
| 44 |
+
latent_w = width // 8
|
| 45 |
+
latent_f = num_frames
|
| 46 |
+
|
| 47 |
+
hidden_states = torch.randn(
|
| 48 |
+
batch_size, in_channels, latent_f, latent_h, latent_w, device=device, dtype=dtype, requires_grad=requires_grad
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# timestep
|
| 52 |
+
timestep = torch.tensor([999], device=device, dtype=torch.long)
|
| 53 |
+
timestep = timestep.expand(batch_size)
|
| 54 |
+
|
| 55 |
+
# encoder_hidden_states
|
| 56 |
+
seq_len = 512
|
| 57 |
+
hidden_dim = 4096
|
| 58 |
+
encoder_hidden_states = torch.randn(batch_size, seq_len, hidden_dim, device=device, dtype=dtype)
|
| 59 |
+
|
| 60 |
+
return hidden_states, timestep, encoder_hidden_states
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def measure_inference_speed(transformer, hidden_states, timestep, encoder_hidden_states, num_runs=10):
|
| 64 |
+
"""测量推理速度(单步)"""
|
| 65 |
+
try:
|
| 66 |
+
# 预热
|
| 67 |
+
for _ in range(3):
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
_ = transformer(
|
| 70 |
+
hidden_states=hidden_states,
|
| 71 |
+
timestep=timestep,
|
| 72 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 73 |
+
return_dict=True,
|
| 74 |
+
)
|
| 75 |
+
torch.cuda.synchronize()
|
| 76 |
+
|
| 77 |
+
# 正式测速
|
| 78 |
+
times = []
|
| 79 |
+
for _ in range(num_runs):
|
| 80 |
+
torch.cuda.synchronize()
|
| 81 |
+
start_time = time.time()
|
| 82 |
+
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
_ = transformer(
|
| 85 |
+
hidden_states=hidden_states,
|
| 86 |
+
timestep=timestep,
|
| 87 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 88 |
+
return_dict=True,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
torch.cuda.synchronize()
|
| 92 |
+
end_time = time.time()
|
| 93 |
+
times.append(end_time - start_time)
|
| 94 |
+
|
| 95 |
+
return {
|
| 96 |
+
"avg_time_s": round(sum(times) / len(times), 4),
|
| 97 |
+
"min_time_s": round(min(times), 4),
|
| 98 |
+
"max_time_s": round(max(times), 4),
|
| 99 |
+
"std_time_s": round(torch.std(torch.tensor(times)).item(), 4),
|
| 100 |
+
"status": "success",
|
| 101 |
+
}
|
| 102 |
+
except RuntimeError as e:
|
| 103 |
+
if "out of memory" in str(e).lower():
|
| 104 |
+
torch.cuda.empty_cache()
|
| 105 |
+
return {"status": "OOM", "error": str(e)}
|
| 106 |
+
else:
|
| 107 |
+
raise
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states):
|
| 111 |
+
"""测量推理显存"""
|
| 112 |
+
try:
|
| 113 |
+
torch.cuda.reset_peak_memory_stats()
|
| 114 |
+
torch.cuda.empty_cache()
|
| 115 |
+
torch.cuda.synchronize()
|
| 116 |
+
mem_before = torch.cuda.memory_allocated() / 1024**3
|
| 117 |
+
|
| 118 |
+
# Forward (推理模式)
|
| 119 |
+
torch.cuda.reset_peak_memory_stats()
|
| 120 |
+
with torch.no_grad():
|
| 121 |
+
_ = transformer(
|
| 122 |
+
hidden_states=hidden_states,
|
| 123 |
+
timestep=timestep,
|
| 124 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 125 |
+
return_dict=True,
|
| 126 |
+
attention_kwargs=None,
|
| 127 |
+
)
|
| 128 |
+
torch.cuda.synchronize()
|
| 129 |
+
|
| 130 |
+
inference_peak = torch.cuda.max_memory_allocated() / 1024**3
|
| 131 |
+
inference_mem_diff = inference_peak - mem_before
|
| 132 |
+
|
| 133 |
+
return {
|
| 134 |
+
"mem_before_gb": round(mem_before, 3),
|
| 135 |
+
"inference_peak_gb": round(inference_peak, 3),
|
| 136 |
+
"inference_mem_diff_gb": round(inference_mem_diff, 3),
|
| 137 |
+
"status": "success",
|
| 138 |
+
}
|
| 139 |
+
except RuntimeError as e:
|
| 140 |
+
if "out of memory" in str(e).lower():
|
| 141 |
+
torch.cuda.empty_cache()
|
| 142 |
+
return {"status": "OOM", "error": str(e)}
|
| 143 |
+
else:
|
| 144 |
+
raise
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states):
|
| 148 |
+
"""测量训练显存(包含backward)"""
|
| 149 |
+
try:
|
| 150 |
+
torch.cuda.reset_peak_memory_stats()
|
| 151 |
+
torch.cuda.empty_cache()
|
| 152 |
+
torch.cuda.synchronize()
|
| 153 |
+
mem_before = torch.cuda.memory_allocated() / 1024**3
|
| 154 |
+
|
| 155 |
+
# Forward + Backward (训练模式)
|
| 156 |
+
torch.cuda.reset_peak_memory_stats()
|
| 157 |
+
|
| 158 |
+
# Forward
|
| 159 |
+
output = transformer(
|
| 160 |
+
hidden_states=hidden_states,
|
| 161 |
+
timestep=timestep,
|
| 162 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 163 |
+
return_dict=True,
|
| 164 |
+
attention_kwargs=None,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# 创建一个简单的loss并backward
|
| 168 |
+
loss = output.sample.sum()
|
| 169 |
+
loss.backward()
|
| 170 |
+
|
| 171 |
+
torch.cuda.synchronize()
|
| 172 |
+
|
| 173 |
+
training_peak = torch.cuda.max_memory_allocated() / 1024**3
|
| 174 |
+
training_mem_diff = training_peak - mem_before
|
| 175 |
+
|
| 176 |
+
# 清理梯度
|
| 177 |
+
transformer.zero_grad(set_to_none=True)
|
| 178 |
+
|
| 179 |
+
return {
|
| 180 |
+
"mem_before_gb": round(mem_before, 3),
|
| 181 |
+
"training_peak_gb": round(training_peak, 3),
|
| 182 |
+
"training_mem_diff_gb": round(training_mem_diff, 3),
|
| 183 |
+
"status": "success",
|
| 184 |
+
}
|
| 185 |
+
except RuntimeError as e:
|
| 186 |
+
if "out of memory" in str(e).lower():
|
| 187 |
+
torch.cuda.empty_cache()
|
| 188 |
+
transformer.zero_grad(set_to_none=True)
|
| 189 |
+
return {"status": "OOM", "error": str(e)}
|
| 190 |
+
else:
|
| 191 |
+
raise
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def warmup(transformer, num_runs=3):
|
| 195 |
+
"""预热"""
|
| 196 |
+
print("🔥 Warming up...")
|
| 197 |
+
for i in range(num_runs):
|
| 198 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(transformer, num_frames=5)
|
| 199 |
+
with torch.no_grad():
|
| 200 |
+
_ = transformer(
|
| 201 |
+
hidden_states=hidden_states,
|
| 202 |
+
timestep=timestep,
|
| 203 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 204 |
+
return_dict=True,
|
| 205 |
+
)
|
| 206 |
+
print(f" Warmup {i + 1}/{num_runs} done")
|
| 207 |
+
torch.cuda.empty_cache()
|
| 208 |
+
print("✅ Warmup completed\n")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def run_experiment(his_tokens_list, experiment_name):
|
| 212 |
+
"""运行完整实验"""
|
| 213 |
+
results = []
|
| 214 |
+
|
| 215 |
+
for his_token in his_tokens_list:
|
| 216 |
+
torch.cuda.reset_peak_memory_stats()
|
| 217 |
+
torch.cuda.empty_cache()
|
| 218 |
+
|
| 219 |
+
total_token = his_token + noise_total_token
|
| 220 |
+
num_frames = round((total_token / noise_per_token - 1) * 4 + 1)
|
| 221 |
+
|
| 222 |
+
print(f"\n{'=' * 60}")
|
| 223 |
+
print(f"{experiment_name} | tokens: {his_token} | frames: {int(num_frames)}")
|
| 224 |
+
print(f"{'=' * 60}")
|
| 225 |
+
|
| 226 |
+
result = {
|
| 227 |
+
"his_token": his_token,
|
| 228 |
+
"total_token": total_token,
|
| 229 |
+
"num_frames": int(num_frames),
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
# 1. 测推理速度 (不需要梯度)
|
| 233 |
+
print("📊 Measuring inference speed...")
|
| 234 |
+
try:
|
| 235 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(
|
| 236 |
+
transformer, num_frames, requires_grad=False
|
| 237 |
+
)
|
| 238 |
+
speed_stats = measure_inference_speed(transformer, hidden_states, timestep, encoder_hidden_states)
|
| 239 |
+
|
| 240 |
+
if speed_stats["status"] == "OOM":
|
| 241 |
+
print(" ❌ OOM - Skipping remaining tests for this config")
|
| 242 |
+
result.update({"speed_status": "OOM", "inference_status": "SKIPPED", "training_status": "SKIPPED"})
|
| 243 |
+
results.append(result)
|
| 244 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 245 |
+
torch.cuda.empty_cache()
|
| 246 |
+
continue
|
| 247 |
+
else:
|
| 248 |
+
print(
|
| 249 |
+
f" Avg: {speed_stats['avg_time_s']:.4f}s | "
|
| 250 |
+
f"Min: {speed_stats['min_time_s']:.4f}s | "
|
| 251 |
+
f"Max: {speed_stats['max_time_s']:.4f}s"
|
| 252 |
+
)
|
| 253 |
+
result.update(speed_stats)
|
| 254 |
+
|
| 255 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 256 |
+
torch.cuda.empty_cache()
|
| 257 |
+
except Exception as e:
|
| 258 |
+
print(f" ❌ Error: {e}")
|
| 259 |
+
result["speed_status"] = "ERROR"
|
| 260 |
+
torch.cuda.empty_cache()
|
| 261 |
+
|
| 262 |
+
# 2. 测推理显存 (不需要梯度)
|
| 263 |
+
print("💾 Measuring inference memory...")
|
| 264 |
+
try:
|
| 265 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(
|
| 266 |
+
transformer, num_frames, requires_grad=False
|
| 267 |
+
)
|
| 268 |
+
inference_mem_stats = measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states)
|
| 269 |
+
|
| 270 |
+
if inference_mem_stats["status"] == "OOM":
|
| 271 |
+
print(" ❌ OOM - Skipping training test")
|
| 272 |
+
result.update(inference_mem_stats)
|
| 273 |
+
result["training_status"] = "SKIPPED"
|
| 274 |
+
results.append(result)
|
| 275 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 276 |
+
torch.cuda.empty_cache()
|
| 277 |
+
continue
|
| 278 |
+
else:
|
| 279 |
+
print(
|
| 280 |
+
f" Peak: {inference_mem_stats['inference_peak_gb']:.3f} GB | "
|
| 281 |
+
f"Diff: {inference_mem_stats['inference_mem_diff_gb']:.3f} GB"
|
| 282 |
+
)
|
| 283 |
+
result.update(inference_mem_stats)
|
| 284 |
+
|
| 285 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 286 |
+
torch.cuda.empty_cache()
|
| 287 |
+
except Exception as e:
|
| 288 |
+
print(f" ❌ Error: {e}")
|
| 289 |
+
result["inference_status"] = "ERROR"
|
| 290 |
+
torch.cuda.empty_cache()
|
| 291 |
+
|
| 292 |
+
# 3. 测训练显存 (需要梯度)
|
| 293 |
+
print("🔥 Measuring training memory...")
|
| 294 |
+
try:
|
| 295 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(
|
| 296 |
+
transformer, num_frames, requires_grad=True
|
| 297 |
+
)
|
| 298 |
+
training_mem_stats = measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states)
|
| 299 |
+
|
| 300 |
+
if training_mem_stats["status"] == "OOM":
|
| 301 |
+
print(" ❌ OOM")
|
| 302 |
+
result.update(training_mem_stats)
|
| 303 |
+
else:
|
| 304 |
+
print(
|
| 305 |
+
f" Peak: {training_mem_stats['training_peak_gb']:.3f} GB | "
|
| 306 |
+
f"Diff: {training_mem_stats['training_mem_diff_gb']:.3f} GB"
|
| 307 |
+
)
|
| 308 |
+
result.update(training_mem_stats)
|
| 309 |
+
|
| 310 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 311 |
+
torch.cuda.empty_cache()
|
| 312 |
+
except Exception as e:
|
| 313 |
+
print(f" ❌ Error: {e}")
|
| 314 |
+
result["training_status"] = "ERROR"
|
| 315 |
+
torch.cuda.empty_cache()
|
| 316 |
+
|
| 317 |
+
results.append(result)
|
| 318 |
+
|
| 319 |
+
return results
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# 运行实验
|
| 323 |
+
warmup(transformer)
|
| 324 |
+
|
| 325 |
+
print("\n" + "=" * 80)
|
| 326 |
+
print("STANDARD EXPERIMENT")
|
| 327 |
+
print("=" * 80)
|
| 328 |
+
results_standard = run_experiment(his_tokens, "Standard")
|
| 329 |
+
|
| 330 |
+
print("\n" + "=" * 80)
|
| 331 |
+
print("NAIVE EXPERIMENT")
|
| 332 |
+
print("=" * 80)
|
| 333 |
+
results_naive = run_experiment(his_tokens_naive, "Naive")
|
| 334 |
+
|
| 335 |
+
# 保存结果
|
| 336 |
+
benchmark_results["experiments"] = [
|
| 337 |
+
{"name": "standard", "results": results_standard},
|
| 338 |
+
{"name": "naive", "results": results_naive},
|
| 339 |
+
]
|
| 340 |
+
|
| 341 |
+
output_file = "benchmark_patchification_results.json"
|
| 342 |
+
with open(output_file, "w") as f:
|
| 343 |
+
json.dump(benchmark_results, f, indent=2)
|
| 344 |
+
|
| 345 |
+
print("\n" + "=" * 80)
|
| 346 |
+
print(f"✅ Results saved to {output_file}")
|
| 347 |
+
print("=" * 80)
|
| 348 |
+
|
| 349 |
+
# 打印汇总表格
|
| 350 |
+
print("\n" + "=" * 80)
|
| 351 |
+
print("BENCHMARK SUMMARY")
|
| 352 |
+
print("=" * 80)
|
| 353 |
+
|
| 354 |
+
for exp in benchmark_results["experiments"]:
|
| 355 |
+
print(f"\n=== {exp['name'].upper()} ===")
|
| 356 |
+
print(f"{'Tokens':>6} {'Frames':>6} {'Speed(s)':>10} {'Infer(GB)':>11} {'Train(GB)':>11} {'Status':>10}")
|
| 357 |
+
print("-" * 72)
|
| 358 |
+
for r in exp["results"]:
|
| 359 |
+
speed_str = f"{r.get('avg_time_s', 0):.4f}s" if r.get("status") == "success" else "N/A"
|
| 360 |
+
infer_str = f"{r.get('inference_mem_diff_gb', 0):.3f}" if r.get("inference_peak_gb") else "N/A"
|
| 361 |
+
train_str = f"{r.get('training_mem_diff_gb', 0):.3f}" if r.get("training_peak_gb") else "N/A"
|
| 362 |
+
|
| 363 |
+
# 判断整体状态
|
| 364 |
+
if r.get("speed_status") == "OOM":
|
| 365 |
+
status = "OOM"
|
| 366 |
+
elif r.get("training_status") == "OOM":
|
| 367 |
+
status = "OOM(train)"
|
| 368 |
+
elif r.get("status") == "success":
|
| 369 |
+
status = "OK"
|
| 370 |
+
else:
|
| 371 |
+
status = "PARTIAL"
|
| 372 |
+
|
| 373 |
+
print(f"{r['his_token']:6d} {r['num_frames']:6d} {speed_str:>10} {infer_str:>11} {train_str:>11} {status:>10}")
|
| 374 |
+
|
| 375 |
+
print("\n" + "=" * 80)
|
| 376 |
+
print("Legend:")
|
| 377 |
+
print(" Speed(s) - Average inference time per step")
|
| 378 |
+
print(" Infer(GB) - Memory usage during inference (forward only)")
|
| 379 |
+
print(" Train(GB) - Memory usage during training (forward + backward)")
|
| 380 |
+
print(" Status - OK/OOM/OOM(train)/PARTIAL")
|
| 381 |
+
print("=" * 80)
|
Helios/_DEV/tools/others/benchmark/benchmark_patchification_results.json
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"timestamp": "2026-02-06T05:34:36.528673",
|
| 3 |
+
"noise_total_token": 8640,
|
| 4 |
+
"experiments": [
|
| 5 |
+
{
|
| 6 |
+
"name": "standard",
|
| 7 |
+
"results": [
|
| 8 |
+
{
|
| 9 |
+
"his_token": 960,
|
| 10 |
+
"total_token": 9600,
|
| 11 |
+
"num_frames": 37,
|
| 12 |
+
"avg_time_s": 4.1635,
|
| 13 |
+
"min_time_s": 4.1583,
|
| 14 |
+
"max_time_s": 4.1741,
|
| 15 |
+
"std_time_s": 0.0041,
|
| 16 |
+
"status": "success",
|
| 17 |
+
"mem_before_gb": 26.787,
|
| 18 |
+
"inference_peak_gb": 30.565,
|
| 19 |
+
"inference_mem_diff_gb": 3.778,
|
| 20 |
+
"training_peak_gb": 68.509,
|
| 21 |
+
"training_mem_diff_gb": 41.722
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"his_token": 1920,
|
| 25 |
+
"total_token": 10560,
|
| 26 |
+
"num_frames": 41,
|
| 27 |
+
"avg_time_s": 4.7998,
|
| 28 |
+
"min_time_s": 4.798,
|
| 29 |
+
"max_time_s": 4.8031,
|
| 30 |
+
"std_time_s": 0.0013,
|
| 31 |
+
"status": "success",
|
| 32 |
+
"mem_before_gb": 26.819,
|
| 33 |
+
"inference_peak_gb": 31.001,
|
| 34 |
+
"inference_mem_diff_gb": 4.182,
|
| 35 |
+
"training_peak_gb": 70.252,
|
| 36 |
+
"training_mem_diff_gb": 43.433
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"his_token": 3840,
|
| 40 |
+
"total_token": 12480,
|
| 41 |
+
"num_frames": 49,
|
| 42 |
+
"avg_time_s": 6.1835,
|
| 43 |
+
"min_time_s": 6.1744,
|
| 44 |
+
"max_time_s": 6.1921,
|
| 45 |
+
"std_time_s": 0.0049,
|
| 46 |
+
"status": "success",
|
| 47 |
+
"mem_before_gb": 26.82,
|
| 48 |
+
"inference_peak_gb": 31.815,
|
| 49 |
+
"inference_mem_diff_gb": 4.995,
|
| 50 |
+
"training_peak_gb": 73.733,
|
| 51 |
+
"training_mem_diff_gb": 46.913
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"his_token": 5760,
|
| 55 |
+
"total_token": 14400,
|
| 56 |
+
"num_frames": 57,
|
| 57 |
+
"avg_time_s": 7.7019,
|
| 58 |
+
"min_time_s": 7.6963,
|
| 59 |
+
"max_time_s": 7.7083,
|
| 60 |
+
"std_time_s": 0.0039,
|
| 61 |
+
"status": "OOM",
|
| 62 |
+
"mem_before_gb": 26.821,
|
| 63 |
+
"inference_peak_gb": 32.628,
|
| 64 |
+
"inference_mem_diff_gb": 5.808,
|
| 65 |
+
"error": "CUDA out of memory. Tried to allocate 1.04 GiB. GPU 0 has a total capacity of 79.11 GiB of which 196.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 75.12 GiB is allocated by PyTorch, and 3.04 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)"
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"his_token": 7680,
|
| 69 |
+
"total_token": 16320,
|
| 70 |
+
"num_frames": 65,
|
| 71 |
+
"avg_time_s": 9.3743,
|
| 72 |
+
"min_time_s": 9.3587,
|
| 73 |
+
"max_time_s": 9.3922,
|
| 74 |
+
"std_time_s": 0.0092,
|
| 75 |
+
"status": "OOM",
|
| 76 |
+
"mem_before_gb": 26.822,
|
| 77 |
+
"inference_peak_gb": 33.442,
|
| 78 |
+
"inference_mem_diff_gb": 6.621,
|
| 79 |
+
"error": "CUDA out of memory. Tried to allocate 1.19 GiB. GPU 0 has a total capacity of 79.11 GiB of which 108.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 77.18 GiB is allocated by PyTorch, and 1.07 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)"
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"his_token": 9600,
|
| 83 |
+
"total_token": 18240,
|
| 84 |
+
"num_frames": 73,
|
| 85 |
+
"avg_time_s": 11.2228,
|
| 86 |
+
"min_time_s": 11.2066,
|
| 87 |
+
"max_time_s": 11.2309,
|
| 88 |
+
"std_time_s": 0.0076,
|
| 89 |
+
"status": "OOM",
|
| 90 |
+
"mem_before_gb": 26.823,
|
| 91 |
+
"inference_peak_gb": 34.256,
|
| 92 |
+
"inference_mem_diff_gb": 7.434,
|
| 93 |
+
"error": "CUDA out of memory. Tried to allocate 1.34 GiB. GPU 0 has a total capacity of 79.11 GiB of which 868.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 75.75 GiB is allocated by PyTorch, and 1.76 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)"
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"his_token": 11520,
|
| 97 |
+
"total_token": 20160,
|
| 98 |
+
"num_frames": 81,
|
| 99 |
+
"avg_time_s": 13.2451,
|
| 100 |
+
"min_time_s": 13.2332,
|
| 101 |
+
"max_time_s": 13.251,
|
| 102 |
+
"std_time_s": 0.0055,
|
| 103 |
+
"status": "OOM",
|
| 104 |
+
"mem_before_gb": 26.824,
|
| 105 |
+
"inference_peak_gb": 35.071,
|
| 106 |
+
"inference_mem_diff_gb": 8.248,
|
| 107 |
+
"error": "CUDA out of memory. Tried to allocate 1.48 GiB. GPU 0 has a total capacity of 79.11 GiB of which 608.56 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 75.14 GiB is allocated by PyTorch, and 2.62 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)"
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"his_token": 13440,
|
| 111 |
+
"total_token": 22080,
|
| 112 |
+
"num_frames": 89,
|
| 113 |
+
"avg_time_s": 15.2558,
|
| 114 |
+
"min_time_s": 15.24,
|
| 115 |
+
"max_time_s": 15.2622,
|
| 116 |
+
"std_time_s": 0.0081,
|
| 117 |
+
"status": "OOM",
|
| 118 |
+
"mem_before_gb": 26.825,
|
| 119 |
+
"inference_peak_gb": 35.885,
|
| 120 |
+
"inference_mem_diff_gb": 9.06,
|
| 121 |
+
"error": "CUDA out of memory. Tried to allocate 1.63 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.36 GiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 74.19 GiB is allocated by PyTorch, and 2.80 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)"
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"his_token": 15360,
|
| 125 |
+
"total_token": 24000,
|
| 126 |
+
"num_frames": 97,
|
| 127 |
+
"avg_time_s": 17.5647,
|
| 128 |
+
"min_time_s": 17.5502,
|
| 129 |
+
"max_time_s": 17.5807,
|
| 130 |
+
"std_time_s": 0.0095,
|
| 131 |
+
"status": "OOM",
|
| 132 |
+
"mem_before_gb": 26.825,
|
| 133 |
+
"inference_peak_gb": 36.699,
|
| 134 |
+
"inference_mem_diff_gb": 9.873,
|
| 135 |
+
"error": "CUDA out of memory. Tried to allocate 1.78 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.39 GiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 74.90 GiB is allocated by PyTorch, and 2.07 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)"
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"his_token": 17280,
|
| 139 |
+
"total_token": 25920,
|
| 140 |
+
"num_frames": 105,
|
| 141 |
+
"avg_time_s": 20.0106,
|
| 142 |
+
"min_time_s": 19.9988,
|
| 143 |
+
"max_time_s": 20.0365,
|
| 144 |
+
"std_time_s": 0.012,
|
| 145 |
+
"status": "OOM",
|
| 146 |
+
"mem_before_gb": 26.826,
|
| 147 |
+
"inference_peak_gb": 37.512,
|
| 148 |
+
"inference_mem_diff_gb": 10.686,
|
| 149 |
+
"error": "CUDA out of memory. Tried to allocate 1.92 GiB. GPU 0 has a total capacity of 79.11 GiB of which 1.18 GiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 70.20 GiB is allocated by PyTorch, and 6.99 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)"
|
| 150 |
+
}
|
| 151 |
+
]
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"name": "naive",
|
| 155 |
+
"results": [
|
| 156 |
+
{
|
| 157 |
+
"his_token": 960,
|
| 158 |
+
"total_token": 9600,
|
| 159 |
+
"num_frames": 37,
|
| 160 |
+
"avg_time_s": 4.1671,
|
| 161 |
+
"min_time_s": 4.1616,
|
| 162 |
+
"max_time_s": 4.171,
|
| 163 |
+
"std_time_s": 0.0032,
|
| 164 |
+
"status": "success",
|
| 165 |
+
"mem_before_gb": 26.818,
|
| 166 |
+
"inference_peak_gb": 30.595,
|
| 167 |
+
"inference_mem_diff_gb": 3.777,
|
| 168 |
+
"training_peak_gb": 68.509,
|
| 169 |
+
"training_mem_diff_gb": 41.69
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"his_token": 1920,
|
| 173 |
+
"total_token": 10560,
|
| 174 |
+
"num_frames": 41,
|
| 175 |
+
"avg_time_s": 4.8,
|
| 176 |
+
"min_time_s": 4.7986,
|
| 177 |
+
"max_time_s": 4.8014,
|
| 178 |
+
"std_time_s": 0.0009,
|
| 179 |
+
"status": "success",
|
| 180 |
+
"mem_before_gb": 26.819,
|
| 181 |
+
"inference_peak_gb": 31.001,
|
| 182 |
+
"inference_mem_diff_gb": 4.182,
|
| 183 |
+
"training_peak_gb": 70.252,
|
| 184 |
+
"training_mem_diff_gb": 43.433
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"his_token": 2160,
|
| 188 |
+
"total_token": 10800,
|
| 189 |
+
"num_frames": 42,
|
| 190 |
+
"avg_time_s": 4.9164,
|
| 191 |
+
"min_time_s": 4.9075,
|
| 192 |
+
"max_time_s": 4.9335,
|
| 193 |
+
"std_time_s": 0.0082,
|
| 194 |
+
"status": "success",
|
| 195 |
+
"mem_before_gb": 26.819,
|
| 196 |
+
"inference_peak_gb": 31.105,
|
| 197 |
+
"inference_mem_diff_gb": 4.286,
|
| 198 |
+
"training_peak_gb": 70.689,
|
| 199 |
+
"training_mem_diff_gb": 43.87
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"his_token": 2190,
|
| 203 |
+
"total_token": 10830,
|
| 204 |
+
"num_frames": 42,
|
| 205 |
+
"avg_time_s": 4.9196,
|
| 206 |
+
"min_time_s": 4.9037,
|
| 207 |
+
"max_time_s": 4.9359,
|
| 208 |
+
"std_time_s": 0.0105,
|
| 209 |
+
"status": "success",
|
| 210 |
+
"mem_before_gb": 26.819,
|
| 211 |
+
"inference_peak_gb": 31.105,
|
| 212 |
+
"inference_mem_diff_gb": 4.286,
|
| 213 |
+
"training_peak_gb": 70.689,
|
| 214 |
+
"training_mem_diff_gb": 43.87
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"his_token": 2220,
|
| 218 |
+
"total_token": 10860,
|
| 219 |
+
"num_frames": 42,
|
| 220 |
+
"avg_time_s": 4.9201,
|
| 221 |
+
"min_time_s": 4.9098,
|
| 222 |
+
"max_time_s": 4.9369,
|
| 223 |
+
"std_time_s": 0.0086,
|
| 224 |
+
"status": "success",
|
| 225 |
+
"mem_before_gb": 26.819,
|
| 226 |
+
"inference_peak_gb": 31.105,
|
| 227 |
+
"inference_mem_diff_gb": 4.286,
|
| 228 |
+
"training_peak_gb": 70.689,
|
| 229 |
+
"training_mem_diff_gb": 43.87
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"his_token": 2250,
|
| 233 |
+
"total_token": 10890,
|
| 234 |
+
"num_frames": 42,
|
| 235 |
+
"avg_time_s": 4.9168,
|
| 236 |
+
"min_time_s": 4.9079,
|
| 237 |
+
"max_time_s": 4.9294,
|
| 238 |
+
"std_time_s": 0.0073,
|
| 239 |
+
"status": "success",
|
| 240 |
+
"mem_before_gb": 26.819,
|
| 241 |
+
"inference_peak_gb": 31.105,
|
| 242 |
+
"inference_mem_diff_gb": 4.286,
|
| 243 |
+
"training_peak_gb": 70.689,
|
| 244 |
+
"training_mem_diff_gb": 43.87
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"his_token": 2280,
|
| 248 |
+
"total_token": 10920,
|
| 249 |
+
"num_frames": 42,
|
| 250 |
+
"avg_time_s": 4.9187,
|
| 251 |
+
"min_time_s": 4.9082,
|
| 252 |
+
"max_time_s": 4.9277,
|
| 253 |
+
"std_time_s": 0.0058,
|
| 254 |
+
"status": "success",
|
| 255 |
+
"mem_before_gb": 26.819,
|
| 256 |
+
"inference_peak_gb": 31.105,
|
| 257 |
+
"inference_mem_diff_gb": 4.286,
|
| 258 |
+
"training_peak_gb": 70.689,
|
| 259 |
+
"training_mem_diff_gb": 43.87
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"his_token": 2310,
|
| 263 |
+
"total_token": 10950,
|
| 264 |
+
"num_frames": 43,
|
| 265 |
+
"avg_time_s": 5.1375,
|
| 266 |
+
"min_time_s": 5.1308,
|
| 267 |
+
"max_time_s": 5.1426,
|
| 268 |
+
"std_time_s": 0.0039,
|
| 269 |
+
"status": "success",
|
| 270 |
+
"mem_before_gb": 26.819,
|
| 271 |
+
"inference_peak_gb": 31.205,
|
| 272 |
+
"inference_mem_diff_gb": 4.386,
|
| 273 |
+
"training_peak_gb": 71.118,
|
| 274 |
+
"training_mem_diff_gb": 44.298
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"his_token": 2340,
|
| 278 |
+
"total_token": 10980,
|
| 279 |
+
"num_frames": 43,
|
| 280 |
+
"avg_time_s": 5.1378,
|
| 281 |
+
"min_time_s": 5.1338,
|
| 282 |
+
"max_time_s": 5.1434,
|
| 283 |
+
"std_time_s": 0.0036,
|
| 284 |
+
"status": "success",
|
| 285 |
+
"mem_before_gb": 26.819,
|
| 286 |
+
"inference_peak_gb": 31.205,
|
| 287 |
+
"inference_mem_diff_gb": 4.386,
|
| 288 |
+
"training_peak_gb": 71.118,
|
| 289 |
+
"training_mem_diff_gb": 44.298
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"his_token": 2370,
|
| 293 |
+
"total_token": 11010,
|
| 294 |
+
"num_frames": 43,
|
| 295 |
+
"avg_time_s": 5.1388,
|
| 296 |
+
"min_time_s": 5.1317,
|
| 297 |
+
"max_time_s": 5.1453,
|
| 298 |
+
"std_time_s": 0.0051,
|
| 299 |
+
"status": "success",
|
| 300 |
+
"mem_before_gb": 26.819,
|
| 301 |
+
"inference_peak_gb": 31.205,
|
| 302 |
+
"inference_mem_diff_gb": 4.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
|
| 5 |
+
os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes"
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import time
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from helios.modules.kernels import (
|
| 13 |
+
replace_all_norms_with_flash_norms,
|
| 14 |
+
replace_linear_with_tiled_linear,
|
| 15 |
+
replace_rope_with_flash_rope,
|
| 16 |
+
)
|
| 17 |
+
from helios.modules.transformer_helios import HeliosTransformer3DModel
|
| 18 |
+
|
| 19 |
+
from diffusers.training_utils import free_memory
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# ============================================================================
|
| 23 |
+
# 配置参数
|
| 24 |
+
# ============================================================================
|
| 25 |
+
model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
|
| 26 |
+
TEST_NUM_FRAMES = 21
|
| 27 |
+
NUM_SPEED_RUNS = 10 # 速度测试的运行次数
|
| 28 |
+
HEIGHT = 384
|
| 29 |
+
WIDTH = 640
|
| 30 |
+
|
| 31 |
+
benchmark_results = {
|
| 32 |
+
"timestamp": datetime.now().isoformat(),
|
| 33 |
+
"test_config": {"num_frames": TEST_NUM_FRAMES, "height": HEIGHT, "width": WIDTH, "num_speed_runs": NUM_SPEED_RUNS},
|
| 34 |
+
"experiments": [],
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ============================================================================
|
| 39 |
+
# 辅助函数
|
| 40 |
+
# ============================================================================
|
| 41 |
+
def create_dummy_inputs(transformer, num_frames, height=384, width=640, requires_grad=False):
|
| 42 |
+
"""创建transformer的dummy输入"""
|
| 43 |
+
batch_size = 1
|
| 44 |
+
device = transformer.device
|
| 45 |
+
dtype = transformer.dtype
|
| 46 |
+
|
| 47 |
+
in_channels = transformer.config.in_channels
|
| 48 |
+
latent_h = height // 8
|
| 49 |
+
latent_w = width // 8
|
| 50 |
+
latent_f = num_frames
|
| 51 |
+
|
| 52 |
+
hidden_states = torch.randn(
|
| 53 |
+
batch_size, in_channels, latent_f, latent_h, latent_w, device=device, dtype=dtype, requires_grad=requires_grad
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
timestep = torch.tensor([999], device=device, dtype=torch.long)
|
| 57 |
+
timestep = timestep.expand(batch_size)
|
| 58 |
+
|
| 59 |
+
seq_len = 512
|
| 60 |
+
hidden_dim = 4096
|
| 61 |
+
encoder_hidden_states = torch.randn(batch_size, seq_len, hidden_dim, device=device, dtype=dtype)
|
| 62 |
+
|
| 63 |
+
return hidden_states, timestep, encoder_hidden_states
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def measure_inference_speed(transformer, hidden_states, timestep, encoder_hidden_states, num_runs=10):
|
| 67 |
+
"""测量推理速度"""
|
| 68 |
+
try:
|
| 69 |
+
# 预热
|
| 70 |
+
for _ in range(3):
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
_ = transformer(
|
| 73 |
+
hidden_states=hidden_states,
|
| 74 |
+
timestep=timestep,
|
| 75 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 76 |
+
return_dict=False,
|
| 77 |
+
)[0]
|
| 78 |
+
torch.cuda.synchronize()
|
| 79 |
+
|
| 80 |
+
# 正式测速
|
| 81 |
+
times = []
|
| 82 |
+
for _ in range(num_runs):
|
| 83 |
+
torch.cuda.synchronize()
|
| 84 |
+
start_time = time.time()
|
| 85 |
+
|
| 86 |
+
with torch.no_grad():
|
| 87 |
+
_ = transformer(
|
| 88 |
+
hidden_states=hidden_states,
|
| 89 |
+
timestep=timestep,
|
| 90 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 91 |
+
return_dict=False,
|
| 92 |
+
)[0]
|
| 93 |
+
|
| 94 |
+
torch.cuda.synchronize()
|
| 95 |
+
end_time = time.time()
|
| 96 |
+
times.append(end_time - start_time)
|
| 97 |
+
|
| 98 |
+
return {
|
| 99 |
+
"avg_time_s": round(sum(times) / len(times), 4),
|
| 100 |
+
"min_time_s": round(min(times), 4),
|
| 101 |
+
"max_time_s": round(max(times), 4),
|
| 102 |
+
"std_time_s": round(torch.std(torch.tensor(times)).item(), 4),
|
| 103 |
+
"status": "success",
|
| 104 |
+
}
|
| 105 |
+
except RuntimeError as e:
|
| 106 |
+
if "out of memory" in str(e).lower():
|
| 107 |
+
torch.cuda.empty_cache()
|
| 108 |
+
free_memory()
|
| 109 |
+
return {"status": "OOM", "error": str(e)}
|
| 110 |
+
else:
|
| 111 |
+
raise
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states):
|
| 115 |
+
"""测量推理显存"""
|
| 116 |
+
try:
|
| 117 |
+
torch.cuda.reset_peak_memory_stats()
|
| 118 |
+
torch.cuda.empty_cache()
|
| 119 |
+
free_memory()
|
| 120 |
+
torch.cuda.synchronize()
|
| 121 |
+
mem_before = torch.cuda.memory_allocated() / 1024**3
|
| 122 |
+
|
| 123 |
+
torch.cuda.reset_peak_memory_stats()
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
_ = transformer(
|
| 126 |
+
hidden_states=hidden_states,
|
| 127 |
+
timestep=timestep,
|
| 128 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 129 |
+
return_dict=False,
|
| 130 |
+
attention_kwargs=None,
|
| 131 |
+
)[0]
|
| 132 |
+
torch.cuda.synchronize()
|
| 133 |
+
|
| 134 |
+
inference_peak = torch.cuda.max_memory_allocated() / 1024**3
|
| 135 |
+
inference_mem_diff = inference_peak - mem_before
|
| 136 |
+
|
| 137 |
+
return {
|
| 138 |
+
"mem_before_gb": round(mem_before, 3),
|
| 139 |
+
"inference_peak_gb": round(inference_peak, 3),
|
| 140 |
+
"inference_mem_diff_gb": round(inference_mem_diff, 3),
|
| 141 |
+
"status": "success",
|
| 142 |
+
}
|
| 143 |
+
except RuntimeError as e:
|
| 144 |
+
if "out of memory" in str(e).lower():
|
| 145 |
+
torch.cuda.empty_cache()
|
| 146 |
+
free_memory()
|
| 147 |
+
return {"status": "OOM", "error": str(e)}
|
| 148 |
+
else:
|
| 149 |
+
raise
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def measure_training_speed(transformer, hidden_states, timestep, encoder_hidden_states, num_runs=10):
|
| 153 |
+
"""测量训练速度(forward + backward)"""
|
| 154 |
+
try:
|
| 155 |
+
# 预热
|
| 156 |
+
for _ in range(3):
|
| 157 |
+
output = transformer(
|
| 158 |
+
hidden_states=hidden_states,
|
| 159 |
+
timestep=timestep,
|
| 160 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 161 |
+
return_dict=False,
|
| 162 |
+
)[0]
|
| 163 |
+
loss = output.sum()
|
| 164 |
+
loss.backward()
|
| 165 |
+
transformer.zero_grad(set_to_none=True)
|
| 166 |
+
torch.cuda.synchronize()
|
| 167 |
+
|
| 168 |
+
# 正式测速
|
| 169 |
+
times = []
|
| 170 |
+
for _ in range(num_runs):
|
| 171 |
+
torch.cuda.synchronize()
|
| 172 |
+
start_time = time.time()
|
| 173 |
+
|
| 174 |
+
output = transformer(
|
| 175 |
+
hidden_states=hidden_states,
|
| 176 |
+
timestep=timestep,
|
| 177 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 178 |
+
return_dict=False,
|
| 179 |
+
)[0]
|
| 180 |
+
loss = output.sum()
|
| 181 |
+
loss.backward()
|
| 182 |
+
transformer.zero_grad(set_to_none=True)
|
| 183 |
+
|
| 184 |
+
torch.cuda.synchronize()
|
| 185 |
+
end_time = time.time()
|
| 186 |
+
times.append(end_time - start_time)
|
| 187 |
+
|
| 188 |
+
return {
|
| 189 |
+
"avg_time_s": round(sum(times) / len(times), 4),
|
| 190 |
+
"min_time_s": round(min(times), 4),
|
| 191 |
+
"max_time_s": round(max(times), 4),
|
| 192 |
+
"std_time_s": round(torch.std(torch.tensor(times)).item(), 4),
|
| 193 |
+
"status": "success",
|
| 194 |
+
}
|
| 195 |
+
except RuntimeError as e:
|
| 196 |
+
if "out of memory" in str(e).lower():
|
| 197 |
+
torch.cuda.empty_cache()
|
| 198 |
+
free_memory()
|
| 199 |
+
transformer.zero_grad(set_to_none=True)
|
| 200 |
+
return {"status": "OOM", "error": str(e)}
|
| 201 |
+
else:
|
| 202 |
+
raise
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states):
|
| 206 |
+
"""测量训练显存(forward + backward)"""
|
| 207 |
+
try:
|
| 208 |
+
torch.cuda.reset_peak_memory_stats()
|
| 209 |
+
torch.cuda.empty_cache()
|
| 210 |
+
free_memory()
|
| 211 |
+
torch.cuda.synchronize()
|
| 212 |
+
mem_before = torch.cuda.memory_allocated() / 1024**3
|
| 213 |
+
|
| 214 |
+
torch.cuda.reset_peak_memory_stats()
|
| 215 |
+
|
| 216 |
+
output = transformer(
|
| 217 |
+
hidden_states=hidden_states,
|
| 218 |
+
timestep=timestep,
|
| 219 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 220 |
+
return_dict=False,
|
| 221 |
+
attention_kwargs=None,
|
| 222 |
+
)[0]
|
| 223 |
+
|
| 224 |
+
loss = output.sum()
|
| 225 |
+
loss.backward()
|
| 226 |
+
|
| 227 |
+
torch.cuda.synchronize()
|
| 228 |
+
|
| 229 |
+
training_peak = torch.cuda.max_memory_allocated() / 1024**3
|
| 230 |
+
training_mem_diff = training_peak - mem_before
|
| 231 |
+
|
| 232 |
+
transformer.zero_grad(set_to_none=True)
|
| 233 |
+
|
| 234 |
+
return {
|
| 235 |
+
"mem_before_gb": round(mem_before, 3),
|
| 236 |
+
"training_peak_gb": round(training_peak, 3),
|
| 237 |
+
"training_mem_diff_gb": round(training_mem_diff, 3),
|
| 238 |
+
"status": "success",
|
| 239 |
+
}
|
| 240 |
+
except RuntimeError as e:
|
| 241 |
+
if "out of memory" in str(e).lower():
|
| 242 |
+
torch.cuda.empty_cache()
|
| 243 |
+
free_memory()
|
| 244 |
+
transformer.zero_grad(set_to_none=True)
|
| 245 |
+
return {"status": "OOM", "error": str(e)}
|
| 246 |
+
else:
|
| 247 |
+
raise
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def run_single_config(transformer, config_name, num_frames):
|
| 251 |
+
"""运行单个配置的完整测试"""
|
| 252 |
+
print(f"\n{'=' * 70}")
|
| 253 |
+
print(f"Testing: {config_name}")
|
| 254 |
+
print(f"{'=' * 70}")
|
| 255 |
+
|
| 256 |
+
result = {"config": config_name, "num_frames": num_frames}
|
| 257 |
+
|
| 258 |
+
# 1. 测推理速度
|
| 259 |
+
print("📊 Measuring inference speed...")
|
| 260 |
+
try:
|
| 261 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(
|
| 262 |
+
transformer, num_frames, HEIGHT, WIDTH, requires_grad=False
|
| 263 |
+
)
|
| 264 |
+
speed_stats = measure_inference_speed(
|
| 265 |
+
transformer, hidden_states, timestep, encoder_hidden_states, NUM_SPEED_RUNS
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
if speed_stats["status"] == "OOM":
|
| 269 |
+
print(" ❌ OOM - Skipping remaining tests")
|
| 270 |
+
result.update(
|
| 271 |
+
{
|
| 272 |
+
"inference_speed_status": "OOM",
|
| 273 |
+
"inference_memory_status": "SKIPPED",
|
| 274 |
+
"training_speed_status": "SKIPPED",
|
| 275 |
+
"training_memory_status": "SKIPPED",
|
| 276 |
+
}
|
| 277 |
+
)
|
| 278 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 279 |
+
torch.cuda.empty_cache()
|
| 280 |
+
free_memory()
|
| 281 |
+
return result
|
| 282 |
+
else:
|
| 283 |
+
print(
|
| 284 |
+
f" ✓ Avg: {speed_stats['avg_time_s']:.4f}s | "
|
| 285 |
+
f"Min: {speed_stats['min_time_s']:.4f}s | "
|
| 286 |
+
f"Max: {speed_stats['max_time_s']:.4f}s"
|
| 287 |
+
)
|
| 288 |
+
result.update(
|
| 289 |
+
{
|
| 290 |
+
"inference_speed_avg_s": speed_stats["avg_time_s"],
|
| 291 |
+
"inference_speed_min_s": speed_stats["min_time_s"],
|
| 292 |
+
"inference_speed_max_s": speed_stats["max_time_s"],
|
| 293 |
+
"inference_speed_std_s": speed_stats["std_time_s"],
|
| 294 |
+
"inference_speed_status": "success",
|
| 295 |
+
}
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 299 |
+
torch.cuda.empty_cache()
|
| 300 |
+
free_memory()
|
| 301 |
+
except Exception as e:
|
| 302 |
+
print(f" ❌ Error: {e}")
|
| 303 |
+
result["inference_speed_status"] = "ERROR"
|
| 304 |
+
torch.cuda.empty_cache()
|
| 305 |
+
free_memory()
|
| 306 |
+
|
| 307 |
+
# 2. 测推理显存
|
| 308 |
+
print("💾 Measuring inference memory...")
|
| 309 |
+
try:
|
| 310 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(
|
| 311 |
+
transformer, num_frames, HEIGHT, WIDTH, requires_grad=False
|
| 312 |
+
)
|
| 313 |
+
mem_stats = measure_inference_memory(transformer, hidden_states, timestep, encoder_hidden_states)
|
| 314 |
+
|
| 315 |
+
if mem_stats["status"] == "OOM":
|
| 316 |
+
print(" ❌ OOM - Skipping training tests")
|
| 317 |
+
result.update(
|
| 318 |
+
{
|
| 319 |
+
"inference_memory_status": "OOM",
|
| 320 |
+
"training_speed_status": "SKIPPED",
|
| 321 |
+
"training_memory_status": "SKIPPED",
|
| 322 |
+
}
|
| 323 |
+
)
|
| 324 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 325 |
+
torch.cuda.empty_cache()
|
| 326 |
+
free_memory()
|
| 327 |
+
return result
|
| 328 |
+
else:
|
| 329 |
+
print(
|
| 330 |
+
f" ✓ Peak: {mem_stats['inference_peak_gb']:.3f} GB | "
|
| 331 |
+
f"Diff: {mem_stats['inference_mem_diff_gb']:.3f} GB"
|
| 332 |
+
)
|
| 333 |
+
result.update(
|
| 334 |
+
{
|
| 335 |
+
"inference_memory_peak_gb": mem_stats["inference_peak_gb"],
|
| 336 |
+
"inference_memory_diff_gb": mem_stats["inference_mem_diff_gb"],
|
| 337 |
+
"inference_memory_status": "success",
|
| 338 |
+
}
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 342 |
+
torch.cuda.empty_cache()
|
| 343 |
+
free_memory()
|
| 344 |
+
except Exception as e:
|
| 345 |
+
print(f" ❌ Error: {e}")
|
| 346 |
+
result["inference_memory_status"] = "ERROR"
|
| 347 |
+
torch.cuda.empty_cache()
|
| 348 |
+
free_memory()
|
| 349 |
+
|
| 350 |
+
# 3. 测训练速度
|
| 351 |
+
print("⚡ Measuring training speed...")
|
| 352 |
+
try:
|
| 353 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(
|
| 354 |
+
transformer, num_frames, HEIGHT, WIDTH, requires_grad=True
|
| 355 |
+
)
|
| 356 |
+
train_speed_stats = measure_training_speed(
|
| 357 |
+
transformer, hidden_states, timestep, encoder_hidden_states, NUM_SPEED_RUNS
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
if train_speed_stats["status"] == "OOM":
|
| 361 |
+
print(" ❌ OOM")
|
| 362 |
+
result.update({"training_speed_status": "OOM", "training_memory_status": "SKIPPED"})
|
| 363 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 364 |
+
torch.cuda.empty_cache()
|
| 365 |
+
free_memory()
|
| 366 |
+
return result
|
| 367 |
+
else:
|
| 368 |
+
print(
|
| 369 |
+
f" ✓ Avg: {train_speed_stats['avg_time_s']:.4f}s | "
|
| 370 |
+
f"Min: {train_speed_stats['min_time_s']:.4f}s | "
|
| 371 |
+
f"Max: {train_speed_stats['max_time_s']:.4f}s"
|
| 372 |
+
)
|
| 373 |
+
result.update(
|
| 374 |
+
{
|
| 375 |
+
"training_speed_avg_s": train_speed_stats["avg_time_s"],
|
| 376 |
+
"training_speed_min_s": train_speed_stats["min_time_s"],
|
| 377 |
+
"training_speed_max_s": train_speed_stats["max_time_s"],
|
| 378 |
+
"training_speed_std_s": train_speed_stats["std_time_s"],
|
| 379 |
+
"training_speed_status": "success",
|
| 380 |
+
}
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 384 |
+
torch.cuda.empty_cache()
|
| 385 |
+
free_memory()
|
| 386 |
+
except Exception as e:
|
| 387 |
+
print(f" ❌ Error: {e}")
|
| 388 |
+
result["training_speed_status"] = "ERROR"
|
| 389 |
+
torch.cuda.empty_cache()
|
| 390 |
+
free_memory()
|
| 391 |
+
|
| 392 |
+
# 4. 测训练显存
|
| 393 |
+
print("🔥 Measuring training memory...")
|
| 394 |
+
try:
|
| 395 |
+
hidden_states, timestep, encoder_hidden_states = create_dummy_inputs(
|
| 396 |
+
transformer, num_frames, HEIGHT, WIDTH, requires_grad=True
|
| 397 |
+
)
|
| 398 |
+
train_mem_stats = measure_training_memory(transformer, hidden_states, timestep, encoder_hidden_states)
|
| 399 |
+
|
| 400 |
+
if train_mem_stats["status"] == "OOM":
|
| 401 |
+
print(" ❌ OOM")
|
| 402 |
+
result["training_memory_status"] = "OOM"
|
| 403 |
+
else:
|
| 404 |
+
print(
|
| 405 |
+
f" ✓ Peak: {train_mem_stats['training_peak_gb']:.3f} GB | "
|
| 406 |
+
f"Diff: {train_mem_stats['training_mem_diff_gb']:.3f} GB"
|
| 407 |
+
)
|
| 408 |
+
result.update(
|
| 409 |
+
{
|
| 410 |
+
"training_memory_peak_gb": train_mem_stats["training_peak_gb"],
|
| 411 |
+
"training_memory_diff_gb": train_mem_stats["training_mem_diff_gb"],
|
| 412 |
+
"training_memory_status": "success",
|
| 413 |
+
}
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
del hidden_states, timestep, encoder_hidden_states
|
| 417 |
+
torch.cuda.empty_cache()
|
| 418 |
+
free_memory()
|
| 419 |
+
except Exception as e:
|
| 420 |
+
print(f" ❌ Error: {e}")
|
| 421 |
+
result["training_memory_status"] = "ERROR"
|
| 422 |
+
torch.cuda.empty_cache()
|
| 423 |
+
free_memory()
|
| 424 |
+
|
| 425 |
+
return result
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
# ============================================================================
|
| 429 |
+
# 主测试流程
|
| 430 |
+
# ============================================================================
|
| 431 |
+
print("=" * 70)
|
| 432 |
+
print("OPTIMIZATION BENCHMARK - SAME LENGTH COMPARISON")
|
| 433 |
+
print("=" * 70)
|
| 434 |
+
print(f"Model: {model_id}")
|
| 435 |
+
print(f"Test frames: {TEST_NUM_FRAMES}")
|
| 436 |
+
print(f"Resolution: {HEIGHT}x{WIDTH}")
|
| 437 |
+
print(f"Speed test runs: {NUM_SPEED_RUNS}")
|
| 438 |
+
print("=" * 70)
|
| 439 |
+
|
| 440 |
+
# ============================================================================
|
| 441 |
+
# 配置1: 原始模型
|
| 442 |
+
# ============================================================================
|
| 443 |
+
print("\n" + "=" * 70)
|
| 444 |
+
print("CONFIG 1/5: BASELINE (No optimizations)")
|
| 445 |
+
print("=" * 70)
|
| 446 |
+
|
| 447 |
+
transformer_baseline = HeliosTransformer3DModel.from_pretrained(
|
| 448 |
+
model_id,
|
| 449 |
+
subfolder="transformer",
|
| 450 |
+
torch_dtype=torch.bfloat16,
|
| 451 |
+
use_default_loader=True,
|
| 452 |
+
)
|
| 453 |
+
transformer_baseline.enable_gradient_checkpointing()
|
| 454 |
+
transformer_baseline.set_attention_backend("_flash_3_hub")
|
| 455 |
+
transformer_baseline.to("cuda")
|
| 456 |
+
|
| 457 |
+
result_baseline = run_single_config(transformer_baseline, "Baseline", TEST_NUM_FRAMES)
|
| 458 |
+
benchmark_results["experiments"].append(result_baseline)
|
| 459 |
+
|
| 460 |
+
del transformer_baseline
|
| 461 |
+
torch.cuda.empty_cache()
|
| 462 |
+
free_memory()
|
| 463 |
+
|
| 464 |
+
# ============================================================================
|
| 465 |
+
# 配置2: 只替换 TiledLinear
|
| 466 |
+
# ============================================================================
|
| 467 |
+
print("\n" + "=" * 70)
|
| 468 |
+
print("CONFIG 2/5: TiledLinear only")
|
| 469 |
+
print("=" * 70)
|
| 470 |
+
|
| 471 |
+
transformer_tiled = HeliosTransformer3DModel.from_pretrained(
|
| 472 |
+
model_id,
|
| 473 |
+
subfolder="transformer",
|
| 474 |
+
torch_dtype=torch.bfloat16,
|
| 475 |
+
use_default_loader=True,
|
| 476 |
+
)
|
| 477 |
+
transformer_tiled.enable_gradient_checkpointing()
|
| 478 |
+
transformer_tiled.set_attention_backend("_flash_3_hub")
|
| 479 |
+
transformer_tiled = replace_linear_with_tiled_linear(transformer_tiled)
|
| 480 |
+
transformer_tiled.to("cuda")
|
| 481 |
+
|
| 482 |
+
result_tiled = run_single_config(transformer_tiled, "TiledLinear", TEST_NUM_FRAMES)
|
| 483 |
+
benchmark_results["experiments"].append(result_tiled)
|
| 484 |
+
|
| 485 |
+
transformer_tiled = None
|
| 486 |
+
del transformer_tiled
|
| 487 |
+
torch.cuda.empty_cache()
|
| 488 |
+
free_memory()
|
| 489 |
+
|
| 490 |
+
# ============================================================================
|
| 491 |
+
# 配置3: 只替换 FlashNorm
|
| 492 |
+
# ============================================================================
|
| 493 |
+
print("\n" + "=" * 70)
|
| 494 |
+
print("CONFIG 3/5: FlashNorm only")
|
| 495 |
+
print("=" * 70)
|
| 496 |
+
|
| 497 |
+
transformer_flashnorm = HeliosTransformer3DModel.from_pretrained(
|
| 498 |
+
model_id,
|
| 499 |
+
subfolder="transformer",
|
| 500 |
+
torch_dtype=torch.bfloat16,
|
| 501 |
+
use_default_loader=True,
|
| 502 |
+
)
|
| 503 |
+
transformer_flashnorm.enable_gradient_checkpointing()
|
| 504 |
+
transformer_flashnorm.set_attention_backend("_flash_3_hub")
|
| 505 |
+
transformer_flashnorm = replace_all_norms_with_flash_norms(transformer_flashnorm)
|
| 506 |
+
transformer_flashnorm.to("cuda")
|
| 507 |
+
|
| 508 |
+
result_flashnorm = run_single_config(transformer_flashnorm, "FlashNorm", TEST_NUM_FRAMES)
|
| 509 |
+
benchmark_results["experiments"].append(result_flashnorm)
|
| 510 |
+
|
| 511 |
+
transformer_flashnorm = None
|
| 512 |
+
del transformer_flashnorm
|
| 513 |
+
torch.cuda.empty_cache()
|
| 514 |
+
free_memory()
|
| 515 |
+
|
| 516 |
+
# ============================================================================
|
| 517 |
+
# 配置4: 只替换 FlashRoPE
|
| 518 |
+
# ============================================================================
|
| 519 |
+
print("\n" + "=" * 70)
|
| 520 |
+
print("CONFIG 4/5: FlashRoPE only")
|
| 521 |
+
print("=" * 70)
|
| 522 |
+
|
| 523 |
+
transformer_flashrope = HeliosTransformer3DModel.from_pretrained(
|
| 524 |
+
model_id,
|
| 525 |
+
subfolder="transformer",
|
| 526 |
+
torch_dtype=torch.bfloat16,
|
| 527 |
+
use_default_loader=True,
|
| 528 |
+
)
|
| 529 |
+
transformer_flashrope.enable_gradient_checkpointing()
|
| 530 |
+
transformer_flashrope.set_attention_backend("_flash_3_hub")
|
| 531 |
+
transformer_flashrope.to("cuda")
|
| 532 |
+
|
| 533 |
+
# FlashRoPE 是全局替换,不可逆
|
| 534 |
+
replace_rope_with_flash_rope()
|
| 535 |
+
|
| 536 |
+
result_flashrope = run_single_config(transformer_flashrope, "FlashRoPE", TEST_NUM_FRAMES)
|
| 537 |
+
benchmark_results["experiments"].append(result_flashrope)
|
| 538 |
+
|
| 539 |
+
transformer_flashrope = None
|
| 540 |
+
del transformer_flashrope
|
| 541 |
+
torch.cuda.empty_cache()
|
| 542 |
+
free_memory()
|
| 543 |
+
|
| 544 |
+
# ============================================================================
|
| 545 |
+
# 配置5: FlashNorm + FlashRoPE
|
| 546 |
+
# ============================================================================
|
| 547 |
+
print("\n" + "=" * 70)
|
| 548 |
+
print("CONFIG 5/5: FlashNorm + FlashRoPE")
|
| 549 |
+
print("=" * 70)
|
| 550 |
+
|
| 551 |
+
transformer_combined = HeliosTransformer3DModel.from_pretrained(
|
| 552 |
+
model_id,
|
| 553 |
+
subfolder="transformer",
|
| 554 |
+
torch_dtype=torch.bfloat16,
|
| 555 |
+
use_default_loader=True,
|
| 556 |
+
)
|
| 557 |
+
transformer_combined.enable_gradient_checkpointing()
|
| 558 |
+
transformer_combined.set_attention_backend("_flash_3_hub")
|
| 559 |
+
transformer_combined = replace_all_norms_with_flash_norms(transformer_combined)
|
| 560 |
+
transformer_combined.to("cuda")
|
| 561 |
+
|
| 562 |
+
# FlashRoPE 已经在配置4中全局替换
|
| 563 |
+
replace_rope_with_flash_rope()
|
| 564 |
+
|
| 565 |
+
result_combined = run_single_config(transformer_combined, "FlashNorm+FlashRoPE", TEST_NUM_FRAMES)
|
| 566 |
+
benchmark_results["experiments"].append(result_combined)
|
| 567 |
+
|
| 568 |
+
transformer_combined = None
|
| 569 |
+
del transformer_combined
|
| 570 |
+
torch.cuda.empty_cache()
|
| 571 |
+
free_memory()
|
| 572 |
+
|
| 573 |
+
# ============================================================================
|
| 574 |
+
# 保存结果
|
| 575 |
+
# ============================================================================
|
| 576 |
+
output_file = "benchmark_triton_results.json"
|
| 577 |
+
with open(output_file, "w") as f:
|
| 578 |
+
json.dump(benchmark_results, f, indent=2)
|
| 579 |
+
|
| 580 |
+
print("\n" + "=" * 70)
|
| 581 |
+
print(f"✅ Results saved to {output_file}")
|
| 582 |
+
print("=" * 70)
|
| 583 |
+
|
| 584 |
+
# ============================================================================
|
| 585 |
+
# 打印汇总表格
|
| 586 |
+
# ============================================================================
|
| 587 |
+
print("\n" + "=" * 70)
|
| 588 |
+
print("BENCHMARK SUMMARY")
|
| 589 |
+
print("=" * 70)
|
| 590 |
+
|
| 591 |
+
# 表头
|
| 592 |
+
print(f"\n{'Config':<20} {'InfSpeed(s)':>12} {'InfMem(GB)':>12} {'TrainSpeed(s)':>14} {'TrainMem(GB)':>13}")
|
| 593 |
+
print("-" * 75)
|
| 594 |
+
|
| 595 |
+
# 打印每个配置的结果
|
| 596 |
+
for exp in benchmark_results["experiments"]:
|
| 597 |
+
config = exp["config"]
|
| 598 |
+
|
| 599 |
+
# 推理速度
|
| 600 |
+
inf_speed = (
|
| 601 |
+
f"{exp.get('inference_speed_avg_s', 0):.4f}" if exp.get("inference_speed_status") == "success" else "N/A"
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
# 推理显存
|
| 605 |
+
inf_mem = (
|
| 606 |
+
f"{exp.get('inference_memory_diff_gb', 0):.3f}" if exp.get("inference_memory_status") == "success" else "N/A"
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
# 训练速度
|
| 610 |
+
train_speed = (
|
| 611 |
+
f"{exp.get('training_speed_avg_s', 0):.4f}" if exp.get("training_speed_status") == "success" else "N/A"
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
# 训练显存
|
| 615 |
+
train_mem = (
|
| 616 |
+
f"{exp.get('training_memory_diff_gb', 0):.3f}" if exp.get("training_memory_status") == "success" else "N/A"
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
print(f"{config:<20} {inf_speed:>12} {inf_mem:>12} {train_speed:>14} {train_mem:>13}")
|
| 620 |
+
|
| 621 |
+
# 计算加速比(如果baseline成功)
|
| 622 |
+
baseline_result = benchmark_results["experiments"][0]
|
| 623 |
+
if baseline_result.get("inference_speed_status") == "success":
|
| 624 |
+
baseline_inf_speed = baseline_result["inference_speed_avg_s"]
|
| 625 |
+
baseline_train_speed = baseline_result.get("training_speed_avg_s", None)
|
| 626 |
+
|
| 627 |
+
print("\n" + "=" * 70)
|
| 628 |
+
print("SPEEDUP vs BASELINE")
|
| 629 |
+
print("=" * 70)
|
| 630 |
+
print(f"{'Config':<20} {'InfSpeedup':>12} {'TrainSpeedup':>14}")
|
| 631 |
+
print("-" * 50)
|
| 632 |
+
|
| 633 |
+
for exp in benchmark_results["experiments"]:
|
| 634 |
+
config = exp["config"]
|
| 635 |
+
|
| 636 |
+
# 推理加速比
|
| 637 |
+
if exp.get("inference_speed_status") == "success":
|
| 638 |
+
speedup_inf = baseline_inf_speed / exp["inference_speed_avg_s"]
|
| 639 |
+
speedup_inf_str = f"{speedup_inf:.2f}x"
|
| 640 |
+
else:
|
| 641 |
+
speedup_inf_str = "N/A"
|
| 642 |
+
|
| 643 |
+
# 训练加速比
|
| 644 |
+
if exp.get("training_speed_status") == "success" and baseline_train_speed:
|
| 645 |
+
speedup_train = baseline_train_speed / exp["training_speed_avg_s"]
|
| 646 |
+
speedup_train_str = f"{speedup_train:.2f}x"
|
| 647 |
+
else:
|
| 648 |
+
speedup_train_str = "N/A"
|
| 649 |
+
|
| 650 |
+
print(f"{config:<20} {speedup_inf_str:>12} {speedup_train_str:>14}")
|
| 651 |
+
|
| 652 |
+
print("\n" + "=" * 70)
|
| 653 |
+
print("Legend:")
|
| 654 |
+
print(" InfSpeed - Inference time (forward only)")
|
| 655 |
+
print(" InfMem - Inference memory usage")
|
| 656 |
+
print(" TrainSpeed - Training time (forward + backward)")
|
| 657 |
+
print(" TrainMem - Training memory usage")
|
| 658 |
+
print(" Speedup - Relative to baseline (higher is better)")
|
| 659 |
+
print("=" * 70)
|
Helios/_DEV/tools/others/benchmark/benchmark_triton_results_helios.json
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"timestamp": "2026-02-06T09:14:11.892609",
|
| 3 |
+
"test_config": {
|
| 4 |
+
"num_frames": 13,
|
| 5 |
+
"height": 384,
|
| 6 |
+
"width": 640,
|
| 7 |
+
"num_speed_runs": 10
|
| 8 |
+
},
|
| 9 |
+
"experiments": [
|
| 10 |
+
{
|
| 11 |
+
"config": "Baseline",
|
| 12 |
+
"num_frames": 13,
|
| 13 |
+
"inference_speed_avg_s": 1.083,
|
| 14 |
+
"inference_speed_min_s": 1.0801,
|
| 15 |
+
"inference_speed_max_s": 1.088,
|
| 16 |
+
"inference_speed_std_s": 0.0027,
|
| 17 |
+
"inference_speed_status": "success",
|
| 18 |
+
"inference_memory_peak_gb": 29.777,
|
| 19 |
+
"inference_memory_diff_gb": 2.993,
|
| 20 |
+
"inference_memory_status": "success",
|
| 21 |
+
"training_speed_avg_s": 4.302,
|
| 22 |
+
"training_speed_min_s": 4.2982,
|
| 23 |
+
"training_speed_max_s": 4.3088,
|
| 24 |
+
"training_speed_std_s": 0.0031,
|
| 25 |
+
"training_speed_status": "success",
|
| 26 |
+
"training_memory_peak_gb": 60.792,
|
| 27 |
+
"training_memory_diff_gb": 33.978,
|
| 28 |
+
"training_memory_status": "success"
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"config": "TiledLinear",
|
| 32 |
+
"num_frames": 13,
|
| 33 |
+
"inference_speed_avg_s": 1.1279,
|
| 34 |
+
"inference_speed_min_s": 1.1222,
|
| 35 |
+
"inference_speed_max_s": 1.1307,
|
| 36 |
+
"inference_speed_std_s": 0.0024,
|
| 37 |
+
"inference_speed_status": "success",
|
| 38 |
+
"inference_memory_peak_gb": 29.807,
|
| 39 |
+
"inference_memory_diff_gb": 2.992,
|
| 40 |
+
"inference_memory_status": "success",
|
| 41 |
+
"training_speed_avg_s": 4.8691,
|
| 42 |
+
"training_speed_min_s": 4.8631,
|
| 43 |
+
"training_speed_max_s": 4.8769,
|
| 44 |
+
"training_speed_std_s": 0.0035,
|
| 45 |
+
"training_speed_status": "success",
|
| 46 |
+
"training_memory_peak_gb": 60.867,
|
| 47 |
+
"training_memory_diff_gb": 34.052,
|
| 48 |
+
"training_memory_status": "success"
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"config": "FlashNorm",
|
| 52 |
+
"num_frames": 13,
|
| 53 |
+
"inference_speed_avg_s": 0.9742,
|
| 54 |
+
"inference_speed_min_s": 0.9724,
|
| 55 |
+
"inference_speed_max_s": 0.9762,
|
| 56 |
+
"inference_speed_std_s": 0.0011,
|
| 57 |
+
"inference_speed_status": "success",
|
| 58 |
+
"inference_memory_peak_gb": 29.777,
|
| 59 |
+
"inference_memory_diff_gb": 2.993,
|
| 60 |
+
"inference_memory_status": "success",
|
| 61 |
+
"training_speed_avg_s": 3.8406,
|
| 62 |
+
"training_speed_min_s": 3.8371,
|
| 63 |
+
"training_speed_max_s": 3.8455,
|
| 64 |
+
"training_speed_std_s": 0.0025,
|
| 65 |
+
"training_speed_status": "success",
|
| 66 |
+
"training_memory_peak_gb": 59.703,
|
| 67 |
+
"training_memory_diff_gb": 32.888,
|
| 68 |
+
"training_memory_status": "success"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"config": "FlashRoPE",
|
| 72 |
+
"num_frames": 13,
|
| 73 |
+
"inference_speed_avg_s": 1.0208,
|
| 74 |
+
"inference_speed_min_s": 1.0183,
|
| 75 |
+
"inference_speed_max_s": 1.0252,
|
| 76 |
+
"inference_speed_std_s": 0.0021,
|
| 77 |
+
"inference_speed_status": "success",
|
| 78 |
+
"inference_memory_peak_gb": 29.807,
|
| 79 |
+
"inference_memory_diff_gb": 2.992,
|
| 80 |
+
"inference_memory_status": "success",
|
| 81 |
+
"training_speed_avg_s": 4.0924,
|
| 82 |
+
"training_speed_min_s": 4.0881,
|
| 83 |
+
"training_speed_max_s": 4.099,
|
| 84 |
+
"training_speed_std_s": 0.0044,
|
| 85 |
+
"training_speed_status": "success",
|
| 86 |
+
"training_memory_peak_gb": 60.817,
|
| 87 |
+
"training_memory_diff_gb": 34.002,
|
| 88 |
+
"training_memory_status": "success"
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"config": "FlashNorm+FlashRoPE",
|
| 92 |
+
"num_frames": 13,
|
| 93 |
+
"inference_speed_avg_s": 0.9093,
|
| 94 |
+
"inference_speed_min_s": 0.9073,
|
| 95 |
+
"inference_speed_max_s": 0.9115,
|
| 96 |
+
"inference_speed_std_s": 0.0016,
|
| 97 |
+
"inference_speed_status": "success",
|
| 98 |
+
"inference_memory_peak_gb": 29.807,
|
| 99 |
+
"inference_memory_diff_gb": 2.992,
|
| 100 |
+
"inference_memory_status": "success",
|
| 101 |
+
"training_speed_avg_s": 3.5968,
|
| 102 |
+
"training_speed_min_s": 3.5889,
|
| 103 |
+
"training_speed_max_s": 3.6009,
|
| 104 |
+
"training_speed_std_s": 0.004,
|
| 105 |
+
"training_speed_status": "success",
|
| 106 |
+
"training_memory_peak_gb": 59.728,
|
| 107 |
+
"training_memory_diff_gb": 32.913,
|
| 108 |
+
"training_memory_status": "success"
|
| 109 |
+
}
|
| 110 |
+
]
|
| 111 |
+
}
|
Helios/_DEV/tools/others/benchmark/benchmark_triton_results_wan.json
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"timestamp": "2026-02-06T12:56:41.488612",
|
| 3 |
+
"test_config": {
|
| 4 |
+
"num_frames": 21,
|
| 5 |
+
"height": 384,
|
| 6 |
+
"width": 640,
|
| 7 |
+
"num_speed_runs": 10
|
| 8 |
+
},
|
| 9 |
+
"experiments": [
|
| 10 |
+
{
|
| 11 |
+
"config": "Baseline",
|
| 12 |
+
"num_frames": 21,
|
| 13 |
+
"inference_speed_avg_s": 1.9735,
|
| 14 |
+
"inference_speed_min_s": 1.97,
|
| 15 |
+
"inference_speed_max_s": 1.9756,
|
| 16 |
+
"inference_speed_std_s": 0.0016,
|
| 17 |
+
"inference_speed_status": "success",
|
| 18 |
+
"inference_memory_peak_gb": 31.615,
|
| 19 |
+
"inference_memory_diff_gb": 4.831,
|
| 20 |
+
"inference_memory_status": "success",
|
| 21 |
+
"training_speed_avg_s": 7.9606,
|
| 22 |
+
"training_speed_min_s": 7.9545,
|
| 23 |
+
"training_speed_max_s": 7.9712,
|
| 24 |
+
"training_speed_std_s": 0.0053,
|
| 25 |
+
"training_speed_status": "success",
|
| 26 |
+
"training_memory_peak_gb": 65.959,
|
| 27 |
+
"training_memory_diff_gb": 39.144,
|
| 28 |
+
"training_memory_status": "success"
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"config": "TiledLinear",
|
| 32 |
+
"num_frames": 21,
|
| 33 |
+
"inference_speed_avg_s": 2.0023,
|
| 34 |
+
"inference_speed_min_s": 1.9987,
|
| 35 |
+
"inference_speed_max_s": 2.0085,
|
| 36 |
+
"inference_speed_std_s": 0.0028,
|
| 37 |
+
"inference_speed_status": "success",
|
| 38 |
+
"inference_memory_peak_gb": 31.647,
|
| 39 |
+
"inference_memory_diff_gb": 4.832,
|
| 40 |
+
"inference_memory_status": "success",
|
| 41 |
+
"training_speed_avg_s": 8.689,
|
| 42 |
+
"training_speed_min_s": 8.6836,
|
| 43 |
+
"training_speed_max_s": 8.6957,
|
| 44 |
+
"training_speed_std_s": 0.0036,
|
| 45 |
+
"training_speed_status": "success",
|
| 46 |
+
"training_memory_peak_gb": 65.429,
|
| 47 |
+
"training_memory_diff_gb": 38.614,
|
| 48 |
+
"training_memory_status": "success"
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"config": "FlashNorm",
|
| 52 |
+
"num_frames": 21,
|
| 53 |
+
"inference_speed_avg_s": 1.7982,
|
| 54 |
+
"inference_speed_min_s": 1.7923,
|
| 55 |
+
"inference_speed_max_s": 1.8029,
|
| 56 |
+
"inference_speed_std_s": 0.0035,
|
| 57 |
+
"inference_speed_status": "success",
|
| 58 |
+
"inference_memory_peak_gb": 31.647,
|
| 59 |
+
"inference_memory_diff_gb": 4.832,
|
| 60 |
+
"inference_memory_status": "success",
|
| 61 |
+
"training_speed_avg_s": 7.2154,
|
| 62 |
+
"training_speed_min_s": 7.2076,
|
| 63 |
+
"training_speed_max_s": 7.223,
|
| 64 |
+
"training_speed_std_s": 0.0045,
|
| 65 |
+
"training_speed_status": "success",
|
| 66 |
+
"training_memory_peak_gb": 64.213,
|
| 67 |
+
"training_memory_diff_gb": 37.397,
|
| 68 |
+
"training_memory_status": "success"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"config": "FlashRoPE",
|
| 72 |
+
"num_frames": 21,
|
| 73 |
+
"inference_speed_avg_s": 1.8678,
|
| 74 |
+
"inference_speed_min_s": 1.8634,
|
| 75 |
+
"inference_speed_max_s": 1.8743,
|
| 76 |
+
"inference_speed_std_s": 0.0034,
|
| 77 |
+
"inference_speed_status": "success",
|
| 78 |
+
"inference_memory_peak_gb": 31.647,
|
| 79 |
+
"inference_memory_diff_gb": 4.832,
|
| 80 |
+
"inference_memory_status": "success",
|
| 81 |
+
"training_speed_avg_s": 7.5754,
|
| 82 |
+
"training_speed_min_s": 7.5696,
|
| 83 |
+
"training_speed_max_s": 7.5802,
|
| 84 |
+
"training_speed_std_s": 0.0038,
|
| 85 |
+
"training_speed_status": "success",
|
| 86 |
+
"training_memory_peak_gb": 66.0,
|
| 87 |
+
"training_memory_diff_gb": 39.185,
|
| 88 |
+
"training_memory_status": "success"
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"config": "FlashNorm+FlashRoPE",
|
| 92 |
+
"num_frames": 21,
|
| 93 |
+
"inference_speed_avg_s": 1.6882,
|
| 94 |
+
"inference_speed_min_s": 1.6835,
|
| 95 |
+
"inference_speed_max_s": 1.6913,
|
| 96 |
+
"inference_speed_std_s": 0.0029,
|
| 97 |
+
"inference_speed_status": "success",
|
| 98 |
+
"inference_memory_peak_gb": 31.647,
|
| 99 |
+
"inference_memory_diff_gb": 4.832,
|
| 100 |
+
"inference_memory_status": "success",
|
| 101 |
+
"training_speed_avg_s": 6.8077,
|
| 102 |
+
"training_speed_min_s": 6.8014,
|
| 103 |
+
"training_speed_max_s": 6.8185,
|
| 104 |
+
"training_speed_std_s": 0.0049,
|
| 105 |
+
"training_speed_status": "success",
|
| 106 |
+
"training_memory_peak_gb": 64.252,
|
| 107 |
+
"training_memory_diff_gb": 37.436,
|
| 108 |
+
"training_memory_status": "success"
|
| 109 |
+
}
|
| 110 |
+
]
|
| 111 |
+
}
|
Helios/_DEV2/__pycache__/infer_helios.cpython-312.pyc
ADDED
|
Binary file (30.3 kB). View file
|
|
|
Helios/_DEV2/demo_data/MovieGenVideoBench_extended.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV2/demo_data/VBench_extended.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV2/example/prompt.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement.
|
| 2 |
+
An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in thought pondering the history of the universe as he sits at a cafe in Paris, his eyes focus on people offscreen as they walk as he sits mostly motionless, he is dressed in a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses and has a very professorial appearance, and the end he offers a subtle closed-mouth smile as if he found the answer to the mystery of life, the lighting is very cinematic with the golden light and the Parisian streets and city in the background, depth of field, cinematic 35mm film.
|
| 3 |
+
A handheld tracking shot following a red balloon floating above the ground in an abandoned street. The balloon drifts gracefully, its bright red color contrasting sharply against the decaying urban backdrop. The street is littered with debris and graffiti-covered walls, with broken windows and rusted cars scattered about. Shadows dance across the scene as sunlight filters through gaps in the buildings. The camera moves fluidly, capturing the balloon's gentle ascent and descent, emphasizing its playful motion. A close-up of the balloon transitions to a wider shot, showcasing the desolate environment.
|
| 4 |
+
The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from it's tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds.
|
| 5 |
+
A drone camera circles around a beautiful historic church built on a rocky outcropping along the Amalfi Coast, the view showcases historic and magnificent architectural details and tiered pathways and patios, waves are seen crashing against the rocks below as the view overlooks the horizon of the coastal waters and hilly landscapes of the Amalfi Coast Italy, several distant people are seen walking and enjoying vistas on patios of the dramatic ocean views, the warm glow of the afternoon sun creates a magical and romantic feeling to the scene, the view is stunning captured with beautiful photography.
|
| 6 |
+
A large orange octopus is seen resting on the bottom of the ocean floor, blending in with the sandy and rocky terrain. Its tentacles are spread out around its body, and its eyes are closed. The octopus is unaware of a king crab that is crawling towards it from behind a rock, its claws raised and ready to attack. The crab is brown and spiny, with long legs and antennae. The scene is captured from a wide angle, showing the vastness and depth of the ocean. The water is clear and blue, with rays of sunlight filtering through. The shot is sharp and crisp, with a high dynamic range. The octopus and the crab are in focus, while the background is slightly blurred, creating a depth of field effect.
|
| 7 |
+
A vibrant tropical fish glides gracefully through colorful ocean reefs, surrounded by swaying coral, shimmering schools of tiny fish, and beams of sunlight filtering down from the water’s surface. The scene feels alive with movement, as bubbles rise gently and the reef glows in vivid shades of blue, orange, and pink, creating a tranquil yet dynamic underwater atmosphere.
|
| 8 |
+
Cinematic closeup and detailed portrait of a reindeer in a snowy forest at sunset. The lighting is cinematic and gorgeous and soft and sun-kissed, with golden backlight and dreamy bokeh and lens flares. The color grade is cinematic and magical.
|
| 9 |
+
3D animation of a small, round, fluffy creature with big, expressive eyes explores a vibrant, enchanted forest. The creature, a whimsical blend of a rabbit and a squirrel, has soft blue fur and a bushy, striped tail. It hops along a sparkling stream, its eyes wide with wonder. The forest is alive with magical elements: flowers that glow and change colors, trees with leaves in shades of purple and silver, and small floating lights that resemble fireflies. The creature stops to interact playfully with a group of tiny, fairy-like beings dancing around a mushroom ring. The creature looks up in awe at a large, glowing tree that seems to be the heart of the forest.
|
| 10 |
+
A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, and distant mountain ranges passing by quickly. The train window frames the view, adding a sense of speed and motion as the landscape rushes past. The camera remains static but emphasizes the fast-paced movement outside. The overall atmosphere is serene yet exhilarating, capturing the essence of travel and exploration. Medium shot focusing on the train window and the rushing scenery beyond.
|
| 11 |
+
|
Helios/_DEV2/example/prompt_interactive_helios.csv
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
id,prompt_index,prompt
|
| 2 |
+
6,0,"Underwater tornado affecting the ocean floor in a dramatic and chaotic scene. The water is murky, swirling violently, carrying debris and marine life into the vortex. Schools of fish scatter in panic, trying to avoid the powerful currents. Coral reefs and rocks are uprooted and tossed around, creating a tumultuous environment. In the background, large schools of fish swim away from the chaos, while smaller organisms cling to whatever they can find for safety. The camera remains stationary, capturing the intensity of the underwater tornado as it disrupts the serene ocean floor. Close-up shot emphasizing the turbulent motion and destruction."
|
| 3 |
+
6,1,"The underwater vortex intensifies its grip on the seabed, pulling a rusted, barnacle-encrusted anchor from the sand. The heavy iron object spins lethargically at first before being whipped upward into the murky funnel, smashing through floating debris with violent force. Sediment billows in thick clouds around the base of the tornado, obscuring the terrified marine life darting through the gloom. The chaotic currents tear at the ocean floor, exposing deeper layers of rock and silt as the destruction mounts. Close-up shot emphasizing the turbulent motion and destruction."
|
| 4 |
+
6,2,"The underwater tornado rages with unrelenting fury, now dislodging a massive, ancient shipwreck rib from the sediment. The curved wooden beam, blackened by time, groans silently as it is wrenched free and sucked into the spiraling column of water. Murky currents thrash wildly, tossing the heavy timber like a twig amidst the swirling sand and uprooted coral. Smaller debris clatters against the rotating wood, adding to the visual chaos of the deep-sea storm. The vortex dominates the frame, a terrifying engine of nature reshaping the seabed. Close-up shot emphasizing the turbulent motion and destruction."
|
| 5 |
+
6,3,"The violent vortex now ensnares a large, glowing jellyfish, dragging its long, bioluminescent tentacles into the chaotic spiral. The delicate creature spins helplessly, its translucent bell pulsing rapidly against the crushing force of the murky water. Swirling currents rip through the surrounding gloom, tossing sand and fragmented shells in every direction as the tornado dominates the seabed. The glowing blue light of the jellyfish streaks through the darkness, creating a ghostly blur within the churning debris field. Close-up shot emphasizing the turbulent motion and destruction."
|
| 6 |
+
6,4,"The swirling underwater vortex now seizes a heavy, encrusted treasure chest, its lid flapping open as it is torn from the ocean floor. Gold coins and silver trinkets spill out, glittering briefly in the murky water before being swept instantly into the violent funnel. The heavy wooden box tumbles end over end, colliding with floating rocks and adding to the debris field. Swirling sediment and bubbles surround the spilling fortune, highlighting the chaotic power of the storm as it ravages the seabed. Close-up shot emphasizing the turbulent motion and destruction."
|
| 7 |
+
6,5,"The violent underwater tornado continues its rampage, now ripping a massive, stone tiki statue from its resting place on the ocean floor. The carved face of the heavy idol spins wildly as it is sucked into the murky vortex, colliding with swirling rocks and sand. Debris crashes against the stone surface, chipping away at its ancient features while the chaotic currents drag it higher into the funnel. The surrounding water remains thick with sediment, obscuring the background as the heavy statue becomes another victim of the deep-sea storm. Close-up shot emphasizing the turbulent motion and destruction."
|
| 8 |
+
8,1,"A medium close-up of a serene, young East Asian woman with long pink hair, wearing a simple white gown that flows softly around her. She stands amidst gently falling sakura petals, which swirl around her, partially obscuring her figure in a dreamy, ethereal haze. Her delicate features are calm and tranquil as she gazes off into the distance. The background is blurred, featuring a soft pink and white sky with faint outlines of cherry blossom branches. The scene is bathed in a gentle, diffused light, creating a soft, dreamlike atmosphere."
|
| 9 |
+
8,2,"In a serene, still environment, a woman gently lifts her hand towards a delicate flower petal, her fingertips barely touching the wisps of smoke floating nearby. She has a soft, contemplative expression on her face, and her hand moves slowly and gracefully. The scene is captured from a medium close-up angle, focusing on her hand and the petal, with the subtle movement and interaction emphasized. The background is blurred, creating a gentle focus on the main action. The lighting is soft and diffused, adding to the tranquil atmosphere."
|
| 10 |
+
8,3,"A gentle breeze rustles through the air, causing cherry blossom petals to dance gracefully around a young woman's outstretched hand. She stands with a serene expression, wearing a traditional hanfu gown with flowing sleeves. The background showcases a tranquil garden with a winding path and blooming cherry trees. Soft sunlight filters through the leaves, casting dappled shadows on the ground. The scene is captured in a medium close-up, focusing on her hand and the swirling petals, with a slow pan to reveal the beautiful surroundings."
|
| 11 |
+
8,4,"A serene woman with closed eyes and soft, resting eyelashes, exuding a sense of tranquility and peace. She sits gracefully with her hands gently folded in her lap, wearing a flowing, pastel-colored dress that complements her calm demeanor. The lighting is soft and diffused, casting a gentle glow over her face. The background is a blurred, natural setting with hints of greenery and a tranquil atmosphere. The camera focuses closely on her face, capturing the subtle rise and fall of her breath as she maintains a peaceful composure. Close-up shot, emphasizing her serene expression and the gentle movement of her body."
|
| 12 |
+
8,5,"A serene nature scene where a young woman with flowing hair and a gentle expression steps forward gracefully on a grassy meadow. In the background, a small bird flutters and lands on a nearby tree branch. The woman's soft movements contrast with the bird's quick flight, creating a peaceful and harmonious atmosphere. The camera follows her as she moves, capturing the delicate interplay between the woman and the natural world in a medium close-up. The lighting is soft and natural, casting a warm glow over the scene."
|
| 13 |
+
8,6,"A serene moment captured in a magical realism style, where a graceful bird perches delicately on the outstretched finger of a woman. The bird has vibrant plumage and a calm demeanor. Pink and faint cyan-blue smoke begins to swirl and thicken around them, gently enveloping the scene in a soft, misty haze. The woman stands gracefully, her hand extended, with a serene expression. The background is a dimly lit, cozy room with warm wooden elements and soft lighting, adding to the enchanting atmosphere. Medium close-up shot focusing on the interaction between the woman and the bird, with the smoke swirling in the foreground."
|
| 14 |
+
11,1,"In a serene autumn clearing bathed in the warm, golden hues of late afternoon sunlight filtering through tall maple trees, a carpet of vibrant red and orange leaves blankets the ground. A rustic wooden footbridge arches gracefully over a gently trickling stream. Center frame, a sleek silver-gray house cat trots briskly across the leaf-strewn ground, its tail flicking energetically. As a cool breeze stirs, more leaves swirl and dance across the lens, adding a dynamic motion to the tranquil scene. Medium shot capturing the cat in motion against the backdrop of falling leaves."
|
| 15 |
+
11,2,"In a lush forest setting, a playful house cat bounds towards the treeline, leaping gracefully over a fallen log. Mid-stride, the cat transforms into a sleek, smoky brown wildcat with tufted ears and lean, powerful muscles. It continues to run swiftly through the drifting autumn leaves, propelled by its agility and strength. The camera follows the wildcat in a smooth tracking shot, capturing the dynamic motion and the rich, vibrant colors of the forest floor."
|
| 16 |
+
11,3,"In the warm golden hour, a wildcat leaps gracefully across a sparkling stream. As it runs, its body broadens and its fur transforms from its original color to a deep russet tone, morphing seamlessly into a sleek red fox. The fox's bushy, vibrant plume tail catches the sunlight, illuminating its swift movement as it dashes forward. The scene is captured from a dynamic tracking shot, emphasizing the fluid transition and the natural beauty of the changing landscape. Close-up and mid-shot transitions highlight the transformation and the glowing amber sky."
|
| 17 |
+
11,4,"In twilight, a red fox races across an old stone bridge, its chest heaving and coat gradually graying as it transforms into a majestic gray wolf mid-jump. The wolf then gallops through an open forest clearing, leaping over a babbling stream, and continues up the hillside. The sky transitions from orange to deep purple, with stars beginning to twinkle overhead. The camera follows the wolf's swift movement, starting from a medium shot on the bridge and zooming out to a wide-angle view of the wolf bounding towards the hillside under the fading light."
|
| 18 |
+
11,5,"In a serene moonlit forest, the transformation of a wolf into an antelope unfolds gracefully. Initially, the wolf's limbs elongate and refine, its fur shortening from its dense winter coat to a sleek, tawny color. As it shifts, small horns begin to emerge from its forehead. The antelope then swiftly bounds between trees, leaping over obstacles with ease, and finally clearing a tranquil stream in a single graceful leap. The camera captures this magical metamorphosis with smooth tracking shots and close-ups, emphasizing the fluidity and beauty of the change."
|
| 19 |
+
11,6,"In a mystical scene under the bright moonlight, an antelope gradually transforms into a powerful horse. Initially, the antelope has a slender frame with a rich chestnut coat. As the transformation progresses, it grows taller and heavier, developing the muscular build and sturdy legs of a horse. The horse then begins to gallop majestically towards the horizon, its mane flowing freely in the wind. Its hooves rhythmically ring against the leaf-strewn ground, seamlessly completing the metamorphosis from cat-like agility to equine power. The scene is captured in a sweeping aerial shot, emphasizing the fluidity and grace of the transformation."
|
| 20 |
+
14,1,"Close-up from the left side of a forest clearing, focus on a little girl in a light pink tulle dress with long flowing brown hair. She gazes slightly upward with a gentle, serene expression. The ground is covered in green grass and scattered wildflowers, with light mist creating an ethereal atmosphere. Sunbeams filter through the tall tree branches, casting dappled light. The scene is rendered in fantasy realism with soft, dreamy lighting, emphasizing the magical quality of the forest."
|
| 21 |
+
14,2,"A slow pullback reveals a glowing magical stone appearing on the right side of the frame. In the center, a young girl remains stationary, her expression serene and focused. Sunbeams filter through the clouds, shifting slightly as the camera moves backward, casting gentle shadows across the scene. The background gradually comes into view, showcasing a mystical forest with tall trees and vibrant greenery. The camera captures the magic and wonder of the moment in a medium-wide shot."
|
| 22 |
+
14,3,"Start with a close-up of a young boy in a blue robe adorned with a light tulle cloak as he enters from the right side of the frame. As he stops, the camera slowly pulls back to reveal a girl watching him intently from a few feet away. In the background, a large stone statue remains stationary, adding a sense of permanence and stillness to the scene. The environment is a dimly lit, ancient-looking room with stone walls and pillars. The camera movement emphasizes the interaction between the characters and their surroundings, capturing their expressions and body language clearly. Medium to wide shot transition."
|
| 23 |
+
14,4,"A slight pan and pullback reveal a young boy nodding his head, his face showing a mixture of curiosity and determination. In response, a young girl raises her hand in acknowledgment, her expression serene and focused. Both children stand near a luminous stone that continues to emit a soft, warm glow, casting gentle light over the surrounding area. The scene takes place in a dimly lit forest clearing, with tall trees and dense undergrowth visible in the background. Medium shot transitioning to wide shot."
|
| 24 |
+
14,5,"In a serene forest clearing, a young woman with flowing blonde hair turns towards a young man standing beside her. As the camera pulls to a medium shot, the couple's intimate moment is revealed against a backdrop of vibrant wildflowers and wisps of mist gently hovering above the ground. The environment is bathed in soft, natural light, enhancing the romantic atmosphere. The camera movement smoothly captures the subtle shift in their positions, bringing the entire scene into clear focus."
|
| 25 |
+
14,6,"Wide shot: A young boy in a casual outfit walks out to the right, while a girl stays stationary to the left. In the middle of a fully lit forest clearing, a luminous stone emits a warm glow, surrounded by drifting mist and soft sunbeams filtering through the canopy. The camera pans slowly to follow the boy as he moves, capturing the serene beauty of the misty landscape and the mystical ambiance created by the glowing stone."
|
| 26 |
+
20,0,"A majestic lion named Leo stands regally in the heart of a dense jungle, embodying the essence of a king. Leo has a golden mane that flows gracefully around his broad shoulders, and his piercing amber eyes survey the landscape with confidence and authority. He is positioned on a rocky outcrop, towering over the lush greenery below. The background showcases a vibrant jungle scene with tall trees, cascading vines, and dappled sunlight filtering through the canopy. Leo's posture is proud and commanding, with his tail held high. The scene is captured from a medium close-up perspective, emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 27 |
+
20,1,"Leo shifts his powerful weight slightly on the rocky outcrop, his golden mane rippling as he does so. Suddenly, he opens his massive jaws to release a deep, resonant roar that vibrates through the humid air, revealing his formidable white teeth. The dappled sunlight filtering through the canopy dances across his fur as his chest expands with the effort. The vibrant jungle remains lush and green around him, with tall trees and cascading vines framing his commanding figure. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 28 |
+
20,2,"Leo maintains his regal position on the rocky outcrop as the humid jungle air settles around his broad shoulders. He suddenly lowers his massive head to sniff a vibrant blue butterfly that has fluttered near his nose, his piercing amber eyes momentarily softening with curiosity. The dappled sunlight continues to filter through the tall trees and cascading vines, illuminating the golden hues of his mane against the lush green background. His tail remains held high, a symbol of his enduring authority over the landscape. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 29 |
+
20,3,"Leo stands tall on the rocky outcrop in the heart of the dense jungle, his golden mane glowing in the dappled sunlight. He lifts a massive paw to swipe gently at a low-hanging vine that dangles just within his reach, testing its texture with sharp claws. His piercing amber eyes remain alert, scanning the lush greenery and tall trees that surround him. The vibrant background of cascading vines and filtered light frames his regal form perfectly. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 30 |
+
20,4,"Leo remains on the rocky outcrop in the heart of the dense jungle, his golden mane catching the filtered light. He suddenly turns his head sharply to the left, his ears twitching as he focuses on a brightly colored parrot that lands on a nearby branch. His piercing amber eyes lock onto the bird with intense focus, analyzing the new arrival amidst the tall trees and cascading vines. The lush greenery provides a vibrant backdrop as he stands with authority, his posture commanding and proud. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 31 |
+
20,5,"Leo stands regally on the rocky outcrop in the heart of the dense jungle, his golden mane flowing around his broad shoulders. He dips his head low to lap cool water from a small, clear puddle that has formed in a crevice of the stone, his rough tongue splashing gently. His piercing amber eyes briefly close in satisfaction before reopening to survey the lush greenery, tall trees, and cascading vines. The dappled sunlight filters through the canopy, highlighting the wet fur on his muzzle. A medium close-up perspective emphasizing Leo’s powerful stance and the regal aura surrounding him."
|
| 32 |
+
153,0,"90s VHS-style The Weather Channel scene, featuring a weatherman standing in front of a green screen with a large map of storm systems behind him. The weatherman, dressed in a casual but professional outfit, points emphatically at the rapidly moving storms on the map. His face shows concern and urgency as he speaks directly to the camera. The background map displays swirling patterns indicating severe weather conditions. The overall scene has a vintage, grainy texture with the characteristic noise and color palette of old VHS recordings. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 33 |
+
153,1,"The weatherman now reaches into his pocket and pulls out a chunky black walkie-talkie, pressing it against his ear with a sudden look of intense focus. He nods sharply while listening to an urgent update, his brow furrowing deeper under the studio lights. The green screen map behind him flickers slightly as the swirling storm systems intensify in color, shifting from red to deep purple. The vintage VHS grain distorts the edges of his suit jacket as he lowers the device and turns back to address the viewers with renewed alarm. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 34 |
+
153,2,"The weatherman suddenly unrolls a large, paper topographic map across a small stand that appears from the side, smoothing out the creases with frantic energy. He traces a specific mountain range with his finger, highlighting a dangerous path the storm is taking, his eyes wide with genuine fear. The digital map behind him glitches momentarily, syncing with his analogue demonstration as the VHS static rolls vertically across the frame. The studio lights reflect off the glossy paper surface as he taps a specific valley location repeatedly. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 35 |
+
153,3,"The weatherman abruptly grabs a bright red marker pen from the desk edge and begins circling a specific coastal city directly on the camera lens itself. He draws a jagged, erratic line across the glass to simulate the storm's unpredictable path, his hand shaking slightly with adrenaline. The ink squeaks audibly against the surface as the green screen map behind him pulses with warning icons. The VHS static buzzes louder, momentarily distorting his face as he caps the marker and stares intensely through his red drawings. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 36 |
+
153,4,"The weatherman now lifts a large, distinct ""Hurricane Warning"" sign made of heavy cardboard, holding it up beside his face for the audience to see clearly. The blocky red letters on the sign contrast sharply with his beige suit as he taps the edge of the board for emphasis. Behind him, the digital map swirls violently, the green screen effects blending slightly with the edges of the physical prop. The VHS tracking lines jitter horizontally across the bottom of the frame, enhancing the retro aesthetic as he maintains intense eye contact. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 37 |
+
153,5,"The weatherman suddenly dons a bright yellow rain slicker over his suit, struggling momentarily with the snaps as he prepares for a simulated outdoor report. He pulls the hood up over his head, framing his face tightly while the green screen behind him shifts to show footage of swaying palm trees and flying debris. The synthetic material of the coat reflects the studio lights with a harsh glare, adding to the chaotic atmosphere. The grainy VHS texture creates color bleeding around the vibrant yellow fabric as he shouts over imaginary wind. Medium close-up shot focusing on the weatherman's gestures and expressions."
|
| 38 |
+
200,0,"A female astronaut in a full spacesuit, including an astronaut helmet, is running swiftly away from an unknown threat. She has a determined and focused expression on her face. The spacesuit is sleek, silver, and equipped with various gadgets and sensors. Her hair is visible under the helmet, flowing behind her as she runs. The background shows a desolate, rocky landscape with distant mountains and a dark, starry sky. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency."
|
| 39 |
+
200,1,"The silver-suited astronaut sprints across the rocky terrain, but now she firmly clutches a glowing red geological scanner in her right hand, its lights pulsing rhythmically against the dark environment. Her expression remains intense under the helmet visor as she navigates the uneven ground, the sleek gadgets on her suit reflecting faint starlight. The desolate landscape stretches endlessly around her, framed by jagged mountains in the distance. The medium shot tracks alongside her movement, keeping pace with her urgent stride against the backdrop of the vast, starry void. medium shot mid-run speed urgency"
|
| 40 |
+
200,2,"The female astronaut races forward across the jagged terrain, her silver spacesuit gleaming against the dark void. Suddenly, a small drone detaches from her shoulder armor and hovers briefly before zooming ahead to scout the path. Her face remains locked in focused determination behind the helmet visor as her hair shifts with her rapid movement. The desolate rocky ground and looming distant mountains provide a stark backdrop to her flight. The camera maintains a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 41 |
+
200,3,"The female astronaut sprints across the desolate, rocky landscape, her silver spacesuit reflecting the cold starlight. As she runs, she suddenly raises her left arm to activate a holographic map projected from her wrist gauntlet, displaying a complex grid of blue lines and waypoints. Her expression remains fierce and concentrated behind the helmet visor while her hair moves with the momentum of her stride. The dark mountains loom in the distance under the starry sky. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 42 |
+
200,4,"The female astronaut dashes across the uneven, rocky ground, her sleek silver spacesuit shimmering under the starry sky. Without slowing her rapid pace, she reaches to her belt and deploys a luminous blue energy flare, dropping it behind her to mark her trail. Her face is set in a look of grim determination inside the helmet, with strands of hair floating with her motion. The dark, desolate landscape and distant mountains rush by as she flees. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 43 |
+
200,5,"The silver-clad astronaut sprints relentlessly across the treacherous rocky terrain, her breath fogging the corner of her helmet visor. As she runs, she suddenly taps a control on her chest plate, causing a pair of bright white headlights to activate on either side of her helmet, cutting through the darkness ahead. Her determined eyes scan the illuminated path while the desolate landscape and jagged mountains blur in the background. The starry sky hangs heavy above her swift escape. The scene captures a medium shot of the woman mid-run, emphasizing her speed and urgency"
|
| 44 |
+
312,0,"A young woman standing in the rain, looking up at the sky with a warm, inviting smile on her face. She is dressed in a light, flowy dress that clings to her form as droplets of water fall around her. Her hair is gently tousled from the rain, framing her delicate features. The background shows a blurred cityscape with tall buildings and the faint glow of streetlights. The scene captures the serene beauty of a rainy evening. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 45 |
+
312,2,"The young woman remains framed against the soft blur of city lights, the rain now glistening on her skin as she slowly extends her right hand palm-up to catch the falling droplets. Her expression shifts slightly to one of quiet wonder as the water pools in her cupped fingers. The light fabric of her dress continues to sway subtly with the gentle wind, emphasizing the damp atmosphere. The distant streetlights create bokeh orbs behind her silhouette. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 46 |
+
312,3,"The young woman in the light, flowy dress now closes her eyes, tilting her head back slightly to let the rain wash over her face. She reaches into her pocket and pulls out a bright red origami crane, holding it delicately between her fingers. The paper quickly darkens as it absorbs the moisture, contrasting with the blurred gray cityscape behind her. Her hair is plastered more closely to her cheeks by the persistent downpour, while the streetlights cast a soft, shimmering glow on the wet paper bird. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 47 |
+
312,4,"The young woman in the soaked flowy dress opens her eyes and suddenly unfurls a small, transparent umbrella with a floral pattern above her head. The rain drums rhythmically against the plastic canopy, creating a protective bubble around her upper body while water streams down the sides. The red paper crane she held previously is now tucked away or gone, replaced by her grip on the curved umbrella handle. The blurred city lights reflect beautifully on the wet surface of the umbrella as she gazes forward with renewed calmness. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 48 |
+
312,5,"The young woman stands beneath the transparent floral umbrella, the rain creating a rhythmic patter on its surface. She reaches up with her free hand and adjusts a pair of round, gold-rimmed glasses onto the bridge of her nose, blinking behind the lenses as they catch the ambient city light. Her damp hair frames her face, and the light dress clings softly to her form in the humid air. The blurred cityscape behind her glows with the warmth of streetlights, enhancing the serene mood. Medium close-up, static shot focusing on the girl's face and upper body."
|
| 49 |
+
334,0,"A stylish, young woman riding a sleek black motorcycle down a bustling city street. She wears a fitted leather jacket, dark sunglasses, and a helmet with a visor up, revealing her confident expression. Her posture is relaxed yet controlled as she grips the handlebars firmly. The motorcycle's engine roars as she navigates through traffic. The urban backdrop includes tall buildings, street signs, and passing cars, creating a vibrant, dynamic scene. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 50 |
+
334,1,"The stylish young woman on the sleek black motorcycle leans slightly to the right as she smoothly changes lanes. Her fitted leather jacket gleams under the city lights, and her dark sunglasses reflect the passing scenery. With her helmet visor up, a faint smile plays on her lips, showing her enjoyment of the ride. Suddenly, she extends her left hand to adjust the side mirror, briefly checking the reflection of the vibrant urban backdrop behind her before returning her grip to the handlebars. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 51 |
+
334,2,"The stylish young woman on the sleek black motorcycle accelerates gently, causing her hair to flutter beneath the edge of her helmet. Her fitted leather jacket remains snug against the wind, while her dark sunglasses shield her eyes from the glare. As she cruises past towering skyscrapers and vibrant street signs, she reaches down with her right hand to toggle a switch on the dashboard, activating the motorcycle's bright turn signal. The urban environment blurs slightly in the background, emphasizing her focused movement through the traffic. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 52 |
+
334,3,"The stylish young woman on the sleek black motorcycle maintains her steady pace through the busy urban corridor. Her fitted leather jacket and dark sunglasses remain prominent against the backdrop of tall buildings and passing cars. With her helmet visor up, her confident expression is clear as she navigates the road. As she rides, she briefly lifts her left boot to shift gears, pressing down decisively on the pedal near the footrest. The engine note changes pitch slightly, blending with the city noise, while street signs flash by in the background. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 53 |
+
334,4,"The stylish young woman on the sleek black motorcycle rides confidently forward amidst the bustling traffic. Her fitted leather jacket and dark sunglasses stay consistent with her cool demeanor, while the helmet visor remains up. As she passes a row of tall buildings and street signs, she suddenly raises her left hand to wave at a pedestrian standing on the nearby sidewalk. Her posture stays relaxed despite the momentary gesture, and she quickly returns her hand to the grip to maintain control. The urban backdrop continues to provide a vibrant, dynamic atmosphere around her. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
| 54 |
+
334,5,"The stylish young woman on the sleek black motorcycle rides forward, her fitted leather jacket absorbing the ambient city light. She wears dark sunglasses and keeps her helmet visor up, maintaining a confident, relaxed expression amidst the towering buildings and passing cars. While cruising through the vibrant urban scene, she briefly tilts her head to glance at a large digital billboard flashing colorful advertisements above the street. Her grip on the handlebars remains steady as she takes in the glowing display before refocusing on the road ahead. Medium shot focusing on the girl and the motorcycle, capturing the energy of the city."
|
Helios/_DEV2/example/toy_data/toy_filter.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"cut": [
|
| 4 |
+
0,
|
| 5 |
+
81
|
| 6 |
+
],
|
| 7 |
+
"crop": [
|
| 8 |
+
0,
|
| 9 |
+
832,
|
| 10 |
+
0,
|
| 11 |
+
480
|
| 12 |
+
],
|
| 13 |
+
"fps": 24.0,
|
| 14 |
+
"num_frames": 81,
|
| 15 |
+
"resolution": {
|
| 16 |
+
"height": 480,
|
| 17 |
+
"width": 832
|
| 18 |
+
},
|
| 19 |
+
"cap": [
|
| 20 |
+
"A stunning mid-afternoon landscape photograph with a low camera angle, showcasing several giant wooly mammoths treading through a snowy meadow. Their long, wooly fur gently billows in the brisk wind as they move, creating a sense of natural movement. Snow-covered trees and dramatic snow-capped mountains loom in the distance, adding to the majestic setting. Wispy clouds and a high sun cast a warm glow over the scene, enhancing the serene and awe-inspiring atmosphere. The depth of field brings out the detailed textures of the mammoths and the snowy environment, capturing every nuance of these prehistoric giants in breathtaking clarity."
|
| 21 |
+
],
|
| 22 |
+
"path": "videos/2_240_ori81.mp4"
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cut": [
|
| 26 |
+
0,
|
| 27 |
+
129
|
| 28 |
+
],
|
| 29 |
+
"crop": [
|
| 30 |
+
0,
|
| 31 |
+
832,
|
| 32 |
+
0,
|
| 33 |
+
480
|
| 34 |
+
],
|
| 35 |
+
"fps": 24.0,
|
| 36 |
+
"num_frames": 129,
|
| 37 |
+
"resolution": {
|
| 38 |
+
"height": 480,
|
| 39 |
+
"width": 832
|
| 40 |
+
},
|
| 41 |
+
"cap": [
|
| 42 |
+
"An old man in blue jeans and a white T-shirt takes a leisurely stroll along a bustling street in Mumbai, India, during a breathtaking sunset. He walks with a gentle sway, his weathered face reflecting the warm hues of the setting sun. His hands rest casually in his pockets, and he appears content and at peace. The background features a vibrant mix of colorful buildings, street vendors, and pedestrians, with the sky painted in shades of orange, pink, and purple. The photo has a nostalgic and documentary style, capturing the essence of a serene moment amidst the city's energy. A medium shot with a soft focus on the old man."
|
| 43 |
+
],
|
| 44 |
+
"path": "videos/239_120_ori129.mp4"
|
| 45 |
+
}
|
| 46 |
+
]
|
Helios/_DEV2/helios/__init__.py
ADDED
|
File without changes
|
Helios/_DEV2/helios/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (182 Bytes). View file
|
|
|
Helios/_DEV2/helios/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (171 Bytes). View file
|
|
|
Helios/_DEV2/helios/dataset/__init__.py
ADDED
|
File without changes
|
Helios/_DEV2/helios/dataset/dataloader_dmd.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import random
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
from torch.utils.data import Dataset, Sampler
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BucketedFeatureDataset(Dataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
gan_folders=None,
|
| 15 |
+
ode_folders=None,
|
| 16 |
+
text_folders=None,
|
| 17 |
+
is_use_gt_history=False,
|
| 18 |
+
return_secondary=False,
|
| 19 |
+
force_rebuild=False,
|
| 20 |
+
single_res=True,
|
| 21 |
+
single_length=True,
|
| 22 |
+
single_num_frame=81,
|
| 23 |
+
single_height=384,
|
| 24 |
+
single_width=640,
|
| 25 |
+
seed=42,
|
| 26 |
+
):
|
| 27 |
+
self.is_use_gt_history = is_use_gt_history
|
| 28 |
+
self.return_secondary = return_secondary
|
| 29 |
+
self.force_rebuild = force_rebuild
|
| 30 |
+
self.base_seed = seed
|
| 31 |
+
self._epoch = 0
|
| 32 |
+
|
| 33 |
+
self.single_res = single_res
|
| 34 |
+
self.single_length = single_length
|
| 35 |
+
self.single_num_frame = single_num_frame
|
| 36 |
+
self.single_height = single_height
|
| 37 |
+
self.single_width = single_width
|
| 38 |
+
|
| 39 |
+
self.gan_samples = self._init_samples(gan_folders, "gan")
|
| 40 |
+
self.ode_samples = self._init_samples(ode_folders, "ode")
|
| 41 |
+
self.text_samples = self._init_samples(text_folders, "text")
|
| 42 |
+
|
| 43 |
+
self._align_sample_counts()
|
| 44 |
+
|
| 45 |
+
def _init_samples(self, folders, data_type):
|
| 46 |
+
if folders is None:
|
| 47 |
+
return []
|
| 48 |
+
|
| 49 |
+
folders = [folders] if isinstance(folders, str) else folders
|
| 50 |
+
samples = []
|
| 51 |
+
|
| 52 |
+
for folder in folders:
|
| 53 |
+
cache_file = os.path.join(folder, f"{data_type}_dataset_cache.pkl")
|
| 54 |
+
folder_samples = self._process_folder(folder, cache_file, data_type)
|
| 55 |
+
samples.extend(folder_samples)
|
| 56 |
+
|
| 57 |
+
return samples
|
| 58 |
+
|
| 59 |
+
def _align_sample_counts(self, is_log=True):
|
| 60 |
+
lengths = {"gan": len(self.gan_samples), "ode": len(self.ode_samples), "text": len(self.text_samples)}
|
| 61 |
+
|
| 62 |
+
non_empty_lengths = {k: v for k, v in lengths.items() if v > 0}
|
| 63 |
+
if not non_empty_lengths:
|
| 64 |
+
return
|
| 65 |
+
max_length = max(non_empty_lengths.values())
|
| 66 |
+
|
| 67 |
+
if is_log:
|
| 68 |
+
print(f"\nAligning sample counts to max: {max_length}")
|
| 69 |
+
print(f"Original counts - GAN: {lengths['gan']}, ODE: {lengths['ode']}, TEXT: {lengths['text']}")
|
| 70 |
+
|
| 71 |
+
random.seed(self.base_seed)
|
| 72 |
+
|
| 73 |
+
if self.gan_samples and len(self.gan_samples) < max_length:
|
| 74 |
+
self.gan_samples = self._expand_samples(self.gan_samples, max_length, "GAN")
|
| 75 |
+
|
| 76 |
+
if self.ode_samples and len(self.ode_samples) < max_length:
|
| 77 |
+
self.ode_samples = self._expand_samples(self.ode_samples, max_length, "ODE")
|
| 78 |
+
|
| 79 |
+
if self.text_samples and len(self.text_samples) < max_length:
|
| 80 |
+
self.text_samples = self._expand_samples(self.text_samples, max_length, "TEXT")
|
| 81 |
+
|
| 82 |
+
if is_log:
|
| 83 |
+
print(
|
| 84 |
+
f"Aligned counts - GAN: {len(self.gan_samples)}, ODE: {len(self.ode_samples)}, TEXT: {len(self.text_samples)}\n"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def _expand_samples(self, samples, target_length, data_type):
|
| 88 |
+
original_length = len(samples)
|
| 89 |
+
expanded_samples = samples.copy()
|
| 90 |
+
|
| 91 |
+
while len(expanded_samples) < target_length:
|
| 92 |
+
random_sample = random.choice(samples)
|
| 93 |
+
expanded_samples.append(random_sample)
|
| 94 |
+
|
| 95 |
+
print(f"{data_type}: Expanded from {original_length} to {len(expanded_samples)} samples")
|
| 96 |
+
return expanded_samples
|
| 97 |
+
|
| 98 |
+
def _process_folder(self, folder, cache_file, data_type):
|
| 99 |
+
if self.force_rebuild or not os.path.exists(cache_file):
|
| 100 |
+
# if os.path.exists(cache_file):
|
| 101 |
+
# os.remove(cache_file)
|
| 102 |
+
print(f"{data_type.upper()}: Building metadata cache for folder: {folder}")
|
| 103 |
+
folder_samples = self._build_folder_metadata(folder, data_type)
|
| 104 |
+
|
| 105 |
+
if not self.force_rebuild:
|
| 106 |
+
print(f"{data_type.upper()}: Saving metadata cache for folder: {folder}")
|
| 107 |
+
with open(cache_file, "wb") as f:
|
| 108 |
+
pickle.dump({"samples": folder_samples}, f)
|
| 109 |
+
|
| 110 |
+
print(f"{data_type.upper()}: Cached {len(folder_samples)} samples from {folder}")
|
| 111 |
+
else:
|
| 112 |
+
print(f"{data_type.upper()}: Loading cached metadata from: {folder}")
|
| 113 |
+
with open(cache_file, "rb") as f:
|
| 114 |
+
folder_samples = pickle.load(f)["samples"]
|
| 115 |
+
print(f"{data_type.upper()}: Loaded {len(folder_samples)} samples from cache: {folder}")
|
| 116 |
+
|
| 117 |
+
return folder_samples
|
| 118 |
+
|
| 119 |
+
def _build_folder_metadata(self, folder, data_type):
|
| 120 |
+
feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")]
|
| 121 |
+
samples = []
|
| 122 |
+
|
| 123 |
+
print(f"{data_type.upper()}: Processing {len(feature_files)} files in {folder}...")
|
| 124 |
+
for i, feature_file in enumerate(feature_files):
|
| 125 |
+
if i % 10000 == 0:
|
| 126 |
+
print(f" {data_type.upper()}: Processed {i}/{len(feature_files)} files")
|
| 127 |
+
|
| 128 |
+
feature_path = os.path.join(folder, feature_file)
|
| 129 |
+
|
| 130 |
+
# TODO hard code here now
|
| 131 |
+
if data_type == "gan":
|
| 132 |
+
parts = feature_file.split("_")
|
| 133 |
+
num_frame = int(parts[-3])
|
| 134 |
+
height = int(parts[-2])
|
| 135 |
+
width = int(parts[-1].replace(".pt", ""))
|
| 136 |
+
|
| 137 |
+
if self.is_use_gt_history:
|
| 138 |
+
if (height, width) not in [(self.single_height, self.single_width)]:
|
| 139 |
+
continue
|
| 140 |
+
else:
|
| 141 |
+
if (num_frame, height, width) not in [
|
| 142 |
+
(self.single_num_frame, self.single_height, self.single_width)
|
| 143 |
+
]:
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
samples.append(
|
| 147 |
+
{
|
| 148 |
+
"uttid": os.path.splitext(os.path.basename(feature_file))[0],
|
| 149 |
+
"dataset_name": folder.rstrip("/"),
|
| 150 |
+
"file_path": feature_path,
|
| 151 |
+
}
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
return samples
|
| 155 |
+
|
| 156 |
+
def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None, return_secondary=False):
|
| 157 |
+
self.is_keep_x0 = (True,)
|
| 158 |
+
self.history_sizes = [16, 2, 1]
|
| 159 |
+
self.num_rollout_sections = 9
|
| 160 |
+
|
| 161 |
+
source_latent = base_vae_latent if base_vae_latent is not None else vae_latent
|
| 162 |
+
|
| 163 |
+
x0_latent = None
|
| 164 |
+
if self.is_keep_x0:
|
| 165 |
+
x0_latent = source_latent[0, :, :1, :, :].clone()
|
| 166 |
+
total_sections = source_latent.shape[0]
|
| 167 |
+
latent_window_size = source_latent.shape[2]
|
| 168 |
+
history_window_size = sum(self.history_sizes)
|
| 169 |
+
section_size = history_window_size + latent_window_size
|
| 170 |
+
|
| 171 |
+
temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w")
|
| 172 |
+
zero_padding_source = torch.zeros(
|
| 173 |
+
temp_source_latent.shape[0],
|
| 174 |
+
history_window_size,
|
| 175 |
+
temp_source_latent.shape[2],
|
| 176 |
+
temp_source_latent.shape[3],
|
| 177 |
+
device=temp_source_latent.device,
|
| 178 |
+
dtype=temp_source_latent.dtype,
|
| 179 |
+
)
|
| 180 |
+
continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1)
|
| 181 |
+
|
| 182 |
+
temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w")
|
| 183 |
+
zero_padding_vae = torch.zeros(
|
| 184 |
+
temp_vae_latent.shape[0],
|
| 185 |
+
history_window_size,
|
| 186 |
+
temp_vae_latent.shape[2],
|
| 187 |
+
temp_vae_latent.shape[3],
|
| 188 |
+
device=temp_vae_latent.device,
|
| 189 |
+
dtype=temp_vae_latent.dtype,
|
| 190 |
+
)
|
| 191 |
+
continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1)
|
| 192 |
+
|
| 193 |
+
sample_seed = self.base_seed + self._epoch * 1000000 + idx
|
| 194 |
+
choice_idx = torch.randint(
|
| 195 |
+
0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed)
|
| 196 |
+
).item()
|
| 197 |
+
if choice_idx == 0 and x0_latent is not None:
|
| 198 |
+
x0_latent = torch.zeros_like(x0_latent)
|
| 199 |
+
|
| 200 |
+
start_indice = choice_idx * latent_window_size
|
| 201 |
+
end_indice = start_indice + section_size
|
| 202 |
+
|
| 203 |
+
history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :]
|
| 204 |
+
target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :]
|
| 205 |
+
|
| 206 |
+
x0_latent_2 = None
|
| 207 |
+
history_latent_2 = None
|
| 208 |
+
target_latent_2 = None
|
| 209 |
+
if return_secondary:
|
| 210 |
+
sample_seed_2 = self.base_seed + self._epoch * 1000000 + idx + 999999
|
| 211 |
+
choice_idx_2 = torch.randint(
|
| 212 |
+
0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed_2)
|
| 213 |
+
).item()
|
| 214 |
+
|
| 215 |
+
x0_latent_2 = None
|
| 216 |
+
if self.is_keep_x0:
|
| 217 |
+
x0_latent_2 = source_latent[0, :, :1, :, :].clone()
|
| 218 |
+
if choice_idx_2 == 0:
|
| 219 |
+
x0_latent_2 = torch.zeros_like(x0_latent_2)
|
| 220 |
+
|
| 221 |
+
start_indice_2 = choice_idx_2 * latent_window_size
|
| 222 |
+
end_indice_2 = start_indice_2 + section_size
|
| 223 |
+
|
| 224 |
+
history_latent_2 = continue_source_latent[:, start_indice_2 : start_indice_2 + history_window_size, :, :]
|
| 225 |
+
target_latent_2 = continue_vae_latent[:, start_indice_2 + history_window_size : end_indice_2, :, :]
|
| 226 |
+
|
| 227 |
+
return (x0_latent, history_latent, target_latent), (x0_latent_2, history_latent_2, target_latent_2)
|
| 228 |
+
|
| 229 |
+
def set_epoch(self, epoch):
|
| 230 |
+
self._epoch = epoch
|
| 231 |
+
random.seed(self.base_seed + epoch)
|
| 232 |
+
self._align_sample_counts(is_log=False)
|
| 233 |
+
|
| 234 |
+
def __len__(self):
|
| 235 |
+
return max(len(self.gan_samples), len(self.ode_samples), len(self.text_samples))
|
| 236 |
+
|
| 237 |
+
def __getitem__(self, idx):
|
| 238 |
+
while True:
|
| 239 |
+
try:
|
| 240 |
+
output_dict = {}
|
| 241 |
+
|
| 242 |
+
if self.gan_samples:
|
| 243 |
+
gan_sample = self.gan_samples[idx]
|
| 244 |
+
gan_feature = torch.load(gan_sample["file_path"], map_location="cpu", weights_only=False)
|
| 245 |
+
if self.is_use_gt_history:
|
| 246 |
+
(
|
| 247 |
+
(x0_latent, history_latent, target_latent),
|
| 248 |
+
(x0_latent_2, history_latent_2, target_latent_2),
|
| 249 |
+
) = self.prepare_stage1_latent(
|
| 250 |
+
gan_feature["vae_latent"],
|
| 251 |
+
idx,
|
| 252 |
+
return_secondary=self.return_secondary,
|
| 253 |
+
)
|
| 254 |
+
output_dict.update(
|
| 255 |
+
{
|
| 256 |
+
"gan_uttid": gan_sample["uttid"],
|
| 257 |
+
"gan_dataset_name": gan_sample["dataset_name"],
|
| 258 |
+
"gan_vae_latents": target_latent,
|
| 259 |
+
"gan_x0_latents": x0_latent,
|
| 260 |
+
"gan_history_latents": history_latent,
|
| 261 |
+
"gan_vae_latents_2": target_latent_2,
|
| 262 |
+
"gan_x0_latents_2": x0_latent_2,
|
| 263 |
+
"gan_history_latents_2": history_latent_2,
|
| 264 |
+
"gan_prompt_raws": gan_feature["prompt_raw"],
|
| 265 |
+
"gan_prompt_embeds": gan_feature["prompt_embed"],
|
| 266 |
+
}
|
| 267 |
+
)
|
| 268 |
+
else:
|
| 269 |
+
output_dict.update(
|
| 270 |
+
{
|
| 271 |
+
"gan_uttid": gan_sample["uttid"],
|
| 272 |
+
"gan_dataset_name": gan_sample["dataset_name"],
|
| 273 |
+
"gan_vae_latents": gan_feature["vae_latent"],
|
| 274 |
+
"gan_prompt_raws": gan_feature["prompt_raw"],
|
| 275 |
+
"gan_prompt_embeds": gan_feature["prompt_embed"],
|
| 276 |
+
}
|
| 277 |
+
)
|
| 278 |
+
gan_sample = None
|
| 279 |
+
gan_feature = None
|
| 280 |
+
del gan_sample
|
| 281 |
+
del gan_feature
|
| 282 |
+
|
| 283 |
+
if self.ode_samples:
|
| 284 |
+
ode_sample = self.ode_samples[idx]
|
| 285 |
+
ode_feature = torch.load(ode_sample["file_path"], map_location="cpu", weights_only=False)
|
| 286 |
+
output_dict.update(
|
| 287 |
+
{
|
| 288 |
+
"ode_uttid": ode_sample["uttid"],
|
| 289 |
+
"ode_dataset_name": ode_sample["dataset_name"],
|
| 290 |
+
"ode_latent_window_size": ode_feature["latent_window_size"],
|
| 291 |
+
"ode_latents": ode_feature["ode_latents"],
|
| 292 |
+
"ode_prompt_raws": ode_feature["prompt_raw"],
|
| 293 |
+
"ode_prompt_embeds": ode_feature["prompt_embed"][0],
|
| 294 |
+
}
|
| 295 |
+
)
|
| 296 |
+
ode_sample = None
|
| 297 |
+
ode_feature = None
|
| 298 |
+
del ode_sample
|
| 299 |
+
del ode_feature
|
| 300 |
+
|
| 301 |
+
if self.text_samples:
|
| 302 |
+
text_sample = self.text_samples[idx]
|
| 303 |
+
text_feature = torch.load(text_sample["file_path"], map_location="cpu", weights_only=False)
|
| 304 |
+
output_dict.update(
|
| 305 |
+
{
|
| 306 |
+
"text_uttid": text_sample["uttid"],
|
| 307 |
+
"text_dataset_name": text_sample["dataset_name"],
|
| 308 |
+
"text_prompt_raws": text_feature["prompt_raw"],
|
| 309 |
+
"text_prompt_embeds": text_feature["prompt_embed"],
|
| 310 |
+
}
|
| 311 |
+
)
|
| 312 |
+
text_sample = None
|
| 313 |
+
text_feature = None
|
| 314 |
+
del text_sample
|
| 315 |
+
del text_feature
|
| 316 |
+
|
| 317 |
+
return output_dict
|
| 318 |
+
|
| 319 |
+
except Exception as e:
|
| 320 |
+
idx = random.randint(0, len(self) - 1)
|
| 321 |
+
print(f"Error loading sample at idx {idx}, retrying... Error: {e}")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class BucketedSampler(Sampler):
|
| 325 |
+
def __init__(
|
| 326 |
+
self,
|
| 327 |
+
dataset,
|
| 328 |
+
batch_size,
|
| 329 |
+
dataset_sampling_ratios={},
|
| 330 |
+
drop_last=False,
|
| 331 |
+
shuffle=True,
|
| 332 |
+
seed=42,
|
| 333 |
+
num_sp_groups=1,
|
| 334 |
+
sp_world_size=1,
|
| 335 |
+
global_rank=0,
|
| 336 |
+
):
|
| 337 |
+
self.dataset = dataset
|
| 338 |
+
self.batch_size = batch_size
|
| 339 |
+
self.drop_last = drop_last
|
| 340 |
+
self.shuffle = shuffle
|
| 341 |
+
self.seed = seed
|
| 342 |
+
self.generator = torch.Generator()
|
| 343 |
+
self._epoch = 0
|
| 344 |
+
|
| 345 |
+
# Distributed parameters
|
| 346 |
+
self.num_sp_groups = num_sp_groups
|
| 347 |
+
self.sp_world_size = sp_world_size
|
| 348 |
+
self.global_rank = global_rank
|
| 349 |
+
self.ith_sp_group = self.global_rank // self.sp_world_size
|
| 350 |
+
|
| 351 |
+
def set_epoch(self, epoch):
|
| 352 |
+
self._epoch = epoch
|
| 353 |
+
|
| 354 |
+
def _shard_indices_for_sp_group(self, indices):
|
| 355 |
+
"""
|
| 356 |
+
Shard indices across SP groups.
|
| 357 |
+
Each SP group gets a disjoint subset of the data.
|
| 358 |
+
"""
|
| 359 |
+
if self.num_sp_groups == 1:
|
| 360 |
+
return indices
|
| 361 |
+
|
| 362 |
+
# Convert to tensor if it's a list
|
| 363 |
+
if isinstance(indices, list):
|
| 364 |
+
indices_tensor = torch.tensor(indices, dtype=torch.long)
|
| 365 |
+
else:
|
| 366 |
+
indices_tensor = indices
|
| 367 |
+
|
| 368 |
+
# Pad indices if necessary to make it divisible by num_sp_groups
|
| 369 |
+
total_size = len(indices_tensor)
|
| 370 |
+
if total_size % self.num_sp_groups != 0:
|
| 371 |
+
if not self.drop_last:
|
| 372 |
+
padding_size = self.num_sp_groups - (total_size % self.num_sp_groups)
|
| 373 |
+
indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]])
|
| 374 |
+
else:
|
| 375 |
+
# If drop_last, truncate to be divisible
|
| 376 |
+
if self.drop_last:
|
| 377 |
+
truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups
|
| 378 |
+
indices_tensor = indices_tensor[:truncate_size]
|
| 379 |
+
|
| 380 |
+
# Shard: each SP group gets every num_sp_groups-th element
|
| 381 |
+
sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups]
|
| 382 |
+
|
| 383 |
+
return sp_group_indices.tolist()
|
| 384 |
+
|
| 385 |
+
def __iter__(self):
|
| 386 |
+
# Use epoch-level seed for reproducibility
|
| 387 |
+
epoch_seed = self.seed + self._epoch
|
| 388 |
+
self.generator.manual_seed(epoch_seed)
|
| 389 |
+
|
| 390 |
+
# Get all indices
|
| 391 |
+
all_indices = list(range(len(self.dataset)))
|
| 392 |
+
|
| 393 |
+
# Global shuffle before sharding (important for distributed consistency)
|
| 394 |
+
if self.shuffle:
|
| 395 |
+
perm = torch.randperm(len(all_indices), generator=self.generator).tolist()
|
| 396 |
+
all_indices = [all_indices[i] for i in perm]
|
| 397 |
+
|
| 398 |
+
# Shard indices for this SP group
|
| 399 |
+
sp_group_indices = self._shard_indices_for_sp_group(all_indices)
|
| 400 |
+
|
| 401 |
+
# Create batches
|
| 402 |
+
for i in range(0, len(sp_group_indices), self.batch_size):
|
| 403 |
+
batch = sp_group_indices[i : i + self.batch_size]
|
| 404 |
+
if len(batch) == self.batch_size or not self.drop_last:
|
| 405 |
+
yield batch
|
| 406 |
+
|
| 407 |
+
def __len__(self):
|
| 408 |
+
# Total samples in dataset
|
| 409 |
+
total_samples = len(self.dataset)
|
| 410 |
+
|
| 411 |
+
# Account for SP group sharding
|
| 412 |
+
sp_group_samples = total_samples // self.num_sp_groups
|
| 413 |
+
if not self.drop_last and total_samples % self.num_sp_groups != 0:
|
| 414 |
+
sp_group_samples += 1
|
| 415 |
+
|
| 416 |
+
# Calculate number of batches
|
| 417 |
+
total_batches = sp_group_samples // self.batch_size
|
| 418 |
+
if not self.drop_last and sp_group_samples % self.batch_size != 0:
|
| 419 |
+
total_batches += 1
|
| 420 |
+
|
| 421 |
+
return total_batches
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def collate_fn(batch):
|
| 425 |
+
return {
|
| 426 |
+
key: torch.stack([d[key] for d in batch])
|
| 427 |
+
if isinstance(batch[0][key], torch.Tensor)
|
| 428 |
+
else [d[key] for d in batch]
|
| 429 |
+
for key in batch[0]
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
if __name__ == "__main__":
|
| 434 |
+
from accelerate import Accelerator
|
| 435 |
+
from torchdata.stateful_dataloader import StatefulDataLoader
|
| 436 |
+
|
| 437 |
+
dataloader_num_workers = 8
|
| 438 |
+
batch_size = 2
|
| 439 |
+
num_train_epochs = 2
|
| 440 |
+
seed = 0
|
| 441 |
+
|
| 442 |
+
gan_folder = [
|
| 443 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_long_960",
|
| 444 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/gan_latents/ultravideo/clips_short_960",
|
| 445 |
+
]
|
| 446 |
+
ode_folder = [
|
| 447 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/ode_pairs/vidprom_filtered_extended",
|
| 448 |
+
]
|
| 449 |
+
text_folder = [
|
| 450 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/mixkit_filter",
|
| 451 |
+
"/mnt/hdfs/data/ysh_new/userful_things_wan/text-embedding/vidprom_filtered_extended",
|
| 452 |
+
]
|
| 453 |
+
|
| 454 |
+
accelerator = Accelerator()
|
| 455 |
+
print(accelerator.process_index, accelerator.num_processes)
|
| 456 |
+
|
| 457 |
+
dataset = BucketedFeatureDataset(
|
| 458 |
+
gan_folders=gan_folder,
|
| 459 |
+
ode_folders=ode_folder,
|
| 460 |
+
text_folders=text_folder,
|
| 461 |
+
is_use_gt_history=True,
|
| 462 |
+
force_rebuild=True,
|
| 463 |
+
seed=seed,
|
| 464 |
+
)
|
| 465 |
+
sampler = BucketedSampler(
|
| 466 |
+
dataset,
|
| 467 |
+
batch_size=batch_size,
|
| 468 |
+
drop_last=True,
|
| 469 |
+
shuffle=True,
|
| 470 |
+
seed=seed,
|
| 471 |
+
num_sp_groups=accelerator.num_processes // 1,
|
| 472 |
+
sp_world_size=1,
|
| 473 |
+
global_rank=accelerator.process_index,
|
| 474 |
+
)
|
| 475 |
+
dataloader = StatefulDataLoader(
|
| 476 |
+
dataset,
|
| 477 |
+
batch_sampler=sampler,
|
| 478 |
+
collate_fn=collate_fn,
|
| 479 |
+
num_workers=dataloader_num_workers,
|
| 480 |
+
prefetch_factor=2 if dataloader_num_workers > 0 else None,
|
| 481 |
+
)
|
| 482 |
+
print(len(dataset), len(dataloader))
|
| 483 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 484 |
+
|
| 485 |
+
step = 0
|
| 486 |
+
global_step = 0
|
| 487 |
+
first_epoch = 0
|
| 488 |
+
print("Testing dataloader...")
|
| 489 |
+
dataset_counts = defaultdict(int)
|
| 490 |
+
for epoch in range(first_epoch, num_train_epochs):
|
| 491 |
+
sampler.set_epoch(epoch)
|
| 492 |
+
dataset.set_epoch(epoch)
|
| 493 |
+
for i, batch in enumerate(dataloader):
|
| 494 |
+
# Get metadata
|
| 495 |
+
gan_uttid = batch["gan_uttid"]
|
| 496 |
+
ode_uttid = batch["ode_uttid"]
|
| 497 |
+
text_uttid = batch["text_uttid"]
|
| 498 |
+
|
| 499 |
+
# Get feature
|
| 500 |
+
# For GAN
|
| 501 |
+
gan_vae_latents = batch["gan_vae_latents"]
|
| 502 |
+
gan_prompt_raws = batch["gan_prompt_raws"]
|
| 503 |
+
gan_prompt_embeds = batch["gan_prompt_embeds"]
|
| 504 |
+
print(gan_vae_latents.shape, gan_prompt_embeds.shape, gan_prompt_raws)
|
| 505 |
+
|
| 506 |
+
# For ODE
|
| 507 |
+
ode_prompt_raws = batch["ode_prompt_raws"]
|
| 508 |
+
ode_prompt_embeds = batch["ode_prompt_embeds"]
|
| 509 |
+
print(ode_prompt_embeds.shape, ode_prompt_raws)
|
| 510 |
+
|
| 511 |
+
# For Text
|
| 512 |
+
text_prompt_raws = batch["text_prompt_raws"]
|
| 513 |
+
text_prompt_embeds = batch["text_prompt_embeds"]
|
| 514 |
+
print(text_prompt_embeds.shape, text_prompt_raws)
|
| 515 |
+
|
| 516 |
+
if accelerator.process_index == 0:
|
| 517 |
+
# print info
|
| 518 |
+
print(f" Step {step}:")
|
| 519 |
+
print(f" Batch {i}:")
|
| 520 |
+
print(f" Batch size: {len(gan_uttid)}")
|
| 521 |
+
print(f" Uttids: {gan_uttid}, {ode_uttid}, {text_uttid}")
|
| 522 |
+
print(
|
| 523 |
+
f" Data Name: {batch['gan_dataset_name']}, {batch['ode_dataset_name']}, {batch['text_dataset_name']}"
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
for dataset_name in batch["gan_dataset_name"]:
|
| 527 |
+
dataset_counts[dataset_name] += 1
|
| 528 |
+
|
| 529 |
+
step += 1
|
| 530 |
+
|
| 531 |
+
print("实际采样统计:", dict(dataset_counts))
|
Helios/_DEV2/helios/dataset/dataloader_history_latents_dist.py
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import random
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
from torch.utils.data import Dataset, Sampler
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BucketedFeatureDataset(Dataset):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
feature_folders,
|
| 15 |
+
history_sizes=[16, 2, 1],
|
| 16 |
+
is_keep_x0=True,
|
| 17 |
+
force_rebuild=False,
|
| 18 |
+
return_all_vae_latent=False,
|
| 19 |
+
return_prompt_raw=False,
|
| 20 |
+
num_rollout_sections=3,
|
| 21 |
+
single_res=False,
|
| 22 |
+
single_height=384,
|
| 23 |
+
single_width=640,
|
| 24 |
+
seed=42,
|
| 25 |
+
):
|
| 26 |
+
self.history_sizes = history_sizes
|
| 27 |
+
self.is_keep_x0 = is_keep_x0
|
| 28 |
+
self.force_rebuild = force_rebuild
|
| 29 |
+
self.return_all_vae_latent = return_all_vae_latent
|
| 30 |
+
self.return_prompt_raw = return_prompt_raw
|
| 31 |
+
self.num_rollout_sections = num_rollout_sections
|
| 32 |
+
self.single_res = single_res
|
| 33 |
+
self.single_height = single_height
|
| 34 |
+
self.single_width = single_width
|
| 35 |
+
assert self.is_keep_x0, "is_keep_x0 need to be True now!"
|
| 36 |
+
|
| 37 |
+
self.base_seed = seed
|
| 38 |
+
self._epoch = 0
|
| 39 |
+
|
| 40 |
+
if isinstance(feature_folders, str):
|
| 41 |
+
self.feature_folders = [feature_folders]
|
| 42 |
+
else:
|
| 43 |
+
self.feature_folders = feature_folders
|
| 44 |
+
|
| 45 |
+
self.samples = []
|
| 46 |
+
self.buckets = defaultdict(list)
|
| 47 |
+
|
| 48 |
+
for folder in self.feature_folders:
|
| 49 |
+
cache_file = os.path.join(folder, "dataset_cache.pkl")
|
| 50 |
+
self._process_folder(folder, cache_file)
|
| 51 |
+
|
| 52 |
+
def _process_folder(self, folder, cache_file):
|
| 53 |
+
if self.force_rebuild or not os.path.exists(cache_file):
|
| 54 |
+
print(f"Building metadata cache for folder: {folder}")
|
| 55 |
+
folder_samples, folder_buckets = self._build_folder_metadata(folder)
|
| 56 |
+
|
| 57 |
+
print(f"Saving metadata cache for folder: {folder}")
|
| 58 |
+
cached_data = {"samples": folder_samples, "buckets": folder_buckets}
|
| 59 |
+
if not self.force_rebuild:
|
| 60 |
+
with open(cache_file, "wb") as f:
|
| 61 |
+
pickle.dump(cached_data, f)
|
| 62 |
+
print(f"Cached {len(folder_samples)} samples from {folder}\n")
|
| 63 |
+
else:
|
| 64 |
+
print(f"Loading cached metadata from: {folder}")
|
| 65 |
+
with open(cache_file, "rb") as f:
|
| 66 |
+
cached_data = pickle.load(f)
|
| 67 |
+
folder_samples = cached_data["samples"]
|
| 68 |
+
folder_buckets = cached_data["buckets"]
|
| 69 |
+
print(f"Loaded {len(folder_samples)} samples from cache: {folder}\n")
|
| 70 |
+
|
| 71 |
+
sample_idx_offset = len(self.samples)
|
| 72 |
+
self.samples.extend(folder_samples)
|
| 73 |
+
|
| 74 |
+
for bucket_key, indices in folder_buckets.items():
|
| 75 |
+
adjusted_indices = [idx + sample_idx_offset for idx in indices]
|
| 76 |
+
self.buckets[bucket_key].extend(adjusted_indices)
|
| 77 |
+
|
| 78 |
+
def _build_folder_metadata(self, folder):
|
| 79 |
+
feature_files = [f for f in os.listdir(folder) if f.endswith(".pt")]
|
| 80 |
+
samples = []
|
| 81 |
+
buckets = defaultdict(list)
|
| 82 |
+
sample_idx = 0
|
| 83 |
+
|
| 84 |
+
print(f"Processing {len(feature_files)} files in {folder}...")
|
| 85 |
+
|
| 86 |
+
for i, feature_file in enumerate(feature_files):
|
| 87 |
+
if i % 10000 == 0:
|
| 88 |
+
print(f" Processed {i}/{len(feature_files)} files")
|
| 89 |
+
|
| 90 |
+
feature_path = os.path.join(folder, feature_file)
|
| 91 |
+
|
| 92 |
+
# Parse filename
|
| 93 |
+
parts = feature_file.split("_")
|
| 94 |
+
uttid = "_".join(parts[:-3])
|
| 95 |
+
num_frame = int(parts[-3])
|
| 96 |
+
height = int(parts[-2])
|
| 97 |
+
width = int(parts[-1].replace(".pt", ""))
|
| 98 |
+
|
| 99 |
+
# keep length >= 121
|
| 100 |
+
if num_frame < 121:
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
# keep resolution
|
| 104 |
+
allowed_resolutions = [
|
| 105 |
+
(self.single_height, self.single_width),
|
| 106 |
+
(self.single_height // 2, self.single_width // 2),
|
| 107 |
+
(self.single_height // 4, self.single_width // 4),
|
| 108 |
+
]
|
| 109 |
+
if self.single_res and (height, width) not in allowed_resolutions:
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
bucket_key = (num_frame, height, width)
|
| 113 |
+
|
| 114 |
+
sample_info = {
|
| 115 |
+
"uttid": uttid,
|
| 116 |
+
"dataset_name": folder.rstrip("/"),
|
| 117 |
+
"file_path": feature_path,
|
| 118 |
+
"bucket_key": bucket_key,
|
| 119 |
+
"num_frame": num_frame,
|
| 120 |
+
"height": height,
|
| 121 |
+
"width": width,
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
samples.append(sample_info)
|
| 125 |
+
buckets[bucket_key].append(sample_idx)
|
| 126 |
+
sample_idx += 1
|
| 127 |
+
|
| 128 |
+
return samples, buckets
|
| 129 |
+
|
| 130 |
+
def set_epoch(self, epoch):
|
| 131 |
+
self._epoch = epoch
|
| 132 |
+
|
| 133 |
+
def prepare_stage1_latent(self, vae_latent, idx, base_vae_latent=None):
|
| 134 |
+
source_latent = base_vae_latent if base_vae_latent is not None else vae_latent
|
| 135 |
+
|
| 136 |
+
x0_latent = None
|
| 137 |
+
if self.is_keep_x0:
|
| 138 |
+
x0_latent = source_latent[0, :, :1, :, :].clone()
|
| 139 |
+
total_sections = source_latent.shape[0]
|
| 140 |
+
latent_window_size = source_latent.shape[2]
|
| 141 |
+
history_window_size = sum(self.history_sizes)
|
| 142 |
+
section_size = history_window_size + latent_window_size
|
| 143 |
+
|
| 144 |
+
temp_source_latent = rearrange(source_latent, "b c t h w -> c (b t) h w")
|
| 145 |
+
zero_padding_source = torch.zeros(
|
| 146 |
+
temp_source_latent.shape[0],
|
| 147 |
+
history_window_size,
|
| 148 |
+
temp_source_latent.shape[2],
|
| 149 |
+
temp_source_latent.shape[3],
|
| 150 |
+
device=temp_source_latent.device,
|
| 151 |
+
dtype=temp_source_latent.dtype,
|
| 152 |
+
)
|
| 153 |
+
continue_source_latent = torch.cat([zero_padding_source, temp_source_latent], dim=1)
|
| 154 |
+
|
| 155 |
+
temp_vae_latent = rearrange(vae_latent, "b c t h w -> c (b t) h w")
|
| 156 |
+
zero_padding_vae = torch.zeros(
|
| 157 |
+
temp_vae_latent.shape[0],
|
| 158 |
+
history_window_size,
|
| 159 |
+
temp_vae_latent.shape[2],
|
| 160 |
+
temp_vae_latent.shape[3],
|
| 161 |
+
device=temp_vae_latent.device,
|
| 162 |
+
dtype=temp_vae_latent.dtype,
|
| 163 |
+
)
|
| 164 |
+
continue_vae_latent = torch.cat([zero_padding_vae, temp_vae_latent], dim=1)
|
| 165 |
+
|
| 166 |
+
sample_seed = self.base_seed + self._epoch * 1000000 + idx
|
| 167 |
+
choice_idx = torch.randint(
|
| 168 |
+
0, total_sections, (1,), generator=torch.Generator().manual_seed(sample_seed)
|
| 169 |
+
).item()
|
| 170 |
+
if choice_idx == 0 and x0_latent is not None:
|
| 171 |
+
x0_latent = torch.zeros_like(x0_latent)
|
| 172 |
+
|
| 173 |
+
clean_all_vae_latent = None
|
| 174 |
+
if self.return_all_vae_latent:
|
| 175 |
+
max_start_idx = total_sections - self.num_rollout_sections
|
| 176 |
+
if max_start_idx < 0:
|
| 177 |
+
raise ValueError(
|
| 178 |
+
f"Not enough sections: total_sections={total_sections}, num_rollout_sections={self.num_rollout_sections}"
|
| 179 |
+
)
|
| 180 |
+
start_section_idx = random.randint(0, max_start_idx)
|
| 181 |
+
start_indice = start_section_idx * latent_window_size
|
| 182 |
+
end_indice = start_indice + history_window_size + self.num_rollout_sections * latent_window_size
|
| 183 |
+
clean_all_vae_latent = continue_source_latent[:, start_indice:end_indice, :, :]
|
| 184 |
+
|
| 185 |
+
start_indice = choice_idx * latent_window_size
|
| 186 |
+
end_indice = start_indice + section_size
|
| 187 |
+
|
| 188 |
+
history_latent = continue_source_latent[:, start_indice : start_indice + history_window_size, :, :]
|
| 189 |
+
target_latent = continue_vae_latent[:, start_indice + history_window_size : end_indice, :, :]
|
| 190 |
+
|
| 191 |
+
return x0_latent, history_latent, target_latent, clean_all_vae_latent
|
| 192 |
+
|
| 193 |
+
def __len__(self):
|
| 194 |
+
return len(self.samples)
|
| 195 |
+
|
| 196 |
+
def __getitem__(self, idx):
|
| 197 |
+
anchor_f = self.samples[idx]["num_frame"]
|
| 198 |
+
anchor_h = self.samples[idx]["height"]
|
| 199 |
+
anchor_w = self.samples[idx]["width"]
|
| 200 |
+
while True:
|
| 201 |
+
sample_info = self.samples[idx]
|
| 202 |
+
|
| 203 |
+
if (
|
| 204 |
+
anchor_f != sample_info["num_frame"]
|
| 205 |
+
or anchor_h != sample_info["height"]
|
| 206 |
+
or anchor_w != sample_info["width"]
|
| 207 |
+
):
|
| 208 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 209 |
+
print("Try to find a same dim sample, retrying...")
|
| 210 |
+
continue
|
| 211 |
+
|
| 212 |
+
try:
|
| 213 |
+
base_vae_latent = None
|
| 214 |
+
if (anchor_h, anchor_w) in [
|
| 215 |
+
(self.single_height // 2, self.single_width // 2),
|
| 216 |
+
(self.single_height // 4, self.single_width // 4),
|
| 217 |
+
]:
|
| 218 |
+
base_file_path = (
|
| 219 |
+
sample_info["file_path"]
|
| 220 |
+
.replace("/mid", "")
|
| 221 |
+
.replace("/low", "")
|
| 222 |
+
.replace(
|
| 223 |
+
f"{self.single_height // 2}_{self.single_width // 2}",
|
| 224 |
+
f"{self.single_height}_{self.single_width}",
|
| 225 |
+
)
|
| 226 |
+
.replace(
|
| 227 |
+
f"{self.single_height // 4}_{self.single_width // 4}",
|
| 228 |
+
f"{self.single_height}_{self.single_width}",
|
| 229 |
+
)
|
| 230 |
+
)
|
| 231 |
+
base_vae_latent = torch.load(base_file_path, map_location="cpu", weights_only=False)["vae_latent"]
|
| 232 |
+
|
| 233 |
+
feature_data = torch.load(sample_info["file_path"], map_location="cpu", weights_only=False)
|
| 234 |
+
x0_latent, history_latent, target_latent, clean_all_vae_latent = self.prepare_stage1_latent(
|
| 235 |
+
feature_data["vae_latent"], idx, base_vae_latent
|
| 236 |
+
)
|
| 237 |
+
if self.return_prompt_raw:
|
| 238 |
+
prompt_raws = feature_data["prompt_raw"]
|
| 239 |
+
break
|
| 240 |
+
except Exception:
|
| 241 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 242 |
+
print(f"Error loading {sample_info['file_path']}, retrying...")
|
| 243 |
+
file_name = os.path.basename(sample_info["file_path"])
|
| 244 |
+
txt_name = f"{file_name}.txt"
|
| 245 |
+
with open(txt_name, "w") as f:
|
| 246 |
+
f.write(sample_info["file_path"] + "\n")
|
| 247 |
+
|
| 248 |
+
output_dict = {
|
| 249 |
+
"uttid": sample_info["uttid"],
|
| 250 |
+
"bucket_key": sample_info["bucket_key"],
|
| 251 |
+
"dataset_name": sample_info["dataset_name"],
|
| 252 |
+
"num_frame": sample_info["num_frame"],
|
| 253 |
+
"height": sample_info["height"],
|
| 254 |
+
"width": sample_info["width"],
|
| 255 |
+
"x0_latents": x0_latent,
|
| 256 |
+
"history_latents": history_latent,
|
| 257 |
+
"target_latents": target_latent,
|
| 258 |
+
"clean_all_latents": clean_all_vae_latent,
|
| 259 |
+
"prompt_embeds": feature_data["prompt_embed"],
|
| 260 |
+
"prompt_attention_masks": feature_data.get("prompt_attention_mask", None),
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
if self.return_prompt_raw:
|
| 264 |
+
output_dict["prompt_raws"] = prompt_raws
|
| 265 |
+
|
| 266 |
+
return output_dict
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class BucketedSampler(Sampler):
|
| 270 |
+
def __init__(
|
| 271 |
+
self,
|
| 272 |
+
dataset,
|
| 273 |
+
batch_size,
|
| 274 |
+
drop_last=False,
|
| 275 |
+
shuffle=True,
|
| 276 |
+
seed=42,
|
| 277 |
+
dataset_sampling_ratios=None,
|
| 278 |
+
num_sp_groups=1,
|
| 279 |
+
sp_world_size=1,
|
| 280 |
+
global_rank=0,
|
| 281 |
+
):
|
| 282 |
+
self.dataset = dataset
|
| 283 |
+
self.batch_size = batch_size
|
| 284 |
+
self.drop_last = drop_last
|
| 285 |
+
self.shuffle = shuffle
|
| 286 |
+
self.seed = seed
|
| 287 |
+
self.generator = torch.Generator()
|
| 288 |
+
self.buckets = dataset.buckets
|
| 289 |
+
self._epoch = 0
|
| 290 |
+
|
| 291 |
+
# Distributed parameters
|
| 292 |
+
self.num_sp_groups = num_sp_groups
|
| 293 |
+
self.sp_world_size = sp_world_size
|
| 294 |
+
self.global_rank = global_rank
|
| 295 |
+
self.ith_sp_group = self.global_rank // self.sp_world_size
|
| 296 |
+
|
| 297 |
+
self.dataset_sampling_ratios = (
|
| 298 |
+
{key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()}
|
| 299 |
+
if dataset_sampling_ratios is not None
|
| 300 |
+
else {}
|
| 301 |
+
)
|
| 302 |
+
self._prepare_dataset_buckets()
|
| 303 |
+
|
| 304 |
+
def _prepare_dataset_buckets(self):
|
| 305 |
+
self.dataset_buckets = {}
|
| 306 |
+
|
| 307 |
+
for bucket_key, sample_indices in self.buckets.items():
|
| 308 |
+
dataset_groups = {}
|
| 309 |
+
for idx in sample_indices:
|
| 310 |
+
dataset_name = self.dataset.samples[idx]["dataset_name"]
|
| 311 |
+
if dataset_name not in dataset_groups:
|
| 312 |
+
dataset_groups[dataset_name] = []
|
| 313 |
+
dataset_groups[dataset_name].append(idx)
|
| 314 |
+
self.dataset_buckets[bucket_key] = dataset_groups
|
| 315 |
+
|
| 316 |
+
def set_epoch(self, epoch):
|
| 317 |
+
self._epoch = epoch
|
| 318 |
+
|
| 319 |
+
def _shard_indices_for_sp_group(self, indices):
|
| 320 |
+
"""
|
| 321 |
+
Shard indices across SP groups, similar to DP_SP_BatchSampler.
|
| 322 |
+
Each SP group gets a disjoint subset of the data.
|
| 323 |
+
"""
|
| 324 |
+
if self.num_sp_groups == 1:
|
| 325 |
+
return indices
|
| 326 |
+
|
| 327 |
+
# Convert to tensor if it's a list
|
| 328 |
+
if isinstance(indices, list):
|
| 329 |
+
indices_tensor = torch.tensor(indices, dtype=torch.long)
|
| 330 |
+
else:
|
| 331 |
+
indices_tensor = indices
|
| 332 |
+
|
| 333 |
+
# Pad indices if necessary to make it divisible by num_sp_groups
|
| 334 |
+
total_size = len(indices_tensor)
|
| 335 |
+
if total_size % self.num_sp_groups != 0:
|
| 336 |
+
if not self.drop_last:
|
| 337 |
+
padding_size = self.num_sp_groups - (total_size % self.num_sp_groups)
|
| 338 |
+
indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]])
|
| 339 |
+
else:
|
| 340 |
+
# If drop_last, truncate to be divisible
|
| 341 |
+
if self.drop_last:
|
| 342 |
+
truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups
|
| 343 |
+
indices_tensor = indices_tensor[:truncate_size]
|
| 344 |
+
|
| 345 |
+
# Shard: each SP group gets every num_sp_groups-th element
|
| 346 |
+
sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups]
|
| 347 |
+
|
| 348 |
+
return sp_group_indices.tolist()
|
| 349 |
+
|
| 350 |
+
def _apply_global_ratio_sampling(self):
|
| 351 |
+
if not self.dataset_sampling_ratios:
|
| 352 |
+
return
|
| 353 |
+
|
| 354 |
+
dataset_sample_map = {}
|
| 355 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 356 |
+
for dataset_name, indices in dataset_groups.items():
|
| 357 |
+
if dataset_name not in dataset_sample_map:
|
| 358 |
+
dataset_sample_map[dataset_name] = {"indices": [], "buckets": []}
|
| 359 |
+
dataset_sample_map[dataset_name]["indices"].extend(indices)
|
| 360 |
+
dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices))
|
| 361 |
+
|
| 362 |
+
total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values())
|
| 363 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 364 |
+
|
| 365 |
+
sampled_dataset_map = {}
|
| 366 |
+
for dataset_name, info in dataset_sample_map.items():
|
| 367 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 368 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 369 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 370 |
+
|
| 371 |
+
indices = info["indices"]
|
| 372 |
+
buckets = info["buckets"]
|
| 373 |
+
|
| 374 |
+
if len(indices) >= target_samples:
|
| 375 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist()
|
| 376 |
+
sampled_indices = [indices[i] for i in selected]
|
| 377 |
+
sampled_buckets = [buckets[i] for i in selected]
|
| 378 |
+
else:
|
| 379 |
+
sampled_indices = []
|
| 380 |
+
sampled_buckets = []
|
| 381 |
+
remaining = target_samples
|
| 382 |
+
|
| 383 |
+
while remaining > 0:
|
| 384 |
+
repeat_count = min(remaining, len(indices))
|
| 385 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist()
|
| 386 |
+
sampled_indices.extend([indices[i] for i in selected])
|
| 387 |
+
sampled_buckets.extend([buckets[i] for i in selected])
|
| 388 |
+
remaining -= repeat_count
|
| 389 |
+
|
| 390 |
+
sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets}
|
| 391 |
+
else:
|
| 392 |
+
sampled_dataset_map[dataset_name] = info
|
| 393 |
+
|
| 394 |
+
new_dataset_buckets = {}
|
| 395 |
+
for bucket_key in self.dataset_buckets.keys():
|
| 396 |
+
new_dataset_buckets[bucket_key] = {}
|
| 397 |
+
|
| 398 |
+
for dataset_name, info in sampled_dataset_map.items():
|
| 399 |
+
indices = info["indices"]
|
| 400 |
+
buckets = info["buckets"]
|
| 401 |
+
|
| 402 |
+
for idx, bucket_key in zip(indices, buckets):
|
| 403 |
+
if dataset_name not in new_dataset_buckets[bucket_key]:
|
| 404 |
+
new_dataset_buckets[bucket_key][dataset_name] = []
|
| 405 |
+
new_dataset_buckets[bucket_key][dataset_name].append(idx)
|
| 406 |
+
|
| 407 |
+
self.dataset_buckets = new_dataset_buckets
|
| 408 |
+
|
| 409 |
+
def __iter__(self):
|
| 410 |
+
# Use epoch-level seed for reproducibility
|
| 411 |
+
epoch_seed = self.seed + self._epoch
|
| 412 |
+
self.generator.manual_seed(epoch_seed)
|
| 413 |
+
|
| 414 |
+
if self.dataset_sampling_ratios:
|
| 415 |
+
self._apply_global_ratio_sampling()
|
| 416 |
+
|
| 417 |
+
bucket_iterators = {}
|
| 418 |
+
bucket_batches = {}
|
| 419 |
+
|
| 420 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 421 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 422 |
+
|
| 423 |
+
# Global shuffle before sharding (important for distributed consistency)
|
| 424 |
+
if self.shuffle:
|
| 425 |
+
perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist()
|
| 426 |
+
balanced_indices = [balanced_indices[i] for i in perm]
|
| 427 |
+
|
| 428 |
+
# Shard indices for this SP group
|
| 429 |
+
sp_group_indices = self._shard_indices_for_sp_group(balanced_indices)
|
| 430 |
+
|
| 431 |
+
batches = []
|
| 432 |
+
for i in range(0, len(sp_group_indices), self.batch_size):
|
| 433 |
+
batch = sp_group_indices[i : i + self.batch_size]
|
| 434 |
+
if len(batch) == self.batch_size or not self.drop_last:
|
| 435 |
+
batches.append(batch)
|
| 436 |
+
|
| 437 |
+
if batches:
|
| 438 |
+
bucket_batches[bucket_key] = batches
|
| 439 |
+
bucket_iterators[bucket_key] = iter(batches)
|
| 440 |
+
|
| 441 |
+
remaining_buckets = list(bucket_iterators.keys())
|
| 442 |
+
|
| 443 |
+
while remaining_buckets:
|
| 444 |
+
idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item()
|
| 445 |
+
bucket_key = remaining_buckets[idx]
|
| 446 |
+
bucket_iter = bucket_iterators[bucket_key]
|
| 447 |
+
|
| 448 |
+
try:
|
| 449 |
+
batch = next(bucket_iter)
|
| 450 |
+
yield batch
|
| 451 |
+
except StopIteration:
|
| 452 |
+
remaining_buckets.remove(bucket_key)
|
| 453 |
+
|
| 454 |
+
def _create_balanced_indices(self, dataset_groups):
|
| 455 |
+
return sum(dataset_groups.values(), [])
|
| 456 |
+
|
| 457 |
+
def _equal_sampling(self, dataset_groups):
|
| 458 |
+
all_indices = []
|
| 459 |
+
dataset_names = list(dataset_groups.keys())
|
| 460 |
+
|
| 461 |
+
if len(dataset_names) <= 1:
|
| 462 |
+
return sum(dataset_groups.values(), [])
|
| 463 |
+
|
| 464 |
+
min_samples = min(len(indices) for indices in dataset_groups.values())
|
| 465 |
+
|
| 466 |
+
for dataset_name, indices in dataset_groups.items():
|
| 467 |
+
if len(indices) > min_samples:
|
| 468 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist()
|
| 469 |
+
sampled_indices = [indices[i] for i in selected]
|
| 470 |
+
else:
|
| 471 |
+
sampled_indices = indices
|
| 472 |
+
all_indices.extend(sampled_indices)
|
| 473 |
+
|
| 474 |
+
return all_indices
|
| 475 |
+
|
| 476 |
+
def _ratio_sampling(self, dataset_groups):
|
| 477 |
+
return sum(dataset_groups.values(), [])
|
| 478 |
+
|
| 479 |
+
def __len__(self):
|
| 480 |
+
if self.dataset_sampling_ratios:
|
| 481 |
+
temp_generator = torch.Generator()
|
| 482 |
+
temp_generator.manual_seed(self.seed)
|
| 483 |
+
|
| 484 |
+
dataset_sample_map = {}
|
| 485 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 486 |
+
for dataset_name, indices in dataset_groups.items():
|
| 487 |
+
if dataset_name not in dataset_sample_map:
|
| 488 |
+
dataset_sample_map[dataset_name] = []
|
| 489 |
+
dataset_sample_map[dataset_name].extend(indices)
|
| 490 |
+
|
| 491 |
+
total_samples = sum(len(indices) for indices in dataset_sample_map.values())
|
| 492 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 493 |
+
|
| 494 |
+
sampled_total = 0
|
| 495 |
+
for dataset_name, indices in dataset_sample_map.items():
|
| 496 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 497 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 498 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 499 |
+
sampled_total += target_samples
|
| 500 |
+
else:
|
| 501 |
+
sampled_total += len(indices)
|
| 502 |
+
|
| 503 |
+
# Account for SP group sharding
|
| 504 |
+
sp_group_samples = sampled_total // self.num_sp_groups
|
| 505 |
+
if not self.drop_last and sampled_total % self.num_sp_groups != 0:
|
| 506 |
+
sp_group_samples += 1
|
| 507 |
+
|
| 508 |
+
total_batches = sp_group_samples // self.batch_size
|
| 509 |
+
if not self.drop_last and sp_group_samples % self.batch_size != 0:
|
| 510 |
+
total_batches += 1
|
| 511 |
+
return total_batches
|
| 512 |
+
else:
|
| 513 |
+
total_batches = 0
|
| 514 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 515 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 516 |
+
|
| 517 |
+
# Account for SP group sharding
|
| 518 |
+
sp_group_size = len(balanced_indices) // self.num_sp_groups
|
| 519 |
+
if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0:
|
| 520 |
+
sp_group_size += 1
|
| 521 |
+
|
| 522 |
+
num_batches = sp_group_size // self.batch_size
|
| 523 |
+
if not self.drop_last and sp_group_size % self.batch_size != 0:
|
| 524 |
+
num_batches += 1
|
| 525 |
+
total_batches += num_batches
|
| 526 |
+
return total_batches
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def collate_fn(batch):
|
| 530 |
+
return {
|
| 531 |
+
key: torch.stack([d[key] for d in batch])
|
| 532 |
+
if isinstance(batch[0][key], torch.Tensor)
|
| 533 |
+
else [d[key] for d in batch]
|
| 534 |
+
for key in batch[0]
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
if __name__ == "__main__":
|
| 539 |
+
import torch.distributed.checkpoint as dcp
|
| 540 |
+
from accelerate import Accelerator
|
| 541 |
+
from torchdata.stateful_dataloader import StatefulDataLoader
|
| 542 |
+
|
| 543 |
+
feature_folder = [
|
| 544 |
+
"demo_data/ultravideo-long",
|
| 545 |
+
]
|
| 546 |
+
dataloader_num_workers = 0
|
| 547 |
+
batch_size = 2
|
| 548 |
+
num_train_epochs = 2
|
| 549 |
+
seed = 0
|
| 550 |
+
output_dir = "accelerate_checkpoints"
|
| 551 |
+
checkpoint_dirs = (
|
| 552 |
+
[
|
| 553 |
+
d
|
| 554 |
+
for d in os.listdir(output_dir)
|
| 555 |
+
if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d))
|
| 556 |
+
]
|
| 557 |
+
if os.path.exists(output_dir)
|
| 558 |
+
else []
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
dataset_ratios = {}
|
| 562 |
+
# dataset_ratios = {
|
| 563 |
+
# "demo_data/ultravideo-long": 0.9,
|
| 564 |
+
# }
|
| 565 |
+
|
| 566 |
+
accelerator = Accelerator()
|
| 567 |
+
print(accelerator.process_index, accelerator.num_processes)
|
| 568 |
+
|
| 569 |
+
dataset = BucketedFeatureDataset(
|
| 570 |
+
feature_folder,
|
| 571 |
+
force_rebuild=True,
|
| 572 |
+
return_all_vae_latent=True,
|
| 573 |
+
return_prompt_raw=True,
|
| 574 |
+
single_res=True,
|
| 575 |
+
single_height=384,
|
| 576 |
+
single_width=640,
|
| 577 |
+
seed=seed,
|
| 578 |
+
)
|
| 579 |
+
sampler = BucketedSampler(
|
| 580 |
+
dataset,
|
| 581 |
+
batch_size=batch_size,
|
| 582 |
+
drop_last=True,
|
| 583 |
+
shuffle=True,
|
| 584 |
+
dataset_sampling_ratios=dataset_ratios,
|
| 585 |
+
seed=seed,
|
| 586 |
+
# num_sp_groups=get_world_size() // get_sp_world_size(),
|
| 587 |
+
# sp_world_size=get_sp_world_size(),
|
| 588 |
+
# global_rank=get_world_rank(),
|
| 589 |
+
num_sp_groups=accelerator.num_processes // 1,
|
| 590 |
+
sp_world_size=1,
|
| 591 |
+
global_rank=accelerator.process_index,
|
| 592 |
+
)
|
| 593 |
+
dataloader = StatefulDataLoader(
|
| 594 |
+
dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=dataloader_num_workers
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
print(len(dataset), len(dataloader))
|
| 598 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 599 |
+
|
| 600 |
+
step = 0
|
| 601 |
+
global_step = 0
|
| 602 |
+
first_epoch = 0
|
| 603 |
+
num_update_steps_per_epoch = len(dataloader)
|
| 604 |
+
if checkpoint_dirs:
|
| 605 |
+
latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1]))
|
| 606 |
+
checkpoint_path = os.path.join(output_dir, latest_checkpoint)
|
| 607 |
+
print(f"Found checkpoint: {checkpoint_path}")
|
| 608 |
+
|
| 609 |
+
accelerator.load_state(checkpoint_path)
|
| 610 |
+
global_step = int(latest_checkpoint.split("-")[1])
|
| 611 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 612 |
+
|
| 613 |
+
states = {
|
| 614 |
+
"dataloader": dataloader,
|
| 615 |
+
}
|
| 616 |
+
dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint")
|
| 617 |
+
dcp.load(states, checkpoint_id=dcp_dir)
|
| 618 |
+
|
| 619 |
+
print(f"Resuming from step {global_step}, epoch {first_epoch}")
|
| 620 |
+
|
| 621 |
+
print("Testing dataloader...")
|
| 622 |
+
step = global_step
|
| 623 |
+
dataset_counts = defaultdict(int)
|
| 624 |
+
for epoch in range(first_epoch, num_train_epochs):
|
| 625 |
+
sampler.set_epoch(epoch)
|
| 626 |
+
dataset.set_epoch(epoch)
|
| 627 |
+
for i, batch in enumerate(dataloader):
|
| 628 |
+
# Get metadata
|
| 629 |
+
uttid = batch["uttid"]
|
| 630 |
+
num_frame = batch["num_frame"]
|
| 631 |
+
height = batch["height"]
|
| 632 |
+
width = batch["width"]
|
| 633 |
+
bucket_key = batch["bucket_key"]
|
| 634 |
+
|
| 635 |
+
# Get feature
|
| 636 |
+
x0_latents = batch["x0_latents"]
|
| 637 |
+
history_latents = batch["history_latents"]
|
| 638 |
+
target_latents = batch["target_latents"]
|
| 639 |
+
prompt_embeds = batch["prompt_embeds"]
|
| 640 |
+
|
| 641 |
+
if accelerator.process_index == 0:
|
| 642 |
+
# print info
|
| 643 |
+
print(f" Step {step}:")
|
| 644 |
+
print(f" Batch {i}:")
|
| 645 |
+
# print(f" Data Name: {batch['dataset_name']}")
|
| 646 |
+
print(f" Batch size: {len(uttid)}")
|
| 647 |
+
print(f" Uttids: {uttid}")
|
| 648 |
+
print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}")
|
| 649 |
+
print(f" Bucket key: {bucket_key[0]}")
|
| 650 |
+
print(f" X0 latent shape: {x0_latents.shape}")
|
| 651 |
+
print(f" History latent shape: {history_latents.shape}")
|
| 652 |
+
print(f" Context latent shape: {target_latents.shape}")
|
| 653 |
+
print(f" Prompt embed shape: {prompt_embeds.shape}")
|
| 654 |
+
# print(f" Prompt attention mask shape: {prompt_attention_masks.shape}")
|
| 655 |
+
|
| 656 |
+
# verify
|
| 657 |
+
assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch"
|
| 658 |
+
assert all(h == height[0] for h in height), "Heights not consistent in batch"
|
| 659 |
+
assert all(w == width[0] for w in width), "Widths not consistent in batch"
|
| 660 |
+
|
| 661 |
+
print(" ✓ Batch dimensions are consistent")
|
| 662 |
+
|
| 663 |
+
for dataset_name in batch["dataset_name"]:
|
| 664 |
+
dataset_counts[dataset_name] += 1
|
| 665 |
+
|
| 666 |
+
step += 1
|
| 667 |
+
|
| 668 |
+
# if step == 20:
|
| 669 |
+
# checkpoint_dir = f"checkpoint-{step}"
|
| 670 |
+
# save_path = os.path.join(output_dir, checkpoint_dir)
|
| 671 |
+
# os.makedirs(save_path, exist_ok=True)
|
| 672 |
+
|
| 673 |
+
# if accelerator.is_main_process:
|
| 674 |
+
# print(f"Saving checkpoint at step {step}")
|
| 675 |
+
|
| 676 |
+
# accelerator.save_state(save_path)
|
| 677 |
+
|
| 678 |
+
# print(accelerator.process_index, accelerator.num_processes)
|
| 679 |
+
# states = {
|
| 680 |
+
# "dataloader": dataloader,
|
| 681 |
+
# }
|
| 682 |
+
# dcp_dir = os.path.join(save_path, "distributed_checkpoint")
|
| 683 |
+
# dcp.save(states, checkpoint_id=dcp_dir)
|
| 684 |
+
|
| 685 |
+
print("实际采样统计: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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import pickle
|
| 4 |
+
import random
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
import torchvision
|
| 11 |
+
from torch.utils.data import Dataset, Sampler
|
| 12 |
+
from video_reader import PyVideoReader
|
| 13 |
+
|
| 14 |
+
from diffusers.training_utils import free_memory
|
| 15 |
+
from diffusers.utils import export_to_video
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
resolution_bucket_options = {
|
| 19 |
+
640: [
|
| 20 |
+
(768, 320),
|
| 21 |
+
(768, 384),
|
| 22 |
+
(640, 384),
|
| 23 |
+
(768, 512),
|
| 24 |
+
(576, 448),
|
| 25 |
+
(512, 512),
|
| 26 |
+
(448, 576),
|
| 27 |
+
(512, 768),
|
| 28 |
+
(384, 640),
|
| 29 |
+
(384, 768),
|
| 30 |
+
(320, 768),
|
| 31 |
+
],
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
length_bucket_options = {
|
| 35 |
+
1: [
|
| 36 |
+
501,
|
| 37 |
+
481,
|
| 38 |
+
461,
|
| 39 |
+
441,
|
| 40 |
+
421,
|
| 41 |
+
401,
|
| 42 |
+
381,
|
| 43 |
+
361,
|
| 44 |
+
341,
|
| 45 |
+
321,
|
| 46 |
+
301,
|
| 47 |
+
281,
|
| 48 |
+
261,
|
| 49 |
+
241,
|
| 50 |
+
221,
|
| 51 |
+
193,
|
| 52 |
+
181,
|
| 53 |
+
161,
|
| 54 |
+
141,
|
| 55 |
+
121,
|
| 56 |
+
101,
|
| 57 |
+
81,
|
| 58 |
+
61,
|
| 59 |
+
41,
|
| 60 |
+
21,
|
| 61 |
+
],
|
| 62 |
+
2: [193, 177, 161, 156, 145, 133, 129, 121, 113, 109, 97, 85, 81, 73, 65, 61, 49, 37, 25],
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def find_nearest_resolution_bucket(h, w, resolution=640):
|
| 67 |
+
min_metric = float("inf")
|
| 68 |
+
best_bucket = None
|
| 69 |
+
for bucket_h, bucket_w in resolution_bucket_options[resolution]:
|
| 70 |
+
metric = abs(h * bucket_w - w * bucket_h)
|
| 71 |
+
if metric <= min_metric:
|
| 72 |
+
min_metric = metric
|
| 73 |
+
best_bucket = (bucket_h, bucket_w)
|
| 74 |
+
return best_bucket
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def find_nearest_length_bucket(length, stride=1):
|
| 78 |
+
buckets = length_bucket_options[stride]
|
| 79 |
+
min_bucket = min(buckets)
|
| 80 |
+
if length < min_bucket:
|
| 81 |
+
return length
|
| 82 |
+
valid_buckets = [bucket for bucket in buckets if bucket <= length]
|
| 83 |
+
return max(valid_buckets)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def read_cut_crop_and_resize(
|
| 87 |
+
video_path, f_prime, h_prime, w_prime, stride=1, start_frame=None, end_frame=None, crop=None
|
| 88 |
+
):
|
| 89 |
+
frame_indices = list(range(start_frame, end_frame, stride))
|
| 90 |
+
assert len(frame_indices) == f_prime
|
| 91 |
+
|
| 92 |
+
vr = PyVideoReader(video_path, threads=0) # 0 means auto (let ffmpeg pick the optimal number)
|
| 93 |
+
frames = torch.from_numpy(vr.get_batch(frame_indices)).float()
|
| 94 |
+
|
| 95 |
+
frames = (frames / 127.5) - 1
|
| 96 |
+
video = frames.permute(0, 3, 1, 2)
|
| 97 |
+
|
| 98 |
+
s_x, e_x, s_y, e_y = crop
|
| 99 |
+
video = video[:, :, s_y:e_y, s_x:e_x]
|
| 100 |
+
|
| 101 |
+
frames, channels, h, w = video.shape
|
| 102 |
+
aspect_ratio_original = h / w
|
| 103 |
+
aspect_ratio_target = h_prime / w_prime
|
| 104 |
+
|
| 105 |
+
if aspect_ratio_original >= aspect_ratio_target:
|
| 106 |
+
new_h = int(w * aspect_ratio_target)
|
| 107 |
+
top = (h - new_h) // 2
|
| 108 |
+
bottom = top + new_h
|
| 109 |
+
left = 0
|
| 110 |
+
right = w
|
| 111 |
+
else:
|
| 112 |
+
new_w = int(h / aspect_ratio_target)
|
| 113 |
+
left = (w - new_w) // 2
|
| 114 |
+
right = left + new_w
|
| 115 |
+
top = 0
|
| 116 |
+
bottom = h
|
| 117 |
+
|
| 118 |
+
# Crop the video
|
| 119 |
+
cropped_video = video[:, :, top:bottom, left:right]
|
| 120 |
+
# Resize the cropped video
|
| 121 |
+
resized_video = torchvision.transforms.functional.resize(cropped_video, (h_prime, w_prime))
|
| 122 |
+
return resized_video
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def save_frames(frame_raw, fps=24, video_path="1.mp4"):
|
| 126 |
+
save_list = []
|
| 127 |
+
for frame in frame_raw:
|
| 128 |
+
frame = (frame + 1) / 2 * 255
|
| 129 |
+
frame = torchvision.transforms.transforms.ToPILImage()(frame.to(torch.uint8)).convert("RGB")
|
| 130 |
+
save_list.append(frame)
|
| 131 |
+
frame = None
|
| 132 |
+
del frame
|
| 133 |
+
export_to_video(save_list, video_path, fps=fps)
|
| 134 |
+
|
| 135 |
+
save_list = None
|
| 136 |
+
del save_list
|
| 137 |
+
free_memory()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class BucketedFeatureDataset(Dataset):
|
| 141 |
+
def __init__(
|
| 142 |
+
self,
|
| 143 |
+
json_files,
|
| 144 |
+
video_folders,
|
| 145 |
+
stride=1,
|
| 146 |
+
base_fps=None,
|
| 147 |
+
resolution=640,
|
| 148 |
+
force_rebuild=True,
|
| 149 |
+
single_res=False,
|
| 150 |
+
single_length=False,
|
| 151 |
+
single_num_frame=81,
|
| 152 |
+
single_height=384,
|
| 153 |
+
single_width=640,
|
| 154 |
+
multi_res=False,
|
| 155 |
+
id_token: Optional[str] = None,
|
| 156 |
+
):
|
| 157 |
+
self.stride = stride
|
| 158 |
+
self.base_fps = base_fps
|
| 159 |
+
self.resolution = resolution
|
| 160 |
+
self.force_rebuild = force_rebuild
|
| 161 |
+
self.single_res = single_res
|
| 162 |
+
self.single_height = single_height
|
| 163 |
+
self.single_width = single_width
|
| 164 |
+
self.single_length = single_length
|
| 165 |
+
self.single_num_frame = single_num_frame
|
| 166 |
+
self.multi_res = multi_res
|
| 167 |
+
self.id_token = id_token or ""
|
| 168 |
+
self._epoch = 0
|
| 169 |
+
|
| 170 |
+
if isinstance(json_files, str):
|
| 171 |
+
self.json_files = [json_files]
|
| 172 |
+
else:
|
| 173 |
+
self.json_files = json_files
|
| 174 |
+
|
| 175 |
+
if isinstance(video_folders, str):
|
| 176 |
+
self.video_folders = [video_folders]
|
| 177 |
+
else:
|
| 178 |
+
self.video_folders = video_folders
|
| 179 |
+
|
| 180 |
+
assert len(self.json_files) == len(self.video_folders), (
|
| 181 |
+
f"json_files ({len(self.json_files)}) and video_folders ({len(self.video_folders)}) must have the same length"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
self.samples = []
|
| 185 |
+
self.buckets = defaultdict(list)
|
| 186 |
+
|
| 187 |
+
for json_file, video_folder in zip(self.json_files, self.video_folders):
|
| 188 |
+
cache_file = json_file.replace(".json", "_cache.pkl").replace(".csv", "_cache.pkl")
|
| 189 |
+
self._process_json_file(json_file, video_folder, cache_file)
|
| 190 |
+
|
| 191 |
+
def _process_json_file(self, json_file, video_folder, cache_file):
|
| 192 |
+
if self.force_rebuild or not os.path.exists(cache_file):
|
| 193 |
+
if os.path.exists(cache_file):
|
| 194 |
+
print(f"Remove {cache_file}")
|
| 195 |
+
os.remove(cache_file)
|
| 196 |
+
print(f"Building metadata cache for file: {json_file}")
|
| 197 |
+
print(f" Video folder: {video_folder}")
|
| 198 |
+
file_samples, file_buckets = self._build_file_metadata(json_file, video_folder)
|
| 199 |
+
|
| 200 |
+
print(f"Saving metadata cache to: {cache_file}")
|
| 201 |
+
cached_data = {"samples": file_samples, "buckets": file_buckets}
|
| 202 |
+
with open(cache_file, "wb") as f:
|
| 203 |
+
pickle.dump(cached_data, f)
|
| 204 |
+
print(f"Cached {len(file_samples)} samples from {json_file}\n")
|
| 205 |
+
else:
|
| 206 |
+
print(f"Loading cached metadata from: {cache_file}")
|
| 207 |
+
with open(cache_file, "rb") as f:
|
| 208 |
+
cached_data = pickle.load(f)
|
| 209 |
+
file_samples = cached_data["samples"]
|
| 210 |
+
file_buckets = cached_data["buckets"]
|
| 211 |
+
print(f"Loaded {len(file_samples)} samples from cache: {cache_file}\n")
|
| 212 |
+
|
| 213 |
+
sample_idx_offset = len(self.samples)
|
| 214 |
+
self.samples.extend(file_samples)
|
| 215 |
+
|
| 216 |
+
for bucket_key, indices in file_buckets.items():
|
| 217 |
+
adjusted_indices = [idx + sample_idx_offset for idx in indices]
|
| 218 |
+
self.buckets[bucket_key].extend(adjusted_indices)
|
| 219 |
+
|
| 220 |
+
def _build_file_metadata(self, json_file, video_folder):
|
| 221 |
+
with open(json_file, "r") as f:
|
| 222 |
+
data = json.load(f)
|
| 223 |
+
|
| 224 |
+
print(f"Scanning video folder: {video_folder}")
|
| 225 |
+
existing_videos = set()
|
| 226 |
+
for root, dirs, files in os.walk(video_folder):
|
| 227 |
+
for file in files:
|
| 228 |
+
if file.endswith(".mp4"):
|
| 229 |
+
rel_path = os.path.relpath(os.path.join(root, file), video_folder)
|
| 230 |
+
existing_videos.add(rel_path)
|
| 231 |
+
print(f"Found {len(existing_videos)} video files")
|
| 232 |
+
|
| 233 |
+
df = pd.DataFrame(
|
| 234 |
+
[
|
| 235 |
+
{
|
| 236 |
+
"cut": item["cut"],
|
| 237 |
+
"crop": item["crop"],
|
| 238 |
+
"path": item["path"],
|
| 239 |
+
"num_frames": item["num_frames"],
|
| 240 |
+
"width": item["resolution"]["width"],
|
| 241 |
+
"height": item["resolution"]["height"],
|
| 242 |
+
"fps": item["fps"],
|
| 243 |
+
"cap": item["cap"],
|
| 244 |
+
}
|
| 245 |
+
for item in data
|
| 246 |
+
]
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
samples = []
|
| 250 |
+
buckets = defaultdict(list)
|
| 251 |
+
sample_idx = 0
|
| 252 |
+
|
| 253 |
+
print(f"Processing {len(df)} records from {json_file} with stride={self.stride}...")
|
| 254 |
+
for i, row in df.iterrows():
|
| 255 |
+
if i % 10000 == 0:
|
| 256 |
+
print(f" Processed {i}/{len(df)} records")
|
| 257 |
+
|
| 258 |
+
video_file = (
|
| 259 |
+
row["path"]
|
| 260 |
+
.replace("videos_clip_v1_20241111/", "")
|
| 261 |
+
.replace("videos_clip_v2_20241111/", "")
|
| 262 |
+
.replace("videos_clip_v4_20241111/", "")
|
| 263 |
+
)
|
| 264 |
+
if video_file not in existing_videos:
|
| 265 |
+
print("bad video!")
|
| 266 |
+
continue
|
| 267 |
+
video_path = os.path.join(video_folder, video_file)
|
| 268 |
+
|
| 269 |
+
cut_start_frame = row["cut"][0]
|
| 270 |
+
cut_end_frame = row["cut"][1]
|
| 271 |
+
num_frame = cut_end_frame - cut_start_frame
|
| 272 |
+
|
| 273 |
+
if self.single_length:
|
| 274 |
+
if num_frame < self.single_num_frame:
|
| 275 |
+
continue
|
| 276 |
+
else:
|
| 277 |
+
if num_frame < 121:
|
| 278 |
+
continue
|
| 279 |
+
|
| 280 |
+
uttid = os.path.basename(video_file).replace(".mp4", "") + f"_{cut_start_frame}-{cut_end_frame}"
|
| 281 |
+
fps = row["fps"]
|
| 282 |
+
|
| 283 |
+
crop = row["crop"]
|
| 284 |
+
width = crop[1] - crop[0]
|
| 285 |
+
height = crop[3] - crop[2]
|
| 286 |
+
|
| 287 |
+
prompt = row["cap"][0]
|
| 288 |
+
|
| 289 |
+
# TODO need to be checked
|
| 290 |
+
effective_num_frame = (num_frame + self.stride - 1) // self.stride
|
| 291 |
+
bucket_num_frame = find_nearest_length_bucket(effective_num_frame, stride=self.stride)
|
| 292 |
+
bucket_height, bucket_width = find_nearest_resolution_bucket(height, width, resolution=self.resolution)
|
| 293 |
+
|
| 294 |
+
if self.single_res or self.multi_res:
|
| 295 |
+
allowed_resolutions = [(self.single_height, self.single_width)]
|
| 296 |
+
if self.multi_res:
|
| 297 |
+
allowed_resolutions.extend(
|
| 298 |
+
[
|
| 299 |
+
(self.single_height // 2, self.single_width // 2),
|
| 300 |
+
(self.single_height // 4, self.single_width // 4),
|
| 301 |
+
]
|
| 302 |
+
)
|
| 303 |
+
if (bucket_height, bucket_width) not in allowed_resolutions:
|
| 304 |
+
print("continue res")
|
| 305 |
+
continue
|
| 306 |
+
bucket_height, bucket_width = random.choice(allowed_resolutions)
|
| 307 |
+
|
| 308 |
+
if self.single_length:
|
| 309 |
+
bucket_num_frame = self.single_num_frame
|
| 310 |
+
|
| 311 |
+
if self.base_fps is not None:
|
| 312 |
+
stride = max(int(fps / self.base_fps), 1)
|
| 313 |
+
required_frames = bucket_num_frame * stride
|
| 314 |
+
if required_frames >= num_frame:
|
| 315 |
+
print("continue frame")
|
| 316 |
+
continue
|
| 317 |
+
else:
|
| 318 |
+
stride = self.stride
|
| 319 |
+
|
| 320 |
+
bucket_key = (bucket_num_frame, bucket_height, bucket_width)
|
| 321 |
+
|
| 322 |
+
sample_info = {
|
| 323 |
+
"uttid": uttid,
|
| 324 |
+
"dataset_name": json_file.rstrip("/"),
|
| 325 |
+
"video_folder": video_folder,
|
| 326 |
+
"video_path": video_path,
|
| 327 |
+
"bucket_key": bucket_key,
|
| 328 |
+
"prompt": self.id_token + prompt,
|
| 329 |
+
"fps": fps,
|
| 330 |
+
"stride": stride,
|
| 331 |
+
"effective_num_frame": effective_num_frame,
|
| 332 |
+
"num_frame": num_frame,
|
| 333 |
+
"height": height,
|
| 334 |
+
"width": width,
|
| 335 |
+
"bucket_num_frame": bucket_num_frame,
|
| 336 |
+
"bucket_height": bucket_height,
|
| 337 |
+
"bucket_width": bucket_width,
|
| 338 |
+
"cut_start_frame": cut_start_frame,
|
| 339 |
+
"cut_end_frame": cut_end_frame,
|
| 340 |
+
"crop": crop,
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
samples.append(sample_info)
|
| 344 |
+
buckets[bucket_key].append(sample_idx)
|
| 345 |
+
sample_idx += 1
|
| 346 |
+
|
| 347 |
+
return samples, buckets
|
| 348 |
+
|
| 349 |
+
def set_epoch(self, epoch):
|
| 350 |
+
self._epoch = epoch
|
| 351 |
+
|
| 352 |
+
def __len__(self):
|
| 353 |
+
return len(self.samples)
|
| 354 |
+
|
| 355 |
+
def __getitem__(self, idx):
|
| 356 |
+
anchor_h = self.samples[idx]["bucket_height"]
|
| 357 |
+
anchor_w = self.samples[idx]["bucket_width"]
|
| 358 |
+
anchor_f = self.samples[idx]["bucket_num_frame"]
|
| 359 |
+
|
| 360 |
+
max_retries = 1000
|
| 361 |
+
retry_count = 0
|
| 362 |
+
|
| 363 |
+
while retry_count < max_retries:
|
| 364 |
+
sample_info = self.samples[idx]
|
| 365 |
+
|
| 366 |
+
if (
|
| 367 |
+
anchor_h != sample_info["bucket_height"]
|
| 368 |
+
or anchor_w != sample_info["bucket_width"]
|
| 369 |
+
or anchor_f != sample_info["bucket_num_frame"]
|
| 370 |
+
):
|
| 371 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 372 |
+
retry_count += 1
|
| 373 |
+
continue
|
| 374 |
+
|
| 375 |
+
try:
|
| 376 |
+
stride = sample_info["stride"]
|
| 377 |
+
cut_start_frame = sample_info["cut_start_frame"]
|
| 378 |
+
cut_end_frame = sample_info["cut_end_frame"]
|
| 379 |
+
bucket_num_frame = sample_info["bucket_num_frame"]
|
| 380 |
+
|
| 381 |
+
max_start_frame = cut_end_frame - bucket_num_frame * stride
|
| 382 |
+
if max_start_frame < cut_start_frame:
|
| 383 |
+
start_frame = cut_start_frame
|
| 384 |
+
else:
|
| 385 |
+
start_frame = random.randint(cut_start_frame, max_start_frame)
|
| 386 |
+
end_frame = start_frame + bucket_num_frame * stride
|
| 387 |
+
|
| 388 |
+
video_data = read_cut_crop_and_resize(
|
| 389 |
+
video_path=sample_info["video_path"],
|
| 390 |
+
f_prime=sample_info["bucket_num_frame"],
|
| 391 |
+
h_prime=sample_info["bucket_height"],
|
| 392 |
+
w_prime=sample_info["bucket_width"],
|
| 393 |
+
stride=stride,
|
| 394 |
+
start_frame=start_frame,
|
| 395 |
+
end_frame=end_frame,
|
| 396 |
+
crop=sample_info["crop"],
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
return {
|
| 400 |
+
"uttid": sample_info["uttid"],
|
| 401 |
+
"bucket_key": sample_info["bucket_key"],
|
| 402 |
+
"dataset_name": sample_info["dataset_name"],
|
| 403 |
+
"video_metadata": {
|
| 404 |
+
"num_frames": sample_info["bucket_num_frame"],
|
| 405 |
+
"height": sample_info["bucket_height"],
|
| 406 |
+
"width": sample_info["bucket_width"],
|
| 407 |
+
"fps": sample_info["fps"],
|
| 408 |
+
"stride": stride,
|
| 409 |
+
"effective_num_frame": sample_info["effective_num_frame"],
|
| 410 |
+
},
|
| 411 |
+
"videos": video_data,
|
| 412 |
+
"prompts": sample_info["prompt"],
|
| 413 |
+
"first_frames_images": (video_data[0] + 1) / 2 * 255,
|
| 414 |
+
}
|
| 415 |
+
except Exception as e:
|
| 416 |
+
print(f"Error loading {sample_info['video_path']}: {e}")
|
| 417 |
+
idx = random.randint(0, len(self.samples) - 1)
|
| 418 |
+
retry_count += 1
|
| 419 |
+
|
| 420 |
+
print(f"Failed to load sample after {max_retries} retries, returning None")
|
| 421 |
+
return None
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class BucketedSampler(Sampler):
|
| 425 |
+
def __init__(
|
| 426 |
+
self,
|
| 427 |
+
dataset,
|
| 428 |
+
batch_size,
|
| 429 |
+
drop_last=False,
|
| 430 |
+
shuffle=True,
|
| 431 |
+
seed=42,
|
| 432 |
+
dataset_sampling_ratios=None,
|
| 433 |
+
num_sp_groups=1,
|
| 434 |
+
sp_world_size=1,
|
| 435 |
+
global_rank=0,
|
| 436 |
+
):
|
| 437 |
+
self.dataset = dataset
|
| 438 |
+
self.batch_size = batch_size
|
| 439 |
+
self.drop_last = drop_last
|
| 440 |
+
self.shuffle = shuffle
|
| 441 |
+
self.seed = seed
|
| 442 |
+
self.generator = torch.Generator()
|
| 443 |
+
self.buckets = dataset.buckets
|
| 444 |
+
self._epoch = 0
|
| 445 |
+
|
| 446 |
+
# Distributed parameters
|
| 447 |
+
self.num_sp_groups = num_sp_groups
|
| 448 |
+
self.sp_world_size = sp_world_size
|
| 449 |
+
self.global_rank = global_rank
|
| 450 |
+
self.ith_sp_group = self.global_rank // self.sp_world_size
|
| 451 |
+
|
| 452 |
+
self.dataset_sampling_ratios = (
|
| 453 |
+
{key.rstrip("/"): value for key, value in dataset_sampling_ratios.items()}
|
| 454 |
+
if dataset_sampling_ratios is not None
|
| 455 |
+
else {}
|
| 456 |
+
)
|
| 457 |
+
self._prepare_dataset_buckets()
|
| 458 |
+
|
| 459 |
+
def _prepare_dataset_buckets(self):
|
| 460 |
+
self.dataset_buckets = {}
|
| 461 |
+
|
| 462 |
+
for bucket_key, sample_indices in self.buckets.items():
|
| 463 |
+
dataset_groups = {}
|
| 464 |
+
for idx in sample_indices:
|
| 465 |
+
dataset_name = self.dataset.samples[idx]["dataset_name"]
|
| 466 |
+
if dataset_name not in dataset_groups:
|
| 467 |
+
dataset_groups[dataset_name] = []
|
| 468 |
+
dataset_groups[dataset_name].append(idx)
|
| 469 |
+
self.dataset_buckets[bucket_key] = dataset_groups
|
| 470 |
+
|
| 471 |
+
def set_epoch(self, epoch):
|
| 472 |
+
self._epoch = epoch
|
| 473 |
+
|
| 474 |
+
def _shard_indices_for_sp_group(self, indices):
|
| 475 |
+
"""
|
| 476 |
+
Shard indices across SP groups, similar to DP_SP_BatchSampler.
|
| 477 |
+
Each SP group gets a disjoint subset of the data.
|
| 478 |
+
"""
|
| 479 |
+
if self.num_sp_groups == 1:
|
| 480 |
+
return indices
|
| 481 |
+
|
| 482 |
+
# Convert to tensor if it's a list
|
| 483 |
+
if isinstance(indices, list):
|
| 484 |
+
indices_tensor = torch.tensor(indices, dtype=torch.long)
|
| 485 |
+
else:
|
| 486 |
+
indices_tensor = indices
|
| 487 |
+
|
| 488 |
+
# Pad indices if necessary to make it divisible by num_sp_groups
|
| 489 |
+
total_size = len(indices_tensor)
|
| 490 |
+
if total_size % self.num_sp_groups != 0:
|
| 491 |
+
if not self.drop_last:
|
| 492 |
+
padding_size = self.num_sp_groups - (total_size % self.num_sp_groups)
|
| 493 |
+
indices_tensor = torch.cat([indices_tensor, indices_tensor[:padding_size]])
|
| 494 |
+
else:
|
| 495 |
+
# If drop_last, truncate to be divisible
|
| 496 |
+
if self.drop_last:
|
| 497 |
+
truncate_size = (total_size // self.num_sp_groups) * self.num_sp_groups
|
| 498 |
+
indices_tensor = indices_tensor[:truncate_size]
|
| 499 |
+
|
| 500 |
+
# Shard: each SP group gets every num_sp_groups-th element
|
| 501 |
+
sp_group_indices = indices_tensor[self.ith_sp_group :: self.num_sp_groups]
|
| 502 |
+
|
| 503 |
+
return sp_group_indices.tolist()
|
| 504 |
+
|
| 505 |
+
def _apply_global_ratio_sampling(self):
|
| 506 |
+
if not self.dataset_sampling_ratios:
|
| 507 |
+
return
|
| 508 |
+
|
| 509 |
+
dataset_sample_map = {}
|
| 510 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 511 |
+
for dataset_name, indices in dataset_groups.items():
|
| 512 |
+
if dataset_name not in dataset_sample_map:
|
| 513 |
+
dataset_sample_map[dataset_name] = {"indices": [], "buckets": []}
|
| 514 |
+
dataset_sample_map[dataset_name]["indices"].extend(indices)
|
| 515 |
+
dataset_sample_map[dataset_name]["buckets"].extend([bucket_key] * len(indices))
|
| 516 |
+
|
| 517 |
+
total_samples = sum(len(info["indices"]) for info in dataset_sample_map.values())
|
| 518 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 519 |
+
|
| 520 |
+
sampled_dataset_map = {}
|
| 521 |
+
for dataset_name, info in dataset_sample_map.items():
|
| 522 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 523 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 524 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 525 |
+
|
| 526 |
+
indices = info["indices"]
|
| 527 |
+
buckets = info["buckets"]
|
| 528 |
+
|
| 529 |
+
if len(indices) >= target_samples:
|
| 530 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:target_samples].tolist()
|
| 531 |
+
sampled_indices = [indices[i] for i in selected]
|
| 532 |
+
sampled_buckets = [buckets[i] for i in selected]
|
| 533 |
+
else:
|
| 534 |
+
sampled_indices = []
|
| 535 |
+
sampled_buckets = []
|
| 536 |
+
remaining = target_samples
|
| 537 |
+
|
| 538 |
+
while remaining > 0:
|
| 539 |
+
repeat_count = min(remaining, len(indices))
|
| 540 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:repeat_count].tolist()
|
| 541 |
+
sampled_indices.extend([indices[i] for i in selected])
|
| 542 |
+
sampled_buckets.extend([buckets[i] for i in selected])
|
| 543 |
+
remaining -= repeat_count
|
| 544 |
+
|
| 545 |
+
sampled_dataset_map[dataset_name] = {"indices": sampled_indices, "buckets": sampled_buckets}
|
| 546 |
+
else:
|
| 547 |
+
sampled_dataset_map[dataset_name] = info
|
| 548 |
+
|
| 549 |
+
new_dataset_buckets = {}
|
| 550 |
+
for bucket_key in self.dataset_buckets.keys():
|
| 551 |
+
new_dataset_buckets[bucket_key] = {}
|
| 552 |
+
|
| 553 |
+
for dataset_name, info in sampled_dataset_map.items():
|
| 554 |
+
indices = info["indices"]
|
| 555 |
+
buckets = info["buckets"]
|
| 556 |
+
|
| 557 |
+
for idx, bucket_key in zip(indices, buckets):
|
| 558 |
+
if dataset_name not in new_dataset_buckets[bucket_key]:
|
| 559 |
+
new_dataset_buckets[bucket_key][dataset_name] = []
|
| 560 |
+
new_dataset_buckets[bucket_key][dataset_name].append(idx)
|
| 561 |
+
|
| 562 |
+
self.dataset_buckets = new_dataset_buckets
|
| 563 |
+
|
| 564 |
+
def __iter__(self):
|
| 565 |
+
# Use epoch-level seed for reproducibility
|
| 566 |
+
epoch_seed = self.seed + self._epoch
|
| 567 |
+
self.generator.manual_seed(epoch_seed)
|
| 568 |
+
|
| 569 |
+
if self.dataset_sampling_ratios:
|
| 570 |
+
self._apply_global_ratio_sampling()
|
| 571 |
+
|
| 572 |
+
bucket_iterators = {}
|
| 573 |
+
bucket_batches = {}
|
| 574 |
+
|
| 575 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 576 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 577 |
+
|
| 578 |
+
# Global shuffle before sharding (important for distributed consistency)
|
| 579 |
+
if self.shuffle:
|
| 580 |
+
perm = torch.randperm(len(balanced_indices), generator=self.generator).tolist()
|
| 581 |
+
balanced_indices = [balanced_indices[i] for i in perm]
|
| 582 |
+
|
| 583 |
+
# Shard indices for this SP group
|
| 584 |
+
sp_group_indices = self._shard_indices_for_sp_group(balanced_indices)
|
| 585 |
+
|
| 586 |
+
batches = []
|
| 587 |
+
for i in range(0, len(sp_group_indices), self.batch_size):
|
| 588 |
+
batch = sp_group_indices[i : i + self.batch_size]
|
| 589 |
+
if len(batch) == self.batch_size or not self.drop_last:
|
| 590 |
+
batches.append(batch)
|
| 591 |
+
|
| 592 |
+
if batches:
|
| 593 |
+
bucket_batches[bucket_key] = batches
|
| 594 |
+
bucket_iterators[bucket_key] = iter(batches)
|
| 595 |
+
|
| 596 |
+
remaining_buckets = list(bucket_iterators.keys())
|
| 597 |
+
|
| 598 |
+
while remaining_buckets:
|
| 599 |
+
idx = torch.randint(len(remaining_buckets), (1,), generator=self.generator).item()
|
| 600 |
+
bucket_key = remaining_buckets[idx]
|
| 601 |
+
bucket_iter = bucket_iterators[bucket_key]
|
| 602 |
+
|
| 603 |
+
try:
|
| 604 |
+
batch = next(bucket_iter)
|
| 605 |
+
yield batch
|
| 606 |
+
except StopIteration:
|
| 607 |
+
remaining_buckets.remove(bucket_key)
|
| 608 |
+
|
| 609 |
+
def _create_balanced_indices(self, dataset_groups):
|
| 610 |
+
return sum(dataset_groups.values(), [])
|
| 611 |
+
|
| 612 |
+
def _equal_sampling(self, dataset_groups):
|
| 613 |
+
all_indices = []
|
| 614 |
+
dataset_names = list(dataset_groups.keys())
|
| 615 |
+
|
| 616 |
+
if len(dataset_names) <= 1:
|
| 617 |
+
return sum(dataset_groups.values(), [])
|
| 618 |
+
|
| 619 |
+
min_samples = min(len(indices) for indices in dataset_groups.values())
|
| 620 |
+
|
| 621 |
+
for dataset_name, indices in dataset_groups.items():
|
| 622 |
+
if len(indices) > min_samples:
|
| 623 |
+
selected = torch.randperm(len(indices), generator=self.generator)[:min_samples].tolist()
|
| 624 |
+
sampled_indices = [indices[i] for i in selected]
|
| 625 |
+
else:
|
| 626 |
+
sampled_indices = indices
|
| 627 |
+
all_indices.extend(sampled_indices)
|
| 628 |
+
|
| 629 |
+
return all_indices
|
| 630 |
+
|
| 631 |
+
def _ratio_sampling(self, dataset_groups):
|
| 632 |
+
return sum(dataset_groups.values(), [])
|
| 633 |
+
|
| 634 |
+
def __len__(self):
|
| 635 |
+
if self.dataset_sampling_ratios:
|
| 636 |
+
temp_generator = torch.Generator()
|
| 637 |
+
temp_generator.manual_seed(self.seed)
|
| 638 |
+
|
| 639 |
+
dataset_sample_map = {}
|
| 640 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 641 |
+
for dataset_name, indices in dataset_groups.items():
|
| 642 |
+
if dataset_name not in dataset_sample_map:
|
| 643 |
+
dataset_sample_map[dataset_name] = []
|
| 644 |
+
dataset_sample_map[dataset_name].extend(indices)
|
| 645 |
+
|
| 646 |
+
total_samples = sum(len(indices) for indices in dataset_sample_map.values())
|
| 647 |
+
total_ratio = sum(self.dataset_sampling_ratios.values())
|
| 648 |
+
|
| 649 |
+
sampled_total = 0
|
| 650 |
+
for dataset_name, indices in dataset_sample_map.items():
|
| 651 |
+
if dataset_name in self.dataset_sampling_ratios:
|
| 652 |
+
ratio = self.dataset_sampling_ratios[dataset_name] / total_ratio
|
| 653 |
+
target_samples = max(1, int(total_samples * ratio))
|
| 654 |
+
sampled_total += target_samples
|
| 655 |
+
else:
|
| 656 |
+
sampled_total += len(indices)
|
| 657 |
+
|
| 658 |
+
# Account for SP group sharding
|
| 659 |
+
sp_group_samples = sampled_total // self.num_sp_groups
|
| 660 |
+
if not self.drop_last and sampled_total % self.num_sp_groups != 0:
|
| 661 |
+
sp_group_samples += 1
|
| 662 |
+
|
| 663 |
+
total_batches = sp_group_samples // self.batch_size
|
| 664 |
+
if not self.drop_last and sp_group_samples % self.batch_size != 0:
|
| 665 |
+
total_batches += 1
|
| 666 |
+
return total_batches
|
| 667 |
+
else:
|
| 668 |
+
total_batches = 0
|
| 669 |
+
for bucket_key, dataset_groups in self.dataset_buckets.items():
|
| 670 |
+
balanced_indices = self._create_balanced_indices(dataset_groups)
|
| 671 |
+
|
| 672 |
+
# Account for SP group sharding
|
| 673 |
+
sp_group_size = len(balanced_indices) // self.num_sp_groups
|
| 674 |
+
if not self.drop_last and len(balanced_indices) % self.num_sp_groups != 0:
|
| 675 |
+
sp_group_size += 1
|
| 676 |
+
|
| 677 |
+
num_batches = sp_group_size // self.batch_size
|
| 678 |
+
if not self.drop_last and sp_group_size % self.batch_size != 0:
|
| 679 |
+
num_batches += 1
|
| 680 |
+
total_batches += num_batches
|
| 681 |
+
return total_batches
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def collate_fn(batch):
|
| 685 |
+
batch = [item for item in batch if item is not None]
|
| 686 |
+
|
| 687 |
+
if len(batch) == 0:
|
| 688 |
+
return None
|
| 689 |
+
|
| 690 |
+
def collate_dict(data_list):
|
| 691 |
+
if isinstance(data_list[0], dict):
|
| 692 |
+
return {key: collate_dict([d[key] for d in data_list]) for key in data_list[0]}
|
| 693 |
+
elif isinstance(data_list[0], torch.Tensor):
|
| 694 |
+
return torch.stack(data_list)
|
| 695 |
+
else:
|
| 696 |
+
return data_list
|
| 697 |
+
|
| 698 |
+
return {key: collate_dict([d[key] for d in batch]) for key in batch[0]}
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
if __name__ == "__main__":
|
| 702 |
+
import torch.distributed.checkpoint as dcp
|
| 703 |
+
from accelerate import Accelerator
|
| 704 |
+
from torchdata.stateful_dataloader import StatefulDataLoader
|
| 705 |
+
|
| 706 |
+
json_file = [
|
| 707 |
+
"opensoraplan/jsons/video_mixkit_513f_1997.json",
|
| 708 |
+
]
|
| 709 |
+
video_folder = [
|
| 710 |
+
"opensoraplan/videos",
|
| 711 |
+
]
|
| 712 |
+
stride = 1
|
| 713 |
+
batch_size = 2
|
| 714 |
+
num_train_epochs = 1
|
| 715 |
+
seed = 0
|
| 716 |
+
num_workers = 8
|
| 717 |
+
output_dir = "accelerate_checkpoints"
|
| 718 |
+
checkpoint_dirs = (
|
| 719 |
+
[
|
| 720 |
+
d
|
| 721 |
+
for d in os.listdir(output_dir)
|
| 722 |
+
if d.startswith("checkpoint-") and os.path.isdir(os.path.join(output_dir, d))
|
| 723 |
+
]
|
| 724 |
+
if os.path.exists(output_dir)
|
| 725 |
+
else []
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
dataset_ratios = {}
|
| 729 |
+
# dataset_ratios = {
|
| 730 |
+
# "/mnt/hdfs/data/ysh_new/userful_things_wan/open-sora-plan-istock/istock_v4/latents": 0.9,
|
| 731 |
+
# "/mnt/hdfs/data/ysh_new/userful_things_wan/sekai/sekai-real-walking-hq-193/latents_stride1": 0.1
|
| 732 |
+
# }
|
| 733 |
+
|
| 734 |
+
accelerator = Accelerator()
|
| 735 |
+
print(accelerator.process_index, accelerator.num_processes)
|
| 736 |
+
|
| 737 |
+
dataset = BucketedFeatureDataset(
|
| 738 |
+
json_files=json_file,
|
| 739 |
+
video_folders=video_folder,
|
| 740 |
+
stride=stride,
|
| 741 |
+
force_rebuild=False,
|
| 742 |
+
resolution=640,
|
| 743 |
+
single_res=True,
|
| 744 |
+
single_height=384,
|
| 745 |
+
single_width=640,
|
| 746 |
+
single_length=True,
|
| 747 |
+
single_num_frame=81,
|
| 748 |
+
multi_res=True,
|
| 749 |
+
)
|
| 750 |
+
sampler = BucketedSampler(
|
| 751 |
+
dataset,
|
| 752 |
+
batch_size=batch_size,
|
| 753 |
+
drop_last=True,
|
| 754 |
+
shuffle=False,
|
| 755 |
+
dataset_sampling_ratios=dataset_ratios,
|
| 756 |
+
seed=seed,
|
| 757 |
+
# num_sp_groups=get_world_size() // get_sp_world_size(),
|
| 758 |
+
# sp_world_size=get_sp_world_size(),
|
| 759 |
+
# global_rank=get_world_rank(),
|
| 760 |
+
num_sp_groups=accelerator.num_processes // 1,
|
| 761 |
+
sp_world_size=1,
|
| 762 |
+
global_rank=accelerator.process_index,
|
| 763 |
+
)
|
| 764 |
+
dataloader = StatefulDataLoader(dataset, batch_sampler=sampler, collate_fn=collate_fn, num_workers=num_workers)
|
| 765 |
+
|
| 766 |
+
print(len(dataset), len(dataloader))
|
| 767 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 768 |
+
|
| 769 |
+
step = 0
|
| 770 |
+
global_step = 0
|
| 771 |
+
first_epoch = 0
|
| 772 |
+
num_update_steps_per_epoch = len(dataloader)
|
| 773 |
+
if checkpoint_dirs:
|
| 774 |
+
latest_checkpoint = max(checkpoint_dirs, key=lambda x: int(x.split("-")[1]))
|
| 775 |
+
checkpoint_path = os.path.join(output_dir, latest_checkpoint)
|
| 776 |
+
print(f"Found checkpoint: {checkpoint_path}")
|
| 777 |
+
|
| 778 |
+
accelerator.load_state(checkpoint_path)
|
| 779 |
+
global_step = int(latest_checkpoint.split("-")[1])
|
| 780 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 781 |
+
|
| 782 |
+
states = {
|
| 783 |
+
"dataloader": dataloader,
|
| 784 |
+
}
|
| 785 |
+
dcp_dir = os.path.join(checkpoint_path, "distributed_checkpoint")
|
| 786 |
+
dcp.load(states, checkpoint_id=dcp_dir)
|
| 787 |
+
|
| 788 |
+
print(f"Resuming from step {global_step}, epoch {first_epoch}")
|
| 789 |
+
|
| 790 |
+
print("Testing dataloader...")
|
| 791 |
+
step = global_step
|
| 792 |
+
dataset_counts = defaultdict(int)
|
| 793 |
+
for epoch in range(first_epoch, num_train_epochs):
|
| 794 |
+
sampler.set_epoch(epoch)
|
| 795 |
+
dataset.set_epoch(epoch)
|
| 796 |
+
for i, batch in enumerate(dataloader):
|
| 797 |
+
# Get metadata
|
| 798 |
+
uttid = batch["uttid"]
|
| 799 |
+
bucket_key = batch["bucket_key"]
|
| 800 |
+
num_frame = batch["video_metadata"]["num_frames"]
|
| 801 |
+
height = batch["video_metadata"]["height"]
|
| 802 |
+
width = batch["video_metadata"]["width"]
|
| 803 |
+
|
| 804 |
+
# Get feature
|
| 805 |
+
video_data = batch["videos"]
|
| 806 |
+
prompt = batch["prompts"]
|
| 807 |
+
first_frames_images = batch["first_frames_images"]
|
| 808 |
+
first_frames_images = [torchvision.transforms.ToPILImage()(x.to(torch.uint8)) for x in first_frames_images]
|
| 809 |
+
|
| 810 |
+
# save_frames(video_data[0].squeeze(0), video_path="1.mp4")
|
| 811 |
+
# import pdb;pdb.set_trace()
|
| 812 |
+
|
| 813 |
+
if accelerator.process_index == 0:
|
| 814 |
+
# print info
|
| 815 |
+
print(f" Step {step}:")
|
| 816 |
+
print(f" Batch {i}:")
|
| 817 |
+
# print(f" Data Name: {batch['dataset_name']}")
|
| 818 |
+
print(f" Batch size: {len(uttid)}")
|
| 819 |
+
print(f" Uttids: {uttid}")
|
| 820 |
+
print(f" Dimensions - frames: {num_frame[0]}, height: {height[0]}, width: {width[0]}")
|
| 821 |
+
print(f" Bucket key: {bucket_key[0]}")
|
| 822 |
+
print(f" Videos shape: {video_data.shape}")
|
| 823 |
+
print(f" Cpation: {prompt}")
|
| 824 |
+
|
| 825 |
+
# verify
|
| 826 |
+
assert all(nf == num_frame[0] for nf in num_frame), "Frame numbers not consistent in batch"
|
| 827 |
+
assert all(h == height[0] for h in height), "Heights not consistent in batch"
|
| 828 |
+
assert all(w == width[0] for w in width), "Widths not consistent in batch"
|
| 829 |
+
|
| 830 |
+
print(" ✓ Batch dimensions are consistent")
|
| 831 |
+
|
| 832 |
+
for dataset_name in batch["dataset_name"]:
|
| 833 |
+
dataset_counts[dataset_name] += 1
|
| 834 |
+
|
| 835 |
+
step += 1
|
| 836 |
+
|
| 837 |
+
# if step == 20:
|
| 838 |
+
# checkpoint_dir = f"checkpoint-{step}"
|
| 839 |
+
# save_path = os.path.join(output_dir, checkpoint_dir)
|
| 840 |
+
# os.makedirs(save_path, exist_ok=True)
|
| 841 |
+
|
| 842 |
+
# if accelerator.is_main_process:
|
| 843 |
+
# print(f"Saving checkpoint at step {step}")
|
| 844 |
+
|
| 845 |
+
# accelerator.save_state(save_path)
|
| 846 |
+
|
| 847 |
+
# print(accelerator.process_index, accelerator.num_processes)
|
| 848 |
+
# states = {
|
| 849 |
+
# "dataloader": dataloader,
|
| 850 |
+
# }
|
| 851 |
+
# dcp_dir = os.path.join(save_path, "distributed_checkpoint")
|
| 852 |
+
# dcp.save(states, checkpoint_id=dcp_dir)
|
| 853 |
+
|
| 854 |
+
print("实际采样统计:", dict(dataset_counts))
|
Helios/_DEV2/helios/diffusers_version/__init__.py
ADDED
|
File without changes
|
Helios/_DEV2/helios/diffusers_version/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (200 Bytes). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (189 Bytes). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-311.pyc
ADDED
|
Binary file (63.2 kB). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-312.pyc
ADDED
|
Binary file (61.9 kB). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/__pycache__/scheduling_helios_diffusers.cpython-311.pyc
ADDED
|
Binary file (39.9 kB). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/__pycache__/scheduling_helios_diffusers.cpython-312.pyc
ADDED
|
Binary file (39.7 kB). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/__pycache__/transformer_helios_diffusers.cpython-311.pyc
ADDED
|
Binary file (44.1 kB). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/__pycache__/transformer_helios_diffusers.cpython-312.pyc
ADDED
|
Binary file (49.8 kB). View file
|
|
|
Helios/_DEV2/helios/diffusers_version/pipeline_helios_diffusers.py
ADDED
|
@@ -0,0 +1,1460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import html
|
| 16 |
+
import math
|
| 17 |
+
from itertools import accumulate
|
| 18 |
+
from typing import Any, Callable
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import regex as re
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 25 |
+
|
| 26 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 27 |
+
from diffusers.image_processor import PipelineImageInput
|
| 28 |
+
from diffusers.loaders import HeliosLoraLoaderMixin
|
| 29 |
+
from diffusers.models import AutoencoderKLWan, HeliosTransformer3DModel
|
| 30 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 31 |
+
from diffusers.schedulers import HeliosScheduler
|
| 32 |
+
from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
from diffusers.video_processor import VideoProcessor
|
| 35 |
+
|
| 36 |
+
from ..pipelines.pipeline_output import HeliosPipelineOutput
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if is_torch_xla_available():
|
| 40 |
+
import torch_xla.core.xla_model as xm
|
| 41 |
+
|
| 42 |
+
XLA_AVAILABLE = True
|
| 43 |
+
else:
|
| 44 |
+
XLA_AVAILABLE = False
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 47 |
+
|
| 48 |
+
if is_ftfy_available():
|
| 49 |
+
import ftfy
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
EXAMPLE_DOC_STRING = """
|
| 53 |
+
Examples:
|
| 54 |
+
```python
|
| 55 |
+
>>> import torch
|
| 56 |
+
>>> from diffusers.utils import export_to_video
|
| 57 |
+
>>> from diffusers import AutoencoderKLWan, HeliosPipeline
|
| 58 |
+
|
| 59 |
+
>>> # Available models: BestWishYsh/Helios-Base, BestWishYsh/Helios-Mid, BestWishYsh/Helios-Distilled
|
| 60 |
+
>>> model_id = "BestWishYsh/Helios-Base"
|
| 61 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 62 |
+
>>> pipe = HeliosPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
| 63 |
+
>>> pipe.to("cuda")
|
| 64 |
+
|
| 65 |
+
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
|
| 66 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 67 |
+
|
| 68 |
+
>>> output = pipe(
|
| 69 |
+
... prompt=prompt,
|
| 70 |
+
... negative_prompt=negative_prompt,
|
| 71 |
+
... height=384,
|
| 72 |
+
... width=640,
|
| 73 |
+
... num_frames=132,
|
| 74 |
+
... guidance_scale=5.0,
|
| 75 |
+
... ).frames[0]
|
| 76 |
+
>>> export_to_video(output, "output.mp4", fps=24)
|
| 77 |
+
```
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def optimized_scale(positive_flat, negative_flat):
|
| 82 |
+
positive_flat = positive_flat.float()
|
| 83 |
+
negative_flat = negative_flat.float()
|
| 84 |
+
# Calculate dot production
|
| 85 |
+
dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
|
| 86 |
+
# Squared norm of uncondition
|
| 87 |
+
squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
|
| 88 |
+
# st_star = v_cond^T * v_uncond / ||v_uncond||^2
|
| 89 |
+
st_star = dot_product / squared_norm
|
| 90 |
+
return st_star
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def basic_clean(text):
|
| 94 |
+
text = ftfy.fix_text(text)
|
| 95 |
+
text = html.unescape(html.unescape(text))
|
| 96 |
+
return text.strip()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def whitespace_clean(text):
|
| 100 |
+
text = re.sub(r"\s+", " ", text)
|
| 101 |
+
text = text.strip()
|
| 102 |
+
return text
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def prompt_clean(text):
|
| 106 |
+
text = whitespace_clean(basic_clean(text))
|
| 107 |
+
return text
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
|
| 111 |
+
def calculate_shift(
|
| 112 |
+
image_seq_len,
|
| 113 |
+
base_seq_len: int = 256,
|
| 114 |
+
max_seq_len: int = 4096,
|
| 115 |
+
base_shift: float = 0.5,
|
| 116 |
+
max_shift: float = 1.15,
|
| 117 |
+
):
|
| 118 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
| 119 |
+
b = base_shift - m * base_seq_len
|
| 120 |
+
mu = image_seq_len * m + b
|
| 121 |
+
return mu
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class HeliosPipeline(DiffusionPipeline, HeliosLoraLoaderMixin):
|
| 125 |
+
r"""
|
| 126 |
+
Pipeline for text-to-video / image-to-video / video-to-video generation using Helios.
|
| 127 |
+
|
| 128 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 129 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
tokenizer ([`T5Tokenizer`]):
|
| 133 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
| 134 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 135 |
+
text_encoder ([`T5EncoderModel`]):
|
| 136 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 137 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 138 |
+
transformer ([`HeliosTransformer3DModel`]):
|
| 139 |
+
Conditional Transformer to denoise the input latents.
|
| 140 |
+
scheduler ([`HeliosScheduler`]):
|
| 141 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 142 |
+
vae ([`AutoencoderKLWan`]):
|
| 143 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
| 147 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 148 |
+
_optional_components = ["transformer"]
|
| 149 |
+
|
| 150 |
+
def __init__(
|
| 151 |
+
self,
|
| 152 |
+
tokenizer: AutoTokenizer,
|
| 153 |
+
text_encoder: UMT5EncoderModel,
|
| 154 |
+
vae: AutoencoderKLWan,
|
| 155 |
+
scheduler: HeliosScheduler,
|
| 156 |
+
transformer: HeliosTransformer3DModel,
|
| 157 |
+
is_cfg_zero_star: bool = False,
|
| 158 |
+
is_distilled: bool = False,
|
| 159 |
+
):
|
| 160 |
+
super().__init__()
|
| 161 |
+
|
| 162 |
+
self.register_modules(
|
| 163 |
+
vae=vae,
|
| 164 |
+
text_encoder=text_encoder,
|
| 165 |
+
tokenizer=tokenizer,
|
| 166 |
+
transformer=transformer,
|
| 167 |
+
scheduler=scheduler,
|
| 168 |
+
)
|
| 169 |
+
self.register_to_config(is_cfg_zero_star=is_cfg_zero_star)
|
| 170 |
+
self.register_to_config(is_distilled=is_distilled)
|
| 171 |
+
self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
|
| 172 |
+
self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
|
| 173 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 174 |
+
|
| 175 |
+
def _get_t5_prompt_embeds(
|
| 176 |
+
self,
|
| 177 |
+
prompt: str | list[str] = None,
|
| 178 |
+
num_videos_per_prompt: int = 1,
|
| 179 |
+
max_sequence_length: int = 226,
|
| 180 |
+
device: torch.device | None = None,
|
| 181 |
+
dtype: torch.dtype | None = None,
|
| 182 |
+
):
|
| 183 |
+
device = device or self._execution_device
|
| 184 |
+
dtype = dtype or self.text_encoder.dtype
|
| 185 |
+
|
| 186 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 187 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 188 |
+
batch_size = len(prompt)
|
| 189 |
+
|
| 190 |
+
text_inputs = self.tokenizer(
|
| 191 |
+
prompt,
|
| 192 |
+
padding="max_length",
|
| 193 |
+
max_length=max_sequence_length,
|
| 194 |
+
truncation=True,
|
| 195 |
+
add_special_tokens=True,
|
| 196 |
+
return_attention_mask=True,
|
| 197 |
+
return_tensors="pt",
|
| 198 |
+
)
|
| 199 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 200 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 201 |
+
|
| 202 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 203 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 204 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 205 |
+
prompt_embeds = torch.stack(
|
| 206 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 210 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 211 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 212 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 213 |
+
|
| 214 |
+
return prompt_embeds, text_inputs.attention_mask.bool()
|
| 215 |
+
|
| 216 |
+
def encode_prompt(
|
| 217 |
+
self,
|
| 218 |
+
prompt: str | list[str],
|
| 219 |
+
negative_prompt: str | list[str] | None = None,
|
| 220 |
+
do_classifier_free_guidance: bool = True,
|
| 221 |
+
num_videos_per_prompt: int = 1,
|
| 222 |
+
prompt_embeds: torch.Tensor | None = None,
|
| 223 |
+
negative_prompt_embeds: torch.Tensor | None = None,
|
| 224 |
+
max_sequence_length: int = 226,
|
| 225 |
+
device: torch.device | None = None,
|
| 226 |
+
dtype: torch.dtype | None = None,
|
| 227 |
+
):
|
| 228 |
+
r"""
|
| 229 |
+
Encodes the prompt into text encoder hidden states.
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
prompt (`str` or `list[str]`, *optional*):
|
| 233 |
+
prompt to be encoded
|
| 234 |
+
negative_prompt (`str` or `list[str]`, *optional*):
|
| 235 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 236 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 237 |
+
less than `1`).
|
| 238 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 239 |
+
Whether to use classifier free guidance or not.
|
| 240 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 241 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
| 242 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 243 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 244 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 245 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 246 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 247 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 248 |
+
argument.
|
| 249 |
+
device: (`torch.device`, *optional*):
|
| 250 |
+
torch device
|
| 251 |
+
dtype: (`torch.dtype`, *optional*):
|
| 252 |
+
torch dtype
|
| 253 |
+
"""
|
| 254 |
+
device = device or self._execution_device
|
| 255 |
+
|
| 256 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 257 |
+
if prompt is not None:
|
| 258 |
+
batch_size = len(prompt)
|
| 259 |
+
else:
|
| 260 |
+
batch_size = prompt_embeds.shape[0]
|
| 261 |
+
|
| 262 |
+
if prompt_embeds is None:
|
| 263 |
+
prompt_embeds, _ = self._get_t5_prompt_embeds(
|
| 264 |
+
prompt=prompt,
|
| 265 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 266 |
+
max_sequence_length=max_sequence_length,
|
| 267 |
+
device=device,
|
| 268 |
+
dtype=dtype,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 272 |
+
negative_prompt = negative_prompt or ""
|
| 273 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 274 |
+
|
| 275 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 276 |
+
raise TypeError(
|
| 277 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 278 |
+
f" {type(prompt)}."
|
| 279 |
+
)
|
| 280 |
+
elif batch_size != len(negative_prompt):
|
| 281 |
+
raise ValueError(
|
| 282 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 283 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 284 |
+
" the batch size of `prompt`."
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
negative_prompt_embeds, _ = self._get_t5_prompt_embeds(
|
| 288 |
+
prompt=negative_prompt,
|
| 289 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 290 |
+
max_sequence_length=max_sequence_length,
|
| 291 |
+
device=device,
|
| 292 |
+
dtype=dtype,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
return prompt_embeds, negative_prompt_embeds
|
| 296 |
+
|
| 297 |
+
def check_inputs(
|
| 298 |
+
self,
|
| 299 |
+
prompt,
|
| 300 |
+
negative_prompt,
|
| 301 |
+
height,
|
| 302 |
+
width,
|
| 303 |
+
prompt_embeds=None,
|
| 304 |
+
negative_prompt_embeds=None,
|
| 305 |
+
callback_on_step_end_tensor_inputs=None,
|
| 306 |
+
image=None,
|
| 307 |
+
video=None,
|
| 308 |
+
use_interpolate_prompt=False,
|
| 309 |
+
num_videos_per_prompt=None,
|
| 310 |
+
interpolate_time_list=None,
|
| 311 |
+
interpolation_steps=None,
|
| 312 |
+
guidance_scale=None,
|
| 313 |
+
):
|
| 314 |
+
if height % 16 != 0 or width % 16 != 0:
|
| 315 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
| 316 |
+
|
| 317 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 318 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 319 |
+
):
|
| 320 |
+
raise ValueError(
|
| 321 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
if prompt is not None and prompt_embeds is not None:
|
| 325 |
+
raise ValueError(
|
| 326 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 327 |
+
" only forward one of the two."
|
| 328 |
+
)
|
| 329 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 330 |
+
raise ValueError(
|
| 331 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 332 |
+
" only forward one of the two."
|
| 333 |
+
)
|
| 334 |
+
elif prompt is None and prompt_embeds is None:
|
| 335 |
+
raise ValueError(
|
| 336 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 337 |
+
)
|
| 338 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 339 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 340 |
+
elif negative_prompt is not None and (
|
| 341 |
+
not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
| 342 |
+
):
|
| 343 |
+
raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
| 344 |
+
|
| 345 |
+
if image is not None and video is not None:
|
| 346 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 347 |
+
|
| 348 |
+
if use_interpolate_prompt:
|
| 349 |
+
assert num_videos_per_prompt == 1, f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}"
|
| 350 |
+
assert isinstance(prompt, list), "prompt must be a list"
|
| 351 |
+
assert len(prompt) == len(interpolate_time_list), (
|
| 352 |
+
f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}"
|
| 353 |
+
)
|
| 354 |
+
assert min(interpolate_time_list) > interpolation_steps, (
|
| 355 |
+
f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}"
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
if guidance_scale > 1.0 and self.config.is_distilled:
|
| 359 |
+
logger.warning(f"Guidance scale {guidance_scale} is ignored for step-wise distilled models.")
|
| 360 |
+
|
| 361 |
+
def prepare_latents(
|
| 362 |
+
self,
|
| 363 |
+
batch_size: int,
|
| 364 |
+
num_channels_latents: int = 16,
|
| 365 |
+
height: int = 384,
|
| 366 |
+
width: int = 640,
|
| 367 |
+
num_frames: int = 33,
|
| 368 |
+
dtype: torch.dtype | None = None,
|
| 369 |
+
device: torch.device | None = None,
|
| 370 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 371 |
+
latents: torch.Tensor | None = None,
|
| 372 |
+
) -> torch.Tensor:
|
| 373 |
+
if latents is not None:
|
| 374 |
+
return latents.to(device=device, dtype=dtype)
|
| 375 |
+
|
| 376 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 377 |
+
shape = (
|
| 378 |
+
batch_size,
|
| 379 |
+
num_channels_latents,
|
| 380 |
+
num_latent_frames,
|
| 381 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 382 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 383 |
+
)
|
| 384 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 385 |
+
raise ValueError(
|
| 386 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 387 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 391 |
+
return latents
|
| 392 |
+
|
| 393 |
+
def prepare_image_latents(
|
| 394 |
+
self,
|
| 395 |
+
image: torch.Tensor,
|
| 396 |
+
latents_mean: torch.Tensor,
|
| 397 |
+
latents_std: torch.Tensor,
|
| 398 |
+
num_latent_frames_per_chunk: int,
|
| 399 |
+
dtype: torch.dtype | None = None,
|
| 400 |
+
device: torch.device | None = None,
|
| 401 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 402 |
+
latents: torch.Tensor | None = None,
|
| 403 |
+
fake_latents: torch.Tensor | None = None,
|
| 404 |
+
) -> torch.Tensor:
|
| 405 |
+
device = device or self._execution_device
|
| 406 |
+
if latents is None:
|
| 407 |
+
image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype)
|
| 408 |
+
latents = self.vae.encode(image).latent_dist.sample(generator=generator)
|
| 409 |
+
latents = (latents - latents_mean) * latents_std
|
| 410 |
+
if fake_latents is None:
|
| 411 |
+
min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
|
| 412 |
+
fake_video = image.repeat(1, 1, min_frames, 1, 1).to(device=device, dtype=self.vae.dtype)
|
| 413 |
+
fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(generator=generator)
|
| 414 |
+
fake_latents_full = (fake_latents_full - latents_mean) * latents_std
|
| 415 |
+
fake_latents = fake_latents_full[:, :, -1:, :, :]
|
| 416 |
+
return latents.to(device=device, dtype=dtype), fake_latents.to(device=device, dtype=dtype)
|
| 417 |
+
|
| 418 |
+
def prepare_video_latents(
|
| 419 |
+
self,
|
| 420 |
+
video: torch.Tensor,
|
| 421 |
+
latents_mean: torch.Tensor,
|
| 422 |
+
latents_std: torch.Tensor,
|
| 423 |
+
num_latent_frames_per_chunk: int,
|
| 424 |
+
dtype: torch.dtype | None = None,
|
| 425 |
+
device: torch.device | None = None,
|
| 426 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 427 |
+
latents: torch.Tensor | None = None,
|
| 428 |
+
) -> torch.Tensor:
|
| 429 |
+
device = device or self._execution_device
|
| 430 |
+
video = video.to(device=device, dtype=self.vae.dtype)
|
| 431 |
+
if latents is None:
|
| 432 |
+
num_frames = video.shape[2]
|
| 433 |
+
min_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
|
| 434 |
+
num_chunks = num_frames // min_frames
|
| 435 |
+
if num_chunks == 0:
|
| 436 |
+
raise ValueError(
|
| 437 |
+
f"Video must have at least {min_frames} frames "
|
| 438 |
+
f"(got {num_frames} frames). "
|
| 439 |
+
f"Required: (num_latent_frames_per_chunk - 1) * {self.vae_scale_factor_temporal} + 1 = ({num_latent_frames_per_chunk} - 1) * {self.vae_scale_factor_temporal} + 1 = {min_frames}"
|
| 440 |
+
)
|
| 441 |
+
total_valid_frames = num_chunks * min_frames
|
| 442 |
+
start_frame = num_frames - total_valid_frames
|
| 443 |
+
|
| 444 |
+
first_frame = video[:, :, 0:1, :, :]
|
| 445 |
+
first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(generator=generator)
|
| 446 |
+
first_frame_latent = (first_frame_latent - latents_mean) * latents_std
|
| 447 |
+
|
| 448 |
+
latents_chunks = []
|
| 449 |
+
for i in range(num_chunks):
|
| 450 |
+
chunk_start = start_frame + i * min_frames
|
| 451 |
+
chunk_end = chunk_start + min_frames
|
| 452 |
+
video_chunk = video[:, :, chunk_start:chunk_end, :, :]
|
| 453 |
+
chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(generator=generator)
|
| 454 |
+
chunk_latents = (chunk_latents - latents_mean) * latents_std
|
| 455 |
+
latents_chunks.append(chunk_latents)
|
| 456 |
+
latents = torch.cat(latents_chunks, dim=2)
|
| 457 |
+
return first_frame_latent.to(device=device, dtype=dtype), latents.to(device=device, dtype=dtype)
|
| 458 |
+
|
| 459 |
+
def interpolate_prompt_embeds(
|
| 460 |
+
self,
|
| 461 |
+
prompt_embeds_1: torch.Tensor,
|
| 462 |
+
prompt_embeds_2: torch.Tensor,
|
| 463 |
+
interpolation_steps: int = 3,
|
| 464 |
+
):
|
| 465 |
+
x = torch.lerp(
|
| 466 |
+
prompt_embeds_1,
|
| 467 |
+
prompt_embeds_2,
|
| 468 |
+
torch.linspace(0, 1, steps=interpolation_steps).unsqueeze(1).unsqueeze(2).to(prompt_embeds_1),
|
| 469 |
+
)
|
| 470 |
+
interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0))
|
| 471 |
+
return interpolated_prompt_embeds
|
| 472 |
+
|
| 473 |
+
def sample_block_noise(
|
| 474 |
+
self,
|
| 475 |
+
batch_size,
|
| 476 |
+
channel,
|
| 477 |
+
num_frames,
|
| 478 |
+
height,
|
| 479 |
+
width,
|
| 480 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 481 |
+
device: torch.device | None = None,
|
| 482 |
+
generator: torch.Generator | None = None,
|
| 483 |
+
):
|
| 484 |
+
# NOTE: A generator must be provided to ensure correct and reproducible results.
|
| 485 |
+
# Creating a default generator here is a fallback only — without a fixed seed,
|
| 486 |
+
# the output will be non-deterministic and may produce incorrect results in CP context.
|
| 487 |
+
if generator is None:
|
| 488 |
+
generator = torch.Generator(device=device)
|
| 489 |
+
elif isinstance(generator, list):
|
| 490 |
+
generator = generator[0]
|
| 491 |
+
|
| 492 |
+
gamma = self.scheduler.config.gamma
|
| 493 |
+
_, ph, pw = patch_size
|
| 494 |
+
block_size = ph * pw
|
| 495 |
+
|
| 496 |
+
cov = (
|
| 497 |
+
torch.eye(block_size, device=device) * (1 + gamma)
|
| 498 |
+
- torch.ones(block_size, block_size, device=device) * gamma
|
| 499 |
+
)
|
| 500 |
+
cov += torch.eye(block_size, device=device) * 1e-8
|
| 501 |
+
cov = cov.float() # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16.
|
| 502 |
+
|
| 503 |
+
L = torch.linalg.cholesky(cov)
|
| 504 |
+
block_number = batch_size * channel * num_frames * (height // ph) * (width // pw)
|
| 505 |
+
z = torch.randn(block_number, block_size, generator=generator, device=generator.device).to(device=device)
|
| 506 |
+
noise = z @ L.T
|
| 507 |
+
|
| 508 |
+
noise = noise.view(batch_size, channel, num_frames, height // ph, width // pw, ph, pw)
|
| 509 |
+
noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(batch_size, channel, num_frames, height, width)
|
| 510 |
+
|
| 511 |
+
return noise
|
| 512 |
+
|
| 513 |
+
def record_relative_l1(
|
| 514 |
+
self,
|
| 515 |
+
records: list[dict[str, float | int]] | None,
|
| 516 |
+
chunk_index: int,
|
| 517 |
+
stage_index: int | None,
|
| 518 |
+
step_index: int,
|
| 519 |
+
timestep: torch.Tensor,
|
| 520 |
+
latents_t: torch.Tensor,
|
| 521 |
+
latents_t_minus_1: torch.Tensor,
|
| 522 |
+
):
|
| 523 |
+
if records is None:
|
| 524 |
+
return
|
| 525 |
+
|
| 526 |
+
latents_t = latents_t.detach().float()
|
| 527 |
+
latents_t_minus_1 = latents_t_minus_1.detach().float()
|
| 528 |
+
delta_abs = (latents_t_minus_1 - latents_t).abs()
|
| 529 |
+
latents_abs = latents_t.abs()
|
| 530 |
+
relative_l1 = (delta_abs / latents_abs.clamp_min(1e-8)).mean()
|
| 531 |
+
relative_l1_ratio = delta_abs.mean() / latents_abs.mean().clamp_min(1e-8)
|
| 532 |
+
timestep_value = timestep.detach().float().mean().item() if torch.is_tensor(timestep) else float(timestep)
|
| 533 |
+
|
| 534 |
+
records.append(
|
| 535 |
+
{
|
| 536 |
+
"chunk_index": int(chunk_index),
|
| 537 |
+
"stage_index": -1 if stage_index is None else int(stage_index),
|
| 538 |
+
"step_index": int(step_index),
|
| 539 |
+
"timestep": float(timestep_value),
|
| 540 |
+
"relative_l1": float(relative_l1.item()),
|
| 541 |
+
"relative_l1_ratio": float(relative_l1_ratio.item()),
|
| 542 |
+
}
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
def stage1_sample(
|
| 546 |
+
self,
|
| 547 |
+
latents: torch.Tensor = None,
|
| 548 |
+
prompt_embeds: torch.Tensor = None,
|
| 549 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 550 |
+
timesteps: torch.Tensor = None,
|
| 551 |
+
guidance_scale: float | None = 5.0,
|
| 552 |
+
indices_hidden_states: torch.Tensor = None,
|
| 553 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 554 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 555 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 556 |
+
latents_history_short: torch.Tensor = None,
|
| 557 |
+
latents_history_mid: torch.Tensor = None,
|
| 558 |
+
latents_history_long: torch.Tensor = None,
|
| 559 |
+
attention_kwargs: dict | None = None,
|
| 560 |
+
device: torch.device | None = None,
|
| 561 |
+
transformer_dtype: torch.dtype = None,
|
| 562 |
+
generator: torch.Generator | None = None,
|
| 563 |
+
num_warmup_steps: int | None = None,
|
| 564 |
+
# ------------ CFG Zero ------------
|
| 565 |
+
use_zero_init: bool | None = True,
|
| 566 |
+
zero_steps: int | None = 1,
|
| 567 |
+
# ------------ Callback ------------
|
| 568 |
+
callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
|
| 569 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 570 |
+
progress_bar=None,
|
| 571 |
+
chunk_index: int = 0,
|
| 572 |
+
relative_l1_records: list[dict[str, float | int]] | None = None,
|
| 573 |
+
):
|
| 574 |
+
batch_size = latents.shape[0]
|
| 575 |
+
|
| 576 |
+
for i, t in enumerate(timesteps):
|
| 577 |
+
if self.interrupt:
|
| 578 |
+
continue
|
| 579 |
+
|
| 580 |
+
self._current_timestep = t
|
| 581 |
+
timestep = t.expand(latents.shape[0])
|
| 582 |
+
|
| 583 |
+
latent_model_input = latents.to(transformer_dtype)
|
| 584 |
+
self.transformer.set_short_attn_debug_context(
|
| 585 |
+
chunk_index=chunk_index,
|
| 586 |
+
stage="stage1",
|
| 587 |
+
stage_index=None,
|
| 588 |
+
step_index=i,
|
| 589 |
+
total_steps=len(timesteps),
|
| 590 |
+
pass_name="cond",
|
| 591 |
+
timestep=float(t.detach().cpu().item()) if torch.is_tensor(t) else float(t),
|
| 592 |
+
)
|
| 593 |
+
with self.transformer.cache_context("cond"):
|
| 594 |
+
noise_pred = self.transformer(
|
| 595 |
+
hidden_states=latent_model_input,
|
| 596 |
+
timestep=timestep,
|
| 597 |
+
encoder_hidden_states=prompt_embeds,
|
| 598 |
+
indices_hidden_states=indices_hidden_states,
|
| 599 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 600 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 601 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 602 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 603 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 604 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 605 |
+
attention_kwargs=attention_kwargs,
|
| 606 |
+
return_dict=False,
|
| 607 |
+
)[0]
|
| 608 |
+
|
| 609 |
+
if self.do_classifier_free_guidance:
|
| 610 |
+
self.transformer.set_short_attn_debug_context(
|
| 611 |
+
chunk_index=chunk_index,
|
| 612 |
+
stage="stage1",
|
| 613 |
+
stage_index=None,
|
| 614 |
+
step_index=i,
|
| 615 |
+
total_steps=len(timesteps),
|
| 616 |
+
pass_name="uncond",
|
| 617 |
+
timestep=float(t.detach().cpu().item()) if torch.is_tensor(t) else float(t),
|
| 618 |
+
)
|
| 619 |
+
with self.transformer.cache_context("uncond"):
|
| 620 |
+
noise_uncond = self.transformer(
|
| 621 |
+
hidden_states=latent_model_input,
|
| 622 |
+
timestep=timestep,
|
| 623 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 624 |
+
indices_hidden_states=indices_hidden_states,
|
| 625 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 626 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 627 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 628 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 629 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 630 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 631 |
+
attention_kwargs=attention_kwargs,
|
| 632 |
+
return_dict=False,
|
| 633 |
+
)[0]
|
| 634 |
+
|
| 635 |
+
if self.config.is_cfg_zero_star:
|
| 636 |
+
noise_pred_text = noise_pred
|
| 637 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 638 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 639 |
+
|
| 640 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 641 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 642 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 643 |
+
|
| 644 |
+
if (i <= zero_steps) and use_zero_init:
|
| 645 |
+
noise_pred = noise_pred_text * 0.0
|
| 646 |
+
else:
|
| 647 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (noise_pred_text - noise_uncond * alpha)
|
| 648 |
+
else:
|
| 649 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 650 |
+
|
| 651 |
+
latents_t = latents
|
| 652 |
+
latents = self.scheduler.step(
|
| 653 |
+
noise_pred,
|
| 654 |
+
t,
|
| 655 |
+
latents,
|
| 656 |
+
return_dict=False,
|
| 657 |
+
)[0]
|
| 658 |
+
self.record_relative_l1(relative_l1_records, chunk_index, None, i, t, latents_t, latents)
|
| 659 |
+
|
| 660 |
+
if callback_on_step_end is not None:
|
| 661 |
+
callback_kwargs = {}
|
| 662 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 663 |
+
callback_kwargs[k] = locals()[k]
|
| 664 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 665 |
+
|
| 666 |
+
latents = callback_outputs.pop("latents", latents)
|
| 667 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 668 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 669 |
+
|
| 670 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 671 |
+
progress_bar.update()
|
| 672 |
+
|
| 673 |
+
if XLA_AVAILABLE:
|
| 674 |
+
xm.mark_step()
|
| 675 |
+
|
| 676 |
+
return latents
|
| 677 |
+
|
| 678 |
+
def stage2_sample(
|
| 679 |
+
self,
|
| 680 |
+
latents: torch.Tensor = None,
|
| 681 |
+
pyramid_num_stages: int = None,
|
| 682 |
+
pyramid_num_inference_steps_list: list[int] = None,
|
| 683 |
+
prompt_embeds: torch.Tensor = None,
|
| 684 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 685 |
+
guidance_scale: float | None = 5.0,
|
| 686 |
+
indices_hidden_states: torch.Tensor = None,
|
| 687 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 688 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 689 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 690 |
+
latents_history_short: torch.Tensor = None,
|
| 691 |
+
latents_history_mid: torch.Tensor = None,
|
| 692 |
+
latents_history_long: torch.Tensor = None,
|
| 693 |
+
attention_kwargs: dict | None = None,
|
| 694 |
+
device: torch.device | None = None,
|
| 695 |
+
transformer_dtype: torch.dtype = None,
|
| 696 |
+
generator: torch.Generator | None = None,
|
| 697 |
+
# ------------ CFG Zero ------------
|
| 698 |
+
use_zero_init: bool | None = True,
|
| 699 |
+
zero_steps: int | None = 1,
|
| 700 |
+
# -------------- DMD --------------
|
| 701 |
+
is_amplify_first_chunk: bool = False,
|
| 702 |
+
# ------------ Callback ------------
|
| 703 |
+
callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
|
| 704 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 705 |
+
progress_bar=None,
|
| 706 |
+
chunk_index: int = 0,
|
| 707 |
+
relative_l1_records: list[dict[str, float | int]] | None = None,
|
| 708 |
+
):
|
| 709 |
+
batch_size, num_channel, num_frames, height, width = latents.shape
|
| 710 |
+
latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, num_channel, height, width)
|
| 711 |
+
for _ in range(pyramid_num_stages - 1):
|
| 712 |
+
height //= 2
|
| 713 |
+
width //= 2
|
| 714 |
+
latents = (
|
| 715 |
+
F.interpolate(
|
| 716 |
+
latents,
|
| 717 |
+
size=(height, width),
|
| 718 |
+
mode="bilinear",
|
| 719 |
+
)
|
| 720 |
+
* 2
|
| 721 |
+
)
|
| 722 |
+
latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4)
|
| 723 |
+
|
| 724 |
+
batch_size = latents.shape[0]
|
| 725 |
+
start_point_list = None
|
| 726 |
+
if self.config.is_distilled:
|
| 727 |
+
start_point_list = [latents]
|
| 728 |
+
|
| 729 |
+
i = 0
|
| 730 |
+
total_stage2_steps = sum(pyramid_num_inference_steps_list)
|
| 731 |
+
for i_s in range(pyramid_num_stages):
|
| 732 |
+
patch_size = self.transformer.config.patch_size
|
| 733 |
+
image_seq_len = (latents.shape[-1] * latents.shape[-2] * latents.shape[-3]) // (
|
| 734 |
+
patch_size[0] * patch_size[1] * patch_size[2]
|
| 735 |
+
)
|
| 736 |
+
mu = calculate_shift(
|
| 737 |
+
image_seq_len,
|
| 738 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
| 739 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
| 740 |
+
self.scheduler.config.get("base_shift", 0.5),
|
| 741 |
+
self.scheduler.config.get("max_shift", 1.15),
|
| 742 |
+
)
|
| 743 |
+
self.scheduler.set_timesteps(
|
| 744 |
+
pyramid_num_inference_steps_list[i_s],
|
| 745 |
+
i_s,
|
| 746 |
+
device=device,
|
| 747 |
+
mu=mu,
|
| 748 |
+
is_amplify_first_chunk=is_amplify_first_chunk,
|
| 749 |
+
)
|
| 750 |
+
timesteps = self.scheduler.timesteps
|
| 751 |
+
|
| 752 |
+
if i_s > 0:
|
| 753 |
+
height *= 2
|
| 754 |
+
width *= 2
|
| 755 |
+
num_frames = latents.shape[2]
|
| 756 |
+
latents = latents.permute(0, 2, 1, 3, 4).reshape(
|
| 757 |
+
batch_size * num_frames, num_channel, height // 2, width // 2
|
| 758 |
+
)
|
| 759 |
+
latents = F.interpolate(latents, size=(height, width), mode="nearest")
|
| 760 |
+
latents = latents.reshape(batch_size, num_frames, num_channel, height, width).permute(0, 2, 1, 3, 4)
|
| 761 |
+
# Fix the stage
|
| 762 |
+
ori_sigma = 1 - self.scheduler.ori_start_sigmas[i_s] # the original coeff of signal
|
| 763 |
+
gamma = self.scheduler.config.gamma
|
| 764 |
+
alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
|
| 765 |
+
beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
|
| 766 |
+
|
| 767 |
+
batch_size, channel, num_frames, height, width = latents.shape
|
| 768 |
+
noise = self.sample_block_noise(
|
| 769 |
+
batch_size, channel, num_frames, height, width, patch_size, device, generator
|
| 770 |
+
)
|
| 771 |
+
noise = noise.to(device=device, dtype=transformer_dtype)
|
| 772 |
+
latents = alpha * latents + beta * noise # To fix the block artifact
|
| 773 |
+
|
| 774 |
+
if self.config.is_distilled:
|
| 775 |
+
start_point_list.append(latents)
|
| 776 |
+
|
| 777 |
+
for idx, t in enumerate(timesteps):
|
| 778 |
+
timestep = t.expand(latents.shape[0]).to(torch.int64)
|
| 779 |
+
|
| 780 |
+
self.transformer.set_short_attn_debug_context(
|
| 781 |
+
chunk_index=chunk_index,
|
| 782 |
+
stage="stage2",
|
| 783 |
+
stage_index=i_s,
|
| 784 |
+
step_index=i,
|
| 785 |
+
total_steps=total_stage2_steps,
|
| 786 |
+
pass_name="cond",
|
| 787 |
+
timestep=float(t.detach().cpu().item()) if torch.is_tensor(t) else float(t),
|
| 788 |
+
)
|
| 789 |
+
with self.transformer.cache_context("cond"):
|
| 790 |
+
noise_pred = self.transformer(
|
| 791 |
+
hidden_states=latents.to(transformer_dtype),
|
| 792 |
+
timestep=timestep,
|
| 793 |
+
encoder_hidden_states=prompt_embeds,
|
| 794 |
+
attention_kwargs=attention_kwargs,
|
| 795 |
+
return_dict=False,
|
| 796 |
+
indices_hidden_states=indices_hidden_states,
|
| 797 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 798 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 799 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 800 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 801 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 802 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 803 |
+
)[0]
|
| 804 |
+
|
| 805 |
+
if self.do_classifier_free_guidance:
|
| 806 |
+
self.transformer.set_short_attn_debug_context(
|
| 807 |
+
chunk_index=chunk_index,
|
| 808 |
+
stage="stage2",
|
| 809 |
+
stage_index=i_s,
|
| 810 |
+
step_index=i,
|
| 811 |
+
total_steps=total_stage2_steps,
|
| 812 |
+
pass_name="uncond",
|
| 813 |
+
timestep=float(t.detach().cpu().item()) if torch.is_tensor(t) else float(t),
|
| 814 |
+
)
|
| 815 |
+
with self.transformer.cache_context("uncond"):
|
| 816 |
+
noise_uncond = self.transformer(
|
| 817 |
+
hidden_states=latents.to(transformer_dtype),
|
| 818 |
+
timestep=timestep,
|
| 819 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 820 |
+
attention_kwargs=attention_kwargs,
|
| 821 |
+
return_dict=False,
|
| 822 |
+
indices_hidden_states=indices_hidden_states,
|
| 823 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 824 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 825 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 826 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 827 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 828 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 829 |
+
)[0]
|
| 830 |
+
|
| 831 |
+
if self.config.is_cfg_zero_star:
|
| 832 |
+
noise_pred_text = noise_pred
|
| 833 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 834 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 835 |
+
|
| 836 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 837 |
+
alpha = alpha.view(batch_size, *([1] * (len(noise_pred_text.shape) - 1)))
|
| 838 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 839 |
+
|
| 840 |
+
if (i_s == 0 and idx <= zero_steps) and use_zero_init:
|
| 841 |
+
noise_pred = noise_pred_text * 0.0
|
| 842 |
+
else:
|
| 843 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (
|
| 844 |
+
noise_pred_text - noise_uncond * alpha
|
| 845 |
+
)
|
| 846 |
+
else:
|
| 847 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 848 |
+
|
| 849 |
+
latents_t = latents
|
| 850 |
+
latents = self.scheduler.step(
|
| 851 |
+
noise_pred,
|
| 852 |
+
t,
|
| 853 |
+
latents,
|
| 854 |
+
generator=generator,
|
| 855 |
+
return_dict=False,
|
| 856 |
+
cur_sampling_step=idx,
|
| 857 |
+
dmd_noisy_tensor=start_point_list[i_s] if start_point_list is not None else None,
|
| 858 |
+
dmd_sigmas=self.scheduler.sigmas,
|
| 859 |
+
dmd_timesteps=self.scheduler.timesteps,
|
| 860 |
+
all_timesteps=timesteps,
|
| 861 |
+
)[0]
|
| 862 |
+
self.record_relative_l1(relative_l1_records, chunk_index, i_s, i, t, latents_t, latents)
|
| 863 |
+
|
| 864 |
+
if callback_on_step_end is not None:
|
| 865 |
+
callback_kwargs = {}
|
| 866 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 867 |
+
callback_kwargs[k] = locals()[k]
|
| 868 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 869 |
+
|
| 870 |
+
latents = callback_outputs.pop("latents", latents)
|
| 871 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 872 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 873 |
+
|
| 874 |
+
progress_bar.update()
|
| 875 |
+
|
| 876 |
+
if XLA_AVAILABLE:
|
| 877 |
+
xm.mark_step()
|
| 878 |
+
|
| 879 |
+
i += 1
|
| 880 |
+
|
| 881 |
+
return latents
|
| 882 |
+
|
| 883 |
+
@property
|
| 884 |
+
def guidance_scale(self):
|
| 885 |
+
return self._guidance_scale
|
| 886 |
+
|
| 887 |
+
@property
|
| 888 |
+
def do_classifier_free_guidance(self):
|
| 889 |
+
return self._guidance_scale > 1.0
|
| 890 |
+
|
| 891 |
+
@property
|
| 892 |
+
def num_timesteps(self):
|
| 893 |
+
return self._num_timesteps
|
| 894 |
+
|
| 895 |
+
@property
|
| 896 |
+
def current_timestep(self):
|
| 897 |
+
return self._current_timestep
|
| 898 |
+
|
| 899 |
+
@property
|
| 900 |
+
def interrupt(self):
|
| 901 |
+
return self._interrupt
|
| 902 |
+
|
| 903 |
+
@property
|
| 904 |
+
def attention_kwargs(self):
|
| 905 |
+
return self._attention_kwargs
|
| 906 |
+
|
| 907 |
+
@torch.no_grad()
|
| 908 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 909 |
+
def __call__(
|
| 910 |
+
self,
|
| 911 |
+
prompt: str | list[str] = None,
|
| 912 |
+
negative_prompt: str | list[str] = None,
|
| 913 |
+
height: int = 384,
|
| 914 |
+
width: int = 640,
|
| 915 |
+
num_frames: int = 132,
|
| 916 |
+
num_inference_steps: int = 50,
|
| 917 |
+
sigmas: list[float] = None,
|
| 918 |
+
guidance_scale: float = 5.0,
|
| 919 |
+
num_videos_per_prompt: int | None = 1,
|
| 920 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 921 |
+
latents: torch.Tensor | None = None,
|
| 922 |
+
prompt_embeds: torch.Tensor | None = None,
|
| 923 |
+
negative_prompt_embeds: torch.Tensor | None = None,
|
| 924 |
+
output_type: str | None = "np",
|
| 925 |
+
return_dict: bool = True,
|
| 926 |
+
attention_kwargs: dict[str, Any] | None = None,
|
| 927 |
+
callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None,
|
| 928 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 929 |
+
max_sequence_length: int = 512,
|
| 930 |
+
# ------------ I2V ------------
|
| 931 |
+
image: PipelineImageInput | None = None,
|
| 932 |
+
image_latents: torch.Tensor | None = None,
|
| 933 |
+
fake_image_latents: torch.Tensor | None = None,
|
| 934 |
+
add_noise_to_image_latents: bool = True,
|
| 935 |
+
image_noise_sigma_min: float = 0.111,
|
| 936 |
+
image_noise_sigma_max: float = 0.135,
|
| 937 |
+
# ------------ V2V ------------
|
| 938 |
+
video: PipelineImageInput | None = None,
|
| 939 |
+
video_latents: torch.Tensor | None = None,
|
| 940 |
+
add_noise_to_video_latents: bool = True,
|
| 941 |
+
video_noise_sigma_min: float = 0.111,
|
| 942 |
+
video_noise_sigma_max: float = 0.135,
|
| 943 |
+
# ------------ Interactive ------------
|
| 944 |
+
use_interpolate_prompt: bool = False,
|
| 945 |
+
interpolate_time_list: list = [7, 7, 7],
|
| 946 |
+
interpolation_steps: int = 3,
|
| 947 |
+
# ------------ Stage 1 ------------
|
| 948 |
+
history_sizes: list = [16, 2, 1],
|
| 949 |
+
num_latent_frames_per_chunk: int = 9,
|
| 950 |
+
keep_first_frame: bool = True,
|
| 951 |
+
is_skip_first_chunk: bool = False,
|
| 952 |
+
# ------------ Stage 2 ------------
|
| 953 |
+
is_enable_stage2: bool = False,
|
| 954 |
+
pyramid_num_stages: int = 3,
|
| 955 |
+
pyramid_num_inference_steps_list: list = [10, 10, 10],
|
| 956 |
+
# ------------ CFG Zero ------------
|
| 957 |
+
use_zero_init: bool | None = True,
|
| 958 |
+
zero_steps: int | None = 1,
|
| 959 |
+
# ------------ DMD ------------
|
| 960 |
+
is_amplify_first_chunk: bool = False,
|
| 961 |
+
# ------------ Debug ------------
|
| 962 |
+
output_relative_l1: bool = False,
|
| 963 |
+
short_attn_debug: dict[str, Any] | None = None,
|
| 964 |
+
):
|
| 965 |
+
r"""
|
| 966 |
+
The call function to the pipeline for generation.
|
| 967 |
+
|
| 968 |
+
Args:
|
| 969 |
+
prompt (`str` or `list[str]`, *optional*):
|
| 970 |
+
The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
|
| 971 |
+
negative_prompt (`str` or `list[str]`, *optional*):
|
| 972 |
+
The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
|
| 973 |
+
instead. Ignored when not using guidance (`guidance_scale` < `1`).
|
| 974 |
+
height (`int`, defaults to `384`):
|
| 975 |
+
The height in pixels of the generated image.
|
| 976 |
+
width (`int`, defaults to `640`):
|
| 977 |
+
The width in pixels of the generated image.
|
| 978 |
+
num_frames (`int`, defaults to `132`):
|
| 979 |
+
The number of frames in the generated video.
|
| 980 |
+
num_inference_steps (`int`, defaults to `50`):
|
| 981 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 982 |
+
expense of slower inference.
|
| 983 |
+
guidance_scale (`float`, defaults to `5.0`):
|
| 984 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 985 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 986 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 987 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 988 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 989 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 990 |
+
The number of images to generate per prompt.
|
| 991 |
+
generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
|
| 992 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 993 |
+
generation deterministic.
|
| 994 |
+
latents (`torch.Tensor`, *optional*):
|
| 995 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 996 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 997 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 998 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 999 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 1000 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 1001 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
| 1002 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 1003 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 1004 |
+
Whether or not to return a [`HeliosPipelineOutput`] instead of a plain tuple.
|
| 1005 |
+
attention_kwargs (`dict`, *optional*):
|
| 1006 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 1007 |
+
`self.processor` in
|
| 1008 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 1009 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 1010 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 1011 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 1012 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 1013 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 1014 |
+
callback_on_step_end_tensor_inputs (`list`, *optional*):
|
| 1015 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 1016 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 1017 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 1018 |
+
max_sequence_length (`int`, defaults to `512`):
|
| 1019 |
+
The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
|
| 1020 |
+
truncated. If the prompt is shorter, it will be padded to this length.
|
| 1021 |
+
|
| 1022 |
+
Examples:
|
| 1023 |
+
|
| 1024 |
+
Returns:
|
| 1025 |
+
[`~HeliosPipelineOutput`] or `tuple`:
|
| 1026 |
+
If `return_dict` is `True`, [`HeliosPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
| 1027 |
+
the first element is a list with the generated images and the second element is a list of `bool`s
|
| 1028 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
| 1029 |
+
"""
|
| 1030 |
+
|
| 1031 |
+
if image is not None and video is not None:
|
| 1032 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 1033 |
+
|
| 1034 |
+
history_sizes = sorted(history_sizes, reverse=True) # From big to small
|
| 1035 |
+
|
| 1036 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 1037 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 1038 |
+
|
| 1039 |
+
# 1. Check inputs. Raise error if not correct
|
| 1040 |
+
self.check_inputs(
|
| 1041 |
+
prompt,
|
| 1042 |
+
negative_prompt,
|
| 1043 |
+
height,
|
| 1044 |
+
width,
|
| 1045 |
+
prompt_embeds,
|
| 1046 |
+
negative_prompt_embeds,
|
| 1047 |
+
callback_on_step_end_tensor_inputs,
|
| 1048 |
+
image,
|
| 1049 |
+
video,
|
| 1050 |
+
use_interpolate_prompt,
|
| 1051 |
+
num_videos_per_prompt,
|
| 1052 |
+
interpolate_time_list,
|
| 1053 |
+
interpolation_steps,
|
| 1054 |
+
guidance_scale,
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
num_frames = max(num_frames, 1)
|
| 1058 |
+
|
| 1059 |
+
self._guidance_scale = guidance_scale
|
| 1060 |
+
self._attention_kwargs = attention_kwargs
|
| 1061 |
+
self._current_timestep = None
|
| 1062 |
+
self._interrupt = False
|
| 1063 |
+
relative_l1_records = [] if output_relative_l1 else None
|
| 1064 |
+
|
| 1065 |
+
device = self._execution_device
|
| 1066 |
+
vae_dtype = self.vae.dtype
|
| 1067 |
+
|
| 1068 |
+
if short_attn_debug:
|
| 1069 |
+
short_attn_debug = dict(short_attn_debug)
|
| 1070 |
+
patch_size = self.transformer.config.patch_size
|
| 1071 |
+
short_attn_debug.setdefault(
|
| 1072 |
+
"grid",
|
| 1073 |
+
(
|
| 1074 |
+
height // self.vae_scale_factor_spatial // patch_size[1],
|
| 1075 |
+
width // self.vae_scale_factor_spatial // patch_size[2],
|
| 1076 |
+
),
|
| 1077 |
+
)
|
| 1078 |
+
self.transformer.configure_short_attn_debug(short_attn_debug)
|
| 1079 |
+
else:
|
| 1080 |
+
self.transformer.configure_short_attn_debug(None)
|
| 1081 |
+
|
| 1082 |
+
latents_mean = (
|
| 1083 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 1084 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 1085 |
+
.to(device, self.vae.dtype)
|
| 1086 |
+
)
|
| 1087 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 1088 |
+
device, self.vae.dtype
|
| 1089 |
+
)
|
| 1090 |
+
|
| 1091 |
+
# 2. Define call parameters
|
| 1092 |
+
if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)):
|
| 1093 |
+
batch_size = 1
|
| 1094 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1095 |
+
batch_size = len(prompt)
|
| 1096 |
+
else:
|
| 1097 |
+
batch_size = prompt_embeds.shape[0]
|
| 1098 |
+
|
| 1099 |
+
# 3. Encode input prompt
|
| 1100 |
+
if use_interpolate_prompt:
|
| 1101 |
+
interpolate_interval_idx = None
|
| 1102 |
+
interpolate_embeds = None
|
| 1103 |
+
interpolate_cumulative_list = list(accumulate(interpolate_time_list))
|
| 1104 |
+
|
| 1105 |
+
all_prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 1106 |
+
prompt=prompt,
|
| 1107 |
+
negative_prompt=negative_prompt,
|
| 1108 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 1109 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 1110 |
+
prompt_embeds=prompt_embeds,
|
| 1111 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1112 |
+
max_sequence_length=max_sequence_length,
|
| 1113 |
+
device=device,
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
transformer_dtype = self.transformer.dtype
|
| 1117 |
+
all_prompt_embeds = all_prompt_embeds.to(transformer_dtype)
|
| 1118 |
+
if negative_prompt_embeds is not None:
|
| 1119 |
+
if use_interpolate_prompt:
|
| 1120 |
+
negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0)
|
| 1121 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 1122 |
+
|
| 1123 |
+
# 4. Prepare image or video
|
| 1124 |
+
if image is not None:
|
| 1125 |
+
image = self.video_processor.preprocess(image, height=height, width=width)
|
| 1126 |
+
image_latents, fake_image_latents = self.prepare_image_latents(
|
| 1127 |
+
image,
|
| 1128 |
+
latents_mean=latents_mean,
|
| 1129 |
+
latents_std=latents_std,
|
| 1130 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1131 |
+
dtype=torch.float32,
|
| 1132 |
+
device=device,
|
| 1133 |
+
generator=generator,
|
| 1134 |
+
latents=image_latents,
|
| 1135 |
+
fake_latents=fake_image_latents,
|
| 1136 |
+
)
|
| 1137 |
+
|
| 1138 |
+
if image_latents is not None and add_noise_to_image_latents:
|
| 1139 |
+
image_noise_sigma = (
|
| 1140 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1141 |
+
+ image_noise_sigma_min
|
| 1142 |
+
)
|
| 1143 |
+
image_latents = (
|
| 1144 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1145 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1146 |
+
)
|
| 1147 |
+
fake_image_noise_sigma = (
|
| 1148 |
+
torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min)
|
| 1149 |
+
+ video_noise_sigma_min
|
| 1150 |
+
)
|
| 1151 |
+
fake_image_latents = (
|
| 1152 |
+
fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device)
|
| 1153 |
+
+ (1 - fake_image_noise_sigma) * fake_image_latents
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
if video is not None:
|
| 1157 |
+
video = self.video_processor.preprocess_video(video, height=height, width=width)
|
| 1158 |
+
image_latents, video_latents = self.prepare_video_latents(
|
| 1159 |
+
video,
|
| 1160 |
+
latents_mean=latents_mean,
|
| 1161 |
+
latents_std=latents_std,
|
| 1162 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1163 |
+
dtype=torch.float32,
|
| 1164 |
+
device=device,
|
| 1165 |
+
generator=generator,
|
| 1166 |
+
latents=video_latents,
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
if video_latents is not None and add_noise_to_video_latents:
|
| 1170 |
+
image_noise_sigma = (
|
| 1171 |
+
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
|
| 1172 |
+
+ image_noise_sigma_min
|
| 1173 |
+
)
|
| 1174 |
+
image_latents = (
|
| 1175 |
+
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1176 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1177 |
+
)
|
| 1178 |
+
|
| 1179 |
+
noisy_latents_chunks = []
|
| 1180 |
+
num_latent_chunks = video_latents.shape[2] // num_latent_frames_per_chunk
|
| 1181 |
+
for i in range(num_latent_chunks):
|
| 1182 |
+
chunk_start = i * num_latent_frames_per_chunk
|
| 1183 |
+
chunk_end = chunk_start + num_latent_frames_per_chunk
|
| 1184 |
+
latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :]
|
| 1185 |
+
|
| 1186 |
+
chunk_frames = latent_chunk.shape[2]
|
| 1187 |
+
frame_sigmas = (
|
| 1188 |
+
torch.rand(chunk_frames, device=device, generator=generator)
|
| 1189 |
+
* (video_noise_sigma_max - video_noise_sigma_min)
|
| 1190 |
+
+ video_noise_sigma_min
|
| 1191 |
+
)
|
| 1192 |
+
frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1)
|
| 1193 |
+
|
| 1194 |
+
noisy_chunk = (
|
| 1195 |
+
frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device)
|
| 1196 |
+
+ (1 - frame_sigmas) * latent_chunk
|
| 1197 |
+
)
|
| 1198 |
+
noisy_latents_chunks.append(noisy_chunk)
|
| 1199 |
+
video_latents = torch.cat(noisy_latents_chunks, dim=2)
|
| 1200 |
+
|
| 1201 |
+
# 5. Prepare latent variables
|
| 1202 |
+
num_channels_latents = self.transformer.config.in_channels
|
| 1203 |
+
window_num_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
|
| 1204 |
+
num_latent_chunk = max(1, (num_frames + window_num_frames - 1) // window_num_frames)
|
| 1205 |
+
num_history_latent_frames = sum(history_sizes)
|
| 1206 |
+
history_video = None
|
| 1207 |
+
total_generated_latent_frames = 0
|
| 1208 |
+
|
| 1209 |
+
if not keep_first_frame:
|
| 1210 |
+
history_sizes[-1] = history_sizes[-1] + 1
|
| 1211 |
+
history_latents = torch.zeros(
|
| 1212 |
+
batch_size,
|
| 1213 |
+
num_channels_latents,
|
| 1214 |
+
num_history_latent_frames,
|
| 1215 |
+
height // self.vae_scale_factor_spatial,
|
| 1216 |
+
width // self.vae_scale_factor_spatial,
|
| 1217 |
+
device=device,
|
| 1218 |
+
dtype=torch.float32,
|
| 1219 |
+
)
|
| 1220 |
+
if fake_image_latents is not None:
|
| 1221 |
+
history_latents = torch.cat([history_latents[:, :, :-1, :, :], fake_image_latents], dim=2)
|
| 1222 |
+
total_generated_latent_frames += 1
|
| 1223 |
+
if video_latents is not None:
|
| 1224 |
+
history_frames = history_latents.shape[2]
|
| 1225 |
+
video_frames = video_latents.shape[2]
|
| 1226 |
+
if video_frames < history_frames:
|
| 1227 |
+
keep_frames = history_frames - video_frames
|
| 1228 |
+
history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2)
|
| 1229 |
+
else:
|
| 1230 |
+
history_latents = video_latents
|
| 1231 |
+
total_generated_latent_frames += video_latents.shape[2]
|
| 1232 |
+
|
| 1233 |
+
if keep_first_frame:
|
| 1234 |
+
indices = torch.arange(0, sum([1, *history_sizes, num_latent_frames_per_chunk]))
|
| 1235 |
+
(
|
| 1236 |
+
indices_prefix,
|
| 1237 |
+
indices_latents_history_long,
|
| 1238 |
+
indices_latents_history_mid,
|
| 1239 |
+
indices_latents_history_1x,
|
| 1240 |
+
indices_hidden_states,
|
| 1241 |
+
) = indices.split([1, *history_sizes, num_latent_frames_per_chunk], dim=0)
|
| 1242 |
+
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
|
| 1243 |
+
else:
|
| 1244 |
+
indices = torch.arange(0, sum([*history_sizes, num_latent_frames_per_chunk]))
|
| 1245 |
+
(
|
| 1246 |
+
indices_latents_history_long,
|
| 1247 |
+
indices_latents_history_mid,
|
| 1248 |
+
indices_latents_history_short,
|
| 1249 |
+
indices_hidden_states,
|
| 1250 |
+
) = indices.split([*history_sizes, num_latent_frames_per_chunk], dim=0)
|
| 1251 |
+
indices_hidden_states = indices_hidden_states.unsqueeze(0)
|
| 1252 |
+
indices_latents_history_short = indices_latents_history_short.unsqueeze(0)
|
| 1253 |
+
indices_latents_history_mid = indices_latents_history_mid.unsqueeze(0)
|
| 1254 |
+
indices_latents_history_long = indices_latents_history_long.unsqueeze(0)
|
| 1255 |
+
|
| 1256 |
+
# 6. Denoising loop
|
| 1257 |
+
if use_interpolate_prompt:
|
| 1258 |
+
if num_latent_chunk < max(interpolate_cumulative_list):
|
| 1259 |
+
num_latent_chunk = sum(interpolate_cumulative_list)
|
| 1260 |
+
print(f"Update num_latent_chunk to: {num_latent_chunk}")
|
| 1261 |
+
|
| 1262 |
+
if not is_enable_stage2:
|
| 1263 |
+
patch_size = self.transformer.config.patch_size
|
| 1264 |
+
image_seq_len = (
|
| 1265 |
+
num_latent_frames_per_chunk
|
| 1266 |
+
* (height // self.vae_scale_factor_spatial)
|
| 1267 |
+
* (width // self.vae_scale_factor_spatial)
|
| 1268 |
+
// (patch_size[0] * patch_size[1] * patch_size[2])
|
| 1269 |
+
)
|
| 1270 |
+
sigmas = np.linspace(0.999, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
|
| 1271 |
+
mu = calculate_shift(
|
| 1272 |
+
image_seq_len,
|
| 1273 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
| 1274 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
| 1275 |
+
self.scheduler.config.get("base_shift", 0.5),
|
| 1276 |
+
self.scheduler.config.get("max_shift", 1.15),
|
| 1277 |
+
)
|
| 1278 |
+
|
| 1279 |
+
for k in range(num_latent_chunk):
|
| 1280 |
+
if use_interpolate_prompt:
|
| 1281 |
+
assert num_latent_chunk >= max(interpolate_cumulative_list)
|
| 1282 |
+
|
| 1283 |
+
current_interval_idx = 0
|
| 1284 |
+
for idx, cumulative_val in enumerate(interpolate_cumulative_list):
|
| 1285 |
+
if k < cumulative_val:
|
| 1286 |
+
current_interval_idx = idx
|
| 1287 |
+
break
|
| 1288 |
+
|
| 1289 |
+
if current_interval_idx == 0:
|
| 1290 |
+
prompt_embeds = all_prompt_embeds[0].unsqueeze(0)
|
| 1291 |
+
else:
|
| 1292 |
+
interval_start = interpolate_cumulative_list[current_interval_idx - 1]
|
| 1293 |
+
position_in_interval = k - interval_start
|
| 1294 |
+
|
| 1295 |
+
if position_in_interval < interpolation_steps:
|
| 1296 |
+
if interpolate_embeds is None or interpolate_interval_idx != current_interval_idx:
|
| 1297 |
+
interpolate_embeds = self.interpolate_prompt_embeds(
|
| 1298 |
+
prompt_embeds_1=all_prompt_embeds[current_interval_idx - 1].unsqueeze(0),
|
| 1299 |
+
prompt_embeds_2=all_prompt_embeds[current_interval_idx].unsqueeze(0),
|
| 1300 |
+
interpolation_steps=interpolation_steps,
|
| 1301 |
+
)
|
| 1302 |
+
interpolate_interval_idx = current_interval_idx
|
| 1303 |
+
|
| 1304 |
+
prompt_embeds = interpolate_embeds[position_in_interval]
|
| 1305 |
+
else:
|
| 1306 |
+
prompt_embeds = all_prompt_embeds[current_interval_idx].unsqueeze(0)
|
| 1307 |
+
else:
|
| 1308 |
+
prompt_embeds = all_prompt_embeds
|
| 1309 |
+
|
| 1310 |
+
is_first_chunk = k == 0
|
| 1311 |
+
is_second_chunk = k == 1
|
| 1312 |
+
if keep_first_frame:
|
| 1313 |
+
latents_history_long, latents_history_mid, latents_history_1x = history_latents[
|
| 1314 |
+
:, :, -num_history_latent_frames:
|
| 1315 |
+
].split(history_sizes, dim=2)
|
| 1316 |
+
if image_latents is None and is_first_chunk:
|
| 1317 |
+
latents_prefix = torch.zeros(
|
| 1318 |
+
(
|
| 1319 |
+
batch_size,
|
| 1320 |
+
num_channels_latents,
|
| 1321 |
+
1,
|
| 1322 |
+
latents_history_1x.shape[-2],
|
| 1323 |
+
latents_history_1x.shape[-1],
|
| 1324 |
+
),
|
| 1325 |
+
device=device,
|
| 1326 |
+
dtype=latents_history_1x.dtype,
|
| 1327 |
+
)
|
| 1328 |
+
else:
|
| 1329 |
+
latents_prefix = image_latents
|
| 1330 |
+
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
|
| 1331 |
+
else:
|
| 1332 |
+
latents_history_long, latents_history_mid, latents_history_short = history_latents[
|
| 1333 |
+
:, :, -num_history_latent_frames:
|
| 1334 |
+
].split(history_sizes, dim=2)
|
| 1335 |
+
|
| 1336 |
+
latents = self.prepare_latents(
|
| 1337 |
+
batch_size,
|
| 1338 |
+
num_channels_latents,
|
| 1339 |
+
height,
|
| 1340 |
+
width,
|
| 1341 |
+
window_num_frames,
|
| 1342 |
+
dtype=torch.float32,
|
| 1343 |
+
device=device,
|
| 1344 |
+
generator=generator,
|
| 1345 |
+
latents=None,
|
| 1346 |
+
)
|
| 1347 |
+
|
| 1348 |
+
if not is_enable_stage2:
|
| 1349 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device, sigmas=sigmas, mu=mu)
|
| 1350 |
+
timesteps = self.scheduler.timesteps
|
| 1351 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 1352 |
+
self._num_timesteps = len(timesteps)
|
| 1353 |
+
else:
|
| 1354 |
+
num_inference_steps = (
|
| 1355 |
+
sum(pyramid_num_inference_steps_list) * 2
|
| 1356 |
+
if is_amplify_first_chunk and self.config.is_distilled and is_first_chunk
|
| 1357 |
+
else sum(pyramid_num_inference_steps_list)
|
| 1358 |
+
)
|
| 1359 |
+
|
| 1360 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1361 |
+
if is_enable_stage2:
|
| 1362 |
+
latents = self.stage2_sample(
|
| 1363 |
+
latents=latents,
|
| 1364 |
+
pyramid_num_stages=pyramid_num_stages,
|
| 1365 |
+
pyramid_num_inference_steps_list=pyramid_num_inference_steps_list,
|
| 1366 |
+
prompt_embeds=prompt_embeds,
|
| 1367 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1368 |
+
guidance_scale=guidance_scale,
|
| 1369 |
+
indices_hidden_states=indices_hidden_states,
|
| 1370 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1371 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1372 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1373 |
+
latents_history_short=latents_history_short,
|
| 1374 |
+
latents_history_mid=latents_history_mid,
|
| 1375 |
+
latents_history_long=latents_history_long,
|
| 1376 |
+
attention_kwargs=attention_kwargs,
|
| 1377 |
+
device=device,
|
| 1378 |
+
transformer_dtype=transformer_dtype,
|
| 1379 |
+
# ------------ CFG Zero ------------
|
| 1380 |
+
use_zero_init=use_zero_init,
|
| 1381 |
+
zero_steps=zero_steps,
|
| 1382 |
+
# -------------- DMD --------------
|
| 1383 |
+
is_amplify_first_chunk=is_amplify_first_chunk and is_first_chunk,
|
| 1384 |
+
# ------------ Callback ------------
|
| 1385 |
+
callback_on_step_end=callback_on_step_end,
|
| 1386 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1387 |
+
progress_bar=progress_bar,
|
| 1388 |
+
chunk_index=k,
|
| 1389 |
+
relative_l1_records=relative_l1_records,
|
| 1390 |
+
)
|
| 1391 |
+
else:
|
| 1392 |
+
latents = self.stage1_sample(
|
| 1393 |
+
latents=latents,
|
| 1394 |
+
prompt_embeds=prompt_embeds,
|
| 1395 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1396 |
+
timesteps=timesteps,
|
| 1397 |
+
guidance_scale=guidance_scale,
|
| 1398 |
+
indices_hidden_states=indices_hidden_states,
|
| 1399 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1400 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1401 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 1402 |
+
latents_history_short=latents_history_short,
|
| 1403 |
+
latents_history_mid=latents_history_mid,
|
| 1404 |
+
latents_history_long=latents_history_long,
|
| 1405 |
+
attention_kwargs=attention_kwargs,
|
| 1406 |
+
device=device,
|
| 1407 |
+
transformer_dtype=transformer_dtype,
|
| 1408 |
+
generator=generator,
|
| 1409 |
+
num_warmup_steps=num_warmup_steps,
|
| 1410 |
+
# ------------ CFG Zero ------------
|
| 1411 |
+
use_zero_init=use_zero_init,
|
| 1412 |
+
zero_steps=zero_steps,
|
| 1413 |
+
# ------------ Callback ------------
|
| 1414 |
+
callback_on_step_end=callback_on_step_end,
|
| 1415 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1416 |
+
progress_bar=progress_bar,
|
| 1417 |
+
chunk_index=k,
|
| 1418 |
+
relative_l1_records=relative_l1_records,
|
| 1419 |
+
)
|
| 1420 |
+
|
| 1421 |
+
if keep_first_frame and (
|
| 1422 |
+
(is_first_chunk and image_latents is None) or (is_skip_first_chunk and is_second_chunk)
|
| 1423 |
+
):
|
| 1424 |
+
image_latents = latents[:, :, 0:1, :, :]
|
| 1425 |
+
|
| 1426 |
+
total_generated_latent_frames += latents.shape[2]
|
| 1427 |
+
history_latents = torch.cat([history_latents, latents], dim=2)
|
| 1428 |
+
real_history_latents = history_latents[:, :, -total_generated_latent_frames:]
|
| 1429 |
+
current_latents = (
|
| 1430 |
+
real_history_latents[:, :, -num_latent_frames_per_chunk:].to(vae_dtype) / latents_std
|
| 1431 |
+
+ latents_mean
|
| 1432 |
+
)
|
| 1433 |
+
current_video = self.vae.decode(current_latents, return_dict=False)[0]
|
| 1434 |
+
|
| 1435 |
+
if history_video is None:
|
| 1436 |
+
history_video = current_video
|
| 1437 |
+
else:
|
| 1438 |
+
history_video = torch.cat([history_video, current_video], dim=2)
|
| 1439 |
+
|
| 1440 |
+
self._current_timestep = None
|
| 1441 |
+
|
| 1442 |
+
if output_type != "latent":
|
| 1443 |
+
generated_frames = history_video.size(2)
|
| 1444 |
+
generated_frames = (
|
| 1445 |
+
generated_frames - 1
|
| 1446 |
+
) // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
|
| 1447 |
+
history_video = history_video[:, :, :generated_frames]
|
| 1448 |
+
video = self.video_processor.postprocess_video(history_video, output_type=output_type)
|
| 1449 |
+
else:
|
| 1450 |
+
video = real_history_latents
|
| 1451 |
+
|
| 1452 |
+
self.transformer.configure_short_attn_debug(None)
|
| 1453 |
+
|
| 1454 |
+
# Offload all models
|
| 1455 |
+
self.maybe_free_model_hooks()
|
| 1456 |
+
|
| 1457 |
+
if not return_dict:
|
| 1458 |
+
return (video,)
|
| 1459 |
+
|
| 1460 |
+
return HeliosPipelineOutput(frames=video, relative_l1=relative_l1_records)
|
Helios/_DEV2/helios/diffusers_version/scheduling_helios_diffusers.py
ADDED
|
@@ -0,0 +1,947 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Literal
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 23 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 24 |
+
from diffusers.utils import BaseOutput, deprecate
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class HeliosSchedulerOutput(BaseOutput):
|
| 29 |
+
prev_sample: torch.FloatTensor
|
| 30 |
+
model_outputs: torch.FloatTensor | None = None
|
| 31 |
+
last_sample: torch.FloatTensor | None = None
|
| 32 |
+
this_order: int | None = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class HeliosScheduler(SchedulerMixin, ConfigMixin):
|
| 36 |
+
_compatibles = []
|
| 37 |
+
order = 1
|
| 38 |
+
|
| 39 |
+
@register_to_config
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
num_train_timesteps: int = 1000,
|
| 43 |
+
shift: float = 1.0, # Following Stable diffusion 3,
|
| 44 |
+
stages: int = 3,
|
| 45 |
+
stage_range: list = [0, 1 / 3, 2 / 3, 1],
|
| 46 |
+
gamma: float = 1 / 3,
|
| 47 |
+
# For UniPC
|
| 48 |
+
thresholding: bool = False,
|
| 49 |
+
prediction_type: str = "flow_prediction",
|
| 50 |
+
solver_order: int = 2,
|
| 51 |
+
predict_x0: bool = True,
|
| 52 |
+
solver_type: str = "bh2",
|
| 53 |
+
lower_order_final: bool = True,
|
| 54 |
+
disable_corrector: list[int] = [],
|
| 55 |
+
solver_p: SchedulerMixin = None,
|
| 56 |
+
use_flow_sigmas: bool = True,
|
| 57 |
+
scheduler_type: str = "unipc", # ["euler", "unipc", "dmd"]
|
| 58 |
+
use_dynamic_shifting: bool = False,
|
| 59 |
+
time_shift_type: Literal["exponential", "linear"] = "linear",
|
| 60 |
+
):
|
| 61 |
+
self.timestep_ratios = {} # The timestep ratio for each stage
|
| 62 |
+
self.timesteps_per_stage = {} # The detailed timesteps per stage (fix max and min per stage)
|
| 63 |
+
self.sigmas_per_stage = {} # always uniform [1000, 0]
|
| 64 |
+
self.start_sigmas = {} # for start point / upsample renoise
|
| 65 |
+
self.end_sigmas = {} # for end point
|
| 66 |
+
self.ori_start_sigmas = {}
|
| 67 |
+
|
| 68 |
+
# self.init_sigmas()
|
| 69 |
+
self.init_sigmas_for_each_stage()
|
| 70 |
+
self.sigma_min = self.sigmas[-1].item()
|
| 71 |
+
self.sigma_max = self.sigmas[0].item()
|
| 72 |
+
self.gamma = gamma
|
| 73 |
+
|
| 74 |
+
if solver_type not in ["bh1", "bh2"]:
|
| 75 |
+
if solver_type in ["midpoint", "heun", "logrho"]:
|
| 76 |
+
self.register_to_config(solver_type="bh2")
|
| 77 |
+
else:
|
| 78 |
+
raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
|
| 79 |
+
|
| 80 |
+
self.predict_x0 = predict_x0
|
| 81 |
+
self.model_outputs = [None] * solver_order
|
| 82 |
+
self.timestep_list = [None] * solver_order
|
| 83 |
+
self.lower_order_nums = 0
|
| 84 |
+
self.disable_corrector = disable_corrector
|
| 85 |
+
self.solver_p = solver_p
|
| 86 |
+
self.last_sample = None
|
| 87 |
+
self._step_index = None
|
| 88 |
+
self._begin_index = None
|
| 89 |
+
|
| 90 |
+
def init_sigmas(self):
|
| 91 |
+
"""
|
| 92 |
+
initialize the global timesteps and sigmas
|
| 93 |
+
"""
|
| 94 |
+
num_train_timesteps = self.config.num_train_timesteps
|
| 95 |
+
shift = self.config.shift
|
| 96 |
+
|
| 97 |
+
alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps + 1)
|
| 98 |
+
sigmas = 1.0 - alphas
|
| 99 |
+
sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy()
|
| 100 |
+
sigmas = torch.from_numpy(sigmas)
|
| 101 |
+
timesteps = (sigmas * num_train_timesteps).clone()
|
| 102 |
+
|
| 103 |
+
self._step_index = None
|
| 104 |
+
self._begin_index = None
|
| 105 |
+
self.timesteps = timesteps
|
| 106 |
+
self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 107 |
+
|
| 108 |
+
def init_sigmas_for_each_stage(self):
|
| 109 |
+
"""
|
| 110 |
+
Init the timesteps for each stage
|
| 111 |
+
"""
|
| 112 |
+
self.init_sigmas()
|
| 113 |
+
|
| 114 |
+
stage_distance = []
|
| 115 |
+
stages = self.config.stages
|
| 116 |
+
training_steps = self.config.num_train_timesteps
|
| 117 |
+
stage_range = self.config.stage_range
|
| 118 |
+
|
| 119 |
+
# Init the start and end point of each stage
|
| 120 |
+
for i_s in range(stages):
|
| 121 |
+
# To decide the start and ends point
|
| 122 |
+
start_indice = int(stage_range[i_s] * training_steps)
|
| 123 |
+
start_indice = max(start_indice, 0)
|
| 124 |
+
end_indice = int(stage_range[i_s + 1] * training_steps)
|
| 125 |
+
end_indice = min(end_indice, training_steps)
|
| 126 |
+
start_sigma = self.sigmas[start_indice].item()
|
| 127 |
+
end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0
|
| 128 |
+
self.ori_start_sigmas[i_s] = start_sigma
|
| 129 |
+
|
| 130 |
+
if i_s != 0:
|
| 131 |
+
ori_sigma = 1 - start_sigma
|
| 132 |
+
gamma = self.config.gamma
|
| 133 |
+
corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma
|
| 134 |
+
# corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma
|
| 135 |
+
start_sigma = 1 - corrected_sigma
|
| 136 |
+
|
| 137 |
+
stage_distance.append(start_sigma - end_sigma)
|
| 138 |
+
self.start_sigmas[i_s] = start_sigma
|
| 139 |
+
self.end_sigmas[i_s] = end_sigma
|
| 140 |
+
|
| 141 |
+
# Determine the ratio of each stage according to flow length
|
| 142 |
+
tot_distance = sum(stage_distance)
|
| 143 |
+
for i_s in range(stages):
|
| 144 |
+
if i_s == 0:
|
| 145 |
+
start_ratio = 0.0
|
| 146 |
+
else:
|
| 147 |
+
start_ratio = sum(stage_distance[:i_s]) / tot_distance
|
| 148 |
+
if i_s == stages - 1:
|
| 149 |
+
end_ratio = 0.9999999999999999
|
| 150 |
+
else:
|
| 151 |
+
end_ratio = sum(stage_distance[: i_s + 1]) / tot_distance
|
| 152 |
+
|
| 153 |
+
self.timestep_ratios[i_s] = (start_ratio, end_ratio)
|
| 154 |
+
|
| 155 |
+
# Determine the timesteps and sigmas for each stage
|
| 156 |
+
for i_s in range(stages):
|
| 157 |
+
timestep_ratio = self.timestep_ratios[i_s]
|
| 158 |
+
# timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)]
|
| 159 |
+
timestep_max = min(self.timesteps[int(timestep_ratio[0] * training_steps)], 999)
|
| 160 |
+
timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)]
|
| 161 |
+
timesteps = np.linspace(timestep_max, timestep_min, training_steps + 1)
|
| 162 |
+
self.timesteps_per_stage[i_s] = (
|
| 163 |
+
timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1])
|
| 164 |
+
)
|
| 165 |
+
stage_sigmas = np.linspace(0.999, 0, training_steps + 1)
|
| 166 |
+
self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1])
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def step_index(self):
|
| 170 |
+
"""
|
| 171 |
+
The index counter for current timestep. It will increase 1 after each scheduler step.
|
| 172 |
+
"""
|
| 173 |
+
return self._step_index
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def begin_index(self):
|
| 177 |
+
"""
|
| 178 |
+
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
|
| 179 |
+
"""
|
| 180 |
+
return self._begin_index
|
| 181 |
+
|
| 182 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 183 |
+
"""
|
| 184 |
+
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
begin_index (`int`):
|
| 188 |
+
The begin index for the scheduler.
|
| 189 |
+
"""
|
| 190 |
+
self._begin_index = begin_index
|
| 191 |
+
|
| 192 |
+
def _sigma_to_t(self, sigma):
|
| 193 |
+
return sigma * self.config.num_train_timesteps
|
| 194 |
+
|
| 195 |
+
def set_timesteps(
|
| 196 |
+
self,
|
| 197 |
+
num_inference_steps: int,
|
| 198 |
+
stage_index: int | None = None,
|
| 199 |
+
device: str | torch.device = None,
|
| 200 |
+
sigmas: bool | None = None,
|
| 201 |
+
mu: bool | None = None,
|
| 202 |
+
is_amplify_first_chunk: bool = False,
|
| 203 |
+
):
|
| 204 |
+
"""
|
| 205 |
+
Setting the timesteps and sigmas for each stage
|
| 206 |
+
"""
|
| 207 |
+
if self.config.scheduler_type == "dmd":
|
| 208 |
+
if is_amplify_first_chunk:
|
| 209 |
+
num_inference_steps = num_inference_steps * 2 + 1
|
| 210 |
+
else:
|
| 211 |
+
num_inference_steps = num_inference_steps + 1
|
| 212 |
+
|
| 213 |
+
self.num_inference_steps = num_inference_steps
|
| 214 |
+
self.init_sigmas()
|
| 215 |
+
|
| 216 |
+
if self.config.stages == 1:
|
| 217 |
+
if sigmas is None:
|
| 218 |
+
sigmas = np.linspace(1, 1 / self.config.num_train_timesteps, num_inference_steps + 1)[:-1].astype(
|
| 219 |
+
np.float32
|
| 220 |
+
)
|
| 221 |
+
if self.config.shift != 1.0:
|
| 222 |
+
assert not self.config.use_dynamic_shifting
|
| 223 |
+
sigmas = self.time_shift(self.config.shift, 1.0, sigmas)
|
| 224 |
+
timesteps = (sigmas * self.config.num_train_timesteps).copy()
|
| 225 |
+
sigmas = torch.from_numpy(sigmas)
|
| 226 |
+
else:
|
| 227 |
+
stage_timesteps = self.timesteps_per_stage[stage_index]
|
| 228 |
+
timesteps = np.linspace(
|
| 229 |
+
stage_timesteps[0].item(),
|
| 230 |
+
stage_timesteps[-1].item(),
|
| 231 |
+
num_inference_steps,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
stage_sigmas = self.sigmas_per_stage[stage_index]
|
| 235 |
+
ratios = np.linspace(stage_sigmas[0].item(), stage_sigmas[-1].item(), num_inference_steps)
|
| 236 |
+
sigmas = torch.from_numpy(ratios)
|
| 237 |
+
|
| 238 |
+
self.timesteps = torch.from_numpy(timesteps).to(device=device)
|
| 239 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1)]).to(device=device)
|
| 240 |
+
|
| 241 |
+
self._step_index = None
|
| 242 |
+
self.reset_scheduler_history()
|
| 243 |
+
|
| 244 |
+
if self.config.scheduler_type == "dmd":
|
| 245 |
+
self.timesteps = self.timesteps[:-1]
|
| 246 |
+
self.sigmas = torch.cat([self.sigmas[:-2], self.sigmas[-1:]])
|
| 247 |
+
|
| 248 |
+
if self.config.use_dynamic_shifting:
|
| 249 |
+
assert self.config.shift == 1.0
|
| 250 |
+
self.sigmas = self.time_shift(mu, 1.0, self.sigmas)
|
| 251 |
+
if self.config.stages == 1:
|
| 252 |
+
self.timesteps = self.sigmas[:-1] * self.config.num_train_timesteps
|
| 253 |
+
else:
|
| 254 |
+
self.timesteps = self.timesteps_per_stage[stage_index].min() + self.sigmas[:-1] * (
|
| 255 |
+
self.timesteps_per_stage[stage_index].max() - self.timesteps_per_stage[stage_index].min()
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler.time_shift
|
| 259 |
+
def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
|
| 260 |
+
"""
|
| 261 |
+
Apply time shifting to the sigmas.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
mu (`float`):
|
| 265 |
+
The mu parameter for the time shift.
|
| 266 |
+
sigma (`float`):
|
| 267 |
+
The sigma parameter for the time shift.
|
| 268 |
+
t (`torch.Tensor`):
|
| 269 |
+
The input timesteps.
|
| 270 |
+
|
| 271 |
+
Returns:
|
| 272 |
+
`torch.Tensor`:
|
| 273 |
+
The time-shifted timesteps.
|
| 274 |
+
"""
|
| 275 |
+
if self.config.time_shift_type == "exponential":
|
| 276 |
+
return self._time_shift_exponential(mu, sigma, t)
|
| 277 |
+
elif self.config.time_shift_type == "linear":
|
| 278 |
+
return self._time_shift_linear(mu, sigma, t)
|
| 279 |
+
|
| 280 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._time_shift_exponential
|
| 281 |
+
def _time_shift_exponential(self, mu, sigma, t):
|
| 282 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
| 283 |
+
|
| 284 |
+
# Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._time_shift_linear
|
| 285 |
+
def _time_shift_linear(self, mu, sigma, t):
|
| 286 |
+
return mu / (mu + (1 / t - 1) ** sigma)
|
| 287 |
+
|
| 288 |
+
# ---------------------------------- Euler ----------------------------------
|
| 289 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 290 |
+
if schedule_timesteps is None:
|
| 291 |
+
schedule_timesteps = self.timesteps
|
| 292 |
+
|
| 293 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 294 |
+
|
| 295 |
+
# The sigma index that is taken for the **very** first `step`
|
| 296 |
+
# is always the second index (or the last index if there is only 1)
|
| 297 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 298 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 299 |
+
pos = 1 if len(indices) > 1 else 0
|
| 300 |
+
|
| 301 |
+
return indices[pos].item()
|
| 302 |
+
|
| 303 |
+
def _init_step_index(self, timestep):
|
| 304 |
+
if self.begin_index is None:
|
| 305 |
+
if isinstance(timestep, torch.Tensor):
|
| 306 |
+
timestep = timestep.to(self.timesteps.device)
|
| 307 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 308 |
+
else:
|
| 309 |
+
self._step_index = self._begin_index
|
| 310 |
+
|
| 311 |
+
def step_euler(
|
| 312 |
+
self,
|
| 313 |
+
model_output: torch.FloatTensor,
|
| 314 |
+
timestep: float | torch.FloatTensor = None,
|
| 315 |
+
sample: torch.FloatTensor = None,
|
| 316 |
+
generator: torch.Generator | None = None,
|
| 317 |
+
sigma: torch.FloatTensor | None = None,
|
| 318 |
+
sigma_next: torch.FloatTensor | None = None,
|
| 319 |
+
return_dict: bool = True,
|
| 320 |
+
) -> HeliosSchedulerOutput | tuple:
|
| 321 |
+
assert (sigma is None) == (sigma_next is None), "sigma and sigma_next must both be None or both be not None"
|
| 322 |
+
|
| 323 |
+
if sigma is None and sigma_next is None:
|
| 324 |
+
if (
|
| 325 |
+
isinstance(timestep, int)
|
| 326 |
+
or isinstance(timestep, torch.IntTensor)
|
| 327 |
+
or isinstance(timestep, torch.LongTensor)
|
| 328 |
+
):
|
| 329 |
+
raise ValueError(
|
| 330 |
+
(
|
| 331 |
+
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
|
| 332 |
+
" `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
|
| 333 |
+
" one of the `scheduler.timesteps` as a timestep."
|
| 334 |
+
),
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
if self.step_index is None:
|
| 338 |
+
self._step_index = 0
|
| 339 |
+
|
| 340 |
+
# Upcast to avoid precision issues when computing prev_sample
|
| 341 |
+
sample = sample.to(torch.float32)
|
| 342 |
+
|
| 343 |
+
if sigma is None and sigma_next is None:
|
| 344 |
+
sigma = self.sigmas[self.step_index]
|
| 345 |
+
sigma_next = self.sigmas[self.step_index + 1]
|
| 346 |
+
|
| 347 |
+
prev_sample = sample + (sigma_next - sigma) * model_output
|
| 348 |
+
|
| 349 |
+
# Cast sample back to model compatible dtype
|
| 350 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 351 |
+
|
| 352 |
+
# upon completion increase step index by one
|
| 353 |
+
self._step_index += 1
|
| 354 |
+
|
| 355 |
+
if not return_dict:
|
| 356 |
+
return (prev_sample,)
|
| 357 |
+
|
| 358 |
+
return HeliosSchedulerOutput(prev_sample=prev_sample)
|
| 359 |
+
|
| 360 |
+
# ---------------------------------- UniPC ----------------------------------
|
| 361 |
+
def _sigma_to_alpha_sigma_t(self, sigma):
|
| 362 |
+
if self.config.use_flow_sigmas:
|
| 363 |
+
alpha_t = 1 - sigma
|
| 364 |
+
sigma_t = torch.clamp(sigma, min=1e-8)
|
| 365 |
+
else:
|
| 366 |
+
alpha_t = 1 / ((sigma**2 + 1) ** 0.5)
|
| 367 |
+
sigma_t = sigma * alpha_t
|
| 368 |
+
|
| 369 |
+
return alpha_t, sigma_t
|
| 370 |
+
|
| 371 |
+
def convert_model_output(
|
| 372 |
+
self,
|
| 373 |
+
model_output: torch.Tensor,
|
| 374 |
+
*args,
|
| 375 |
+
sample: torch.Tensor = None,
|
| 376 |
+
sigma: torch.Tensor = None,
|
| 377 |
+
**kwargs,
|
| 378 |
+
) -> torch.Tensor:
|
| 379 |
+
r"""
|
| 380 |
+
Convert the model output to the corresponding type the UniPC algorithm needs.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
model_output (`torch.Tensor`):
|
| 384 |
+
The direct output from the learned diffusion model.
|
| 385 |
+
timestep (`int`):
|
| 386 |
+
The current discrete timestep in the diffusion chain.
|
| 387 |
+
sample (`torch.Tensor`):
|
| 388 |
+
A current instance of a sample created by the diffusion process.
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
`torch.Tensor`:
|
| 392 |
+
The converted model output.
|
| 393 |
+
"""
|
| 394 |
+
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
|
| 395 |
+
if sample is None:
|
| 396 |
+
if len(args) > 1:
|
| 397 |
+
sample = args[1]
|
| 398 |
+
else:
|
| 399 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 400 |
+
if timestep is not None:
|
| 401 |
+
deprecate(
|
| 402 |
+
"timesteps",
|
| 403 |
+
"1.0.0",
|
| 404 |
+
"Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
flag = False
|
| 408 |
+
if sigma is None:
|
| 409 |
+
flag = True
|
| 410 |
+
sigma = self.sigmas[self.step_index]
|
| 411 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
|
| 412 |
+
|
| 413 |
+
if self.predict_x0:
|
| 414 |
+
if self.config.prediction_type == "epsilon":
|
| 415 |
+
x0_pred = (sample - sigma_t * model_output) / alpha_t
|
| 416 |
+
elif self.config.prediction_type == "sample":
|
| 417 |
+
x0_pred = model_output
|
| 418 |
+
elif self.config.prediction_type == "v_prediction":
|
| 419 |
+
x0_pred = alpha_t * sample - sigma_t * model_output
|
| 420 |
+
elif self.config.prediction_type == "flow_prediction":
|
| 421 |
+
if flag:
|
| 422 |
+
sigma_t = self.sigmas[self.step_index]
|
| 423 |
+
else:
|
| 424 |
+
sigma_t = sigma
|
| 425 |
+
x0_pred = sample - sigma_t * model_output
|
| 426 |
+
else:
|
| 427 |
+
raise ValueError(
|
| 428 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, "
|
| 429 |
+
"`v_prediction`, or `flow_prediction` for the UniPCMultistepScheduler."
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
if self.config.thresholding:
|
| 433 |
+
x0_pred = self._threshold_sample(x0_pred)
|
| 434 |
+
|
| 435 |
+
return x0_pred
|
| 436 |
+
else:
|
| 437 |
+
if self.config.prediction_type == "epsilon":
|
| 438 |
+
return model_output
|
| 439 |
+
elif self.config.prediction_type == "sample":
|
| 440 |
+
epsilon = (sample - alpha_t * model_output) / sigma_t
|
| 441 |
+
return epsilon
|
| 442 |
+
elif self.config.prediction_type == "v_prediction":
|
| 443 |
+
epsilon = alpha_t * model_output + sigma_t * sample
|
| 444 |
+
return epsilon
|
| 445 |
+
else:
|
| 446 |
+
raise ValueError(
|
| 447 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
|
| 448 |
+
" `v_prediction` for the UniPCMultistepScheduler."
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
def multistep_uni_p_bh_update(
|
| 452 |
+
self,
|
| 453 |
+
model_output: torch.Tensor,
|
| 454 |
+
*args,
|
| 455 |
+
sample: torch.Tensor = None,
|
| 456 |
+
order: int = None,
|
| 457 |
+
sigma: torch.Tensor = None,
|
| 458 |
+
sigma_next: torch.Tensor = None,
|
| 459 |
+
**kwargs,
|
| 460 |
+
) -> torch.Tensor:
|
| 461 |
+
"""
|
| 462 |
+
One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified.
|
| 463 |
+
|
| 464 |
+
Args:
|
| 465 |
+
model_output (`torch.Tensor`):
|
| 466 |
+
The direct output from the learned diffusion model at the current timestep.
|
| 467 |
+
prev_timestep (`int`):
|
| 468 |
+
The previous discrete timestep in the diffusion chain.
|
| 469 |
+
sample (`torch.Tensor`):
|
| 470 |
+
A current instance of a sample created by the diffusion process.
|
| 471 |
+
order (`int`):
|
| 472 |
+
The order of UniP at this timestep (corresponds to the *p* in UniPC-p).
|
| 473 |
+
|
| 474 |
+
Returns:
|
| 475 |
+
`torch.Tensor`:
|
| 476 |
+
The sample tensor at the previous timestep.
|
| 477 |
+
"""
|
| 478 |
+
prev_timestep = args[0] if len(args) > 0 else kwargs.pop("prev_timestep", None)
|
| 479 |
+
if sample is None:
|
| 480 |
+
if len(args) > 1:
|
| 481 |
+
sample = args[1]
|
| 482 |
+
else:
|
| 483 |
+
raise ValueError("missing `sample` as a required keyword argument")
|
| 484 |
+
if order is None:
|
| 485 |
+
if len(args) > 2:
|
| 486 |
+
order = args[2]
|
| 487 |
+
else:
|
| 488 |
+
raise ValueError("missing `order` as a required keyword argument")
|
| 489 |
+
if prev_timestep is not None:
|
| 490 |
+
deprecate(
|
| 491 |
+
"prev_timestep",
|
| 492 |
+
"1.0.0",
|
| 493 |
+
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 494 |
+
)
|
| 495 |
+
model_output_list = self.model_outputs
|
| 496 |
+
|
| 497 |
+
s0 = self.timestep_list[-1]
|
| 498 |
+
m0 = model_output_list[-1]
|
| 499 |
+
x = sample
|
| 500 |
+
|
| 501 |
+
if self.solver_p:
|
| 502 |
+
x_t = self.solver_p.step(model_output, s0, x).prev_sample
|
| 503 |
+
return x_t
|
| 504 |
+
|
| 505 |
+
if sigma_next is None and sigma is None:
|
| 506 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
|
| 507 |
+
else:
|
| 508 |
+
sigma_t, sigma_s0 = sigma_next, sigma
|
| 509 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 510 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 511 |
+
|
| 512 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 513 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 514 |
+
|
| 515 |
+
h = lambda_t - lambda_s0
|
| 516 |
+
device = sample.device
|
| 517 |
+
|
| 518 |
+
rks = []
|
| 519 |
+
D1s = []
|
| 520 |
+
for i in range(1, order):
|
| 521 |
+
si = self.step_index - i
|
| 522 |
+
mi = model_output_list[-(i + 1)]
|
| 523 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 524 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 525 |
+
rk = (lambda_si - lambda_s0) / h
|
| 526 |
+
rks.append(rk)
|
| 527 |
+
D1s.append((mi - m0) / rk)
|
| 528 |
+
|
| 529 |
+
rks.append(1.0)
|
| 530 |
+
rks = torch.tensor(rks, device=device)
|
| 531 |
+
|
| 532 |
+
R = []
|
| 533 |
+
b = []
|
| 534 |
+
|
| 535 |
+
hh = -h if self.predict_x0 else h
|
| 536 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 537 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 538 |
+
|
| 539 |
+
factorial_i = 1
|
| 540 |
+
|
| 541 |
+
if self.config.solver_type == "bh1":
|
| 542 |
+
B_h = hh
|
| 543 |
+
elif self.config.solver_type == "bh2":
|
| 544 |
+
B_h = torch.expm1(hh)
|
| 545 |
+
else:
|
| 546 |
+
raise NotImplementedError()
|
| 547 |
+
|
| 548 |
+
for i in range(1, order + 1):
|
| 549 |
+
R.append(torch.pow(rks, i - 1))
|
| 550 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 551 |
+
factorial_i *= i + 1
|
| 552 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 553 |
+
|
| 554 |
+
R = torch.stack(R)
|
| 555 |
+
b = torch.tensor(b, device=device)
|
| 556 |
+
|
| 557 |
+
if len(D1s) > 0:
|
| 558 |
+
D1s = torch.stack(D1s, dim=1) # (B, K)
|
| 559 |
+
# for order 2, we use a simplified version
|
| 560 |
+
if order == 2:
|
| 561 |
+
rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 562 |
+
else:
|
| 563 |
+
rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]).to(device).to(x.dtype)
|
| 564 |
+
else:
|
| 565 |
+
D1s = None
|
| 566 |
+
|
| 567 |
+
if self.predict_x0:
|
| 568 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 569 |
+
if D1s is not None:
|
| 570 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
|
| 571 |
+
else:
|
| 572 |
+
pred_res = 0
|
| 573 |
+
x_t = x_t_ - alpha_t * B_h * pred_res
|
| 574 |
+
else:
|
| 575 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 576 |
+
if D1s is not None:
|
| 577 |
+
pred_res = torch.einsum("k,bkc...->bc...", rhos_p, D1s)
|
| 578 |
+
else:
|
| 579 |
+
pred_res = 0
|
| 580 |
+
x_t = x_t_ - sigma_t * B_h * pred_res
|
| 581 |
+
|
| 582 |
+
x_t = x_t.to(x.dtype)
|
| 583 |
+
return x_t
|
| 584 |
+
|
| 585 |
+
def multistep_uni_c_bh_update(
|
| 586 |
+
self,
|
| 587 |
+
this_model_output: torch.Tensor,
|
| 588 |
+
*args,
|
| 589 |
+
last_sample: torch.Tensor = None,
|
| 590 |
+
this_sample: torch.Tensor = None,
|
| 591 |
+
order: int = None,
|
| 592 |
+
sigma_before: torch.Tensor = None,
|
| 593 |
+
sigma: torch.Tensor = None,
|
| 594 |
+
**kwargs,
|
| 595 |
+
) -> torch.Tensor:
|
| 596 |
+
"""
|
| 597 |
+
One step for the UniC (B(h) version).
|
| 598 |
+
|
| 599 |
+
Args:
|
| 600 |
+
this_model_output (`torch.Tensor`):
|
| 601 |
+
The model outputs at `x_t`.
|
| 602 |
+
this_timestep (`int`):
|
| 603 |
+
The current timestep `t`.
|
| 604 |
+
last_sample (`torch.Tensor`):
|
| 605 |
+
The generated sample before the last predictor `x_{t-1}`.
|
| 606 |
+
this_sample (`torch.Tensor`):
|
| 607 |
+
The generated sample after the last predictor `x_{t}`.
|
| 608 |
+
order (`int`):
|
| 609 |
+
The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`.
|
| 610 |
+
|
| 611 |
+
Returns:
|
| 612 |
+
`torch.Tensor`:
|
| 613 |
+
The corrected sample tensor at the current timestep.
|
| 614 |
+
"""
|
| 615 |
+
this_timestep = args[0] if len(args) > 0 else kwargs.pop("this_timestep", None)
|
| 616 |
+
if last_sample is None:
|
| 617 |
+
if len(args) > 1:
|
| 618 |
+
last_sample = args[1]
|
| 619 |
+
else:
|
| 620 |
+
raise ValueError("missing `last_sample` as a required keyword argument")
|
| 621 |
+
if this_sample is None:
|
| 622 |
+
if len(args) > 2:
|
| 623 |
+
this_sample = args[2]
|
| 624 |
+
else:
|
| 625 |
+
raise ValueError("missing `this_sample` as a required keyword argument")
|
| 626 |
+
if order is None:
|
| 627 |
+
if len(args) > 3:
|
| 628 |
+
order = args[3]
|
| 629 |
+
else:
|
| 630 |
+
raise ValueError("missing `order` as a required keyword argument")
|
| 631 |
+
if this_timestep is not None:
|
| 632 |
+
deprecate(
|
| 633 |
+
"this_timestep",
|
| 634 |
+
"1.0.0",
|
| 635 |
+
"Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
model_output_list = self.model_outputs
|
| 639 |
+
|
| 640 |
+
m0 = model_output_list[-1]
|
| 641 |
+
x = last_sample
|
| 642 |
+
x_t = this_sample
|
| 643 |
+
model_t = this_model_output
|
| 644 |
+
|
| 645 |
+
if sigma_before is None and sigma is None:
|
| 646 |
+
sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[self.step_index - 1]
|
| 647 |
+
else:
|
| 648 |
+
sigma_t, sigma_s0 = sigma, sigma_before
|
| 649 |
+
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
|
| 650 |
+
alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
|
| 651 |
+
|
| 652 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 653 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 654 |
+
|
| 655 |
+
h = lambda_t - lambda_s0
|
| 656 |
+
device = this_sample.device
|
| 657 |
+
|
| 658 |
+
rks = []
|
| 659 |
+
D1s = []
|
| 660 |
+
for i in range(1, order):
|
| 661 |
+
si = self.step_index - (i + 1)
|
| 662 |
+
mi = model_output_list[-(i + 1)]
|
| 663 |
+
alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
|
| 664 |
+
lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
|
| 665 |
+
rk = (lambda_si - lambda_s0) / h
|
| 666 |
+
rks.append(rk)
|
| 667 |
+
D1s.append((mi - m0) / rk)
|
| 668 |
+
|
| 669 |
+
rks.append(1.0)
|
| 670 |
+
rks = torch.tensor(rks, device=device)
|
| 671 |
+
|
| 672 |
+
R = []
|
| 673 |
+
b = []
|
| 674 |
+
|
| 675 |
+
hh = -h if self.predict_x0 else h
|
| 676 |
+
h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
|
| 677 |
+
h_phi_k = h_phi_1 / hh - 1
|
| 678 |
+
|
| 679 |
+
factorial_i = 1
|
| 680 |
+
|
| 681 |
+
if self.config.solver_type == "bh1":
|
| 682 |
+
B_h = hh
|
| 683 |
+
elif self.config.solver_type == "bh2":
|
| 684 |
+
B_h = torch.expm1(hh)
|
| 685 |
+
else:
|
| 686 |
+
raise NotImplementedError()
|
| 687 |
+
|
| 688 |
+
for i in range(1, order + 1):
|
| 689 |
+
R.append(torch.pow(rks, i - 1))
|
| 690 |
+
b.append(h_phi_k * factorial_i / B_h)
|
| 691 |
+
factorial_i *= i + 1
|
| 692 |
+
h_phi_k = h_phi_k / hh - 1 / factorial_i
|
| 693 |
+
|
| 694 |
+
R = torch.stack(R)
|
| 695 |
+
b = torch.tensor(b, device=device)
|
| 696 |
+
|
| 697 |
+
if len(D1s) > 0:
|
| 698 |
+
D1s = torch.stack(D1s, dim=1)
|
| 699 |
+
else:
|
| 700 |
+
D1s = None
|
| 701 |
+
|
| 702 |
+
# for order 1, we use a simplified version
|
| 703 |
+
if order == 1:
|
| 704 |
+
rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device)
|
| 705 |
+
else:
|
| 706 |
+
rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype)
|
| 707 |
+
|
| 708 |
+
if self.predict_x0:
|
| 709 |
+
x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
|
| 710 |
+
if D1s is not None:
|
| 711 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 712 |
+
else:
|
| 713 |
+
corr_res = 0
|
| 714 |
+
D1_t = model_t - m0
|
| 715 |
+
x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 716 |
+
else:
|
| 717 |
+
x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
|
| 718 |
+
if D1s is not None:
|
| 719 |
+
corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
|
| 720 |
+
else:
|
| 721 |
+
corr_res = 0
|
| 722 |
+
D1_t = model_t - m0
|
| 723 |
+
x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t)
|
| 724 |
+
x_t = x_t.to(x.dtype)
|
| 725 |
+
return x_t
|
| 726 |
+
|
| 727 |
+
def step_unipc(
|
| 728 |
+
self,
|
| 729 |
+
model_output: torch.Tensor,
|
| 730 |
+
timestep: int | torch.Tensor = None,
|
| 731 |
+
sample: torch.Tensor = None,
|
| 732 |
+
return_dict: bool = True,
|
| 733 |
+
model_outputs: list = None,
|
| 734 |
+
timestep_list: list = None,
|
| 735 |
+
sigma_before: torch.Tensor = None,
|
| 736 |
+
sigma: torch.Tensor = None,
|
| 737 |
+
sigma_next: torch.Tensor = None,
|
| 738 |
+
cus_step_index: int = None,
|
| 739 |
+
cus_lower_order_num: int = None,
|
| 740 |
+
cus_this_order: int = None,
|
| 741 |
+
cus_last_sample: torch.Tensor = None,
|
| 742 |
+
) -> HeliosSchedulerOutput | tuple:
|
| 743 |
+
if self.num_inference_steps is None:
|
| 744 |
+
raise ValueError(
|
| 745 |
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
if cus_step_index is None:
|
| 749 |
+
if self.step_index is None:
|
| 750 |
+
self._step_index = 0
|
| 751 |
+
else:
|
| 752 |
+
self._step_index = cus_step_index
|
| 753 |
+
|
| 754 |
+
if cus_lower_order_num is not None:
|
| 755 |
+
self.lower_order_nums = cus_lower_order_num
|
| 756 |
+
|
| 757 |
+
if cus_this_order is not None:
|
| 758 |
+
self.this_order = cus_this_order
|
| 759 |
+
|
| 760 |
+
if cus_last_sample is not None:
|
| 761 |
+
self.last_sample = cus_last_sample
|
| 762 |
+
|
| 763 |
+
use_corrector = (
|
| 764 |
+
self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# Convert model output using the proper conversion method
|
| 768 |
+
model_output_convert = self.convert_model_output(model_output, sample=sample, sigma=sigma)
|
| 769 |
+
|
| 770 |
+
if model_outputs is not None and timestep_list is not None:
|
| 771 |
+
self.model_outputs = model_outputs[:-1]
|
| 772 |
+
self.timestep_list = timestep_list[:-1]
|
| 773 |
+
|
| 774 |
+
if use_corrector:
|
| 775 |
+
sample = self.multistep_uni_c_bh_update(
|
| 776 |
+
this_model_output=model_output_convert,
|
| 777 |
+
last_sample=self.last_sample,
|
| 778 |
+
this_sample=sample,
|
| 779 |
+
order=self.this_order,
|
| 780 |
+
sigma_before=sigma_before,
|
| 781 |
+
sigma=sigma,
|
| 782 |
+
)
|
| 783 |
+
|
| 784 |
+
if model_outputs is not None and timestep_list is not None:
|
| 785 |
+
model_outputs[-1] = model_output_convert
|
| 786 |
+
self.model_outputs = model_outputs[1:]
|
| 787 |
+
self.timestep_list = timestep_list[1:]
|
| 788 |
+
else:
|
| 789 |
+
for i in range(self.config.solver_order - 1):
|
| 790 |
+
self.model_outputs[i] = self.model_outputs[i + 1]
|
| 791 |
+
self.timestep_list[i] = self.timestep_list[i + 1]
|
| 792 |
+
self.model_outputs[-1] = model_output_convert
|
| 793 |
+
self.timestep_list[-1] = timestep
|
| 794 |
+
|
| 795 |
+
if self.config.lower_order_final:
|
| 796 |
+
this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index)
|
| 797 |
+
else:
|
| 798 |
+
this_order = self.config.solver_order
|
| 799 |
+
self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep
|
| 800 |
+
assert self.this_order > 0
|
| 801 |
+
|
| 802 |
+
self.last_sample = sample
|
| 803 |
+
prev_sample = self.multistep_uni_p_bh_update(
|
| 804 |
+
model_output=model_output, # pass the original non-converted model output, in case solver-p is used
|
| 805 |
+
sample=sample,
|
| 806 |
+
order=self.this_order,
|
| 807 |
+
sigma=sigma,
|
| 808 |
+
sigma_next=sigma_next,
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
if cus_lower_order_num is None:
|
| 812 |
+
if self.lower_order_nums < self.config.solver_order:
|
| 813 |
+
self.lower_order_nums += 1
|
| 814 |
+
|
| 815 |
+
# upon completion increase step index by one
|
| 816 |
+
if cus_step_index is None:
|
| 817 |
+
self._step_index += 1
|
| 818 |
+
|
| 819 |
+
if not return_dict:
|
| 820 |
+
return (prev_sample, model_outputs, self.last_sample, self.this_order)
|
| 821 |
+
|
| 822 |
+
return HeliosSchedulerOutput(
|
| 823 |
+
prev_sample=prev_sample,
|
| 824 |
+
model_outputs=model_outputs,
|
| 825 |
+
last_sample=self.last_sample,
|
| 826 |
+
this_order=self.this_order,
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
# ---------------------------------- For DMD ----------------------------------
|
| 830 |
+
def add_noise(self, original_samples, noise, timestep, sigmas, timesteps):
|
| 831 |
+
sigmas = sigmas.to(noise.device)
|
| 832 |
+
timesteps = timesteps.to(noise.device)
|
| 833 |
+
timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
|
| 834 |
+
sigma = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1)
|
| 835 |
+
sample = (1 - sigma) * original_samples + sigma * noise
|
| 836 |
+
return sample.type_as(noise)
|
| 837 |
+
|
| 838 |
+
def convert_flow_pred_to_x0(self, flow_pred, xt, timestep, sigmas, timesteps):
|
| 839 |
+
# use higher precision for calculations
|
| 840 |
+
original_dtype = flow_pred.dtype
|
| 841 |
+
device = flow_pred.device
|
| 842 |
+
flow_pred, xt, sigmas, timesteps = (x.double().to(device) for x in (flow_pred, xt, sigmas, timesteps))
|
| 843 |
+
|
| 844 |
+
timestep_id = torch.argmin((timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
|
| 845 |
+
sigma_t = sigmas[timestep_id].reshape(-1, 1, 1, 1, 1)
|
| 846 |
+
x0_pred = xt - sigma_t * flow_pred
|
| 847 |
+
return x0_pred.to(original_dtype)
|
| 848 |
+
|
| 849 |
+
def step_dmd(
|
| 850 |
+
self,
|
| 851 |
+
model_output: torch.FloatTensor,
|
| 852 |
+
timestep: float | torch.FloatTensor = None,
|
| 853 |
+
sample: torch.FloatTensor = None,
|
| 854 |
+
generator: torch.Generator | None = None,
|
| 855 |
+
return_dict: bool = True,
|
| 856 |
+
cur_sampling_step: int = 0,
|
| 857 |
+
dmd_noisy_tensor: torch.FloatTensor | None = None,
|
| 858 |
+
dmd_sigmas: torch.FloatTensor | None = None,
|
| 859 |
+
dmd_timesteps: torch.FloatTensor | None = None,
|
| 860 |
+
all_timesteps: torch.FloatTensor | None = None,
|
| 861 |
+
):
|
| 862 |
+
pred_image_or_video = self.convert_flow_pred_to_x0(
|
| 863 |
+
flow_pred=model_output,
|
| 864 |
+
xt=sample,
|
| 865 |
+
timestep=torch.full((model_output.shape[0],), timestep, dtype=torch.long, device=model_output.device),
|
| 866 |
+
sigmas=dmd_sigmas,
|
| 867 |
+
timesteps=dmd_timesteps,
|
| 868 |
+
)
|
| 869 |
+
if cur_sampling_step < len(all_timesteps) - 1:
|
| 870 |
+
prev_sample = self.add_noise(
|
| 871 |
+
pred_image_or_video,
|
| 872 |
+
dmd_noisy_tensor,
|
| 873 |
+
torch.full(
|
| 874 |
+
(model_output.shape[0],),
|
| 875 |
+
all_timesteps[cur_sampling_step + 1],
|
| 876 |
+
dtype=torch.long,
|
| 877 |
+
device=model_output.device,
|
| 878 |
+
),
|
| 879 |
+
sigmas=dmd_sigmas,
|
| 880 |
+
timesteps=dmd_timesteps,
|
| 881 |
+
)
|
| 882 |
+
else:
|
| 883 |
+
prev_sample = pred_image_or_video
|
| 884 |
+
|
| 885 |
+
if not return_dict:
|
| 886 |
+
return (prev_sample,)
|
| 887 |
+
|
| 888 |
+
return HeliosSchedulerOutput(prev_sample=prev_sample)
|
| 889 |
+
|
| 890 |
+
# ---------------------------------- Merge ----------------------------------
|
| 891 |
+
def step(
|
| 892 |
+
self,
|
| 893 |
+
model_output: torch.FloatTensor,
|
| 894 |
+
timestep: float | torch.FloatTensor = None,
|
| 895 |
+
sample: torch.FloatTensor = None,
|
| 896 |
+
generator: torch.Generator | None = None,
|
| 897 |
+
return_dict: bool = True,
|
| 898 |
+
# For DMD
|
| 899 |
+
cur_sampling_step: int = 0,
|
| 900 |
+
dmd_noisy_tensor: torch.FloatTensor | None = None,
|
| 901 |
+
dmd_sigmas: torch.FloatTensor | None = None,
|
| 902 |
+
dmd_timesteps: torch.FloatTensor | None = None,
|
| 903 |
+
all_timesteps: torch.FloatTensor | None = None,
|
| 904 |
+
) -> HeliosSchedulerOutput | tuple:
|
| 905 |
+
if self.config.scheduler_type == "euler":
|
| 906 |
+
return self.step_euler(
|
| 907 |
+
model_output=model_output,
|
| 908 |
+
timestep=timestep,
|
| 909 |
+
sample=sample,
|
| 910 |
+
generator=generator,
|
| 911 |
+
return_dict=return_dict,
|
| 912 |
+
)
|
| 913 |
+
elif self.config.scheduler_type == "unipc":
|
| 914 |
+
return self.step_unipc(
|
| 915 |
+
model_output=model_output,
|
| 916 |
+
timestep=timestep,
|
| 917 |
+
sample=sample,
|
| 918 |
+
return_dict=return_dict,
|
| 919 |
+
)
|
| 920 |
+
elif self.config.scheduler_type == "dmd":
|
| 921 |
+
return self.step_dmd(
|
| 922 |
+
model_output=model_output,
|
| 923 |
+
timestep=timestep,
|
| 924 |
+
sample=sample,
|
| 925 |
+
generator=generator,
|
| 926 |
+
return_dict=return_dict,
|
| 927 |
+
cur_sampling_step=cur_sampling_step,
|
| 928 |
+
dmd_noisy_tensor=dmd_noisy_tensor,
|
| 929 |
+
dmd_sigmas=dmd_sigmas,
|
| 930 |
+
dmd_timesteps=dmd_timesteps,
|
| 931 |
+
all_timesteps=all_timesteps,
|
| 932 |
+
)
|
| 933 |
+
else:
|
| 934 |
+
raise NotImplementedError
|
| 935 |
+
|
| 936 |
+
def reset_scheduler_history(self):
|
| 937 |
+
self.model_outputs = [None] * self.config.solver_order
|
| 938 |
+
self.timestep_list = [None] * self.config.solver_order
|
| 939 |
+
self.lower_order_nums = 0
|
| 940 |
+
self.disable_corrector = self.config.disable_corrector
|
| 941 |
+
self.solver_p = self.config.solver_p
|
| 942 |
+
self.last_sample = None
|
| 943 |
+
self._step_index = None
|
| 944 |
+
self._begin_index = None
|
| 945 |
+
|
| 946 |
+
def __len__(self):
|
| 947 |
+
return self.config.num_train_timesteps
|
Helios/_DEV2/helios/diffusers_version/transformer_helios_diffusers.py
ADDED
|
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Helios Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
from functools import lru_cache
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
|
| 24 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 25 |
+
from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
|
| 26 |
+
from diffusers.models._modeling_parallel import ContextParallelInput, ContextParallelOutput
|
| 27 |
+
from diffusers.models.attention import AttentionMixin, AttentionModuleMixin, FeedForward
|
| 28 |
+
from diffusers.models.attention_dispatch import dispatch_attention_fn
|
| 29 |
+
from diffusers.models.cache_utils import CacheMixin
|
| 30 |
+
from diffusers.models.embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps
|
| 31 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 32 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 33 |
+
from diffusers.models.normalization import FP32LayerNorm
|
| 34 |
+
from diffusers.utils import apply_lora_scale, logging
|
| 35 |
+
from diffusers.utils.torch_utils import maybe_allow_in_graph
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _short_attn_debug_target_matches(value, targets, total=None):
|
| 42 |
+
if targets is None:
|
| 43 |
+
return True
|
| 44 |
+
if not isinstance(targets, (list, tuple, set)):
|
| 45 |
+
targets = [targets]
|
| 46 |
+
for target in targets:
|
| 47 |
+
if target == "last" and total is not None and value == total - 1:
|
| 48 |
+
return True
|
| 49 |
+
if target == "first" and value == 0:
|
| 50 |
+
return True
|
| 51 |
+
if isinstance(target, int) and value == target:
|
| 52 |
+
return True
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@torch.no_grad()
|
| 57 |
+
def _save_short_attn_debug(attn, query, key, original_context_length, original_context_length_list=None):
|
| 58 |
+
config = getattr(attn, "_short_attn_debug_config", None)
|
| 59 |
+
state = getattr(attn, "_short_attn_debug_state", None)
|
| 60 |
+
if not config or not config.get("enabled", True) or attn.is_cross_attention:
|
| 61 |
+
return
|
| 62 |
+
if original_context_length_list is not None and len(original_context_length_list) != 1:
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
block_idx = getattr(attn, "_helios_block_idx", None)
|
| 66 |
+
if not _short_attn_debug_target_matches(block_idx, config.get("blocks")):
|
| 67 |
+
return
|
| 68 |
+
if state is None:
|
| 69 |
+
state = {}
|
| 70 |
+
if not _short_attn_debug_target_matches(state.get("chunk_index", 0), config.get("chunks")):
|
| 71 |
+
return
|
| 72 |
+
if not _short_attn_debug_target_matches(
|
| 73 |
+
state.get("step_index", 0), config.get("steps"), state.get("total_steps")
|
| 74 |
+
):
|
| 75 |
+
return
|
| 76 |
+
pass_names = config.get("pass_names", ["cond"])
|
| 77 |
+
if state.get("pass_name", "cond") not in pass_names:
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
if original_context_length is None:
|
| 81 |
+
return
|
| 82 |
+
history_seq_len = key.shape[1] - original_context_length
|
| 83 |
+
if history_seq_len <= 0:
|
| 84 |
+
return
|
| 85 |
+
|
| 86 |
+
grid_h, grid_w = config.get("grid", (24, 40))
|
| 87 |
+
grid_tokens = int(grid_h) * int(grid_w)
|
| 88 |
+
if grid_tokens <= 0 or original_context_length % grid_tokens != 0:
|
| 89 |
+
return
|
| 90 |
+
|
| 91 |
+
current_frames = original_context_length // grid_tokens
|
| 92 |
+
current_frame = int(config.get("current_frame", current_frames - 1))
|
| 93 |
+
if current_frame < 0:
|
| 94 |
+
current_frame += current_frames
|
| 95 |
+
if current_frame < 0 or current_frame >= current_frames:
|
| 96 |
+
return
|
| 97 |
+
|
| 98 |
+
short_history_frames = int(config.get("short_history_frames", 2))
|
| 99 |
+
prev_short_frame = int(config.get("prev_short_frame", short_history_frames - 1))
|
| 100 |
+
if prev_short_frame < 0:
|
| 101 |
+
prev_short_frame += short_history_frames
|
| 102 |
+
short_len = short_history_frames * grid_tokens
|
| 103 |
+
if history_seq_len < short_len or prev_short_frame < 0 or prev_short_frame >= short_history_frames:
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
+
short_start = history_seq_len - short_len
|
| 107 |
+
prev_start = short_start + prev_short_frame * grid_tokens
|
| 108 |
+
if query.shape[1] == history_seq_len + original_context_length:
|
| 109 |
+
current_start = history_seq_len + current_frame * grid_tokens
|
| 110 |
+
elif query.shape[1] == original_context_length:
|
| 111 |
+
current_start = current_frame * grid_tokens
|
| 112 |
+
else:
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
batch_index = int(config.get("batch_index", 0))
|
| 116 |
+
if batch_index < 0 or batch_index >= query.shape[0]:
|
| 117 |
+
return
|
| 118 |
+
|
| 119 |
+
q_frame = query[batch_index, current_start : current_start + grid_tokens].float()
|
| 120 |
+
k_prev = key[batch_index, prev_start : prev_start + grid_tokens].float()
|
| 121 |
+
if q_frame.shape[0] != grid_tokens or k_prev.shape[0] != grid_tokens:
|
| 122 |
+
return
|
| 123 |
+
|
| 124 |
+
topk = max(2, int(config.get("topk", 2)))
|
| 125 |
+
query_chunk_size = int(config.get("query_chunk_size", 128))
|
| 126 |
+
scale = 1.0 / math.sqrt(q_frame.shape[-1])
|
| 127 |
+
top_scores = []
|
| 128 |
+
top_indices = []
|
| 129 |
+
for start in range(0, grid_tokens, query_chunk_size):
|
| 130 |
+
q_chunk = q_frame[start : start + query_chunk_size]
|
| 131 |
+
scores = torch.einsum("qhd,khd->hqk", q_chunk, k_prev) * scale
|
| 132 |
+
scores = scores.mean(dim=0)
|
| 133 |
+
values, indices = scores.topk(topk, dim=-1)
|
| 134 |
+
top_scores.append(values.cpu())
|
| 135 |
+
top_indices.append(indices.cpu())
|
| 136 |
+
|
| 137 |
+
top_scores = torch.cat(top_scores, dim=0)
|
| 138 |
+
top_indices = torch.cat(top_indices, dim=0)
|
| 139 |
+
top1 = top_indices[:, 0]
|
| 140 |
+
match_y = torch.div(top1, grid_w, rounding_mode="floor")
|
| 141 |
+
match_x = top1 % grid_w
|
| 142 |
+
query_positions = torch.arange(grid_tokens)
|
| 143 |
+
query_y = torch.div(query_positions, grid_w, rounding_mode="floor")
|
| 144 |
+
query_x = query_positions % grid_w
|
| 145 |
+
match_yx = torch.stack([match_y, match_x], dim=-1).reshape(grid_h, grid_w, 2)
|
| 146 |
+
query_yx = torch.stack([query_y, query_x], dim=-1).reshape(grid_h, grid_w, 2)
|
| 147 |
+
displacement_yx = match_yx - query_yx
|
| 148 |
+
|
| 149 |
+
artifact = {
|
| 150 |
+
"block": block_idx,
|
| 151 |
+
"chunk_index": state.get("chunk_index"),
|
| 152 |
+
"stage": state.get("stage"),
|
| 153 |
+
"stage_index": state.get("stage_index"),
|
| 154 |
+
"step_index": state.get("step_index"),
|
| 155 |
+
"total_steps": state.get("total_steps"),
|
| 156 |
+
"pass_name": state.get("pass_name"),
|
| 157 |
+
"timestep": state.get("timestep"),
|
| 158 |
+
"current_frame": current_frame,
|
| 159 |
+
"prev_short_frame": prev_short_frame,
|
| 160 |
+
"grid": (grid_h, grid_w),
|
| 161 |
+
"match_yx": match_yx,
|
| 162 |
+
"query_yx": query_yx,
|
| 163 |
+
"displacement_yx": displacement_yx,
|
| 164 |
+
"topk_indices": top_indices.reshape(grid_h, grid_w, topk),
|
| 165 |
+
"topk_scores": top_scores.reshape(grid_h, grid_w, topk),
|
| 166 |
+
"top1_score": top_scores[:, 0].reshape(grid_h, grid_w),
|
| 167 |
+
"top2_score": top_scores[:, 1].reshape(grid_h, grid_w),
|
| 168 |
+
"margin": (top_scores[:, 0] - top_scores[:, 1]).reshape(grid_h, grid_w),
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
output_dir = config.get("output_dir", "short_attn_debug")
|
| 172 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 173 |
+
filename = (
|
| 174 |
+
f"short_attn_chunk{state.get('chunk_index', 0)}"
|
| 175 |
+
f"_step{state.get('step_index', 0)}"
|
| 176 |
+
f"_block{block_idx}"
|
| 177 |
+
f"_frame{current_frame}"
|
| 178 |
+
f"_{state.get('pass_name', 'cond')}.pt"
|
| 179 |
+
)
|
| 180 |
+
path = os.path.join(output_dir, filename)
|
| 181 |
+
if os.path.exists(path) and not config.get("overwrite", True):
|
| 182 |
+
return
|
| 183 |
+
torch.save(artifact, path)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def pad_for_3d_conv(x, kernel_size):
|
| 187 |
+
b, c, t, h, w = x.shape
|
| 188 |
+
pt, ph, pw = kernel_size
|
| 189 |
+
pad_t = (pt - (t % pt)) % pt
|
| 190 |
+
pad_h = (ph - (h % ph)) % ph
|
| 191 |
+
pad_w = (pw - (w % pw)) % pw
|
| 192 |
+
return torch.nn.functional.pad(x, (0, pad_w, 0, pad_h, 0, pad_t), mode="replicate")
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def center_down_sample_3d(x, kernel_size):
|
| 196 |
+
return torch.nn.functional.avg_pool3d(x, kernel_size, stride=kernel_size)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def apply_rotary_emb_transposed(
|
| 200 |
+
hidden_states: torch.Tensor,
|
| 201 |
+
freqs_cis: torch.Tensor,
|
| 202 |
+
):
|
| 203 |
+
x_1, x_2 = hidden_states.unflatten(-1, (-1, 2)).unbind(-1)
|
| 204 |
+
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
| 205 |
+
out = torch.empty_like(hidden_states)
|
| 206 |
+
out[..., 0::2] = x_1 * cos[..., 0::2] - x_2 * sin[..., 1::2]
|
| 207 |
+
out[..., 1::2] = x_1 * sin[..., 1::2] + x_2 * cos[..., 0::2]
|
| 208 |
+
return out.type_as(hidden_states)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _get_qkv_projections(attn: "HeliosAttention", hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor):
|
| 212 |
+
# encoder_hidden_states is only passed for cross-attention
|
| 213 |
+
if encoder_hidden_states is None:
|
| 214 |
+
encoder_hidden_states = hidden_states
|
| 215 |
+
|
| 216 |
+
if attn.fused_projections:
|
| 217 |
+
if not attn.is_cross_attention:
|
| 218 |
+
# In self-attention layers, we can fuse the entire QKV projection into a single linear
|
| 219 |
+
query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1)
|
| 220 |
+
else:
|
| 221 |
+
# In cross-attention layers, we can only fuse the KV projections into a single linear
|
| 222 |
+
query = attn.to_q(hidden_states)
|
| 223 |
+
key, value = attn.to_kv(encoder_hidden_states).chunk(2, dim=-1)
|
| 224 |
+
else:
|
| 225 |
+
query = attn.to_q(hidden_states)
|
| 226 |
+
key = attn.to_k(encoder_hidden_states)
|
| 227 |
+
value = attn.to_v(encoder_hidden_states)
|
| 228 |
+
return query, key, value
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class HeliosOutputNorm(nn.Module):
|
| 232 |
+
def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine: bool = False):
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
|
| 235 |
+
self.norm = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 236 |
+
|
| 237 |
+
def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor, original_context_length: int):
|
| 238 |
+
temb = temb[:, -original_context_length:, :]
|
| 239 |
+
shift, scale = (self.scale_shift_table.unsqueeze(0).to(temb.device) + temb.unsqueeze(2)).chunk(2, dim=2)
|
| 240 |
+
shift, scale = shift.squeeze(2).to(hidden_states.device), scale.squeeze(2).to(hidden_states.device)
|
| 241 |
+
hidden_states = hidden_states[:, -original_context_length:, :]
|
| 242 |
+
hidden_states = (self.norm(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
| 243 |
+
return hidden_states
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class HeliosAttnProcessor:
|
| 247 |
+
_attention_backend = None
|
| 248 |
+
_parallel_config = None
|
| 249 |
+
|
| 250 |
+
def __init__(self):
|
| 251 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 252 |
+
raise ImportError(
|
| 253 |
+
"HeliosAttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to version 2.0 or higher."
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
def __call__(
|
| 257 |
+
self,
|
| 258 |
+
attn: "HeliosAttention",
|
| 259 |
+
hidden_states: torch.Tensor,
|
| 260 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 261 |
+
attention_mask: torch.Tensor | None = None,
|
| 262 |
+
rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 263 |
+
original_context_length: int = None,
|
| 264 |
+
) -> torch.Tensor:
|
| 265 |
+
query, key, value = _get_qkv_projections(attn, hidden_states, encoder_hidden_states)
|
| 266 |
+
|
| 267 |
+
query = attn.norm_q(query)
|
| 268 |
+
key = attn.norm_k(key)
|
| 269 |
+
|
| 270 |
+
query = query.unflatten(2, (attn.heads, -1))
|
| 271 |
+
key = key.unflatten(2, (attn.heads, -1))
|
| 272 |
+
value = value.unflatten(2, (attn.heads, -1))
|
| 273 |
+
|
| 274 |
+
if rotary_emb is not None:
|
| 275 |
+
query = apply_rotary_emb_transposed(query, rotary_emb)
|
| 276 |
+
key = apply_rotary_emb_transposed(key, rotary_emb)
|
| 277 |
+
|
| 278 |
+
if not attn.is_cross_attention and attn.is_amplify_history:
|
| 279 |
+
history_seq_len = hidden_states.shape[1] - original_context_length
|
| 280 |
+
|
| 281 |
+
if history_seq_len > 0:
|
| 282 |
+
scale_key = 1.0 + torch.sigmoid(attn.history_key_scale) * (attn.max_scale - 1.0)
|
| 283 |
+
if attn.history_scale_mode == "per_head":
|
| 284 |
+
scale_key = scale_key.view(1, 1, -1, 1)
|
| 285 |
+
key = torch.cat([key[:, :history_seq_len] * scale_key, key[:, history_seq_len:]], dim=1)
|
| 286 |
+
|
| 287 |
+
_save_short_attn_debug(attn, query, key, original_context_length)
|
| 288 |
+
|
| 289 |
+
hidden_states = dispatch_attention_fn(
|
| 290 |
+
query,
|
| 291 |
+
key,
|
| 292 |
+
value,
|
| 293 |
+
attn_mask=attention_mask,
|
| 294 |
+
dropout_p=0.0,
|
| 295 |
+
is_causal=False,
|
| 296 |
+
backend=self._attention_backend,
|
| 297 |
+
# Reference: https://github.com/huggingface/diffusers/pull/12909
|
| 298 |
+
parallel_config=(self._parallel_config if encoder_hidden_states is None else None),
|
| 299 |
+
)
|
| 300 |
+
hidden_states = hidden_states.flatten(2, 3)
|
| 301 |
+
hidden_states = hidden_states.type_as(query)
|
| 302 |
+
|
| 303 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 304 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 305 |
+
return hidden_states
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class HeliosAttention(torch.nn.Module, AttentionModuleMixin):
|
| 309 |
+
_default_processor_cls = HeliosAttnProcessor
|
| 310 |
+
_available_processors = [HeliosAttnProcessor]
|
| 311 |
+
|
| 312 |
+
def __init__(
|
| 313 |
+
self,
|
| 314 |
+
dim: int,
|
| 315 |
+
heads: int = 8,
|
| 316 |
+
dim_head: int = 64,
|
| 317 |
+
eps: float = 1e-5,
|
| 318 |
+
dropout: float = 0.0,
|
| 319 |
+
added_kv_proj_dim: int | None = None,
|
| 320 |
+
cross_attention_dim_head: int | None = None,
|
| 321 |
+
processor=None,
|
| 322 |
+
is_cross_attention=None,
|
| 323 |
+
is_amplify_history=False,
|
| 324 |
+
history_scale_mode="per_head", # [scalar, per_head]
|
| 325 |
+
):
|
| 326 |
+
super().__init__()
|
| 327 |
+
|
| 328 |
+
self.inner_dim = dim_head * heads
|
| 329 |
+
self.heads = heads
|
| 330 |
+
self.added_kv_proj_dim = added_kv_proj_dim
|
| 331 |
+
self.cross_attention_dim_head = cross_attention_dim_head
|
| 332 |
+
self.kv_inner_dim = self.inner_dim if cross_attention_dim_head is None else cross_attention_dim_head * heads
|
| 333 |
+
|
| 334 |
+
self.to_q = torch.nn.Linear(dim, self.inner_dim, bias=True)
|
| 335 |
+
self.to_k = torch.nn.Linear(dim, self.kv_inner_dim, bias=True)
|
| 336 |
+
self.to_v = torch.nn.Linear(dim, self.kv_inner_dim, bias=True)
|
| 337 |
+
self.to_out = torch.nn.ModuleList(
|
| 338 |
+
[
|
| 339 |
+
torch.nn.Linear(self.inner_dim, dim, bias=True),
|
| 340 |
+
torch.nn.Dropout(dropout),
|
| 341 |
+
]
|
| 342 |
+
)
|
| 343 |
+
self.norm_q = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True)
|
| 344 |
+
self.norm_k = torch.nn.RMSNorm(dim_head * heads, eps=eps, elementwise_affine=True)
|
| 345 |
+
|
| 346 |
+
self.add_k_proj = self.add_v_proj = None
|
| 347 |
+
if added_kv_proj_dim is not None:
|
| 348 |
+
self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True)
|
| 349 |
+
self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=True)
|
| 350 |
+
self.norm_added_k = torch.nn.RMSNorm(dim_head * heads, eps=eps)
|
| 351 |
+
|
| 352 |
+
if is_cross_attention is not None:
|
| 353 |
+
self.is_cross_attention = is_cross_attention
|
| 354 |
+
else:
|
| 355 |
+
self.is_cross_attention = cross_attention_dim_head is not None
|
| 356 |
+
|
| 357 |
+
self.set_processor(processor)
|
| 358 |
+
|
| 359 |
+
self.is_amplify_history = is_amplify_history
|
| 360 |
+
if is_amplify_history:
|
| 361 |
+
if history_scale_mode == "scalar":
|
| 362 |
+
self.history_key_scale = nn.Parameter(torch.ones(1))
|
| 363 |
+
elif history_scale_mode == "per_head":
|
| 364 |
+
self.history_key_scale = nn.Parameter(torch.ones(heads))
|
| 365 |
+
else:
|
| 366 |
+
raise ValueError(f"Unknown history_scale_mode: {history_scale_mode}")
|
| 367 |
+
self.history_scale_mode = history_scale_mode
|
| 368 |
+
self.max_scale = 10.0
|
| 369 |
+
|
| 370 |
+
def fuse_projections(self):
|
| 371 |
+
if getattr(self, "fused_projections", False):
|
| 372 |
+
return
|
| 373 |
+
|
| 374 |
+
if not self.is_cross_attention:
|
| 375 |
+
concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data])
|
| 376 |
+
concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data])
|
| 377 |
+
out_features, in_features = concatenated_weights.shape
|
| 378 |
+
with torch.device("meta"):
|
| 379 |
+
self.to_qkv = nn.Linear(in_features, out_features, bias=True)
|
| 380 |
+
self.to_qkv.load_state_dict(
|
| 381 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 382 |
+
)
|
| 383 |
+
else:
|
| 384 |
+
concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data])
|
| 385 |
+
concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data])
|
| 386 |
+
out_features, in_features = concatenated_weights.shape
|
| 387 |
+
with torch.device("meta"):
|
| 388 |
+
self.to_kv = nn.Linear(in_features, out_features, bias=True)
|
| 389 |
+
self.to_kv.load_state_dict(
|
| 390 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
if self.added_kv_proj_dim is not None:
|
| 394 |
+
concatenated_weights = torch.cat([self.add_k_proj.weight.data, self.add_v_proj.weight.data])
|
| 395 |
+
concatenated_bias = torch.cat([self.add_k_proj.bias.data, self.add_v_proj.bias.data])
|
| 396 |
+
out_features, in_features = concatenated_weights.shape
|
| 397 |
+
with torch.device("meta"):
|
| 398 |
+
self.to_added_kv = nn.Linear(in_features, out_features, bias=True)
|
| 399 |
+
self.to_added_kv.load_state_dict(
|
| 400 |
+
{"weight": concatenated_weights, "bias": concatenated_bias}, strict=True, assign=True
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
self.fused_projections = True
|
| 404 |
+
|
| 405 |
+
@torch.no_grad()
|
| 406 |
+
def unfuse_projections(self):
|
| 407 |
+
if not getattr(self, "fused_projections", False):
|
| 408 |
+
return
|
| 409 |
+
|
| 410 |
+
if hasattr(self, "to_qkv"):
|
| 411 |
+
delattr(self, "to_qkv")
|
| 412 |
+
if hasattr(self, "to_kv"):
|
| 413 |
+
delattr(self, "to_kv")
|
| 414 |
+
if hasattr(self, "to_added_kv"):
|
| 415 |
+
delattr(self, "to_added_kv")
|
| 416 |
+
|
| 417 |
+
self.fused_projections = False
|
| 418 |
+
|
| 419 |
+
def forward(
|
| 420 |
+
self,
|
| 421 |
+
hidden_states: torch.Tensor,
|
| 422 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 423 |
+
attention_mask: torch.Tensor | None = None,
|
| 424 |
+
rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 425 |
+
original_context_length: int = None,
|
| 426 |
+
**kwargs,
|
| 427 |
+
) -> torch.Tensor:
|
| 428 |
+
return self.processor(
|
| 429 |
+
self,
|
| 430 |
+
hidden_states,
|
| 431 |
+
encoder_hidden_states,
|
| 432 |
+
attention_mask,
|
| 433 |
+
rotary_emb,
|
| 434 |
+
original_context_length,
|
| 435 |
+
**kwargs,
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class HeliosTimeTextEmbedding(nn.Module):
|
| 440 |
+
def __init__(
|
| 441 |
+
self,
|
| 442 |
+
dim: int,
|
| 443 |
+
time_freq_dim: int,
|
| 444 |
+
time_proj_dim: int,
|
| 445 |
+
text_embed_dim: int,
|
| 446 |
+
):
|
| 447 |
+
super().__init__()
|
| 448 |
+
|
| 449 |
+
self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
|
| 450 |
+
self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
|
| 451 |
+
self.act_fn = nn.SiLU()
|
| 452 |
+
self.time_proj = nn.Linear(dim, time_proj_dim)
|
| 453 |
+
self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
|
| 454 |
+
|
| 455 |
+
def forward(
|
| 456 |
+
self,
|
| 457 |
+
timestep: torch.Tensor,
|
| 458 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 459 |
+
is_return_encoder_hidden_states: bool = True,
|
| 460 |
+
):
|
| 461 |
+
timestep = self.timesteps_proj(timestep)
|
| 462 |
+
|
| 463 |
+
time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
|
| 464 |
+
if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
|
| 465 |
+
timestep = timestep.to(time_embedder_dtype)
|
| 466 |
+
temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
|
| 467 |
+
timestep_proj = self.time_proj(self.act_fn(temb))
|
| 468 |
+
|
| 469 |
+
if encoder_hidden_states is not None and is_return_encoder_hidden_states:
|
| 470 |
+
encoder_hidden_states = self.text_embedder(encoder_hidden_states)
|
| 471 |
+
|
| 472 |
+
return temb, timestep_proj, encoder_hidden_states
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class HeliosRotaryPosEmbed(nn.Module):
|
| 476 |
+
def __init__(self, rope_dim, theta):
|
| 477 |
+
super().__init__()
|
| 478 |
+
self.DT, self.DY, self.DX = rope_dim
|
| 479 |
+
self.theta = theta
|
| 480 |
+
self.register_buffer("freqs_base_t", self._get_freqs_base(self.DT), persistent=False)
|
| 481 |
+
self.register_buffer("freqs_base_y", self._get_freqs_base(self.DY), persistent=False)
|
| 482 |
+
self.register_buffer("freqs_base_x", self._get_freqs_base(self.DX), persistent=False)
|
| 483 |
+
|
| 484 |
+
def _get_freqs_base(self, dim):
|
| 485 |
+
return 1.0 / (self.theta ** (torch.arange(0, dim, 2, dtype=torch.float32)[: (dim // 2)] / dim))
|
| 486 |
+
|
| 487 |
+
@torch.no_grad()
|
| 488 |
+
def get_frequency_batched(self, freqs_base, pos):
|
| 489 |
+
freqs = torch.einsum("d,bthw->dbthw", freqs_base, pos)
|
| 490 |
+
freqs = freqs.repeat_interleave(2, dim=0)
|
| 491 |
+
return freqs.cos(), freqs.sin()
|
| 492 |
+
|
| 493 |
+
@torch.no_grad()
|
| 494 |
+
@lru_cache(maxsize=32)
|
| 495 |
+
def _get_spatial_meshgrid(self, height, width, device_str):
|
| 496 |
+
device = torch.device(device_str)
|
| 497 |
+
grid_y_coords = torch.arange(height, device=device, dtype=torch.float32)
|
| 498 |
+
grid_x_coords = torch.arange(width, device=device, dtype=torch.float32)
|
| 499 |
+
grid_y, grid_x = torch.meshgrid(grid_y_coords, grid_x_coords, indexing="ij")
|
| 500 |
+
return grid_y, grid_x
|
| 501 |
+
|
| 502 |
+
@torch.no_grad()
|
| 503 |
+
def forward(self, frame_indices, height, width, device):
|
| 504 |
+
batch_size = frame_indices.shape[0]
|
| 505 |
+
num_frames = frame_indices.shape[1]
|
| 506 |
+
|
| 507 |
+
frame_indices = frame_indices.to(device=device, dtype=torch.float32)
|
| 508 |
+
grid_y, grid_x = self._get_spatial_meshgrid(height, width, str(device))
|
| 509 |
+
|
| 510 |
+
grid_t = frame_indices[:, :, None, None].expand(batch_size, num_frames, height, width)
|
| 511 |
+
grid_y_batch = grid_y[None, None, :, :].expand(batch_size, num_frames, -1, -1)
|
| 512 |
+
grid_x_batch = grid_x[None, None, :, :].expand(batch_size, num_frames, -1, -1)
|
| 513 |
+
|
| 514 |
+
freqs_cos_t, freqs_sin_t = self.get_frequency_batched(self.freqs_base_t, grid_t)
|
| 515 |
+
freqs_cos_y, freqs_sin_y = self.get_frequency_batched(self.freqs_base_y, grid_y_batch)
|
| 516 |
+
freqs_cos_x, freqs_sin_x = self.get_frequency_batched(self.freqs_base_x, grid_x_batch)
|
| 517 |
+
|
| 518 |
+
result = torch.cat([freqs_cos_t, freqs_cos_y, freqs_cos_x, freqs_sin_t, freqs_sin_y, freqs_sin_x], dim=0)
|
| 519 |
+
|
| 520 |
+
return result.permute(1, 0, 2, 3, 4)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@maybe_allow_in_graph
|
| 524 |
+
class HeliosTransformerBlock(nn.Module):
|
| 525 |
+
def __init__(
|
| 526 |
+
self,
|
| 527 |
+
dim: int,
|
| 528 |
+
ffn_dim: int,
|
| 529 |
+
num_heads: int,
|
| 530 |
+
qk_norm: str = "rms_norm_across_heads",
|
| 531 |
+
cross_attn_norm: bool = False,
|
| 532 |
+
eps: float = 1e-6,
|
| 533 |
+
added_kv_proj_dim: int | None = None,
|
| 534 |
+
guidance_cross_attn: bool = False,
|
| 535 |
+
is_amplify_history: bool = False,
|
| 536 |
+
history_scale_mode: str = "per_head", # [scalar, per_head]
|
| 537 |
+
):
|
| 538 |
+
super().__init__()
|
| 539 |
+
|
| 540 |
+
# 1. Self-attention
|
| 541 |
+
self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 542 |
+
self.attn1 = HeliosAttention(
|
| 543 |
+
dim=dim,
|
| 544 |
+
heads=num_heads,
|
| 545 |
+
dim_head=dim // num_heads,
|
| 546 |
+
eps=eps,
|
| 547 |
+
cross_attention_dim_head=None,
|
| 548 |
+
processor=HeliosAttnProcessor(),
|
| 549 |
+
is_amplify_history=is_amplify_history,
|
| 550 |
+
history_scale_mode=history_scale_mode,
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
# 2. Cross-attention
|
| 554 |
+
self.attn2 = HeliosAttention(
|
| 555 |
+
dim=dim,
|
| 556 |
+
heads=num_heads,
|
| 557 |
+
dim_head=dim // num_heads,
|
| 558 |
+
eps=eps,
|
| 559 |
+
added_kv_proj_dim=added_kv_proj_dim,
|
| 560 |
+
cross_attention_dim_head=dim // num_heads,
|
| 561 |
+
processor=HeliosAttnProcessor(),
|
| 562 |
+
)
|
| 563 |
+
self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
| 564 |
+
|
| 565 |
+
# 3. Feed-forward
|
| 566 |
+
self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
|
| 567 |
+
self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 568 |
+
|
| 569 |
+
self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
|
| 570 |
+
|
| 571 |
+
# 4. Guidance cross-attention
|
| 572 |
+
self.guidance_cross_attn = guidance_cross_attn
|
| 573 |
+
|
| 574 |
+
def forward(
|
| 575 |
+
self,
|
| 576 |
+
hidden_states: torch.Tensor,
|
| 577 |
+
encoder_hidden_states: torch.Tensor,
|
| 578 |
+
temb: torch.Tensor,
|
| 579 |
+
rotary_emb: torch.Tensor,
|
| 580 |
+
original_context_length: int = None,
|
| 581 |
+
) -> torch.Tensor:
|
| 582 |
+
if temb.ndim == 4:
|
| 583 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 584 |
+
self.scale_shift_table.unsqueeze(0) + temb.float()
|
| 585 |
+
).chunk(6, dim=2)
|
| 586 |
+
# batch_size, seq_len, 1, inner_dim
|
| 587 |
+
shift_msa = shift_msa.squeeze(2)
|
| 588 |
+
scale_msa = scale_msa.squeeze(2)
|
| 589 |
+
gate_msa = gate_msa.squeeze(2)
|
| 590 |
+
c_shift_msa = c_shift_msa.squeeze(2)
|
| 591 |
+
c_scale_msa = c_scale_msa.squeeze(2)
|
| 592 |
+
c_gate_msa = c_gate_msa.squeeze(2)
|
| 593 |
+
else:
|
| 594 |
+
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 595 |
+
self.scale_shift_table + temb.float()
|
| 596 |
+
).chunk(6, dim=1)
|
| 597 |
+
|
| 598 |
+
# 1. Self-attention
|
| 599 |
+
norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
|
| 600 |
+
attn_output = self.attn1(
|
| 601 |
+
norm_hidden_states,
|
| 602 |
+
None,
|
| 603 |
+
None,
|
| 604 |
+
rotary_emb,
|
| 605 |
+
original_context_length,
|
| 606 |
+
)
|
| 607 |
+
hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
|
| 608 |
+
|
| 609 |
+
# 2. Cross-attention
|
| 610 |
+
if self.guidance_cross_attn:
|
| 611 |
+
history_seq_len = hidden_states.shape[1] - original_context_length
|
| 612 |
+
|
| 613 |
+
history_hidden_states, hidden_states = torch.split(
|
| 614 |
+
hidden_states, [history_seq_len, original_context_length], dim=1
|
| 615 |
+
)
|
| 616 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 617 |
+
attn_output = self.attn2(
|
| 618 |
+
norm_hidden_states,
|
| 619 |
+
encoder_hidden_states,
|
| 620 |
+
None,
|
| 621 |
+
None,
|
| 622 |
+
original_context_length,
|
| 623 |
+
)
|
| 624 |
+
hidden_states = hidden_states + attn_output
|
| 625 |
+
hidden_states = torch.cat([history_hidden_states, hidden_states], dim=1)
|
| 626 |
+
else:
|
| 627 |
+
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 628 |
+
attn_output = self.attn2(
|
| 629 |
+
norm_hidden_states,
|
| 630 |
+
encoder_hidden_states,
|
| 631 |
+
None,
|
| 632 |
+
None,
|
| 633 |
+
original_context_length,
|
| 634 |
+
)
|
| 635 |
+
hidden_states = hidden_states + attn_output
|
| 636 |
+
|
| 637 |
+
# 3. Feed-forward
|
| 638 |
+
norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
|
| 639 |
+
hidden_states
|
| 640 |
+
)
|
| 641 |
+
ff_output = self.ffn(norm_hidden_states)
|
| 642 |
+
hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
|
| 643 |
+
|
| 644 |
+
return hidden_states
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
class HeliosTransformer3DModel(
|
| 648 |
+
ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin, AttentionMixin
|
| 649 |
+
):
|
| 650 |
+
r"""
|
| 651 |
+
A Transformer model for video-like data used in the Helios model.
|
| 652 |
+
|
| 653 |
+
Args:
|
| 654 |
+
patch_size (`tuple[int]`, defaults to `(1, 2, 2)`):
|
| 655 |
+
3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
|
| 656 |
+
num_attention_heads (`int`, defaults to `40`):
|
| 657 |
+
Fixed length for text embeddings.
|
| 658 |
+
attention_head_dim (`int`, defaults to `128`):
|
| 659 |
+
The number of channels in each head.
|
| 660 |
+
in_channels (`int`, defaults to `16`):
|
| 661 |
+
The number of channels in the input.
|
| 662 |
+
out_channels (`int`, defaults to `16`):
|
| 663 |
+
The number of channels in the output.
|
| 664 |
+
text_dim (`int`, defaults to `512`):
|
| 665 |
+
Input dimension for text embeddings.
|
| 666 |
+
freq_dim (`int`, defaults to `256`):
|
| 667 |
+
Dimension for sinusoidal time embeddings.
|
| 668 |
+
ffn_dim (`int`, defaults to `13824`):
|
| 669 |
+
Intermediate dimension in feed-forward network.
|
| 670 |
+
num_layers (`int`, defaults to `40`):
|
| 671 |
+
The number of layers of transformer blocks to use.
|
| 672 |
+
window_size (`tuple[int]`, defaults to `(-1, -1)`):
|
| 673 |
+
Window size for local attention (-1 indicates global attention).
|
| 674 |
+
cross_attn_norm (`bool`, defaults to `True`):
|
| 675 |
+
Enable cross-attention normalization.
|
| 676 |
+
qk_norm (`bool`, defaults to `True`):
|
| 677 |
+
Enable query/key normalization.
|
| 678 |
+
eps (`float`, defaults to `1e-6`):
|
| 679 |
+
Epsilon value for normalization layers.
|
| 680 |
+
add_img_emb (`bool`, defaults to `False`):
|
| 681 |
+
Whether to use img_emb.
|
| 682 |
+
added_kv_proj_dim (`int`, *optional*, defaults to `None`):
|
| 683 |
+
The number of channels to use for the added key and value projections. If `None`, no projection is used.
|
| 684 |
+
"""
|
| 685 |
+
|
| 686 |
+
_supports_gradient_checkpointing = True
|
| 687 |
+
_skip_layerwise_casting_patterns = [
|
| 688 |
+
"patch_embedding",
|
| 689 |
+
"patch_short",
|
| 690 |
+
"patch_mid",
|
| 691 |
+
"patch_long",
|
| 692 |
+
"condition_embedder",
|
| 693 |
+
"norm",
|
| 694 |
+
]
|
| 695 |
+
_no_split_modules = ["HeliosTransformerBlock", "HeliosOutputNorm"]
|
| 696 |
+
_keep_in_fp32_modules = [
|
| 697 |
+
"time_embedder",
|
| 698 |
+
"scale_shift_table",
|
| 699 |
+
"norm1",
|
| 700 |
+
"norm2",
|
| 701 |
+
"norm3",
|
| 702 |
+
"history_key_scale",
|
| 703 |
+
]
|
| 704 |
+
_keys_to_ignore_on_load_unexpected = ["norm_added_q"]
|
| 705 |
+
_repeated_blocks = ["HeliosTransformerBlock"]
|
| 706 |
+
_cp_plan = {
|
| 707 |
+
# Input split at attn level and ffn level.
|
| 708 |
+
"blocks.*.attn1": {
|
| 709 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 710 |
+
"rotary_emb": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 711 |
+
},
|
| 712 |
+
"blocks.*.attn2": {
|
| 713 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 714 |
+
},
|
| 715 |
+
"blocks.*.ffn": {
|
| 716 |
+
"hidden_states": ContextParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
| 717 |
+
},
|
| 718 |
+
# Output gather at attn level and ffn level.
|
| 719 |
+
**{f"blocks.{i}.attn1": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 720 |
+
**{f"blocks.{i}.attn2": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 721 |
+
**{f"blocks.{i}.ffn": ContextParallelOutput(gather_dim=1, expected_dims=3) for i in range(40)},
|
| 722 |
+
}
|
| 723 |
+
|
| 724 |
+
@register_to_config
|
| 725 |
+
def __init__(
|
| 726 |
+
self,
|
| 727 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 728 |
+
num_attention_heads: int = 40,
|
| 729 |
+
attention_head_dim: int = 128,
|
| 730 |
+
in_channels: int = 16,
|
| 731 |
+
out_channels: int = 16,
|
| 732 |
+
text_dim: int = 4096,
|
| 733 |
+
freq_dim: int = 256,
|
| 734 |
+
ffn_dim: int = 13824,
|
| 735 |
+
num_layers: int = 40,
|
| 736 |
+
cross_attn_norm: bool = True,
|
| 737 |
+
qk_norm: str | None = "rms_norm_across_heads",
|
| 738 |
+
eps: float = 1e-6,
|
| 739 |
+
added_kv_proj_dim: int | None = None,
|
| 740 |
+
rope_dim: tuple[int, ...] = (44, 42, 42),
|
| 741 |
+
rope_theta: float = 10000.0,
|
| 742 |
+
guidance_cross_attn: bool = True,
|
| 743 |
+
zero_history_timestep: bool = True,
|
| 744 |
+
has_multi_term_memory_patch: bool = True,
|
| 745 |
+
is_amplify_history: bool = False,
|
| 746 |
+
history_scale_mode: str = "per_head", # [scalar, per_head]
|
| 747 |
+
) -> None:
|
| 748 |
+
super().__init__()
|
| 749 |
+
|
| 750 |
+
inner_dim = num_attention_heads * attention_head_dim
|
| 751 |
+
out_channels = out_channels or in_channels
|
| 752 |
+
|
| 753 |
+
# 1. Patch & position embedding
|
| 754 |
+
self.rope = HeliosRotaryPosEmbed(rope_dim=rope_dim, theta=rope_theta)
|
| 755 |
+
self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 756 |
+
|
| 757 |
+
# 2. Initial Multi Term Memory Patch
|
| 758 |
+
self.zero_history_timestep = zero_history_timestep
|
| 759 |
+
self.inner_dim = inner_dim
|
| 760 |
+
if has_multi_term_memory_patch:
|
| 761 |
+
self.patch_short = nn.Conv3d(in_channels, self.inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 762 |
+
self.patch_mid = nn.Conv3d(
|
| 763 |
+
in_channels,
|
| 764 |
+
self.inner_dim,
|
| 765 |
+
kernel_size=tuple(2 * p for p in patch_size),
|
| 766 |
+
stride=tuple(2 * p for p in patch_size),
|
| 767 |
+
)
|
| 768 |
+
self.patch_long = nn.Conv3d(
|
| 769 |
+
in_channels,
|
| 770 |
+
self.inner_dim,
|
| 771 |
+
kernel_size=tuple(4 * p for p in patch_size),
|
| 772 |
+
stride=tuple(4 * p for p in patch_size),
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
# 3. Condition embeddings
|
| 776 |
+
self.condition_embedder = HeliosTimeTextEmbedding(
|
| 777 |
+
dim=inner_dim,
|
| 778 |
+
time_freq_dim=freq_dim,
|
| 779 |
+
time_proj_dim=inner_dim * 6,
|
| 780 |
+
text_embed_dim=text_dim,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
# 4. Transformer blocks
|
| 784 |
+
self.blocks = nn.ModuleList(
|
| 785 |
+
[
|
| 786 |
+
HeliosTransformerBlock(
|
| 787 |
+
inner_dim,
|
| 788 |
+
ffn_dim,
|
| 789 |
+
num_attention_heads,
|
| 790 |
+
qk_norm,
|
| 791 |
+
cross_attn_norm,
|
| 792 |
+
eps,
|
| 793 |
+
added_kv_proj_dim,
|
| 794 |
+
guidance_cross_attn=guidance_cross_attn,
|
| 795 |
+
is_amplify_history=is_amplify_history,
|
| 796 |
+
history_scale_mode=history_scale_mode,
|
| 797 |
+
)
|
| 798 |
+
for _ in range(num_layers)
|
| 799 |
+
]
|
| 800 |
+
)
|
| 801 |
+
self.short_attn_debug_config = None
|
| 802 |
+
self.short_attn_debug_state = {}
|
| 803 |
+
self._refresh_short_attn_debug_hooks()
|
| 804 |
+
|
| 805 |
+
# 5. Output norm & projection
|
| 806 |
+
self.norm_out = HeliosOutputNorm(inner_dim, eps, elementwise_affine=False)
|
| 807 |
+
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
|
| 808 |
+
|
| 809 |
+
self.gradient_checkpointing = False
|
| 810 |
+
|
| 811 |
+
def _refresh_short_attn_debug_hooks(self):
|
| 812 |
+
for block_idx, block in enumerate(self.blocks):
|
| 813 |
+
block.attn1._helios_block_idx = block_idx
|
| 814 |
+
block.attn1._short_attn_debug_config = self.short_attn_debug_config
|
| 815 |
+
block.attn1._short_attn_debug_state = self.short_attn_debug_state
|
| 816 |
+
block.attn2._short_attn_debug_config = None
|
| 817 |
+
block.attn2._short_attn_debug_state = None
|
| 818 |
+
|
| 819 |
+
def configure_short_attn_debug(self, config: dict[str, Any] | None = None):
|
| 820 |
+
self.short_attn_debug_config = dict(config) if config else None
|
| 821 |
+
if self.short_attn_debug_config is not None:
|
| 822 |
+
self.short_attn_debug_config.setdefault("enabled", True)
|
| 823 |
+
self.short_attn_debug_config.setdefault("blocks", [30])
|
| 824 |
+
self.short_attn_debug_config.setdefault("steps", ["last"])
|
| 825 |
+
self.short_attn_debug_config.setdefault("current_frame", -1)
|
| 826 |
+
self.short_attn_debug_config.setdefault("prev_short_frame", 1)
|
| 827 |
+
self.short_attn_debug_config.setdefault("short_history_frames", 2)
|
| 828 |
+
self.short_attn_debug_config.setdefault("pass_names", ["cond"])
|
| 829 |
+
self.short_attn_debug_config.setdefault("topk", 2)
|
| 830 |
+
self.short_attn_debug_config.setdefault("query_chunk_size", 128)
|
| 831 |
+
self.short_attn_debug_state = {}
|
| 832 |
+
self._refresh_short_attn_debug_hooks()
|
| 833 |
+
|
| 834 |
+
def set_short_attn_debug_context(self, **state):
|
| 835 |
+
if self.short_attn_debug_config is None:
|
| 836 |
+
return
|
| 837 |
+
self.short_attn_debug_state.clear()
|
| 838 |
+
self.short_attn_debug_state.update(state)
|
| 839 |
+
|
| 840 |
+
@apply_lora_scale("attention_kwargs")
|
| 841 |
+
def forward(
|
| 842 |
+
self,
|
| 843 |
+
hidden_states: torch.Tensor,
|
| 844 |
+
timestep: torch.LongTensor,
|
| 845 |
+
encoder_hidden_states: torch.Tensor,
|
| 846 |
+
# ------------ Stage 1 ------------
|
| 847 |
+
indices_hidden_states=None,
|
| 848 |
+
indices_latents_history_short=None,
|
| 849 |
+
indices_latents_history_mid=None,
|
| 850 |
+
indices_latents_history_long=None,
|
| 851 |
+
latents_history_short=None,
|
| 852 |
+
latents_history_mid=None,
|
| 853 |
+
latents_history_long=None,
|
| 854 |
+
return_dict: bool = True,
|
| 855 |
+
attention_kwargs: dict[str, Any] | None = None,
|
| 856 |
+
) -> torch.Tensor | dict[str, torch.Tensor]:
|
| 857 |
+
# 1. Input
|
| 858 |
+
batch_size = hidden_states.shape[0]
|
| 859 |
+
p_t, p_h, p_w = self.config.patch_size
|
| 860 |
+
|
| 861 |
+
# 2. Process noisy latents
|
| 862 |
+
hidden_states = self.patch_embedding(hidden_states)
|
| 863 |
+
_, _, post_patch_num_frames, post_patch_height, post_patch_width = hidden_states.shape
|
| 864 |
+
|
| 865 |
+
if indices_hidden_states is None:
|
| 866 |
+
indices_hidden_states = torch.arange(0, post_patch_num_frames).unsqueeze(0).expand(batch_size, -1)
|
| 867 |
+
|
| 868 |
+
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
| 869 |
+
rotary_emb = self.rope(
|
| 870 |
+
frame_indices=indices_hidden_states,
|
| 871 |
+
height=post_patch_height,
|
| 872 |
+
width=post_patch_width,
|
| 873 |
+
device=hidden_states.device,
|
| 874 |
+
)
|
| 875 |
+
rotary_emb = rotary_emb.flatten(2).transpose(1, 2)
|
| 876 |
+
original_context_length = hidden_states.shape[1]
|
| 877 |
+
|
| 878 |
+
# 3. Process short history latents
|
| 879 |
+
if latents_history_short is not None and indices_latents_history_short is not None:
|
| 880 |
+
latents_history_short = latents_history_short.to(hidden_states)
|
| 881 |
+
latents_history_short = self.patch_short(latents_history_short)
|
| 882 |
+
_, _, _, H1, W1 = latents_history_short.shape
|
| 883 |
+
latents_history_short = latents_history_short.flatten(2).transpose(1, 2)
|
| 884 |
+
|
| 885 |
+
rotary_emb_history_short = self.rope(
|
| 886 |
+
frame_indices=indices_latents_history_short,
|
| 887 |
+
height=H1,
|
| 888 |
+
width=W1,
|
| 889 |
+
device=latents_history_short.device,
|
| 890 |
+
)
|
| 891 |
+
rotary_emb_history_short = rotary_emb_history_short.flatten(2).transpose(1, 2)
|
| 892 |
+
|
| 893 |
+
hidden_states = torch.cat([latents_history_short, hidden_states], dim=1)
|
| 894 |
+
rotary_emb = torch.cat([rotary_emb_history_short, rotary_emb], dim=1)
|
| 895 |
+
|
| 896 |
+
# 4. Process mid history latents
|
| 897 |
+
if latents_history_mid is not None and indices_latents_history_mid is not None:
|
| 898 |
+
latents_history_mid = latents_history_mid.to(hidden_states)
|
| 899 |
+
latents_history_mid = pad_for_3d_conv(latents_history_mid, (2, 4, 4))
|
| 900 |
+
latents_history_mid = self.patch_mid(latents_history_mid)
|
| 901 |
+
latents_history_mid = latents_history_mid.flatten(2).transpose(1, 2)
|
| 902 |
+
|
| 903 |
+
rotary_emb_history_mid = self.rope(
|
| 904 |
+
frame_indices=indices_latents_history_mid,
|
| 905 |
+
height=H1,
|
| 906 |
+
width=W1,
|
| 907 |
+
device=latents_history_mid.device,
|
| 908 |
+
)
|
| 909 |
+
rotary_emb_history_mid = pad_for_3d_conv(rotary_emb_history_mid, (2, 2, 2))
|
| 910 |
+
rotary_emb_history_mid = center_down_sample_3d(rotary_emb_history_mid, (2, 2, 2))
|
| 911 |
+
rotary_emb_history_mid = rotary_emb_history_mid.flatten(2).transpose(1, 2)
|
| 912 |
+
|
| 913 |
+
hidden_states = torch.cat([latents_history_mid, hidden_states], dim=1)
|
| 914 |
+
rotary_emb = torch.cat([rotary_emb_history_mid, rotary_emb], dim=1)
|
| 915 |
+
|
| 916 |
+
# 5. Process long history latents
|
| 917 |
+
if latents_history_long is not None and indices_latents_history_long is not None:
|
| 918 |
+
latents_history_long = latents_history_long.to(hidden_states)
|
| 919 |
+
latents_history_long = pad_for_3d_conv(latents_history_long, (4, 8, 8))
|
| 920 |
+
latents_history_long = self.patch_long(latents_history_long)
|
| 921 |
+
latents_history_long = latents_history_long.flatten(2).transpose(1, 2)
|
| 922 |
+
|
| 923 |
+
rotary_emb_history_long = self.rope(
|
| 924 |
+
frame_indices=indices_latents_history_long,
|
| 925 |
+
height=H1,
|
| 926 |
+
width=W1,
|
| 927 |
+
device=latents_history_long.device,
|
| 928 |
+
)
|
| 929 |
+
rotary_emb_history_long = pad_for_3d_conv(rotary_emb_history_long, (4, 4, 4))
|
| 930 |
+
rotary_emb_history_long = center_down_sample_3d(rotary_emb_history_long, (4, 4, 4))
|
| 931 |
+
rotary_emb_history_long = rotary_emb_history_long.flatten(2).transpose(1, 2)
|
| 932 |
+
|
| 933 |
+
hidden_states = torch.cat([latents_history_long, hidden_states], dim=1)
|
| 934 |
+
rotary_emb = torch.cat([rotary_emb_history_long, rotary_emb], dim=1)
|
| 935 |
+
|
| 936 |
+
history_context_length = hidden_states.shape[1] - original_context_length
|
| 937 |
+
|
| 938 |
+
if indices_hidden_states is not None and self.zero_history_timestep:
|
| 939 |
+
timestep_t0 = torch.zeros((1), dtype=timestep.dtype, device=timestep.device)
|
| 940 |
+
temb_t0, timestep_proj_t0, _ = self.condition_embedder(
|
| 941 |
+
timestep_t0, encoder_hidden_states, is_return_encoder_hidden_states=False
|
| 942 |
+
)
|
| 943 |
+
temb_t0 = temb_t0.unsqueeze(1).expand(batch_size, history_context_length, -1)
|
| 944 |
+
timestep_proj_t0 = (
|
| 945 |
+
timestep_proj_t0.unflatten(-1, (6, -1))
|
| 946 |
+
.view(1, 6, 1, -1)
|
| 947 |
+
.expand(batch_size, -1, history_context_length, -1)
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
temb, timestep_proj, encoder_hidden_states = self.condition_embedder(timestep, encoder_hidden_states)
|
| 951 |
+
timestep_proj = timestep_proj.unflatten(-1, (6, -1))
|
| 952 |
+
|
| 953 |
+
if indices_hidden_states is not None and not self.zero_history_timestep:
|
| 954 |
+
main_repeat_size = hidden_states.shape[1]
|
| 955 |
+
else:
|
| 956 |
+
main_repeat_size = original_context_length
|
| 957 |
+
temb = temb.view(batch_size, 1, -1).expand(batch_size, main_repeat_size, -1)
|
| 958 |
+
timestep_proj = timestep_proj.view(batch_size, 6, 1, -1).expand(batch_size, 6, main_repeat_size, -1)
|
| 959 |
+
|
| 960 |
+
if indices_hidden_states is not None and self.zero_history_timestep:
|
| 961 |
+
temb = torch.cat([temb_t0, temb], dim=1)
|
| 962 |
+
timestep_proj = torch.cat([timestep_proj_t0, timestep_proj], dim=2)
|
| 963 |
+
|
| 964 |
+
if timestep_proj.ndim == 4:
|
| 965 |
+
timestep_proj = timestep_proj.permute(0, 2, 1, 3)
|
| 966 |
+
|
| 967 |
+
# 6. Transformer blocks
|
| 968 |
+
hidden_states = hidden_states.contiguous()
|
| 969 |
+
encoder_hidden_states = encoder_hidden_states.contiguous()
|
| 970 |
+
rotary_emb = rotary_emb.contiguous()
|
| 971 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
| 972 |
+
for block in self.blocks:
|
| 973 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 974 |
+
block,
|
| 975 |
+
hidden_states,
|
| 976 |
+
encoder_hidden_states,
|
| 977 |
+
timestep_proj,
|
| 978 |
+
rotary_emb,
|
| 979 |
+
original_context_length,
|
| 980 |
+
)
|
| 981 |
+
else:
|
| 982 |
+
for block in self.blocks:
|
| 983 |
+
hidden_states = block(
|
| 984 |
+
hidden_states,
|
| 985 |
+
encoder_hidden_states,
|
| 986 |
+
timestep_proj,
|
| 987 |
+
rotary_emb,
|
| 988 |
+
original_context_length,
|
| 989 |
+
)
|
| 990 |
+
|
| 991 |
+
# 7. Normalization
|
| 992 |
+
hidden_states = self.norm_out(hidden_states, temb, original_context_length)
|
| 993 |
+
hidden_states = self.proj_out(hidden_states)
|
| 994 |
+
|
| 995 |
+
# 8. Unpatchify
|
| 996 |
+
hidden_states = hidden_states.reshape(
|
| 997 |
+
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
|
| 998 |
+
)
|
| 999 |
+
hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
|
| 1000 |
+
output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
| 1001 |
+
|
| 1002 |
+
if not return_dict:
|
| 1003 |
+
return (output,)
|
| 1004 |
+
|
| 1005 |
+
return Transformer2DModelOutput(sample=output)
|
Helios/_DEV2/helios/modules/__init__.py
ADDED
|
File without changes
|
Helios/_DEV2/helios/modules/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (190 Bytes). View file
|
|
|
Helios/_DEV2/helios/modules/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (179 Bytes). View file
|
|
|
Helios/_DEV2/helios/modules/__pycache__/transformer_helios.cpython-312.pyc
ADDED
|
Binary file (92.3 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .attention_dispatch import attn_varlen_func, create_navit_attention_masks
|
| 2 |
+
from .fp32_rmsnorm import replace_rmsnorm_with_fp32
|
| 3 |
+
from .tiled_linear import replace_linear_with_tiled_linear
|
| 4 |
+
from .triton_norm import replace_all_norms_with_flash_norms
|
| 5 |
+
from .triton_rope import replace_rope_with_flash_rope
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (652 Bytes). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (564 Bytes). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/attention_dispatch.cpython-311.pyc
ADDED
|
Binary file (7.4 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/attention_dispatch.cpython-312.pyc
ADDED
|
Binary file (6.68 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/fp32_rmsnorm.cpython-311.pyc
ADDED
|
Binary file (2.67 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/fp32_rmsnorm.cpython-312.pyc
ADDED
|
Binary file (2.41 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/tiled_linear.cpython-311.pyc
ADDED
|
Binary file (20.1 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/tiled_linear.cpython-312.pyc
ADDED
|
Binary file (17.8 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/triton_norm.cpython-311.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/triton_norm.cpython-312.pyc
ADDED
|
Binary file (17.5 kB). View file
|
|
|
Helios/_DEV2/helios/modules/helios_kernels/__pycache__/triton_rope.cpython-311.pyc
ADDED
|
Binary file (24.2 kB). View file
|
|
|