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-main/example/toy_data/toy_filter.json +46 -0
- Helios-main/helios/dataset/__init__.py +0 -0
- Helios-main/helios/dataset/dataloader_dmd.py +531 -0
- Helios-main/helios/dataset/dataloader_history_latents_dist.py +685 -0
- Helios-main/helios/dataset/dataloader_mp4_dist.py +854 -0
- Helios-main/helios/pipelines/__init__.py +0 -0
- Helios-main/helios/pipelines/pipeline_output.py +20 -0
- Helios-main/helios/scheduler/__init__.py +0 -0
- Helios-main/helios/scheduler/scheduling_helios.py +1056 -0
- Helios-main/scripts/inference/experiment_interactive/README.md +3 -0
- Helios-main/scripts/inference/experiment_interactive/helios-base_t2v.sh +27 -0
- Helios-main/scripts/inference/experiment_interactive/helios-distilled_t2v.sh +26 -0
- Helios-main/scripts/inference/experiment_interactive/helios-mid_t2v.sh +28 -0
- Helios-main/scripts/inference/helios-base_i2v.sh +26 -0
- Helios-main/scripts/inference/helios-base_t2v.sh +23 -0
- Helios-main/scripts/inference/helios-base_v2v.sh +26 -0
- Helios-main/scripts/inference/helios-distilled_i2v.sh +27 -0
- Helios-main/scripts/inference/helios-distilled_t2v.sh +24 -0
- Helios-main/scripts/inference/helios-distilled_v2v.sh +27 -0
- Helios-main/scripts/inference/helios-mid_i2v.sh +28 -0
- Helios-main/scripts/inference/helios-mid_t2v.sh +25 -0
- Helios-main/scripts/inference/helios-mid_v2v.sh +28 -0
- Helios-main/scripts/training/README.md +37 -0
- Helios-main/scripts/training/compare_yaml.py +65 -0
- Helios-main/scripts/training/configs/correct.yaml +27 -0
- Helios-main/scripts/training/configs/stage_1_init.yaml +182 -0
- Helios-main/scripts/training/configs/stage_1_post.yaml +183 -0
- Helios-main/scripts/training/configs/stage_2_init.yaml +202 -0
- Helios-main/scripts/training/configs/stage_2_post.yaml +203 -0
- Helios-main/scripts/training/configs/stage_3_ode.yaml +229 -0
- Helios-main/scripts/training/configs/stage_3_post.yaml +300 -0
- Helios-main/scripts/training/configs/stage_3_post_gan_version.yaml +300 -0
- Helios-main/tools/gradio/comparison/gradio_compare_diff-ablation.py +536 -0
- Helios-main/tools/gradio/comparison/gradio_compare_diff-ckpt.py +547 -0
- Helios-main/tools/gradio/comparison/gradio_compare_diff-video.py +450 -0
- Helios-main/tools/offload_data/README.md +93 -0
- Helios-main/tools/offload_data/get_long-latents.py +329 -0
- Helios-main/tools/offload_data/get_long-latents.sh +64 -0
- Helios-main/tools/offload_data/get_ode-pairs.py +421 -0
- Helios-main/tools/offload_data/get_ode-pairs.sh +69 -0
- Helios-main/tools/offload_data/get_short-latents.py +341 -0
- Helios-main/tools/offload_data/get_short-latents.sh +64 -0
- Helios-main/tools/offload_data/get_text-embedding.py +256 -0
- Helios-main/tools/offload_data/get_text-embedding.sh +64 -0
- Helios-main/tools/others/benchmark/benchmark_compile_performance.py +234 -0
- Helios-main/tools/others/benchmark/benchmark_compile_results.txt +269 -0
- Helios-main/tools/others/benchmark/benchmark_patchification_performance.py +381 -0
- Helios-main/tools/others/benchmark/benchmark_patchification_results.json +309 -0
- Helios-main/tools/others/benchmark/benchmark_triton_performance.py +659 -0
- Helios-main/tools/others/benchmark/benchmark_triton_results_helios.json +111 -0
Helios-main/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 |
+
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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-main/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("实际采样统计:", dict(dataset_counts))
|
Helios-main/helios/dataset/dataloader_mp4_dist.py
ADDED
|
@@ -0,0 +1,854 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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-main/helios/pipelines/__init__.py
ADDED
|
File without changes
|
Helios-main/helios/pipelines/pipeline_output.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from diffusers.utils import BaseOutput
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class HeliosPipelineOutput(BaseOutput):
|
| 10 |
+
r"""
|
| 11 |
+
Output class for Helios pipelines.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]):
|
| 15 |
+
List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing
|
| 16 |
+
denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape
|
| 17 |
+
`(batch_size, num_frames, channels, height, width)`.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
frames: torch.Tensor
|
Helios-main/helios/scheduler/__init__.py
ADDED
|
File without changes
|
Helios-main/helios/scheduler/scheduling_helios.py
ADDED
|
@@ -0,0 +1,1056 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import List, Optional, Tuple, Union
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 9 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 10 |
+
from diffusers.utils import BaseOutput, deprecate
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class HeliosSchedulerOutput(BaseOutput):
|
| 15 |
+
"""
|
| 16 |
+
Output class for the scheduler's `step` function output.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
|
| 20 |
+
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
|
| 21 |
+
denoising loop.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
prev_sample: torch.FloatTensor
|
| 25 |
+
model_outputs: torch.FloatTensor
|
| 26 |
+
last_sample: torch.FloatTensor
|
| 27 |
+
this_order: int
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class HeliosScheduler(SchedulerMixin, ConfigMixin):
|
| 31 |
+
"""
|
| 32 |
+
Euler scheduler.
|
| 33 |
+
|
| 34 |
+
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
|
| 35 |
+
methods the library implements for all schedulers such as loading and saving.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
num_train_timesteps (`int`, defaults to 1000):
|
| 39 |
+
The number of diffusion steps to train the model.
|
| 40 |
+
timestep_spacing (`str`, defaults to `"linspace"`):
|
| 41 |
+
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
|
| 42 |
+
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
|
| 43 |
+
shift (`float`, defaults to 1.0):
|
| 44 |
+
The shift value for the timestep schedule.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
_compatibles = []
|
| 48 |
+
order = 1
|
| 49 |
+
|
| 50 |
+
@register_to_config
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
num_train_timesteps: int = 1000,
|
| 54 |
+
shift: float = 1.0, # Following Stable diffusion 3,
|
| 55 |
+
stages: int = 3,
|
| 56 |
+
stage_range: List = [0, 1 / 3, 2 / 3, 1],
|
| 57 |
+
gamma: float = 1 / 3,
|
| 58 |
+
# For UniPC
|
| 59 |
+
thresholding: bool = False,
|
| 60 |
+
prediction_type: str = "flow_prediction",
|
| 61 |
+
solver_order: int = 2,
|
| 62 |
+
predict_x0: bool = True,
|
| 63 |
+
solver_type: str = "bh2",
|
| 64 |
+
lower_order_final: bool = True,
|
| 65 |
+
disable_corrector: List[int] = [],
|
| 66 |
+
solver_p: SchedulerMixin = None,
|
| 67 |
+
use_flow_sigmas: bool = True,
|
| 68 |
+
version: str = "v1",
|
| 69 |
+
):
|
| 70 |
+
self.version = version
|
| 71 |
+
self.timestep_ratios = {} # The timestep ratio for each stage
|
| 72 |
+
self.timesteps_per_stage = {} # The detailed timesteps per stage (fix max and min per stage)
|
| 73 |
+
self.sigmas_per_stage = {} # always uniform [1000, 0]
|
| 74 |
+
self.start_sigmas = {} # for start point / upsample renoise
|
| 75 |
+
self.end_sigmas = {} # for end point
|
| 76 |
+
self.ori_start_sigmas = {}
|
| 77 |
+
|
| 78 |
+
# self.init_sigmas()
|
| 79 |
+
self.init_sigmas_for_each_stage()
|
| 80 |
+
self.sigma_min = self.sigmas[-1].item()
|
| 81 |
+
self.sigma_max = self.sigmas[0].item()
|
| 82 |
+
self.gamma = gamma
|
| 83 |
+
|
| 84 |
+
if solver_type not in ["bh1", "bh2"]:
|
| 85 |
+
if solver_type in ["midpoint", "heun", "logrho"]:
|
| 86 |
+
self.register_to_config(solver_type="bh2")
|
| 87 |
+
else:
|
| 88 |
+
raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
|
| 89 |
+
|
| 90 |
+
self.predict_x0 = predict_x0
|
| 91 |
+
self.model_outputs = [None] * solver_order
|
| 92 |
+
self.timestep_list = [None] * solver_order
|
| 93 |
+
self.lower_order_nums = 0
|
| 94 |
+
self.disable_corrector = disable_corrector
|
| 95 |
+
self.solver_p = solver_p
|
| 96 |
+
self.last_sample = None
|
| 97 |
+
self._step_index = None
|
| 98 |
+
self._begin_index = None
|
| 99 |
+
|
| 100 |
+
def init_sigmas(self):
|
| 101 |
+
"""
|
| 102 |
+
initialize the global timesteps and sigmas
|
| 103 |
+
"""
|
| 104 |
+
num_train_timesteps = self.config.num_train_timesteps
|
| 105 |
+
shift = self.config.shift
|
| 106 |
+
|
| 107 |
+
alphas = np.linspace(1, 1 / num_train_timesteps, num_train_timesteps + 1)
|
| 108 |
+
sigmas = 1.0 - alphas
|
| 109 |
+
sigmas = np.flip(shift * sigmas / (1 + (shift - 1) * sigmas))[:-1].copy()
|
| 110 |
+
sigmas = torch.from_numpy(sigmas)
|
| 111 |
+
timesteps = (sigmas * num_train_timesteps).clone()
|
| 112 |
+
|
| 113 |
+
self._step_index = None
|
| 114 |
+
self._begin_index = None
|
| 115 |
+
self.timesteps = timesteps
|
| 116 |
+
self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 117 |
+
|
| 118 |
+
def init_sigmas_for_each_stage(self):
|
| 119 |
+
"""
|
| 120 |
+
Init the timesteps for each stage
|
| 121 |
+
"""
|
| 122 |
+
self.init_sigmas()
|
| 123 |
+
|
| 124 |
+
stage_distance = []
|
| 125 |
+
stages = self.config.stages
|
| 126 |
+
training_steps = self.config.num_train_timesteps
|
| 127 |
+
stage_range = self.config.stage_range
|
| 128 |
+
|
| 129 |
+
# Init the start and end point of each stage
|
| 130 |
+
for i_s in range(stages):
|
| 131 |
+
# To decide the start and ends point
|
| 132 |
+
start_indice = int(stage_range[i_s] * training_steps)
|
| 133 |
+
start_indice = max(start_indice, 0)
|
| 134 |
+
end_indice = int(stage_range[i_s + 1] * training_steps)
|
| 135 |
+
end_indice = min(end_indice, training_steps)
|
| 136 |
+
start_sigma = self.sigmas[start_indice].item()
|
| 137 |
+
end_sigma = self.sigmas[end_indice].item() if end_indice < training_steps else 0.0
|
| 138 |
+
self.ori_start_sigmas[i_s] = start_sigma
|
| 139 |
+
|
| 140 |
+
if i_s != 0:
|
| 141 |
+
ori_sigma = 1 - start_sigma
|
| 142 |
+
gamma = self.config.gamma
|
| 143 |
+
corrected_sigma = (1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)) * ori_sigma
|
| 144 |
+
# corrected_sigma = 1 / (2 - ori_sigma) * ori_sigma
|
| 145 |
+
start_sigma = 1 - corrected_sigma
|
| 146 |
+
|
| 147 |
+
stage_distance.append(start_sigma - end_sigma)
|
| 148 |
+
self.start_sigmas[i_s] = start_sigma
|
| 149 |
+
self.end_sigmas[i_s] = end_sigma
|
| 150 |
+
|
| 151 |
+
if self.version == "v2":
|
| 152 |
+
new_start_indice = (
|
| 153 |
+
len(self.sigmas) - torch.searchsorted(self.sigmas.flip(0), start_sigma, right=True)
|
| 154 |
+
).item()
|
| 155 |
+
self.sigmas_per_stage[i_s] = self.sigmas[new_start_indice:end_indice]
|
| 156 |
+
self.timesteps_per_stage[i_s] = self.timesteps[new_start_indice:end_indice]
|
| 157 |
+
|
| 158 |
+
if self.version == "v2":
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
# Determine the ratio of each stage according to flow length
|
| 162 |
+
tot_distance = sum(stage_distance)
|
| 163 |
+
for i_s in range(stages):
|
| 164 |
+
if i_s == 0:
|
| 165 |
+
start_ratio = 0.0
|
| 166 |
+
else:
|
| 167 |
+
start_ratio = sum(stage_distance[:i_s]) / tot_distance
|
| 168 |
+
if i_s == stages - 1:
|
| 169 |
+
end_ratio = 0.9999999999999999
|
| 170 |
+
else:
|
| 171 |
+
end_ratio = sum(stage_distance[: i_s + 1]) / tot_distance
|
| 172 |
+
|
| 173 |
+
self.timestep_ratios[i_s] = (start_ratio, end_ratio)
|
| 174 |
+
|
| 175 |
+
# Determine the timesteps and sigmas for each stage
|
| 176 |
+
for i_s in range(stages):
|
| 177 |
+
timestep_ratio = self.timestep_ratios[i_s]
|
| 178 |
+
# timestep_max = self.timesteps[int(timestep_ratio[0] * training_steps)]
|
| 179 |
+
timestep_max = min(self.timesteps[int(timestep_ratio[0] * training_steps)], 999)
|
| 180 |
+
timestep_min = self.timesteps[min(int(timestep_ratio[1] * training_steps), training_steps - 1)]
|
| 181 |
+
timesteps = np.linspace(timestep_max, timestep_min, training_steps + 1)
|
| 182 |
+
self.timesteps_per_stage[i_s] = (
|
| 183 |
+
timesteps[:-1] if isinstance(timesteps, torch.Tensor) else torch.from_numpy(timesteps[:-1])
|
| 184 |
+
)
|
| 185 |
+
stage_sigmas = np.linspace(0.999, 0, training_steps + 1)
|
| 186 |
+
self.sigmas_per_stage[i_s] = torch.from_numpy(stage_sigmas[:-1])
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def step_index(self):
|
| 190 |
+
"""
|
| 191 |
+
The index counter for current timestep. It will increase 1 after each scheduler step.
|
| 192 |
+
"""
|
| 193 |
+
return self._step_index
|
| 194 |
+
|
| 195 |
+
@property
|
| 196 |
+
def begin_index(self):
|
| 197 |
+
"""
|
| 198 |
+
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
|
| 199 |
+
"""
|
| 200 |
+
return self._begin_index
|
| 201 |
+
|
| 202 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
|
| 203 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 204 |
+
"""
|
| 205 |
+
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
begin_index (`int`):
|
| 209 |
+
The begin index for the scheduler.
|
| 210 |
+
"""
|
| 211 |
+
self._begin_index = begin_index
|
| 212 |
+
|
| 213 |
+
def _sigma_to_t(self, sigma):
|
| 214 |
+
return sigma * self.config.num_train_timesteps
|
| 215 |
+
|
| 216 |
+
def set_timesteps(
|
| 217 |
+
self,
|
| 218 |
+
num_inference_steps: int,
|
| 219 |
+
stage_index: int,
|
| 220 |
+
device: Union[str, torch.device] = None,
|
| 221 |
+
):
|
| 222 |
+
"""
|
| 223 |
+
Setting the timesteps and sigmas for each stage
|
| 224 |
+
"""
|
| 225 |
+
self.num_inference_steps = num_inference_steps
|
| 226 |
+
self.init_sigmas()
|
| 227 |
+
|
| 228 |
+
if self.version == "v1":
|
| 229 |
+
stage_timesteps = self.timesteps_per_stage[stage_index]
|
| 230 |
+
timestep_max = stage_timesteps[0].item()
|
| 231 |
+
timestep_min = stage_timesteps[-1].item()
|
| 232 |
+
|
| 233 |
+
timesteps = np.linspace(
|
| 234 |
+
timestep_max,
|
| 235 |
+
timestep_min,
|
| 236 |
+
num_inference_steps,
|
| 237 |
+
)
|
| 238 |
+
self.timesteps = torch.from_numpy(timesteps).to(device=device)
|
| 239 |
+
|
| 240 |
+
stage_sigmas = self.sigmas_per_stage[stage_index]
|
| 241 |
+
sigma_max = stage_sigmas[0].item()
|
| 242 |
+
sigma_min = stage_sigmas[-1].item()
|
| 243 |
+
|
| 244 |
+
ratios = np.linspace(sigma_max, sigma_min, num_inference_steps)
|
| 245 |
+
sigmas = torch.from_numpy(ratios).to(device=device)
|
| 246 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 247 |
+
else:
|
| 248 |
+
total_steps = len(self.timesteps_per_stage[stage_index])
|
| 249 |
+
indices = np.linspace(0, total_steps - 1, num_inference_steps, dtype=int)
|
| 250 |
+
|
| 251 |
+
self.timesteps = self.timesteps_per_stage[stage_index][indices].to(device=device)
|
| 252 |
+
|
| 253 |
+
if stage_index == (self.config.stages - 1):
|
| 254 |
+
sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device)
|
| 255 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 256 |
+
else:
|
| 257 |
+
sigmas = self.sigmas_per_stage[stage_index][indices].to(device=device)
|
| 258 |
+
self.sigmas = torch.cat(
|
| 259 |
+
[sigmas, torch.tensor([self.ori_start_sigmas[stage_index + 1]], device=sigmas.device)]
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
self._step_index = None
|
| 263 |
+
self.reset_scheduler_history()
|
| 264 |
+
|
| 265 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 266 |
+
if schedule_timesteps is None:
|
| 267 |
+
schedule_timesteps = self.timesteps
|
| 268 |
+
|
| 269 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 270 |
+
|
| 271 |
+
# The sigma index that is taken for the **very** first `step`
|
| 272 |
+
# is always the second index (or the last index if there is only 1)
|
| 273 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 274 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 275 |
+
pos = 1 if len(indices) > 1 else 0
|
| 276 |
+
|
| 277 |
+
return indices[pos].item()
|
| 278 |
+
|
| 279 |
+
def _init_step_index(self, timestep):
|
| 280 |
+
if self.begin_index is None:
|
| 281 |
+
if isinstance(timestep, torch.Tensor):
|
| 282 |
+
timestep = timestep.to(self.timesteps.device)
|
| 283 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 284 |
+
else:
|
| 285 |
+
self._step_index = self._begin_index
|
| 286 |
+
|
| 287 |
+
def step(
|
| 288 |
+
self,
|
| 289 |
+
model_output: torch.FloatTensor,
|
| 290 |
+
timestep: Union[float, torch.FloatTensor] = None,
|
| 291 |
+
sample: torch.FloatTensor = None,
|
| 292 |
+
generator: Optional[torch.Generator] = None,
|
| 293 |
+
sigma: Optional[torch.FloatTensor] = None,
|
| 294 |
+
sigma_next: Optional[torch.FloatTensor] = None,
|
| 295 |
+
return_dict: bool = True,
|
| 296 |
+
) -> Union[HeliosSchedulerOutput, Tuple]:
|
| 297 |
+
"""
|
| 298 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
|
| 299 |
+
process from the learned model outputs (most often the predicted noise).
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
model_output (`torch.FloatTensor`):
|
| 303 |
+
The direct output from learned diffusion model.
|
| 304 |
+
timestep (`float`):
|
| 305 |
+
The current discrete timestep in the diffusion chain.
|
| 306 |
+
sample (`torch.FloatTensor`):
|
| 307 |
+
A current instance of a sample created by the diffusion process.
|
| 308 |
+
generator (`torch.Generator`, *optional*):
|
| 309 |
+
A random number generator.
|
| 310 |
+
return_dict (`bool`):
|
| 311 |
+
Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
|
| 312 |
+
tuple.
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
[`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
|
| 316 |
+
If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
|
| 317 |
+
returned, otherwise a tuple is returned where the first element is the sample tensor.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
assert (sigma is None) == (sigma_next is None), "sigma and sigma_next must both be None or both be not None"
|
| 321 |
+
|
| 322 |
+
if sigma is None and sigma_next is None:
|
| 323 |
+
if (
|
| 324 |
+
isinstance(timestep, int)
|
| 325 |
+
or isinstance(timestep, torch.IntTensor)
|
| 326 |
+
or isinstance(timestep, torch.LongTensor)
|
| 327 |
+
):
|
| 328 |
+
raise ValueError(
|
| 329 |
+
(
|
| 330 |
+
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
|
| 331 |
+
" `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
|
| 332 |
+
" one of the `scheduler.timesteps` as a timestep."
|
| 333 |
+
),
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
if self.step_index is None:
|
| 337 |
+
self._step_index = 0
|
| 338 |
+
|
| 339 |
+
# Upcast to avoid precision issues when computing prev_sample
|
| 340 |
+
sample = sample.to(torch.float32)
|
| 341 |
+
|
| 342 |
+
if sigma is None and sigma_next is None:
|
| 343 |
+
sigma = self.sigmas[self.step_index]
|
| 344 |
+
sigma_next = self.sigmas[self.step_index + 1]
|
| 345 |
+
|
| 346 |
+
prev_sample = sample + (sigma_next - sigma) * model_output
|
| 347 |
+
|
| 348 |
+
# Cast sample back to model compatible dtype
|
| 349 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 350 |
+
|
| 351 |
+
# upon completion increase step index by one
|
| 352 |
+
self._step_index += 1
|
| 353 |
+
|
| 354 |
+
if not return_dict:
|
| 355 |
+
return (prev_sample,)
|
| 356 |
+
|
| 357 |
+
return HeliosSchedulerOutput(prev_sample=prev_sample)
|
| 358 |
+
|
| 359 |
+
# ---------------------------------- UniPC ----------------------------------
|
| 360 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._sigma_to_alpha_sigma_t
|
| 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: Union[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 |
+
) -> Union[HeliosSchedulerOutput, Tuple]:
|
| 743 |
+
"""
|
| 744 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
|
| 745 |
+
the multistep UniPC.
|
| 746 |
+
|
| 747 |
+
Args:
|
| 748 |
+
model_output (`torch.Tensor`):
|
| 749 |
+
The direct output from learned diffusion model.
|
| 750 |
+
timestep (`int`):
|
| 751 |
+
The current discrete timestep in the diffusion chain.
|
| 752 |
+
sample (`torch.Tensor`):
|
| 753 |
+
A current instance of a sample created by the diffusion process.
|
| 754 |
+
return_dict (`bool`):
|
| 755 |
+
Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
|
| 756 |
+
|
| 757 |
+
Returns:
|
| 758 |
+
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
|
| 759 |
+
If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
|
| 760 |
+
tuple is returned where the first element is the sample tensor.
|
| 761 |
+
|
| 762 |
+
"""
|
| 763 |
+
# don't change
|
| 764 |
+
# print(len(self.model_outputs), len(self.timestep_list), self.disable_corrector, self.solver_p, self._begin_index)
|
| 765 |
+
|
| 766 |
+
if self.num_inference_steps is None:
|
| 767 |
+
raise ValueError(
|
| 768 |
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
if cus_step_index is None:
|
| 772 |
+
if self.step_index is None:
|
| 773 |
+
self._step_index = 0
|
| 774 |
+
else:
|
| 775 |
+
self._step_index = cus_step_index
|
| 776 |
+
|
| 777 |
+
if cus_lower_order_num is not None:
|
| 778 |
+
self.lower_order_nums = cus_lower_order_num
|
| 779 |
+
|
| 780 |
+
if cus_this_order is not None:
|
| 781 |
+
self.this_order = cus_this_order
|
| 782 |
+
|
| 783 |
+
if cus_last_sample is not None:
|
| 784 |
+
self.last_sample = cus_last_sample
|
| 785 |
+
|
| 786 |
+
use_corrector = (
|
| 787 |
+
self.step_index > 0 and self.step_index - 1 not in self.disable_corrector and self.last_sample is not None
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
# Convert model output using the proper conversion method
|
| 791 |
+
model_output_convert = self.convert_model_output(model_output, sample=sample, sigma=sigma)
|
| 792 |
+
|
| 793 |
+
if model_outputs is not None and timestep_list is not None:
|
| 794 |
+
self.model_outputs = model_outputs[:-1]
|
| 795 |
+
self.timestep_list = timestep_list[:-1]
|
| 796 |
+
|
| 797 |
+
# print("1", self.step_index, self.timestep_list)
|
| 798 |
+
|
| 799 |
+
if use_corrector:
|
| 800 |
+
sample = self.multistep_uni_c_bh_update(
|
| 801 |
+
this_model_output=model_output_convert,
|
| 802 |
+
last_sample=self.last_sample,
|
| 803 |
+
this_sample=sample,
|
| 804 |
+
order=self.this_order,
|
| 805 |
+
sigma_before=sigma_before,
|
| 806 |
+
sigma=sigma,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
if model_outputs is not None and timestep_list is not None:
|
| 810 |
+
model_outputs[-1] = model_output_convert
|
| 811 |
+
self.model_outputs = model_outputs[1:]
|
| 812 |
+
self.timestep_list = timestep_list[1:]
|
| 813 |
+
else:
|
| 814 |
+
for i in range(self.config.solver_order - 1):
|
| 815 |
+
self.model_outputs[i] = self.model_outputs[i + 1]
|
| 816 |
+
self.timestep_list[i] = self.timestep_list[i + 1]
|
| 817 |
+
self.model_outputs[-1] = model_output_convert
|
| 818 |
+
self.timestep_list[-1] = timestep
|
| 819 |
+
|
| 820 |
+
if self.config.lower_order_final:
|
| 821 |
+
this_order = min(self.config.solver_order, len(self.timesteps) - self.step_index)
|
| 822 |
+
else:
|
| 823 |
+
this_order = self.config.solver_order
|
| 824 |
+
self.this_order = min(this_order, self.lower_order_nums + 1) # warmup for multistep
|
| 825 |
+
assert self.this_order > 0
|
| 826 |
+
|
| 827 |
+
# change
|
| 828 |
+
# print("2", self.step_index, self.timestep_list, self.lower_order_nums, self.this_order, "\n")
|
| 829 |
+
# print(self._step_index, self.lower_order_nums, use_corrector, self.this_order, self.lower_order_nums)
|
| 830 |
+
# 0 1 False 1 1
|
| 831 |
+
# 1 2 True 2 2
|
| 832 |
+
# 2 2 True 2 2
|
| 833 |
+
# 3 2 True 2 2
|
| 834 |
+
# 4 2 True 2 2
|
| 835 |
+
# 5 2 True 2 2
|
| 836 |
+
# 6 2 True 2 2
|
| 837 |
+
# 7 2 True 2 2
|
| 838 |
+
# 8 2 True 2 2
|
| 839 |
+
# 9 2 True 1 2
|
| 840 |
+
|
| 841 |
+
self.last_sample = sample
|
| 842 |
+
prev_sample = self.multistep_uni_p_bh_update(
|
| 843 |
+
model_output=model_output, # pass the original non-converted model output, in case solver-p is used
|
| 844 |
+
sample=sample,
|
| 845 |
+
order=self.this_order,
|
| 846 |
+
sigma=sigma,
|
| 847 |
+
sigma_next=sigma_next,
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
if cus_lower_order_num is None:
|
| 851 |
+
if self.lower_order_nums < self.config.solver_order:
|
| 852 |
+
self.lower_order_nums += 1
|
| 853 |
+
|
| 854 |
+
# upon completion increase step index by one
|
| 855 |
+
if cus_step_index is None:
|
| 856 |
+
self._step_index += 1
|
| 857 |
+
|
| 858 |
+
if not return_dict:
|
| 859 |
+
return (prev_sample, model_outputs, self.last_sample, self.this_order)
|
| 860 |
+
|
| 861 |
+
return HeliosSchedulerOutput(
|
| 862 |
+
prev_sample=prev_sample,
|
| 863 |
+
model_outputs=model_outputs,
|
| 864 |
+
last_sample=self.last_sample,
|
| 865 |
+
this_order=self.this_order,
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
def reset_scheduler_history(self):
|
| 869 |
+
self.model_outputs = [None] * self.config.solver_order
|
| 870 |
+
self.timestep_list = [None] * self.config.solver_order
|
| 871 |
+
self.lower_order_nums = 0
|
| 872 |
+
self.disable_corrector = self.config.disable_corrector
|
| 873 |
+
self.solver_p = self.config.solver_p
|
| 874 |
+
self.last_sample = None
|
| 875 |
+
self._step_index = None
|
| 876 |
+
self._begin_index = None
|
| 877 |
+
|
| 878 |
+
def __len__(self):
|
| 879 |
+
return self.config.num_train_timesteps
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
if __name__ == "__main__":
|
| 883 |
+
device = "cuda"
|
| 884 |
+
|
| 885 |
+
# ---------------------- For dynamic shifting ----------------------
|
| 886 |
+
from examples.scheduling_unipc_multistep_latest import UniPCMultistepScheduler
|
| 887 |
+
|
| 888 |
+
scheduler_official = UniPCMultistepScheduler.from_pretrained("BestWishYsh/Helios-Base", subfolder="scheduler")
|
| 889 |
+
scheduler_official.set_timesteps(num_inference_steps=50)
|
| 890 |
+
scheduler_official.timesteps
|
| 891 |
+
scheduler_official.sigmas
|
| 892 |
+
|
| 893 |
+
# # Official
|
| 894 |
+
# from scheduling_flow_match_euler_discrete_official import FlowMatchEulerDiscreteScheduler
|
| 895 |
+
# scheduler_official = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000, shift=3.0)
|
| 896 |
+
# scheduler_official.set_timesteps(num_inference_steps=50, sigmas=None)
|
| 897 |
+
# scheduler_official.timesteps
|
| 898 |
+
# scheduler_official.sigmas
|
| 899 |
+
|
| 900 |
+
# import sys
|
| 901 |
+
# sys.path.append("../../")
|
| 902 |
+
# from helios.utils.utils_helios_base import apply_schedule_shift
|
| 903 |
+
|
| 904 |
+
# sigmas = apply_schedule_shift(scheduler_official.sigmas, torch.ones([2, 16, 21, 48, 80]), mu=3)
|
| 905 |
+
# timesteps = sigmas[:-1] * 1000.0
|
| 906 |
+
|
| 907 |
+
# import copy
|
| 908 |
+
# from diffusers.training_utils import compute_density_for_timestep_sampling
|
| 909 |
+
|
| 910 |
+
# def get_sigmas(timesteps, n_dim=4, device="cpu", dtype=torch.float32):
|
| 911 |
+
# sigmas = noise_scheduler_copy.sigmas.to(device=device, dtype=dtype)
|
| 912 |
+
# schedule_timesteps = noise_scheduler_copy.timesteps.to(device)
|
| 913 |
+
# timesteps = timesteps.to(device)
|
| 914 |
+
# step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 915 |
+
# sigma = sigmas[step_indices].flatten()
|
| 916 |
+
# while len(sigma.shape) < n_dim:
|
| 917 |
+
# sigma = sigma.unsqueeze(-1)
|
| 918 |
+
# return sigma
|
| 919 |
+
|
| 920 |
+
# noise_scheduler_copy = copy.deepcopy(scheduler_official)
|
| 921 |
+
|
| 922 |
+
# # Sample noise that we'll add to the latents
|
| 923 |
+
# model_input = torch.ones([2, 16, 9, 88, 68])
|
| 924 |
+
# noise = torch.randn_like(model_input)
|
| 925 |
+
# bsz = model_input.shape[0]
|
| 926 |
+
|
| 927 |
+
# # Sample a random timestep for each image
|
| 928 |
+
# # for weighting schemes where we sample timesteps non-uniformly
|
| 929 |
+
# u = compute_density_for_timestep_sampling(
|
| 930 |
+
# weighting_scheme="logit_normal", batch_size=bsz, logit_mean=0.0, logit_std=1.0, mode_scale=1.29
|
| 931 |
+
# )
|
| 932 |
+
# indices = (u * noise_scheduler_copy.config.num_train_timesteps).long()
|
| 933 |
+
# timesteps = noise_scheduler_copy.timesteps[indices].to(device=model_input.device)
|
| 934 |
+
|
| 935 |
+
# # Add noise according to flow matching.
|
| 936 |
+
# # zt = (1 - texp) * x + texp * z1
|
| 937 |
+
# sigmas = get_sigmas(timesteps, n_dim=model_input.ndim, dtype=model_input.dtype)
|
| 938 |
+
|
| 939 |
+
# import sys
|
| 940 |
+
# sys.path.append("../../")
|
| 941 |
+
# from helios.utils.utils_helios_base import apply_schedule_shift
|
| 942 |
+
|
| 943 |
+
# sigmas = apply_schedule_shift(sigmas, noise) # torch.Size([2, 1, 1, 1, 1])
|
| 944 |
+
# timesteps = sigmas * 1000.0 # rescale to [0, 1000.0)
|
| 945 |
+
# while timesteps.ndim > 1:
|
| 946 |
+
# timesteps = timesteps.squeeze(-1)
|
| 947 |
+
# ---------------------- For dynamic shifting ----------------------
|
| 948 |
+
|
| 949 |
+
# ---------------------- For timestep shifting ----------------------
|
| 950 |
+
stages = 3
|
| 951 |
+
timestep_shift = 1.0
|
| 952 |
+
stage_range = [0, 1 / 3, 2 / 3, 1]
|
| 953 |
+
scheduler_gamma = 1 / 3
|
| 954 |
+
version = "v1"
|
| 955 |
+
scheduler = HeliosScheduler(
|
| 956 |
+
shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version
|
| 957 |
+
)
|
| 958 |
+
print(
|
| 959 |
+
f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}"
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
i_s = 1
|
| 963 |
+
stage2_num_inference_steps_list = [3, 3, 3]
|
| 964 |
+
scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s)
|
| 965 |
+
scheduler.timesteps.to(dtype=torch.float32)
|
| 966 |
+
scheduler.sigmas.to(dtype=torch.float32)
|
| 967 |
+
|
| 968 |
+
# stages = 2
|
| 969 |
+
# timestep_shift = 3.0
|
| 970 |
+
# stage_range = [0, 1 / 2, 1]
|
| 971 |
+
# scheduler_gamma = 1 / 3
|
| 972 |
+
# version = "v2"
|
| 973 |
+
# scheduler = HeliosScheduler(
|
| 974 |
+
# shift=timestep_shift, stages=stages, stage_range=stage_range, gamma=scheduler_gamma, version=version
|
| 975 |
+
# )
|
| 976 |
+
# print(
|
| 977 |
+
# f"The start sigmas and end sigmas of each stage is Start: {scheduler.start_sigmas}, End: {scheduler.end_sigmas}, Ori_start: {scheduler.ori_start_sigmas}"
|
| 978 |
+
# )
|
| 979 |
+
|
| 980 |
+
# i_s = 1
|
| 981 |
+
# stage2_num_inference_steps_list = [10, 10]
|
| 982 |
+
# scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s)
|
| 983 |
+
# scheduler.timesteps.to(dtype=torch.float32)
|
| 984 |
+
# scheduler.sigmas.to(dtype=torch.float32)
|
| 985 |
+
|
| 986 |
+
# scheduler.timesteps_per_stage[0]
|
| 987 |
+
# scheduler.sigmas_per_stage[0]
|
| 988 |
+
# shift1: (999, 743.5120) -> (743.2563, 385.9723) -> (385.6146, 1.3846)
|
| 989 |
+
# shift3: (999, 957.3958) -> (957.3542, 828.9170) -> (828.7885, 3.8198)
|
| 990 |
+
|
| 991 |
+
# timesteps_1 = np.linspace(1, 1000 - 1, 1000, dtype=np.float32)[::-1].copy()
|
| 992 |
+
# timesteps_1 = torch.from_numpy(timesteps_1).to(dtype=torch.float32)
|
| 993 |
+
# sigmas_1 = timesteps_1 / 1000
|
| 994 |
+
# sigmas_1 = apply_schedule_shift(sigmas_1, torch.ones([2, 16, 21, 48, 80]), mu=3)
|
| 995 |
+
# timesteps_2 = sigmas_1 * 1000
|
| 996 |
+
|
| 997 |
+
# import pdb;pdb.set_trace()
|
| 998 |
+
# temp_sigmas = apply_schedule_shift(scheduler.timesteps / 1000, torch.ones([2, 16, 21, 48, 80]), mu=3)
|
| 999 |
+
# temp_timesteps = temp_sigmas * 1000
|
| 1000 |
+
# while temp_timesteps.ndim > 1:
|
| 1001 |
+
# temp_timesteps = temp_timesteps.squeeze(-1)
|
| 1002 |
+
# temp_timesteps = temp_timesteps[:-1]
|
| 1003 |
+
|
| 1004 |
+
# # very important here!
|
| 1005 |
+
# timesteps = temp_timesteps
|
| 1006 |
+
# # self.scheduler.sigmas = temp_sigmas
|
| 1007 |
+
# scheduler.timesteps = temp_timesteps
|
| 1008 |
+
|
| 1009 |
+
# ---------------------- For timestep shifting ----------------------
|
| 1010 |
+
|
| 1011 |
+
# ---------------------- For dynamic shifting ----------------------
|
| 1012 |
+
|
| 1013 |
+
# ---------------------- For per step sigmas & timesteps ----------------------
|
| 1014 |
+
# scheduler = HeliosScheduler(shift=3.0, stages=stages, stage_range=stage_range, gamma=scheduler_gamma)
|
| 1015 |
+
# stage2_num_inference_steps_list = [10, 10, 10]
|
| 1016 |
+
# i_s = 0
|
| 1017 |
+
# scheduler.set_timesteps(stage2_num_inference_steps_list[i_s], i_s)
|
| 1018 |
+
# scheduler.timesteps_per_stage[0]
|
| 1019 |
+
# scheduler.sigmas_per_stage[0]
|
| 1020 |
+
# scheduler.timesteps
|
| 1021 |
+
# scheduler.sigmas
|
| 1022 |
+
# ---------------------- For per step sigmas & timesteps ----------------------
|
| 1023 |
+
|
| 1024 |
+
# ---------------------- For Custom step ----------------------
|
| 1025 |
+
# timesteps = scheduler.timesteps
|
| 1026 |
+
# noise_pred = torch.randn([2, 16, 10, 48, 80], device=device)
|
| 1027 |
+
# latents = torch.randn([2, 16, 10, 48, 80], device=device)
|
| 1028 |
+
# for i, t in enumerate(timesteps):
|
| 1029 |
+
# print(i, t)
|
| 1030 |
+
# # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 1031 |
+
# latents = scheduler.step_custom_unipc(noise_pred, t, latents, return_dict=False)[0]
|
| 1032 |
+
|
| 1033 |
+
# def upsample_tensor(tensor, scale_factor=2):
|
| 1034 |
+
# return torch.nn.functional.interpolate(
|
| 1035 |
+
# tensor, scale_factor=scale_factor, mode="trilinear", align_corners=False
|
| 1036 |
+
# )
|
| 1037 |
+
|
| 1038 |
+
# stage2_num_inference_steps_list = [10, 10, 10]
|
| 1039 |
+
# noise_pred = torch.randn([2, 16, 10, 12, 20], device=device)
|
| 1040 |
+
# latents = torch.randn([2, 16, 10, 12, 20], device=device)
|
| 1041 |
+
# for stage, num_steps in enumerate(stage2_num_inference_steps_list):
|
| 1042 |
+
# print(f"stage: {stage}, num_steps: {num_steps}")
|
| 1043 |
+
# if stage > 0:
|
| 1044 |
+
# latents = upsample_tensor(latents, scale_factor=2)
|
| 1045 |
+
# noise_pred = upsample_tensor(noise_pred, scale_factor=2)
|
| 1046 |
+
|
| 1047 |
+
# scheduler.set_timesteps(num_steps, stage)
|
| 1048 |
+
# timesteps = scheduler.timesteps
|
| 1049 |
+
|
| 1050 |
+
# print(f"Timesteps for stage {stage + 1}: {timesteps}")
|
| 1051 |
+
|
| 1052 |
+
# for i, t in enumerate(timesteps):
|
| 1053 |
+
# # print(i, t, latents.shape)
|
| 1054 |
+
# # latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 1055 |
+
# latents = scheduler.step_unipc(noise_pred, t, latents, return_dict=False)[0]
|
| 1056 |
+
# ---------------------- For Custom step ----------------------
|
Helios-main/scripts/inference/experiment_interactive/README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# <u>Interactive Pipeline</u> by *Helios*
|
| 2 |
+
|
| 3 |
+
⚠️ This feature is still under development — results may not always meet expectations.
|
Helios-main/scripts/inference/experiment_interactive/helios-base_t2v.sh
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Base" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Base" \
|
| 9 |
+
--sample_type "t2v" \
|
| 10 |
+
--num_frames 1452 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--prompt "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." \
|
| 13 |
+
--guidance_scale 5.0 \
|
| 14 |
+
--enable_compile \
|
| 15 |
+
--use_interpolate_prompt \
|
| 16 |
+
--interpolation_steps 3 \
|
| 17 |
+
--interactive_prompt_csv_path "example/prompt_interactive_helios.csv" \
|
| 18 |
+
--interpolate_time 7 \
|
| 19 |
+
--output_folder "./output_helios/helios-base"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# --enable_low_vram_mode \
|
| 23 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 24 |
+
# --num_blocks_per_group
|
| 25 |
+
# --use_cfg_zero_star \
|
| 26 |
+
# --use_zero_init \
|
| 27 |
+
# --zero_steps 1 \
|
Helios-main/scripts/inference/experiment_interactive/helios-distilled_t2v.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Distilled" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Distilled" \
|
| 9 |
+
--sample_type "t2v" \
|
| 10 |
+
--prompt "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." \
|
| 11 |
+
--num_frames 1452 \
|
| 12 |
+
--guidance_scale 1.0 \
|
| 13 |
+
--is_enable_stage2 \
|
| 14 |
+
--pyramid_num_inference_steps_list 2 2 2 \
|
| 15 |
+
--is_amplify_first_chunk \
|
| 16 |
+
--enable_compile \
|
| 17 |
+
--interpolation_steps 3 \
|
| 18 |
+
--interactive_prompt_csv_path "example/prompt_interactive_helios.csv" \
|
| 19 |
+
--interpolate_time 7 \
|
| 20 |
+
--output_folder "./output_helios/helios-distilled"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# --enable_low_vram_mode \
|
| 24 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 25 |
+
# --num_blocks_per_group
|
| 26 |
+
# --pyramid_num_inference_steps_list 1 1 1 \
|
Helios-main/scripts/inference/experiment_interactive/helios-mid_t2v.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Mid" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Mid" \
|
| 9 |
+
--sample_type "t2v" \
|
| 10 |
+
--num_frames 1452 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--prompt "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." \
|
| 13 |
+
--guidance_scale 5.0 \
|
| 14 |
+
--is_enable_stage2 \
|
| 15 |
+
--pyramid_num_inference_steps_list 20 20 20 \
|
| 16 |
+
--use_zero_init \
|
| 17 |
+
--zero_steps 1 \
|
| 18 |
+
--enable_compile \
|
| 19 |
+
--interpolation_steps 3 \
|
| 20 |
+
--interactive_prompt_csv_path "example/prompt_interactive_helios.csv" \
|
| 21 |
+
--interpolate_time 7 \
|
| 22 |
+
--output_folder "./output_helios/helios-mid"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# --enable_low_vram_mode \
|
| 26 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 27 |
+
# --num_blocks_per_group
|
| 28 |
+
# --pyramid_num_inference_steps_list 17 17 17 \
|
Helios-main/scripts/inference/helios-base_i2v.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Base" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Base" \
|
| 9 |
+
--sample_type "i2v" \
|
| 10 |
+
--num_frames 99 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--image_path "example/wave.jpg" \
|
| 13 |
+
--image_noise_sigma_min 0.111 \
|
| 14 |
+
--image_noise_sigma_max 0.135 \
|
| 15 |
+
--prompt "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might." \
|
| 16 |
+
--guidance_scale 5.0 \
|
| 17 |
+
--enable_compile \
|
| 18 |
+
--output_folder "./output_helios/helios-base"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# --enable_low_vram_mode \
|
| 22 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 23 |
+
# --num_blocks_per_group
|
| 24 |
+
# --use_cfg_zero_star \
|
| 25 |
+
# --use_zero_init \
|
| 26 |
+
# --zero_steps 1 \
|
Helios-main/scripts/inference/helios-base_t2v.sh
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Base" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Base" \
|
| 9 |
+
--sample_type "t2v" \
|
| 10 |
+
--num_frames 99 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--prompt "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." \
|
| 13 |
+
--guidance_scale 5.0 \
|
| 14 |
+
--enable_compile \
|
| 15 |
+
--output_folder "./output_helios/helios-base"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# --enable_low_vram_mode \
|
| 19 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 20 |
+
# --num_blocks_per_group
|
| 21 |
+
# --use_cfg_zero_star \
|
| 22 |
+
# --use_zero_init \
|
| 23 |
+
# --zero_steps 1 \
|
Helios-main/scripts/inference/helios-base_v2v.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Base" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Base" \
|
| 9 |
+
--sample_type "v2v" \
|
| 10 |
+
--num_frames 99 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--video_path "example/car.mp4" \
|
| 13 |
+
--video_noise_sigma_min 0.111 \
|
| 14 |
+
--video_noise_sigma_max 0.135 \
|
| 15 |
+
--prompt "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery." \
|
| 16 |
+
--guidance_scale 5.0 \
|
| 17 |
+
--enable_compile \
|
| 18 |
+
--output_folder "./output_helios/helios-base"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# --enable_low_vram_mode \
|
| 22 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 23 |
+
# --num_blocks_per_group
|
| 24 |
+
# --use_cfg_zero_star \
|
| 25 |
+
# --use_zero_init \
|
| 26 |
+
# --zero_steps 1 \
|
Helios-main/scripts/inference/helios-distilled_i2v.sh
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Distilled" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Distilled" \
|
| 9 |
+
--sample_type "i2v" \
|
| 10 |
+
--num_frames 240 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--image_path "example/wave.jpg" \
|
| 13 |
+
--image_noise_sigma_min 0.111 \
|
| 14 |
+
--image_noise_sigma_max 0.135 \
|
| 15 |
+
--prompt "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might." \
|
| 16 |
+
--guidance_scale 1.0 \
|
| 17 |
+
--is_enable_stage2 \
|
| 18 |
+
--pyramid_num_inference_steps_list 2 2 2 \
|
| 19 |
+
--is_amplify_first_chunk \
|
| 20 |
+
--enable_compile \
|
| 21 |
+
--output_folder "./output_helios/helios-distilled"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# --enable_low_vram_mode \
|
| 25 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 26 |
+
# --num_blocks_per_group
|
| 27 |
+
# --pyramid_num_inference_steps_list 1 1 1 \
|
Helios-main/scripts/inference/helios-distilled_t2v.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Distilled" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Distilled" \
|
| 9 |
+
--sample_type "t2v" \
|
| 10 |
+
--num_frames 240 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--prompt "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." \
|
| 13 |
+
--guidance_scale 1.0 \
|
| 14 |
+
--is_enable_stage2 \
|
| 15 |
+
--pyramid_num_inference_steps_list 2 2 2 \
|
| 16 |
+
--is_amplify_first_chunk \
|
| 17 |
+
--enable_compile \
|
| 18 |
+
--output_folder "./output_helios/helios-distilled"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# --enable_low_vram_mode \
|
| 22 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 23 |
+
# --num_blocks_per_group
|
| 24 |
+
# --pyramid_num_inference_steps_list 1 1 1 \
|
Helios-main/scripts/inference/helios-distilled_v2v.sh
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Distilled" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Distilled" \
|
| 9 |
+
--sample_type "v2v" \
|
| 10 |
+
--num_frames 240 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--video_path "example/car.mp4" \
|
| 13 |
+
--video_noise_sigma_min 0.111 \
|
| 14 |
+
--video_noise_sigma_max 0.135 \
|
| 15 |
+
--prompt "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery." \
|
| 16 |
+
--guidance_scale 1.0 \
|
| 17 |
+
--is_enable_stage2 \
|
| 18 |
+
--pyramid_num_inference_steps_list 2 2 2 \
|
| 19 |
+
--is_amplify_first_chunk \
|
| 20 |
+
--enable_compile \
|
| 21 |
+
--output_folder "./output_helios/helios-distilled"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# --enable_low_vram_mode \
|
| 25 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 26 |
+
# --num_blocks_per_group
|
| 27 |
+
# --pyramid_num_inference_steps_list 1 1 1 \
|
Helios-main/scripts/inference/helios-mid_i2v.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Mid" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Mid" \
|
| 9 |
+
--sample_type "i2v" \
|
| 10 |
+
--num_frames 99 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--image_path "example/wave.jpg" \
|
| 13 |
+
--image_noise_sigma_min 0.111 \
|
| 14 |
+
--image_noise_sigma_max 0.135 \
|
| 15 |
+
--prompt "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might." \
|
| 16 |
+
--guidance_scale 5.0 \
|
| 17 |
+
--is_enable_stage2 \
|
| 18 |
+
--pyramid_num_inference_steps_list 20 20 20 \
|
| 19 |
+
--use_zero_init \
|
| 20 |
+
--zero_steps 1 \
|
| 21 |
+
--enable_compile \
|
| 22 |
+
--output_folder "./output_helios/helios-mid"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# --enable_low_vram_mode \
|
| 26 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 27 |
+
# --num_blocks_per_group
|
| 28 |
+
# --pyramid_num_inference_steps_list 17 17 17 \
|
Helios-main/scripts/inference/helios-mid_t2v.sh
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Mid" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Mid" \
|
| 9 |
+
--sample_type "t2v" \
|
| 10 |
+
--num_frames 99 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--prompt "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." \
|
| 13 |
+
--guidance_scale 5.0 \
|
| 14 |
+
--is_enable_stage2 \
|
| 15 |
+
--pyramid_num_inference_steps_list 20 20 20 \
|
| 16 |
+
--use_zero_init \
|
| 17 |
+
--zero_steps 1 \
|
| 18 |
+
--enable_compile \
|
| 19 |
+
--output_folder "./output_helios/helios-mid"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# --enable_low_vram_mode \
|
| 23 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 24 |
+
# --num_blocks_per_group
|
| 25 |
+
# --pyramid_num_inference_steps_list 17 17 17 \
|
Helios-main/scripts/inference/helios-mid_v2v.sh
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example: Running inference with 2-GPU parallelism
|
| 2 |
+
# CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node 2 infer_helios.py \
|
| 3 |
+
# --enable_parallelism \
|
| 4 |
+
# --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
|
| 5 |
+
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
|
| 7 |
+
--base_model_path "BestWishYsh/Helios-Mid" \
|
| 8 |
+
--transformer_path "BestWishYsh/Helios-Mid" \
|
| 9 |
+
--sample_type "v2v" \
|
| 10 |
+
--num_frames 99 \
|
| 11 |
+
--fps 24 \
|
| 12 |
+
--video_path "example/car.mp4" \
|
| 13 |
+
--video_noise_sigma_min 0.111 \
|
| 14 |
+
--video_noise_sigma_max 0.135 \
|
| 15 |
+
--prompt "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery." \
|
| 16 |
+
--guidance_scale 5.0 \
|
| 17 |
+
--is_enable_stage2 \
|
| 18 |
+
--pyramid_num_inference_steps_list 20 20 20 \
|
| 19 |
+
--use_zero_init \
|
| 20 |
+
--zero_steps 1 \
|
| 21 |
+
--enable_compile \
|
| 22 |
+
--output_folder "./output_helios/helios-mid"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# --enable_low_vram_mode \
|
| 26 |
+
# --group_offloading_type "leaf_level" \ # ["leaf_level", "block_level"]
|
| 27 |
+
# --num_blocks_per_group
|
| 28 |
+
# --pyramid_num_inference_steps_list 17 17 17 \
|
Helios-main/scripts/training/README.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# <u>Training Details</u> by *Helios*
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
## 🎉 Overview
|
| 5 |
+
|
| 6 |
+
We use a three-stage progressive pipeline, all the setting can be found [here](./configs). Stage-1 (Base) performs architectural adaptation: we apply Unified History Injection, Easy Anti-Drifting, and Multi-Term Memory Patchification to convert the bidirectional pretrained model into an autoregressive generator. Stage-2 (Mid) targets token compression by introducing Pyramid Unified Predictor Corrector, which aggressively reduces the number of noisy tokens and thus the overall computation. Stage-3 (Distilled) applies Adversarial Hierarchical Distillation, reducing the sampling steps from 50 to 3 and eliminating the need for classifier-free guidance (CFG). Throughout training, we apply dynamic shifting to all timestep-dependent operations to match the noise schedule to the latent size. For Stages 1 and 2, training is further divided into two phases: a high learning-rate phase for rapid convergence, followed by a low learning-rate phase for refinement.
|
| 7 |
+
|
| 8 |
+
<div align=center>
|
| 9 |
+
<img src="https://raw.githubusercontent.com/PKU-YuanGroup/Helios-Page/main/figures/training_configs.png">
|
| 10 |
+
</div>
|
| 11 |
+
|
| 12 |
+
### Data Preparation
|
| 13 |
+
|
| 14 |
+
Please refer to [this guide](../..//tools/offload_data/README.md) for how to obtain the training data required by Helios. And we prepare a toy training data [here](https://huggingface.co/BestWishYsh/HeliosBench-Weights/tree/main/demo_data).
|
| 15 |
+
|
| 16 |
+
### Run the model
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
# Use DDP
|
| 20 |
+
bash scripts/training/train_ddp.sh
|
| 21 |
+
|
| 22 |
+
# or
|
| 23 |
+
|
| 24 |
+
# Use DeepSpeed
|
| 25 |
+
bash scripts/training/train_deepspeed.sh
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Training configuration can be adjusted in `./configs`. You can use `./compare_yaml.py` to check for configuration completeness or differences between stages.
|
| 29 |
+
|
| 30 |
+
### Model Merging
|
| 31 |
+
|
| 32 |
+
After training, you can use this [script](../..//tools/merge_lora_for_helios.py) to merge all the checkpoints and obtain the final safetensors file, similar to [this](https://huggingface.co/BestWishYsh/Helios-Distilled/tree/main/transformer).
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
## 💡 Important
|
| 36 |
+
|
| 37 |
+
Based on the findings in [issue #38](https://github.com/PKU-YuanGroup/Helios/issues/38), we have identified several areas with potential for further improving Helios's performance. These include fixing the train-inference inconsistency in i2v to address the issue where i2v tends to produce very slow motion at the beginning, as well as fully enabling Easy Anti-Drifting to enhance Helios's resistance to quality degradation over time. For the relevant configuration details, please refer to [correct.yaml](./configs/correct.yaml).
|
Helios-main/scripts/training/compare_yaml.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yaml
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def compare_yaml(file1_path, file2_path):
|
| 5 |
+
with open(file1_path, "r") as f1:
|
| 6 |
+
yaml1 = yaml.safe_load(f1)
|
| 7 |
+
|
| 8 |
+
with open(file2_path, "r") as f2:
|
| 9 |
+
yaml2 = yaml.safe_load(f2)
|
| 10 |
+
|
| 11 |
+
missing_keys = []
|
| 12 |
+
different_values = []
|
| 13 |
+
|
| 14 |
+
compare_dict(yaml1, yaml2, "", missing_keys, different_values)
|
| 15 |
+
|
| 16 |
+
print("=" * 60)
|
| 17 |
+
print("Missing Keys")
|
| 18 |
+
print("=" * 60)
|
| 19 |
+
if missing_keys:
|
| 20 |
+
for diff in missing_keys:
|
| 21 |
+
print(diff)
|
| 22 |
+
else:
|
| 23 |
+
print("None")
|
| 24 |
+
|
| 25 |
+
print("\n" + "=" * 60)
|
| 26 |
+
print("Different Values")
|
| 27 |
+
print("=" * 60)
|
| 28 |
+
if different_values:
|
| 29 |
+
for diff in different_values:
|
| 30 |
+
print(diff)
|
| 31 |
+
else:
|
| 32 |
+
print("None")
|
| 33 |
+
|
| 34 |
+
print("\n" + "=" * 60)
|
| 35 |
+
print(f"Total: {len(missing_keys)} missing keys, {len(different_values)} different values")
|
| 36 |
+
print("=" * 60)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def compare_dict(dict1, dict2, path, missing_keys, different_values):
|
| 40 |
+
all_keys = set(dict1.keys()) | set(dict2.keys())
|
| 41 |
+
|
| 42 |
+
for key in all_keys:
|
| 43 |
+
current_path = f"{path}.{key}" if path else key
|
| 44 |
+
|
| 45 |
+
if key not in dict2:
|
| 46 |
+
missing_keys.append(f"[{current_path}] Only in file1: {dict1[key]}")
|
| 47 |
+
elif key not in dict1:
|
| 48 |
+
missing_keys.append(f"[{current_path}] Only in file2: {dict2[key]}")
|
| 49 |
+
else:
|
| 50 |
+
val1, val2 = dict1[key], dict2[key]
|
| 51 |
+
|
| 52 |
+
if isinstance(val1, dict) and isinstance(val2, dict):
|
| 53 |
+
compare_dict(val1, val2, current_path, missing_keys, different_values)
|
| 54 |
+
elif isinstance(val1, list) and isinstance(val2, list):
|
| 55 |
+
if val1 != val2:
|
| 56 |
+
different_values.append(f"[{current_path}]\n File1: {val1}\n File2: {val2}")
|
| 57 |
+
elif val1 != val2:
|
| 58 |
+
different_values.append(f"[{current_path}]\n File1: {val1}\n File2: {val2}")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if __name__ == "__main__":
|
| 62 |
+
compare_yaml(
|
| 63 |
+
"configs/stage_1_init.yaml",
|
| 64 |
+
"configs/stage_1_post.yaml",
|
| 65 |
+
)
|
Helios-main/scripts/training/configs/correct.yaml
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
validation_config:
|
| 2 |
+
# ------------------------------------------------------------------------------------------------------------------------------------
|
| 3 |
+
# ------- During validation/inference, enabling use_dynamic_shifting" yields better results.
|
| 4 |
+
use_dynamic_shifting: true
|
| 5 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 6 |
+
# ------------------------------------------------------------------------------------------------------------------------------------
|
| 7 |
+
|
| 8 |
+
training_config:
|
| 9 |
+
# ------------------------------------------------------------------------------------------------------------------------------------
|
| 10 |
+
# ------- Regarding the issue that I2V tends to produce very slow motion at the beginning:
|
| 11 |
+
# ------- During training, we did not construct the corresponding history context format (i.e., first-frame anchor + last-frame),
|
| 12 |
+
# ------- which means the current I2V inference relies heavily on the model’s zero-shot capability.
|
| 13 |
+
# ------- Incorporating this data format during training should significantly improve performance.
|
| 14 |
+
random_drop_i2v_ratio: 0.1 # should be changed according to valiation
|
| 15 |
+
# ------------------------------------------------------------------------------------------------------------------------------------
|
| 16 |
+
#
|
| 17 |
+
# ------------------------------------------------------------------------------------------------------------------------------------
|
| 18 |
+
# ------- Easy Anit-Drifting (Noise + Blur + Saturation): We actually missed fully turning this on when we trained Helios-Base
|
| 19 |
+
# ------- and Helios-Mid. But based on our ablation experiments on Helios-Distilled, it definitely helps mitigate degradation.
|
| 20 |
+
corrupt_mode_history: "random"
|
| 21 |
+
downsample_min_corrupt_ratio_history: 0.9 # should be changed according to valiation
|
| 22 |
+
downsample_max_corrupt_ratio_history: 1.0 # should be changed according to valiation
|
| 23 |
+
is_add_saturation: true
|
| 24 |
+
saturation_ratio_clean_prob: 0.1 # should be changed according to valiation
|
| 25 |
+
saturation_ratio_min: 0.3 # should be changed according to valiation
|
| 26 |
+
saturation_ratio_max: 1.7 # should be changed according to valiation
|
| 27 |
+
# ------------------------------------------------------------------------------------------------------------------------------------
|
Helios-main/scripts/training/configs/stage_1_init.yaml
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
output_dir: ablation_stage_1_init
|
| 2 |
+
logging_dir: logs
|
| 3 |
+
seed: 43
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
report_to:
|
| 7 |
+
tracker_name: Wan-Train
|
| 8 |
+
wandb_name: ablation_stage_1_init
|
| 9 |
+
report_to: wandb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
data_config:
|
| 13 |
+
# ---- Base ----
|
| 14 |
+
use_shuffle: true
|
| 15 |
+
pin_memory: true
|
| 16 |
+
persistent_workers: true
|
| 17 |
+
force_rebuild: true
|
| 18 |
+
single_res: true
|
| 19 |
+
single_height: 384
|
| 20 |
+
single_width: 640
|
| 21 |
+
dataloader_num_workers: 8
|
| 22 |
+
prefetch_factor: 2
|
| 23 |
+
caption_dropout_p: 0
|
| 24 |
+
id_token: ""
|
| 25 |
+
instance_data_root:
|
| 26 |
+
- "demo_data/ultravideo-long"
|
| 27 |
+
# ---- Stage 1 ----
|
| 28 |
+
use_stage1_dataset: true
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
model_config:
|
| 32 |
+
# ---- Path ----
|
| 33 |
+
pretrained_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 34 |
+
transformer_model_name_or_path: "Wan-AI/Wan2.1-T2V-14B-Diffusers"
|
| 35 |
+
load_checkpoints_custom: false
|
| 36 |
+
# load_model_path:
|
| 37 |
+
load_dcp: false
|
| 38 |
+
# load_dcp_path:
|
| 39 |
+
# ---- Vae ----
|
| 40 |
+
upcast_vae: true
|
| 41 |
+
enable_slicing: false
|
| 42 |
+
enable_tiling: false
|
| 43 |
+
# ---- Lora ----
|
| 44 |
+
lora_rank: 128
|
| 45 |
+
lora_alpha: 128.0
|
| 46 |
+
lora_dropout: 0.0
|
| 47 |
+
lora_layers: "all-linear"
|
| 48 |
+
# lora_target_modules:
|
| 49 |
+
# - to_k
|
| 50 |
+
# - to_q
|
| 51 |
+
# - to_v
|
| 52 |
+
# - to_out.0
|
| 53 |
+
# - ffn.net.0.proj
|
| 54 |
+
# - ffn.net.2
|
| 55 |
+
lora_exclude_modules:
|
| 56 |
+
- down
|
| 57 |
+
- up
|
| 58 |
+
# ---- Other ----
|
| 59 |
+
train_norm_layers: false
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
validation_config:
|
| 63 |
+
validation_steps: 500
|
| 64 |
+
validation_height: 384
|
| 65 |
+
validation_width: 640
|
| 66 |
+
validation_max_num_frames: 99
|
| 67 |
+
validation_prompts:
|
| 68 |
+
- "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."
|
| 69 |
+
# - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field."
|
| 70 |
+
# - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors."
|
| 71 |
+
validation_guidance_scale: 5.0
|
| 72 |
+
validation_latent_window_size:
|
| 73 |
+
- 9
|
| 74 |
+
num_validation_videos: 1
|
| 75 |
+
num_inference_steps: 50
|
| 76 |
+
# ---- Dynamic Shifting ----
|
| 77 |
+
use_dynamic_shifting: true
|
| 78 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
training_config:
|
| 82 |
+
# ---- Environment ----
|
| 83 |
+
allow_tf32: false
|
| 84 |
+
gradient_checkpointing: true
|
| 85 |
+
enable_xformers_memory_efficient_attention: false
|
| 86 |
+
enable_npu_flash_attention: false
|
| 87 |
+
upcast_before_saving: false
|
| 88 |
+
offload: false
|
| 89 |
+
mixed_precision: "bf16"
|
| 90 |
+
# ---- Training Resource ----
|
| 91 |
+
max_train_steps: 1000000
|
| 92 |
+
train_batch_size: 2
|
| 93 |
+
gradient_accumulation_steps: 1
|
| 94 |
+
checkpointing_steps: 500
|
| 95 |
+
resume_from_checkpoint: "latest"
|
| 96 |
+
save_checkpoints_custom: false
|
| 97 |
+
# ---- Optimizer ----
|
| 98 |
+
learning_rate: 5e-5
|
| 99 |
+
lr_scheduler: "constant"
|
| 100 |
+
lr_warmup_steps: 500
|
| 101 |
+
optimizer: "adamw"
|
| 102 |
+
adam_beta1: 0.9
|
| 103 |
+
adam_beta2: 0.999
|
| 104 |
+
adam_weight_decay: 1e-04
|
| 105 |
+
adam_epsilon: 1e-08
|
| 106 |
+
max_grad_norm: 1.0
|
| 107 |
+
weighting_scheme: "logit_normal" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"]
|
| 108 |
+
logit_mean: 0.0
|
| 109 |
+
logit_std: 1.0
|
| 110 |
+
mode_scale: 1.29
|
| 111 |
+
# ---- Dynamic Shifting Parameters ----
|
| 112 |
+
use_dynamic_shifting: false
|
| 113 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 114 |
+
base_seq_len: 256
|
| 115 |
+
max_seq_len: 4096
|
| 116 |
+
base_shift: 0.5
|
| 117 |
+
max_shift: 1.15
|
| 118 |
+
# ---- VAE Decode Parameters ----
|
| 119 |
+
vae_decode_type: "default"
|
| 120 |
+
# ---- EMA Parameters ----
|
| 121 |
+
use_ema: false
|
| 122 |
+
use_ema_validation: false
|
| 123 |
+
ema_decay: 0.999
|
| 124 |
+
ema_start_step: 250
|
| 125 |
+
ema_zero3_port: 10543
|
| 126 |
+
ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json"
|
| 127 |
+
# ---- Stage 1 Parameters ----
|
| 128 |
+
is_enable_stage1: true
|
| 129 |
+
history_sizes:
|
| 130 |
+
- 16
|
| 131 |
+
- 2
|
| 132 |
+
- 1
|
| 133 |
+
latent_window_size:
|
| 134 |
+
# - 12
|
| 135 |
+
# - 10
|
| 136 |
+
- 9
|
| 137 |
+
# - 8
|
| 138 |
+
# - 6
|
| 139 |
+
# - 5
|
| 140 |
+
# - 4
|
| 141 |
+
# - 3
|
| 142 |
+
# - 2
|
| 143 |
+
# - 1
|
| 144 |
+
is_random_drop: true
|
| 145 |
+
random_drop_v2v_ratio: 0.4
|
| 146 |
+
random_drop_t2v_ratio: 0.4
|
| 147 |
+
#
|
| 148 |
+
corrupt_model_input: false
|
| 149 |
+
corrupt_mode_model_input: "noise"
|
| 150 |
+
corrupt_mode_prob_model_input: 0.9
|
| 151 |
+
is_frame_independent_corrupt_model_input: true
|
| 152 |
+
is_chunk_independent_corrupt_model_input: false
|
| 153 |
+
noise_corrupt_ratio_model_input: 0.33333333333333
|
| 154 |
+
noise_corrupt_clean_prob_model_input: 0.1
|
| 155 |
+
downsample_min_corrupt_ratio_model_input: 0.9
|
| 156 |
+
downsample_max_corrupt_ratio_model_input: 1.0
|
| 157 |
+
corrupt_history: true
|
| 158 |
+
corrupt_mode_history: "noise"
|
| 159 |
+
corrupt_mode_prob_history: 0.9
|
| 160 |
+
is_frame_independent_corrupt_history: true
|
| 161 |
+
is_chunk_independent_corrupt_history: false
|
| 162 |
+
noise_corrupt_ratio_history_short: 0.33333333333333
|
| 163 |
+
noise_corrupt_ratio_history_mid: 0.33333333333333
|
| 164 |
+
noise_corrupt_ratio_history_long: 0.33333333333333
|
| 165 |
+
noise_corrupt_clean_prob_history: 0.1
|
| 166 |
+
downsample_min_corrupt_ratio_history: 0.9
|
| 167 |
+
downsample_max_corrupt_ratio_history: 1.0
|
| 168 |
+
#
|
| 169 |
+
is_amplify_history: false
|
| 170 |
+
history_scale_mode: "per_head"
|
| 171 |
+
#
|
| 172 |
+
is_train_full_patch_embedding: false
|
| 173 |
+
is_train_lora_patch_embedding: true
|
| 174 |
+
has_multi_term_memory_patch: true
|
| 175 |
+
is_train_full_multi_term_memory_patchg: true
|
| 176 |
+
is_train_lora_multi_term_memory_patchg: false
|
| 177 |
+
zero_history_timestep: true
|
| 178 |
+
guidance_cross_attn: true
|
| 179 |
+
restrict_self_attn: false
|
| 180 |
+
is_train_restrict_lora: false
|
| 181 |
+
restrict_lora: false
|
| 182 |
+
restrict_lora_rank: 128
|
Helios-main/scripts/training/configs/stage_1_post.yaml
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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44
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
report_to:
|
| 7 |
+
tracker_name: Wan-Train
|
| 8 |
+
wandb_name: ablation_stage_1_post
|
| 9 |
+
report_to: wandb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
data_config:
|
| 13 |
+
# ---- Base ----
|
| 14 |
+
use_shuffle: true
|
| 15 |
+
pin_memory: true
|
| 16 |
+
persistent_workers: true
|
| 17 |
+
force_rebuild: true
|
| 18 |
+
single_res: true
|
| 19 |
+
single_height: 384
|
| 20 |
+
single_width: 640
|
| 21 |
+
dataloader_num_workers: 8
|
| 22 |
+
prefetch_factor: 2
|
| 23 |
+
caption_dropout_p: 0
|
| 24 |
+
id_token: ""
|
| 25 |
+
instance_data_root:
|
| 26 |
+
- "demo_data/ultravideo-long"
|
| 27 |
+
# ---- Stage 1 ----
|
| 28 |
+
use_stage1_dataset: true
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
model_config:
|
| 32 |
+
# ---- Path ----
|
| 33 |
+
pretrained_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 34 |
+
transformer_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 35 |
+
subfolder: "transformer_init"
|
| 36 |
+
load_checkpoints_custom: false
|
| 37 |
+
# load_model_path:
|
| 38 |
+
load_dcp: false
|
| 39 |
+
# load_dcp_path:
|
| 40 |
+
# ---- Vae ----
|
| 41 |
+
upcast_vae: true
|
| 42 |
+
enable_slicing: false
|
| 43 |
+
enable_tiling: false
|
| 44 |
+
# ---- Lora ----
|
| 45 |
+
lora_rank: 128
|
| 46 |
+
lora_alpha: 128.0
|
| 47 |
+
lora_dropout: 0.0
|
| 48 |
+
lora_layers: "all-linear"
|
| 49 |
+
# lora_target_modules:
|
| 50 |
+
# - to_k
|
| 51 |
+
# - to_q
|
| 52 |
+
# - to_v
|
| 53 |
+
# - to_out.0
|
| 54 |
+
# - ffn.net.0.proj
|
| 55 |
+
# - ffn.net.2
|
| 56 |
+
lora_exclude_modules:
|
| 57 |
+
- down
|
| 58 |
+
- up
|
| 59 |
+
# ---- Other ----
|
| 60 |
+
train_norm_layers: false
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
validation_config:
|
| 64 |
+
validation_steps: 500
|
| 65 |
+
validation_height: 384
|
| 66 |
+
validation_width: 640
|
| 67 |
+
validation_max_num_frames: 99
|
| 68 |
+
validation_prompts:
|
| 69 |
+
- "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."
|
| 70 |
+
# - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field."
|
| 71 |
+
# - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors."
|
| 72 |
+
validation_guidance_scale: 5.0
|
| 73 |
+
validation_latent_window_size:
|
| 74 |
+
- 9
|
| 75 |
+
num_validation_videos: 1
|
| 76 |
+
num_inference_steps: 50
|
| 77 |
+
# ---- Dynamic Shifting ----
|
| 78 |
+
use_dynamic_shifting: true
|
| 79 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
training_config:
|
| 83 |
+
# ---- Environment ----
|
| 84 |
+
allow_tf32: false
|
| 85 |
+
gradient_checkpointing: true
|
| 86 |
+
enable_xformers_memory_efficient_attention: false
|
| 87 |
+
enable_npu_flash_attention: false
|
| 88 |
+
upcast_before_saving: false
|
| 89 |
+
offload: false
|
| 90 |
+
mixed_precision: "bf16"
|
| 91 |
+
# ---- Training Resource ----
|
| 92 |
+
max_train_steps: 1000000
|
| 93 |
+
train_batch_size: 2
|
| 94 |
+
gradient_accumulation_steps: 1
|
| 95 |
+
checkpointing_steps: 500
|
| 96 |
+
resume_from_checkpoint: "latest"
|
| 97 |
+
save_checkpoints_custom: false
|
| 98 |
+
# ---- Optimizer ----
|
| 99 |
+
learning_rate: 3e-5
|
| 100 |
+
lr_scheduler: "constant"
|
| 101 |
+
lr_warmup_steps: 500
|
| 102 |
+
optimizer: "adamw"
|
| 103 |
+
adam_beta1: 0.9
|
| 104 |
+
adam_beta2: 0.999
|
| 105 |
+
adam_weight_decay: 1e-04
|
| 106 |
+
adam_epsilon: 1e-08
|
| 107 |
+
max_grad_norm: 1.0
|
| 108 |
+
weighting_scheme: "logit_normal" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"]
|
| 109 |
+
logit_mean: 0.0
|
| 110 |
+
logit_std: 1.0
|
| 111 |
+
mode_scale: 1.29
|
| 112 |
+
# ---- Dynamic Shifting Parameters ----
|
| 113 |
+
use_dynamic_shifting: false
|
| 114 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 115 |
+
base_seq_len: 256
|
| 116 |
+
max_seq_len: 4096
|
| 117 |
+
base_shift: 0.5
|
| 118 |
+
max_shift: 1.15
|
| 119 |
+
# ---- VAE Decode Parameters ----
|
| 120 |
+
vae_decode_type: "default"
|
| 121 |
+
# ---- EMA Parameters ----
|
| 122 |
+
use_ema: false
|
| 123 |
+
use_ema_validation: false
|
| 124 |
+
ema_decay: 0.999
|
| 125 |
+
ema_start_step: 250
|
| 126 |
+
ema_zero3_port: 10543
|
| 127 |
+
ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json"
|
| 128 |
+
# ---- Stage 1 Parameters ----
|
| 129 |
+
is_enable_stage1: true
|
| 130 |
+
history_sizes:
|
| 131 |
+
- 16
|
| 132 |
+
- 2
|
| 133 |
+
- 1
|
| 134 |
+
latent_window_size:
|
| 135 |
+
# - 12
|
| 136 |
+
# - 10
|
| 137 |
+
- 9
|
| 138 |
+
# - 8
|
| 139 |
+
# - 6
|
| 140 |
+
# - 5
|
| 141 |
+
# - 4
|
| 142 |
+
# - 3
|
| 143 |
+
# - 2
|
| 144 |
+
# - 1
|
| 145 |
+
is_random_drop: true
|
| 146 |
+
random_drop_v2v_ratio: 0.4
|
| 147 |
+
random_drop_t2v_ratio: 0.4
|
| 148 |
+
#
|
| 149 |
+
corrupt_model_input: false
|
| 150 |
+
corrupt_mode_model_input: "noise"
|
| 151 |
+
corrupt_mode_prob_model_input: 0.9
|
| 152 |
+
is_frame_independent_corrupt_model_input: true
|
| 153 |
+
is_chunk_independent_corrupt_model_input: false
|
| 154 |
+
noise_corrupt_ratio_model_input: 0.33333333333333
|
| 155 |
+
noise_corrupt_clean_prob_model_input: 0.1
|
| 156 |
+
downsample_min_corrupt_ratio_model_input: 0.9
|
| 157 |
+
downsample_max_corrupt_ratio_model_input: 1.0
|
| 158 |
+
corrupt_history: true
|
| 159 |
+
corrupt_mode_history: "noise"
|
| 160 |
+
corrupt_mode_prob_history: 0.9
|
| 161 |
+
is_frame_independent_corrupt_history: true
|
| 162 |
+
is_chunk_independent_corrupt_history: false
|
| 163 |
+
noise_corrupt_ratio_history_short: 0.33333333333333
|
| 164 |
+
noise_corrupt_ratio_history_mid: 0.33333333333333
|
| 165 |
+
noise_corrupt_ratio_history_long: 0.33333333333333
|
| 166 |
+
noise_corrupt_clean_prob_history: 0.1
|
| 167 |
+
downsample_min_corrupt_ratio_history: 0.9
|
| 168 |
+
downsample_max_corrupt_ratio_history: 1.0
|
| 169 |
+
#
|
| 170 |
+
is_amplify_history: false
|
| 171 |
+
history_scale_mode: "per_head"
|
| 172 |
+
#
|
| 173 |
+
is_train_full_patch_embedding: false
|
| 174 |
+
is_train_lora_patch_embedding: true
|
| 175 |
+
has_multi_term_memory_patch: true
|
| 176 |
+
is_train_full_multi_term_memory_patchg: true
|
| 177 |
+
is_train_lora_multi_term_memory_patchg: false
|
| 178 |
+
zero_history_timestep: true
|
| 179 |
+
guidance_cross_attn: true
|
| 180 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
output_dir: ablation_stage_2_init
|
| 2 |
+
logging_dir: logs
|
| 3 |
+
seed: 45
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
report_to:
|
| 7 |
+
tracker_name: Wan-Train
|
| 8 |
+
wandb_name: ablation_stage_2_init
|
| 9 |
+
report_to: wandb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
data_config:
|
| 13 |
+
# ---- Base ----
|
| 14 |
+
use_shuffle: true
|
| 15 |
+
pin_memory: true
|
| 16 |
+
persistent_workers: true
|
| 17 |
+
force_rebuild: true
|
| 18 |
+
single_res: true
|
| 19 |
+
single_height: 384
|
| 20 |
+
single_width: 640
|
| 21 |
+
dataloader_num_workers: 8
|
| 22 |
+
prefetch_factor: 2
|
| 23 |
+
caption_dropout_p: 0
|
| 24 |
+
id_token: ""
|
| 25 |
+
instance_data_root:
|
| 26 |
+
- "demo_data/ultravideo-long"
|
| 27 |
+
# ---- Stage 1 ----
|
| 28 |
+
use_stage1_dataset: true
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
model_config:
|
| 32 |
+
# ---- Path ----
|
| 33 |
+
pretrained_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 34 |
+
transformer_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 35 |
+
load_checkpoints_custom: false
|
| 36 |
+
# load_model_path:
|
| 37 |
+
load_dcp: false
|
| 38 |
+
# load_dcp_path:
|
| 39 |
+
# ---- Vae ----
|
| 40 |
+
upcast_vae: true
|
| 41 |
+
enable_slicing: false
|
| 42 |
+
enable_tiling: false
|
| 43 |
+
# ---- Lora ----
|
| 44 |
+
lora_rank: 256
|
| 45 |
+
lora_alpha: 256.0
|
| 46 |
+
lora_dropout: 0.0
|
| 47 |
+
lora_layers: "all-linear"
|
| 48 |
+
# lora_target_modules:
|
| 49 |
+
# - to_k
|
| 50 |
+
# - to_q
|
| 51 |
+
# - to_v
|
| 52 |
+
# - to_out.0
|
| 53 |
+
# - ffn.net.0.proj
|
| 54 |
+
# - ffn.net.2
|
| 55 |
+
lora_exclude_modules:
|
| 56 |
+
- down
|
| 57 |
+
- up
|
| 58 |
+
# ---- Other ----
|
| 59 |
+
train_norm_layers: false
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
validation_config:
|
| 63 |
+
validation_steps: 500
|
| 64 |
+
validation_height: 384
|
| 65 |
+
validation_width: 640
|
| 66 |
+
validation_max_num_frames: 99
|
| 67 |
+
validation_prompts:
|
| 68 |
+
- "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."
|
| 69 |
+
# - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field."
|
| 70 |
+
# - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors."
|
| 71 |
+
validation_guidance_scale: 5.0
|
| 72 |
+
validation_latent_window_size:
|
| 73 |
+
- 9
|
| 74 |
+
num_validation_videos: 1
|
| 75 |
+
# ---- Dynamic Shifting ----
|
| 76 |
+
use_dynamic_shifting: true
|
| 77 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 78 |
+
# ---- Stage 2 ----
|
| 79 |
+
stage2_simulated_inference_steps:
|
| 80 |
+
- 20
|
| 81 |
+
- 20
|
| 82 |
+
- 20
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
training_config:
|
| 86 |
+
# ---- Environment ----
|
| 87 |
+
allow_tf32: false
|
| 88 |
+
gradient_checkpointing: true
|
| 89 |
+
enable_xformers_memory_efficient_attention: false
|
| 90 |
+
enable_npu_flash_attention: false
|
| 91 |
+
upcast_before_saving: false
|
| 92 |
+
offload: false
|
| 93 |
+
mixed_precision: "bf16"
|
| 94 |
+
# ---- Training Resource ----
|
| 95 |
+
max_train_steps: 1000000
|
| 96 |
+
train_batch_size: 1
|
| 97 |
+
gradient_accumulation_steps: 1
|
| 98 |
+
checkpointing_steps: 500
|
| 99 |
+
resume_from_checkpoint: "latest"
|
| 100 |
+
save_checkpoints_custom: false
|
| 101 |
+
# ---- Optimizer ----
|
| 102 |
+
learning_rate: 1e-4
|
| 103 |
+
lr_scheduler: "constant_with_warmup"
|
| 104 |
+
lr_warmup_steps: 1000
|
| 105 |
+
optimizer: "adamw"
|
| 106 |
+
adam_beta1: 0.9
|
| 107 |
+
adam_beta2: 0.999
|
| 108 |
+
adam_weight_decay: 1e-04
|
| 109 |
+
adam_epsilon: 1e-08
|
| 110 |
+
max_grad_norm: 1.0
|
| 111 |
+
weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"]
|
| 112 |
+
logit_mean: 0.0
|
| 113 |
+
logit_std: 1.0
|
| 114 |
+
mode_scale: 1.29
|
| 115 |
+
# ---- Dynamic Shifting Parameters ----
|
| 116 |
+
use_dynamic_shifting: false
|
| 117 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 118 |
+
base_seq_len: 256
|
| 119 |
+
max_seq_len: 4096
|
| 120 |
+
base_shift: 0.5
|
| 121 |
+
max_shift: 1.15
|
| 122 |
+
# ---- VAE Decode Parameters ----
|
| 123 |
+
vae_decode_type: "default"
|
| 124 |
+
# ---- EMA Parameters ----
|
| 125 |
+
use_ema: false
|
| 126 |
+
use_ema_validation: false
|
| 127 |
+
ema_decay: 0.999
|
| 128 |
+
ema_start_step: 250
|
| 129 |
+
ema_zero3_port: 10543
|
| 130 |
+
ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json"
|
| 131 |
+
# ---- Stage 1 Parameters ----
|
| 132 |
+
is_enable_stage1: true
|
| 133 |
+
history_sizes:
|
| 134 |
+
- 16
|
| 135 |
+
- 2
|
| 136 |
+
- 1
|
| 137 |
+
latent_window_size:
|
| 138 |
+
# - 12
|
| 139 |
+
# - 10
|
| 140 |
+
- 9
|
| 141 |
+
# - 8
|
| 142 |
+
# - 6
|
| 143 |
+
# - 5
|
| 144 |
+
# - 4
|
| 145 |
+
# - 3
|
| 146 |
+
# - 2
|
| 147 |
+
# - 1
|
| 148 |
+
is_random_drop: true
|
| 149 |
+
random_drop_v2v_ratio: 0.4
|
| 150 |
+
random_drop_t2v_ratio: 0.4
|
| 151 |
+
#
|
| 152 |
+
corrupt_model_input: false
|
| 153 |
+
corrupt_mode_model_input: "noise"
|
| 154 |
+
corrupt_mode_prob_model_input: 0.9
|
| 155 |
+
is_frame_independent_corrupt_model_input: true
|
| 156 |
+
is_chunk_independent_corrupt_model_input: false
|
| 157 |
+
noise_corrupt_ratio_model_input: 0.33333333333333
|
| 158 |
+
noise_corrupt_clean_prob_model_input: 0.1
|
| 159 |
+
downsample_min_corrupt_ratio_model_input: 0.9
|
| 160 |
+
downsample_max_corrupt_ratio_model_input: 1.0
|
| 161 |
+
corrupt_history: true
|
| 162 |
+
corrupt_mode_history: "noise"
|
| 163 |
+
corrupt_mode_prob_history: 0.9
|
| 164 |
+
is_frame_independent_corrupt_history: true
|
| 165 |
+
is_chunk_independent_corrupt_history: false
|
| 166 |
+
noise_corrupt_ratio_history_short: 0.33333333333333
|
| 167 |
+
noise_corrupt_ratio_history_mid: 0.33333333333333
|
| 168 |
+
noise_corrupt_ratio_history_long: 0.33333333333333
|
| 169 |
+
noise_corrupt_clean_prob_history: 0.1
|
| 170 |
+
downsample_min_corrupt_ratio_history: 0.9
|
| 171 |
+
downsample_max_corrupt_ratio_history: 1.0
|
| 172 |
+
#
|
| 173 |
+
is_amplify_history: false
|
| 174 |
+
history_scale_mode: "per_head"
|
| 175 |
+
#
|
| 176 |
+
is_train_full_patch_embedding: false
|
| 177 |
+
is_train_lora_patch_embedding: false
|
| 178 |
+
has_multi_term_memory_patch: true
|
| 179 |
+
is_train_full_multi_term_memory_patchg: false
|
| 180 |
+
is_train_lora_multi_term_memory_patchg: false
|
| 181 |
+
zero_history_timestep: true
|
| 182 |
+
guidance_cross_attn: true
|
| 183 |
+
restrict_self_attn: false
|
| 184 |
+
is_train_restrict_lora: false
|
| 185 |
+
restrict_lora: false
|
| 186 |
+
restrict_lora_rank: 128
|
| 187 |
+
# ---- Stage 2 Parameters ----
|
| 188 |
+
is_enable_stage2: true
|
| 189 |
+
is_navit_pyramid: true
|
| 190 |
+
stage2_num_stages: 3
|
| 191 |
+
stage2_timestep_shift: 1.0
|
| 192 |
+
stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 193 |
+
stage2_stage_range:
|
| 194 |
+
- 0
|
| 195 |
+
- 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 196 |
+
- 0.666666666666666666666666666666666 # Approximate value of 2/3
|
| 197 |
+
- 1
|
| 198 |
+
stage2_sample_ratios:
|
| 199 |
+
- 1
|
| 200 |
+
- 2
|
| 201 |
+
- 1
|
| 202 |
+
efficient_sample: false
|
Helios-main/scripts/training/configs/stage_2_post.yaml
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
output_dir: ablation_stage_2_post
|
| 2 |
+
logging_dir: logs
|
| 3 |
+
seed: 46
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
report_to:
|
| 7 |
+
tracker_name: Wan-Train
|
| 8 |
+
wandb_name: ablation_stage_2_post
|
| 9 |
+
report_to: wandb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
data_config:
|
| 13 |
+
# ---- Base ----
|
| 14 |
+
use_shuffle: true
|
| 15 |
+
pin_memory: true
|
| 16 |
+
persistent_workers: true
|
| 17 |
+
force_rebuild: true
|
| 18 |
+
single_res: true
|
| 19 |
+
single_height: 384
|
| 20 |
+
single_width: 640
|
| 21 |
+
dataloader_num_workers: 8
|
| 22 |
+
prefetch_factor: 2
|
| 23 |
+
caption_dropout_p: 0
|
| 24 |
+
id_token: ""
|
| 25 |
+
instance_data_root:
|
| 26 |
+
- "demo_data/ultravideo-long"
|
| 27 |
+
# ---- Stage 1 ----
|
| 28 |
+
use_stage1_dataset: true
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
model_config:
|
| 32 |
+
# ---- Path ----
|
| 33 |
+
pretrained_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 34 |
+
transformer_model_name_or_path: "BestWishYsh/Helios-Mid"
|
| 35 |
+
subfolder: "transformer_init"
|
| 36 |
+
load_checkpoints_custom: false
|
| 37 |
+
# load_model_path:
|
| 38 |
+
load_dcp: false
|
| 39 |
+
# load_dcp_path:
|
| 40 |
+
# ---- Vae ----
|
| 41 |
+
upcast_vae: true
|
| 42 |
+
enable_slicing: false
|
| 43 |
+
enable_tiling: false
|
| 44 |
+
# ---- Lora ----
|
| 45 |
+
lora_rank: 256
|
| 46 |
+
lora_alpha: 256.0
|
| 47 |
+
lora_dropout: 0.0
|
| 48 |
+
lora_layers: "all-linear"
|
| 49 |
+
# lora_target_modules:
|
| 50 |
+
# - to_k
|
| 51 |
+
# - to_q
|
| 52 |
+
# - to_v
|
| 53 |
+
# - to_out.0
|
| 54 |
+
# - ffn.net.0.proj
|
| 55 |
+
# - ffn.net.2
|
| 56 |
+
lora_exclude_modules:
|
| 57 |
+
- down
|
| 58 |
+
- up
|
| 59 |
+
# ---- Other ----
|
| 60 |
+
train_norm_layers: false
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
validation_config:
|
| 64 |
+
validation_steps: 500
|
| 65 |
+
validation_height: 384
|
| 66 |
+
validation_width: 640
|
| 67 |
+
validation_max_num_frames: 99
|
| 68 |
+
validation_prompts:
|
| 69 |
+
- "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."
|
| 70 |
+
# - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field."
|
| 71 |
+
# - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors."
|
| 72 |
+
validation_guidance_scale: 5.0
|
| 73 |
+
validation_latent_window_size:
|
| 74 |
+
- 9
|
| 75 |
+
num_validation_videos: 1
|
| 76 |
+
# ---- Dynamic Shifting ----
|
| 77 |
+
use_dynamic_shifting: true
|
| 78 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 79 |
+
# ---- Stage 2 ----
|
| 80 |
+
stage2_simulated_inference_steps:
|
| 81 |
+
- 20
|
| 82 |
+
- 20
|
| 83 |
+
- 20
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
training_config:
|
| 87 |
+
# ---- Environment ----
|
| 88 |
+
allow_tf32: false
|
| 89 |
+
gradient_checkpointing: true
|
| 90 |
+
enable_xformers_memory_efficient_attention: false
|
| 91 |
+
enable_npu_flash_attention: false
|
| 92 |
+
upcast_before_saving: false
|
| 93 |
+
offload: false
|
| 94 |
+
mixed_precision: "bf16"
|
| 95 |
+
# ---- Training Resource ----
|
| 96 |
+
max_train_steps: 1000000
|
| 97 |
+
train_batch_size: 1
|
| 98 |
+
gradient_accumulation_steps: 1
|
| 99 |
+
checkpointing_steps: 500
|
| 100 |
+
resume_from_checkpoint: "latest"
|
| 101 |
+
save_checkpoints_custom: false
|
| 102 |
+
# ---- Optimizer ----
|
| 103 |
+
learning_rate: 3e-5
|
| 104 |
+
lr_scheduler: "constant_with_warmup"
|
| 105 |
+
lr_warmup_steps: 500
|
| 106 |
+
optimizer: "adamw"
|
| 107 |
+
adam_beta1: 0.9
|
| 108 |
+
adam_beta2: 0.999
|
| 109 |
+
adam_weight_decay: 1e-04
|
| 110 |
+
adam_epsilon: 1e-08
|
| 111 |
+
max_grad_norm: 1.0
|
| 112 |
+
weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"]
|
| 113 |
+
logit_mean: 0.0
|
| 114 |
+
logit_std: 1.0
|
| 115 |
+
mode_scale: 1.29
|
| 116 |
+
# ---- Dynamic Shifting Parameters ----
|
| 117 |
+
use_dynamic_shifting: false
|
| 118 |
+
time_shift_type: "exponential" # ["exponential", "linear"]
|
| 119 |
+
base_seq_len: 256
|
| 120 |
+
max_seq_len: 4096
|
| 121 |
+
base_shift: 0.5
|
| 122 |
+
max_shift: 1.15
|
| 123 |
+
# ---- VAE Decode Parameters ----
|
| 124 |
+
vae_decode_type: "default"
|
| 125 |
+
# ---- EMA Parameters ----
|
| 126 |
+
use_ema: false
|
| 127 |
+
use_ema_validation: false
|
| 128 |
+
ema_decay: 0.999
|
| 129 |
+
ema_start_step: 250
|
| 130 |
+
ema_zero3_port: 10543
|
| 131 |
+
ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json"
|
| 132 |
+
# ---- Stage 1 Parameters ----
|
| 133 |
+
is_enable_stage1: true
|
| 134 |
+
history_sizes:
|
| 135 |
+
- 16
|
| 136 |
+
- 2
|
| 137 |
+
- 1
|
| 138 |
+
latent_window_size:
|
| 139 |
+
# - 12
|
| 140 |
+
# - 10
|
| 141 |
+
- 9
|
| 142 |
+
# - 8
|
| 143 |
+
# - 6
|
| 144 |
+
# - 5
|
| 145 |
+
# - 4
|
| 146 |
+
# - 3
|
| 147 |
+
# - 2
|
| 148 |
+
# - 1
|
| 149 |
+
is_random_drop: true
|
| 150 |
+
random_drop_v2v_ratio: 0.4
|
| 151 |
+
random_drop_t2v_ratio: 0.4
|
| 152 |
+
#
|
| 153 |
+
corrupt_model_input: false
|
| 154 |
+
corrupt_mode_model_input: "noise"
|
| 155 |
+
corrupt_mode_prob_model_input: 0.9
|
| 156 |
+
is_frame_independent_corrupt_model_input: true
|
| 157 |
+
is_chunk_independent_corrupt_model_input: false
|
| 158 |
+
noise_corrupt_ratio_model_input: 0.33333333333333
|
| 159 |
+
noise_corrupt_clean_prob_model_input: 0.1
|
| 160 |
+
downsample_min_corrupt_ratio_model_input: 0.9
|
| 161 |
+
downsample_max_corrupt_ratio_model_input: 1.0
|
| 162 |
+
corrupt_history: true
|
| 163 |
+
corrupt_mode_history: "noise"
|
| 164 |
+
corrupt_mode_prob_history: 0.9
|
| 165 |
+
is_frame_independent_corrupt_history: true
|
| 166 |
+
is_chunk_independent_corrupt_history: false
|
| 167 |
+
noise_corrupt_ratio_history_short: 0.33333333333333
|
| 168 |
+
noise_corrupt_ratio_history_mid: 0.33333333333333
|
| 169 |
+
noise_corrupt_ratio_history_long: 0.33333333333333
|
| 170 |
+
noise_corrupt_clean_prob_history: 0.1
|
| 171 |
+
downsample_min_corrupt_ratio_history: 0.9
|
| 172 |
+
downsample_max_corrupt_ratio_history: 1.0
|
| 173 |
+
#
|
| 174 |
+
is_amplify_history: false
|
| 175 |
+
history_scale_mode: "per_head"
|
| 176 |
+
#
|
| 177 |
+
is_train_full_patch_embedding: false
|
| 178 |
+
is_train_lora_patch_embedding: true
|
| 179 |
+
has_multi_term_memory_patch: true
|
| 180 |
+
is_train_full_multi_term_memory_patchg: false
|
| 181 |
+
is_train_lora_multi_term_memory_patchg: true
|
| 182 |
+
zero_history_timestep: true
|
| 183 |
+
guidance_cross_attn: true
|
| 184 |
+
restrict_self_attn: false
|
| 185 |
+
is_train_restrict_lora: false
|
| 186 |
+
restrict_lora: false
|
| 187 |
+
restrict_lora_rank: 128
|
| 188 |
+
# ---- Stage 2 Parameters ----
|
| 189 |
+
is_enable_stage2: true
|
| 190 |
+
is_navit_pyramid: true
|
| 191 |
+
stage2_num_stages: 3
|
| 192 |
+
stage2_timestep_shift: 1.0
|
| 193 |
+
stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 194 |
+
stage2_stage_range:
|
| 195 |
+
- 0
|
| 196 |
+
- 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 197 |
+
- 0.666666666666666666666666666666666 # Approximate value of 2/3
|
| 198 |
+
- 1
|
| 199 |
+
stage2_sample_ratios:
|
| 200 |
+
- 1
|
| 201 |
+
- 1
|
| 202 |
+
- 1
|
| 203 |
+
efficient_sample: false
|
Helios-main/scripts/training/configs/stage_3_ode.yaml
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
output_dir: ablation_stage_3_ode
|
| 2 |
+
logging_dir: logs
|
| 3 |
+
seed: 47
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
report_to:
|
| 7 |
+
tracker_name: Wan-Train
|
| 8 |
+
wandb_name: ablation_stage_3_ode
|
| 9 |
+
report_to: wandb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
data_config:
|
| 13 |
+
# ---- Base ----
|
| 14 |
+
use_shuffle: true
|
| 15 |
+
pin_memory: true
|
| 16 |
+
persistent_workers: true
|
| 17 |
+
force_rebuild: true
|
| 18 |
+
single_res: true
|
| 19 |
+
single_height: 384
|
| 20 |
+
single_width: 640
|
| 21 |
+
dataloader_num_workers: 8
|
| 22 |
+
prefetch_factor: 1
|
| 23 |
+
caption_dropout_p: 0
|
| 24 |
+
id_token: ""
|
| 25 |
+
# ---- Stage 1 ----
|
| 26 |
+
use_stage1_dataset: false
|
| 27 |
+
# ---- Stage 3 ----
|
| 28 |
+
use_stage3_dataset: true
|
| 29 |
+
ode_data_root:
|
| 30 |
+
- "demo_data/vidprom_filtered_extended"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
model_config:
|
| 34 |
+
# ---- Path ----
|
| 35 |
+
pretrained_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 36 |
+
transformer_model_name_or_path: "BestWishYsh/Helios-Mid"
|
| 37 |
+
load_checkpoints_custom: false
|
| 38 |
+
# load_model_path:
|
| 39 |
+
load_dcp: false
|
| 40 |
+
# load_dcp_path:
|
| 41 |
+
# ---- Vae ----
|
| 42 |
+
upcast_vae: true
|
| 43 |
+
enable_slicing: false
|
| 44 |
+
enable_tiling: false
|
| 45 |
+
# ---- Lora ----
|
| 46 |
+
lora_rank: 256
|
| 47 |
+
lora_alpha: 256.0
|
| 48 |
+
lora_dropout: 0.0
|
| 49 |
+
lora_layers: "all-linear"
|
| 50 |
+
# lora_target_modules:
|
| 51 |
+
# - to_k
|
| 52 |
+
# - to_q
|
| 53 |
+
# - to_v
|
| 54 |
+
# - to_out.0
|
| 55 |
+
# - ffn.net.0.proj
|
| 56 |
+
# - ffn.net.2
|
| 57 |
+
lora_exclude_modules:
|
| 58 |
+
- down
|
| 59 |
+
- up
|
| 60 |
+
# ---- Other ----
|
| 61 |
+
train_norm_layers: false
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
validation_config:
|
| 65 |
+
validation_steps: 500
|
| 66 |
+
validation_height: 384
|
| 67 |
+
validation_width: 640
|
| 68 |
+
validation_max_num_frames: 99
|
| 69 |
+
validation_prompts:
|
| 70 |
+
- "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."
|
| 71 |
+
# - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field."
|
| 72 |
+
# - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors."
|
| 73 |
+
validation_guidance_scale: 1.0
|
| 74 |
+
validation_latent_window_size:
|
| 75 |
+
- 9
|
| 76 |
+
num_validation_videos: 1
|
| 77 |
+
num_inference_steps: 6
|
| 78 |
+
# ---- Dynamic Shifting ----
|
| 79 |
+
use_dynamic_shifting: true
|
| 80 |
+
time_shift_type: "linear" # ["exponential", "linear"]
|
| 81 |
+
# ---- Pyramid ----
|
| 82 |
+
stage2_simulated_inference_steps:
|
| 83 |
+
- 2
|
| 84 |
+
- 2
|
| 85 |
+
- 2
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
training_config:
|
| 89 |
+
# ---- Environment ----
|
| 90 |
+
allow_tf32: false
|
| 91 |
+
gradient_checkpointing: true
|
| 92 |
+
enable_xformers_memory_efficient_attention: false
|
| 93 |
+
enable_npu_flash_attention: false
|
| 94 |
+
upcast_before_saving: false
|
| 95 |
+
offload: false
|
| 96 |
+
mixed_precision: "bf16"
|
| 97 |
+
# ---- Training Resource ----
|
| 98 |
+
max_train_steps: 1000000
|
| 99 |
+
train_batch_size: 1
|
| 100 |
+
gradient_accumulation_steps: 1
|
| 101 |
+
checkpointing_steps: 250
|
| 102 |
+
resume_from_checkpoint: "latest"
|
| 103 |
+
save_checkpoints_custom: true
|
| 104 |
+
# ---- Optimizer ----
|
| 105 |
+
learning_rate: 2.0e-06
|
| 106 |
+
lr_scheduler: "constant"
|
| 107 |
+
lr_warmup_steps: 500
|
| 108 |
+
optimizer: "adamw"
|
| 109 |
+
adam_beta1: 0.0
|
| 110 |
+
adam_beta2: 0.999
|
| 111 |
+
adam_weight_decay: 1e-03
|
| 112 |
+
adam_epsilon: 1e-08
|
| 113 |
+
max_grad_norm: 10.0
|
| 114 |
+
weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"]
|
| 115 |
+
logit_mean: 0.0
|
| 116 |
+
logit_std: 1.0
|
| 117 |
+
mode_scale: 1.29
|
| 118 |
+
# ---- Dynamic Shifting Parameters ----
|
| 119 |
+
use_dynamic_shifting: true
|
| 120 |
+
time_shift_type: "linear"
|
| 121 |
+
base_seq_len: 256
|
| 122 |
+
max_seq_len: 4096
|
| 123 |
+
base_shift: 0.5
|
| 124 |
+
max_shift: 1.15
|
| 125 |
+
# ---- VAE Decode Parameters ----
|
| 126 |
+
vae_decode_type: "default"
|
| 127 |
+
# ---- EMA Parameters ----
|
| 128 |
+
use_ema: true
|
| 129 |
+
use_ema_validation: false
|
| 130 |
+
ema_decay: 0.99
|
| 131 |
+
ema_start_step: 250
|
| 132 |
+
ema_zero3_port: 10543
|
| 133 |
+
ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json"
|
| 134 |
+
# ---- Stage 1 Parameters ----
|
| 135 |
+
is_enable_stage1: true
|
| 136 |
+
history_sizes:
|
| 137 |
+
- 16
|
| 138 |
+
- 2
|
| 139 |
+
- 1
|
| 140 |
+
latent_window_size:
|
| 141 |
+
# - 12
|
| 142 |
+
# - 10
|
| 143 |
+
- 9
|
| 144 |
+
# - 8
|
| 145 |
+
# - 6
|
| 146 |
+
# - 5
|
| 147 |
+
# - 4
|
| 148 |
+
# - 3
|
| 149 |
+
# - 2
|
| 150 |
+
# - 1
|
| 151 |
+
is_amplify_history: false
|
| 152 |
+
history_scale_mode: "per_head"
|
| 153 |
+
#
|
| 154 |
+
is_train_full_patch_embedding: false
|
| 155 |
+
is_train_lora_patch_embedding: false
|
| 156 |
+
has_multi_term_memory_patch: true
|
| 157 |
+
is_train_full_multi_term_memory_patchg: false
|
| 158 |
+
is_train_lora_multi_term_memory_patchg: true
|
| 159 |
+
zero_history_timestep: true
|
| 160 |
+
guidance_cross_attn: true
|
| 161 |
+
restrict_self_attn: false
|
| 162 |
+
is_train_restrict_lora: false
|
| 163 |
+
restrict_lora: false
|
| 164 |
+
restrict_lora_rank: 128
|
| 165 |
+
# ---- Stage 2 Parameters ----
|
| 166 |
+
is_enable_stage2: true
|
| 167 |
+
is_navit_pyramid: false
|
| 168 |
+
stage2_num_stages: 3
|
| 169 |
+
stage2_timestep_shift: 1.0
|
| 170 |
+
stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 171 |
+
stage2_stage_range:
|
| 172 |
+
- 0
|
| 173 |
+
- 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 174 |
+
- 0.666666666666666666666666666666666 # Approximate value of 2/3
|
| 175 |
+
- 1
|
| 176 |
+
stage2_sample_ratios:
|
| 177 |
+
- 1
|
| 178 |
+
- 1
|
| 179 |
+
- 1
|
| 180 |
+
efficient_sample: false
|
| 181 |
+
# ---- Stage 3 VRAM Parameters ----
|
| 182 |
+
dmd_is_low_vram_mode: true
|
| 183 |
+
# ---- Stage 3 Parameters ----
|
| 184 |
+
log_iters: 250
|
| 185 |
+
no_visualize: false
|
| 186 |
+
is_train_dmd: false
|
| 187 |
+
max_grad_norm_critic: 10.0
|
| 188 |
+
dmd_generator_deepspeed_config: scripts/accelerate_configs/zero2.json
|
| 189 |
+
dmd_critic_deepspeed_config: scripts/accelerate_configs/zero2.json
|
| 190 |
+
critic_learning_rate: 4.0e-07
|
| 191 |
+
dfake_gen_update_ratio: 5
|
| 192 |
+
dmd_denoising_step_list:
|
| 193 |
+
- 1000
|
| 194 |
+
- 750
|
| 195 |
+
- 500
|
| 196 |
+
- 250
|
| 197 |
+
num_critic_input_frames: 9
|
| 198 |
+
dmd_timestep_shift: 5.0
|
| 199 |
+
dmd_last_step_only: false
|
| 200 |
+
dmd_last_section_grad_only: false
|
| 201 |
+
dmd_teacher_forcing: false
|
| 202 |
+
dmd_teacher_forcing_ratio: 0.2
|
| 203 |
+
fake_guidance_scale: 0.0
|
| 204 |
+
real_guidance_scale: 3.0
|
| 205 |
+
# ---- VAE Re-Encode ----
|
| 206 |
+
is_dmd_vae_decode: false
|
| 207 |
+
# ---- Multi Stage Backward Simulated ----
|
| 208 |
+
is_multi_pyramid_stage_backward_simulated: false
|
| 209 |
+
# ---- ODE Regression Parameters ----
|
| 210 |
+
is_use_ode_regression: true
|
| 211 |
+
is_only_ode_regression: true
|
| 212 |
+
ode_regression_weight: 80.0
|
| 213 |
+
# ---- Cold Start Parameters ----
|
| 214 |
+
is_enable_cold_start: false
|
| 215 |
+
cold_start_step: 2000
|
| 216 |
+
stage_cold_start_step: 2000
|
| 217 |
+
# ---- Dynamic Timestep ----
|
| 218 |
+
generator_is_forcing_low_renoise: false
|
| 219 |
+
generator_dynamic_alpha: 4.0
|
| 220 |
+
generator_dynamic_beta: 1.5
|
| 221 |
+
generator_dynamic_sample_type: "uniform"
|
| 222 |
+
generator_dynamic_step: 1000
|
| 223 |
+
# ---- Dynamic ODE Section ----
|
| 224 |
+
ode_num_latent_sections_min: 3
|
| 225 |
+
ode_num_latent_sections_max: 3
|
| 226 |
+
ode_dynamic_alpha: 1.5
|
| 227 |
+
ode_dynamic_beta: 4.0
|
| 228 |
+
ode_dynamic_sample_type: "uniform"
|
| 229 |
+
ode_dynamic_step: 2000
|
Helios-main/scripts/training/configs/stage_3_post.yaml
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
| 1 |
+
output_dir: ablation_stage_3_post
|
| 2 |
+
logging_dir: logs
|
| 3 |
+
seed: 49
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
report_to:
|
| 7 |
+
tracker_name: Wan-Train
|
| 8 |
+
wandb_name: ablation_stage_3_post
|
| 9 |
+
report_to: wandb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
data_config:
|
| 13 |
+
# ---- Base ----
|
| 14 |
+
use_shuffle: true
|
| 15 |
+
pin_memory: true
|
| 16 |
+
persistent_workers: true
|
| 17 |
+
force_rebuild: true
|
| 18 |
+
single_res: true
|
| 19 |
+
single_height: 384
|
| 20 |
+
single_width: 640
|
| 21 |
+
dataloader_num_workers: 8
|
| 22 |
+
prefetch_factor: 1
|
| 23 |
+
caption_dropout_p: 0
|
| 24 |
+
id_token: ""
|
| 25 |
+
# ---- Stage 1 ----
|
| 26 |
+
use_stage1_dataset: false
|
| 27 |
+
# ---- Stage 3 ----
|
| 28 |
+
use_stage3_dataset: true
|
| 29 |
+
gan_data_root:
|
| 30 |
+
- "demo_data/ultravideo-long"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
model_config:
|
| 34 |
+
# ---- Path ----
|
| 35 |
+
pretrained_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 36 |
+
transformer_model_name_or_path: "BestWishYsh/Helios-Distilled"
|
| 37 |
+
subfolder: "transformer_ode"
|
| 38 |
+
real_score_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 39 |
+
load_checkpoints_custom: false
|
| 40 |
+
# load_model_path:
|
| 41 |
+
load_dcp: false
|
| 42 |
+
# load_dcp_path:
|
| 43 |
+
# ---- Vae ----
|
| 44 |
+
upcast_vae: true
|
| 45 |
+
enable_slicing: false
|
| 46 |
+
enable_tiling: false
|
| 47 |
+
# ---- Lora ----
|
| 48 |
+
lora_rank: 256
|
| 49 |
+
lora_alpha: 256.0
|
| 50 |
+
lora_dropout: 0.0
|
| 51 |
+
lora_layers: "all-linear"
|
| 52 |
+
# lora_target_modules:
|
| 53 |
+
# - to_k
|
| 54 |
+
# - to_q
|
| 55 |
+
# - to_v
|
| 56 |
+
# - to_out.0
|
| 57 |
+
# - ffn.net.0.proj
|
| 58 |
+
# - ffn.net.2
|
| 59 |
+
lora_exclude_modules:
|
| 60 |
+
- down
|
| 61 |
+
- up
|
| 62 |
+
# ---- Other ----
|
| 63 |
+
train_norm_layers: false
|
| 64 |
+
# ---- DMD ----
|
| 65 |
+
critic_lora_rank: 256
|
| 66 |
+
critic_lora_alpha: 256.0
|
| 67 |
+
critic_lora_dropout: 0.0
|
| 68 |
+
# ---- Reward Parameters ----
|
| 69 |
+
reward_model_name_or_path: "/mnt/bn/yufan-dev-my/ysh_new/Ckpts/Videoreward"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
validation_config:
|
| 73 |
+
validation_steps: 500
|
| 74 |
+
validation_height: 384
|
| 75 |
+
validation_width: 640
|
| 76 |
+
validation_max_num_frames: 99
|
| 77 |
+
validation_prompts:
|
| 78 |
+
- "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."
|
| 79 |
+
# - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field."
|
| 80 |
+
# - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors."
|
| 81 |
+
validation_guidance_scale: 1.0
|
| 82 |
+
validation_latent_window_size:
|
| 83 |
+
- 9
|
| 84 |
+
num_validation_videos: 1
|
| 85 |
+
num_inference_steps: 6
|
| 86 |
+
# ---- Dynamic Shifting ----
|
| 87 |
+
use_dynamic_shifting: true
|
| 88 |
+
time_shift_type: "linear" # ["exponential", "linear"]
|
| 89 |
+
# ---- Pyramid ----
|
| 90 |
+
stage2_simulated_inference_steps:
|
| 91 |
+
- 2
|
| 92 |
+
- 2
|
| 93 |
+
- 2
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
training_config:
|
| 97 |
+
# ---- Environment ----
|
| 98 |
+
allow_tf32: false
|
| 99 |
+
gradient_checkpointing: true
|
| 100 |
+
enable_xformers_memory_efficient_attention: false
|
| 101 |
+
enable_npu_flash_attention: false
|
| 102 |
+
upcast_before_saving: false
|
| 103 |
+
offload: false
|
| 104 |
+
mixed_precision: "bf16"
|
| 105 |
+
# ---- Training Resource ----
|
| 106 |
+
max_train_steps: 1000000
|
| 107 |
+
train_batch_size: 1
|
| 108 |
+
gradient_accumulation_steps: 1
|
| 109 |
+
checkpointing_steps: 250
|
| 110 |
+
resume_from_checkpoint: "latest"
|
| 111 |
+
save_checkpoints_custom: false
|
| 112 |
+
# ---- Optimizer ----
|
| 113 |
+
learning_rate: 2.0e-06
|
| 114 |
+
lr_scheduler: "constant"
|
| 115 |
+
lr_warmup_steps: 500
|
| 116 |
+
optimizer: "adamw"
|
| 117 |
+
adam_beta1: 0.0
|
| 118 |
+
adam_beta2: 0.999
|
| 119 |
+
adam_weight_decay: 1e-03
|
| 120 |
+
adam_epsilon: 1e-08
|
| 121 |
+
max_grad_norm: 10.0
|
| 122 |
+
weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"]
|
| 123 |
+
logit_mean: 0.0
|
| 124 |
+
logit_std: 1.0
|
| 125 |
+
mode_scale: 1.29
|
| 126 |
+
# ---- Dynamic Shifting Parameters ----
|
| 127 |
+
use_dynamic_shifting: true
|
| 128 |
+
time_shift_type: "linear"
|
| 129 |
+
base_seq_len: 256
|
| 130 |
+
max_seq_len: 4096
|
| 131 |
+
base_shift: 0.5
|
| 132 |
+
max_shift: 1.15
|
| 133 |
+
# ---- VAE Decode Parameters ----
|
| 134 |
+
vae_decode_type: "default"
|
| 135 |
+
# ---- EMA Parameters ----
|
| 136 |
+
use_ema: true
|
| 137 |
+
use_ema_validation: false
|
| 138 |
+
ema_decay: 0.99
|
| 139 |
+
ema_start_step: 750
|
| 140 |
+
ema_zero3_port: 10543
|
| 141 |
+
ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json"
|
| 142 |
+
# ---- Stage 1 Parameters ----
|
| 143 |
+
is_enable_stage1: true
|
| 144 |
+
history_sizes:
|
| 145 |
+
- 16
|
| 146 |
+
- 2
|
| 147 |
+
- 1
|
| 148 |
+
latent_window_size:
|
| 149 |
+
# - 12
|
| 150 |
+
# - 10
|
| 151 |
+
- 9
|
| 152 |
+
# - 8
|
| 153 |
+
# - 6
|
| 154 |
+
# - 5
|
| 155 |
+
# - 4
|
| 156 |
+
# - 3
|
| 157 |
+
# - 2
|
| 158 |
+
# - 1
|
| 159 |
+
is_random_drop: true
|
| 160 |
+
random_drop_v2v_ratio: 0.5
|
| 161 |
+
random_drop_t2v_ratio: 0.4
|
| 162 |
+
#
|
| 163 |
+
corrupt_model_input: false
|
| 164 |
+
corrupt_mode_model_input: "noise"
|
| 165 |
+
corrupt_mode_prob_model_input: 0.9
|
| 166 |
+
is_frame_independent_corrupt_model_input: true
|
| 167 |
+
is_chunk_independent_corrupt_model_input: false
|
| 168 |
+
noise_corrupt_ratio_model_input: 0.33333333333333
|
| 169 |
+
noise_corrupt_clean_prob_model_input: 0.1
|
| 170 |
+
downsample_min_corrupt_ratio_model_input: 0.9
|
| 171 |
+
downsample_max_corrupt_ratio_model_input: 1.0
|
| 172 |
+
corrupt_history: true
|
| 173 |
+
corrupt_mode_history: "noise"
|
| 174 |
+
corrupt_mode_prob_history: 0.9
|
| 175 |
+
is_frame_independent_corrupt_history: true
|
| 176 |
+
is_chunk_independent_corrupt_history: false
|
| 177 |
+
noise_corrupt_ratio_history_short: 0.33333333333333
|
| 178 |
+
noise_corrupt_ratio_history_mid: 0.33333333333333
|
| 179 |
+
noise_corrupt_ratio_history_long: 0.33333333333333
|
| 180 |
+
noise_corrupt_clean_prob_history: 0.1
|
| 181 |
+
downsample_min_corrupt_ratio_history: 0.9
|
| 182 |
+
downsample_max_corrupt_ratio_history: 1.0
|
| 183 |
+
#
|
| 184 |
+
is_add_saturation: true
|
| 185 |
+
saturation_ratio_clean_prob: 0.1
|
| 186 |
+
saturation_ratio_min: 0.3
|
| 187 |
+
saturation_ratio_max: 1.7
|
| 188 |
+
#
|
| 189 |
+
is_amplify_history: false
|
| 190 |
+
history_scale_mode: "per_head"
|
| 191 |
+
#
|
| 192 |
+
is_train_full_patch_embedding: false
|
| 193 |
+
is_train_lora_patch_embedding: false
|
| 194 |
+
has_multi_term_memory_patch: true
|
| 195 |
+
is_train_full_multi_term_memory_patchg: false
|
| 196 |
+
is_train_lora_multi_term_memory_patchg: true
|
| 197 |
+
zero_history_timestep: true
|
| 198 |
+
guidance_cross_attn: true
|
| 199 |
+
restrict_self_attn: false
|
| 200 |
+
is_train_restrict_lora: false
|
| 201 |
+
restrict_lora: false
|
| 202 |
+
restrict_lora_rank: 128
|
| 203 |
+
# ---- Stage 2 Parameters ----
|
| 204 |
+
is_enable_stage2: true
|
| 205 |
+
is_navit_pyramid: false
|
| 206 |
+
stage2_num_stages: 3
|
| 207 |
+
stage2_timestep_shift: 1.0
|
| 208 |
+
stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 209 |
+
stage2_stage_range:
|
| 210 |
+
- 0
|
| 211 |
+
- 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 212 |
+
- 0.666666666666666666666666666666666 # Approximate value of 2/3
|
| 213 |
+
- 1
|
| 214 |
+
stage2_sample_ratios:
|
| 215 |
+
- 1
|
| 216 |
+
- 1
|
| 217 |
+
- 1
|
| 218 |
+
efficient_sample: false
|
| 219 |
+
# ---- Stage 3 VRAM Parameters ----
|
| 220 |
+
dmd_is_low_vram_mode: true
|
| 221 |
+
is_gan_low_vram_mode: true
|
| 222 |
+
dmd_is_offload_grad: false
|
| 223 |
+
# ---- Stage 3 Parameters ----
|
| 224 |
+
log_iters: 125
|
| 225 |
+
no_visualize: false
|
| 226 |
+
is_train_dmd: true
|
| 227 |
+
max_grad_norm_critic: 10.0
|
| 228 |
+
dmd_generator_deepspeed_config: scripts/accelerate_configs/zero2.json
|
| 229 |
+
dmd_critic_deepspeed_config: scripts/accelerate_configs/zero2.json
|
| 230 |
+
critic_learning_rate: 4.0e-07
|
| 231 |
+
dfake_gen_update_ratio: 5
|
| 232 |
+
dmd_denoising_step_list:
|
| 233 |
+
- 1000
|
| 234 |
+
- 750
|
| 235 |
+
- 500
|
| 236 |
+
- 250
|
| 237 |
+
num_critic_input_frames: 9
|
| 238 |
+
dmd_timestep_shift: 5.0
|
| 239 |
+
dmd_last_step_only: false
|
| 240 |
+
dmd_last_section_grad_only: false
|
| 241 |
+
dmd_teacher_forcing: false
|
| 242 |
+
dmd_teacher_forcing_ratio: 0.2
|
| 243 |
+
fake_guidance_scale: 0.0
|
| 244 |
+
real_guidance_scale: 3.0
|
| 245 |
+
# ---- GT History Parameters ----
|
| 246 |
+
is_use_gt_history: true
|
| 247 |
+
use_gt_history_ratio: 1.0
|
| 248 |
+
# ---- VAE Re-Encode ----
|
| 249 |
+
is_dmd_vae_decode: false
|
| 250 |
+
# ---- Multi Stage Backward Simulated ----
|
| 251 |
+
is_multi_pyramid_stage_backward_simulated: false
|
| 252 |
+
is_amplify_first_chunk: true
|
| 253 |
+
# ---- GAN Parameters ----
|
| 254 |
+
is_use_gan: false
|
| 255 |
+
gan_start_step: 1000
|
| 256 |
+
is_separate_gan_grad: false
|
| 257 |
+
is_use_gan_hooks: true
|
| 258 |
+
is_use_gan_final: true
|
| 259 |
+
gan_cond_map_dim: 768
|
| 260 |
+
gan_hooks:
|
| 261 |
+
- 5
|
| 262 |
+
- 15
|
| 263 |
+
- 25
|
| 264 |
+
- 35
|
| 265 |
+
gan_g_weight: 5e-2
|
| 266 |
+
gan_d_weight: 1e-2
|
| 267 |
+
aprox_r1: true
|
| 268 |
+
aprox_r2: true
|
| 269 |
+
r1_weight: 100.0
|
| 270 |
+
r2_weight: 0.0
|
| 271 |
+
r1_sigma: 0.1
|
| 272 |
+
r2_sigma: 0.1
|
| 273 |
+
# ---- Cold Start Parameters ----
|
| 274 |
+
is_enable_cold_start: false
|
| 275 |
+
cold_start_step: 2000
|
| 276 |
+
stage_cold_start_step: 2000
|
| 277 |
+
# ---- Dynamic Timestep ----
|
| 278 |
+
generator_is_forcing_low_renoise: false
|
| 279 |
+
generator_dynamic_alpha: 4.0
|
| 280 |
+
generator_dynamic_beta: 1.5
|
| 281 |
+
generator_dynamic_sample_type: "beta"
|
| 282 |
+
generator_dynamic_step: 500
|
| 283 |
+
critic_dynamic_alpha: 4.0
|
| 284 |
+
critic_dynamic_beta: 1.5
|
| 285 |
+
critic_dynamic_sample_type: "uniform"
|
| 286 |
+
critic_dynamic_step: 500
|
| 287 |
+
# ---- Dynamic DMD Section ----
|
| 288 |
+
dmd_num_latent_sections_min: 1
|
| 289 |
+
dmd_num_latent_sections_max: 1
|
| 290 |
+
dmd_dynamic_alpha: 1.5
|
| 291 |
+
dmd_dynamic_beta: 4.0
|
| 292 |
+
dmd_dynamic_sample_type: "uniform"
|
| 293 |
+
dmd_dynamic_step: 500
|
| 294 |
+
# ---- Dynamic ODE Section ----
|
| 295 |
+
ode_num_latent_sections_min: 3
|
| 296 |
+
ode_num_latent_sections_max: 3
|
| 297 |
+
ode_dynamic_alpha: 1.5
|
| 298 |
+
ode_dynamic_beta: 4.0
|
| 299 |
+
ode_dynamic_sample_type: "uniform"
|
| 300 |
+
ode_dynamic_step: 500
|
Helios-main/scripts/training/configs/stage_3_post_gan_version.yaml
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
output_dir: ablation_stage_3_post_gan_version
|
| 2 |
+
logging_dir: logs
|
| 3 |
+
seed: 49
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
report_to:
|
| 7 |
+
tracker_name: Wan-Train
|
| 8 |
+
wandb_name: ablation_stage_3_post_gan_version
|
| 9 |
+
report_to: wandb
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
data_config:
|
| 13 |
+
# ---- Base ----
|
| 14 |
+
use_shuffle: true
|
| 15 |
+
pin_memory: true
|
| 16 |
+
persistent_workers: true
|
| 17 |
+
force_rebuild: true
|
| 18 |
+
single_res: true
|
| 19 |
+
single_height: 384
|
| 20 |
+
single_width: 640
|
| 21 |
+
dataloader_num_workers: 8
|
| 22 |
+
prefetch_factor: 1
|
| 23 |
+
caption_dropout_p: 0
|
| 24 |
+
id_token: ""
|
| 25 |
+
# ---- Stage 1 ----
|
| 26 |
+
use_stage1_dataset: false
|
| 27 |
+
# ---- Stage 3 ----
|
| 28 |
+
use_stage3_dataset: true
|
| 29 |
+
gan_data_root:
|
| 30 |
+
- "demo_data/ultravideo-long"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
model_config:
|
| 34 |
+
# ---- Path ----
|
| 35 |
+
pretrained_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 36 |
+
transformer_model_name_or_path: "BestWishYsh/Helios-Distilled"
|
| 37 |
+
subfolder: "transformer_ode"
|
| 38 |
+
real_score_model_name_or_path: "BestWishYsh/Helios-Base"
|
| 39 |
+
load_checkpoints_custom: false
|
| 40 |
+
# load_model_path:
|
| 41 |
+
load_dcp: false
|
| 42 |
+
# load_dcp_path:
|
| 43 |
+
# ---- Vae ----
|
| 44 |
+
upcast_vae: true
|
| 45 |
+
enable_slicing: false
|
| 46 |
+
enable_tiling: false
|
| 47 |
+
# ---- Lora ----
|
| 48 |
+
lora_rank: 256
|
| 49 |
+
lora_alpha: 256.0
|
| 50 |
+
lora_dropout: 0.0
|
| 51 |
+
lora_layers: "all-linear"
|
| 52 |
+
# lora_target_modules:
|
| 53 |
+
# - to_k
|
| 54 |
+
# - to_q
|
| 55 |
+
# - to_v
|
| 56 |
+
# - to_out.0
|
| 57 |
+
# - ffn.net.0.proj
|
| 58 |
+
# - ffn.net.2
|
| 59 |
+
lora_exclude_modules:
|
| 60 |
+
- down
|
| 61 |
+
- up
|
| 62 |
+
# ---- Other ----
|
| 63 |
+
train_norm_layers: false
|
| 64 |
+
# ---- DMD ----
|
| 65 |
+
critic_lora_rank: 256
|
| 66 |
+
critic_lora_alpha: 256.0
|
| 67 |
+
critic_lora_dropout: 0.0
|
| 68 |
+
# ---- Reward Parameters ----
|
| 69 |
+
reward_model_name_or_path: "/mnt/bn/yufan-dev-my/ysh_new/Ckpts/Videoreward"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
validation_config:
|
| 73 |
+
validation_steps: 500
|
| 74 |
+
validation_height: 384
|
| 75 |
+
validation_width: 640
|
| 76 |
+
validation_max_num_frames: 99
|
| 77 |
+
validation_prompts:
|
| 78 |
+
- "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."
|
| 79 |
+
# - "Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field."
|
| 80 |
+
# - "A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors."
|
| 81 |
+
validation_guidance_scale: 1.0
|
| 82 |
+
validation_latent_window_size:
|
| 83 |
+
- 9
|
| 84 |
+
num_validation_videos: 1
|
| 85 |
+
num_inference_steps: 6
|
| 86 |
+
# ---- Dynamic Shifting ----
|
| 87 |
+
use_dynamic_shifting: true
|
| 88 |
+
time_shift_type: "linear" # ["exponential", "linear"]
|
| 89 |
+
# ---- Pyramid ----
|
| 90 |
+
stage2_simulated_inference_steps:
|
| 91 |
+
- 2
|
| 92 |
+
- 2
|
| 93 |
+
- 2
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
training_config:
|
| 97 |
+
# ---- Environment ----
|
| 98 |
+
allow_tf32: false
|
| 99 |
+
gradient_checkpointing: true
|
| 100 |
+
enable_xformers_memory_efficient_attention: false
|
| 101 |
+
enable_npu_flash_attention: false
|
| 102 |
+
upcast_before_saving: false
|
| 103 |
+
offload: false
|
| 104 |
+
mixed_precision: "bf16"
|
| 105 |
+
# ---- Training Resource ----
|
| 106 |
+
max_train_steps: 1000000
|
| 107 |
+
train_batch_size: 1
|
| 108 |
+
gradient_accumulation_steps: 1
|
| 109 |
+
checkpointing_steps: 250
|
| 110 |
+
resume_from_checkpoint: "latest"
|
| 111 |
+
save_checkpoints_custom: false
|
| 112 |
+
# ---- Optimizer ----
|
| 113 |
+
learning_rate: 2.0e-06
|
| 114 |
+
lr_scheduler: "constant"
|
| 115 |
+
lr_warmup_steps: 500
|
| 116 |
+
optimizer: "adamw"
|
| 117 |
+
adam_beta1: 0.0
|
| 118 |
+
adam_beta2: 0.999
|
| 119 |
+
adam_weight_decay: 1e-03
|
| 120 |
+
adam_epsilon: 1e-08
|
| 121 |
+
max_grad_norm: 10.0
|
| 122 |
+
weighting_scheme: "none" # ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"]
|
| 123 |
+
logit_mean: 0.0
|
| 124 |
+
logit_std: 1.0
|
| 125 |
+
mode_scale: 1.29
|
| 126 |
+
# ---- Dynamic Shifting Parameters ----
|
| 127 |
+
use_dynamic_shifting: true
|
| 128 |
+
time_shift_type: "linear"
|
| 129 |
+
base_seq_len: 256
|
| 130 |
+
max_seq_len: 4096
|
| 131 |
+
base_shift: 0.5
|
| 132 |
+
max_shift: 1.15
|
| 133 |
+
# ---- VAE Decode Parameters ----
|
| 134 |
+
vae_decode_type: "default"
|
| 135 |
+
# ---- EMA Parameters ----
|
| 136 |
+
use_ema: true
|
| 137 |
+
use_ema_validation: false
|
| 138 |
+
ema_decay: 0.99
|
| 139 |
+
ema_start_step: 750
|
| 140 |
+
ema_zero3_port: 10543
|
| 141 |
+
ema_deepspeed_config_file: "scripts/accelerate_configs/zero3.json"
|
| 142 |
+
# ---- Stage 1 Parameters ----
|
| 143 |
+
is_enable_stage1: true
|
| 144 |
+
history_sizes:
|
| 145 |
+
- 16
|
| 146 |
+
- 2
|
| 147 |
+
- 1
|
| 148 |
+
latent_window_size:
|
| 149 |
+
# - 12
|
| 150 |
+
# - 10
|
| 151 |
+
- 9
|
| 152 |
+
# - 8
|
| 153 |
+
# - 6
|
| 154 |
+
# - 5
|
| 155 |
+
# - 4
|
| 156 |
+
# - 3
|
| 157 |
+
# - 2
|
| 158 |
+
# - 1
|
| 159 |
+
is_random_drop: true
|
| 160 |
+
random_drop_v2v_ratio: 0.5
|
| 161 |
+
random_drop_t2v_ratio: 0.4
|
| 162 |
+
#
|
| 163 |
+
corrupt_model_input: false
|
| 164 |
+
corrupt_mode_model_input: "noise"
|
| 165 |
+
corrupt_mode_prob_model_input: 0.9
|
| 166 |
+
is_frame_independent_corrupt_model_input: true
|
| 167 |
+
is_chunk_independent_corrupt_model_input: false
|
| 168 |
+
noise_corrupt_ratio_model_input: 0.33333333333333
|
| 169 |
+
noise_corrupt_clean_prob_model_input: 0.1
|
| 170 |
+
downsample_min_corrupt_ratio_model_input: 0.9
|
| 171 |
+
downsample_max_corrupt_ratio_model_input: 1.0
|
| 172 |
+
corrupt_history: true
|
| 173 |
+
corrupt_mode_history: "random"
|
| 174 |
+
corrupt_mode_prob_history: 0.9
|
| 175 |
+
is_frame_independent_corrupt_history: true
|
| 176 |
+
is_chunk_independent_corrupt_history: false
|
| 177 |
+
noise_corrupt_ratio_history_short: 0.33333333333333
|
| 178 |
+
noise_corrupt_ratio_history_mid: 0.33333333333333
|
| 179 |
+
noise_corrupt_ratio_history_long: 0.33333333333333
|
| 180 |
+
noise_corrupt_clean_prob_history: 0.1
|
| 181 |
+
downsample_min_corrupt_ratio_history: 0.9
|
| 182 |
+
downsample_max_corrupt_ratio_history: 1.0
|
| 183 |
+
#
|
| 184 |
+
is_add_saturation: true
|
| 185 |
+
saturation_ratio_clean_prob: 0.1
|
| 186 |
+
saturation_ratio_min: 0.3
|
| 187 |
+
saturation_ratio_max: 1.7
|
| 188 |
+
#
|
| 189 |
+
is_amplify_history: false
|
| 190 |
+
history_scale_mode: "per_head"
|
| 191 |
+
#
|
| 192 |
+
is_train_full_patch_embedding: false
|
| 193 |
+
is_train_lora_patch_embedding: false
|
| 194 |
+
has_multi_term_memory_patch: true
|
| 195 |
+
is_train_full_multi_term_memory_patchg: false
|
| 196 |
+
is_train_lora_multi_term_memory_patchg: true
|
| 197 |
+
zero_history_timestep: true
|
| 198 |
+
guidance_cross_attn: true
|
| 199 |
+
restrict_self_attn: false
|
| 200 |
+
is_train_restrict_lora: false
|
| 201 |
+
restrict_lora: false
|
| 202 |
+
restrict_lora_rank: 128
|
| 203 |
+
# ---- Stage 2 Parameters ----
|
| 204 |
+
is_enable_stage2: true
|
| 205 |
+
is_navit_pyramid: false
|
| 206 |
+
stage2_num_stages: 3
|
| 207 |
+
stage2_timestep_shift: 1.0
|
| 208 |
+
stage2_scheduler_gamma: 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 209 |
+
stage2_stage_range:
|
| 210 |
+
- 0
|
| 211 |
+
- 0.333333333333333333333333333333333 # Approximate value of 1/3
|
| 212 |
+
- 0.666666666666666666666666666666666 # Approximate value of 2/3
|
| 213 |
+
- 1
|
| 214 |
+
stage2_sample_ratios:
|
| 215 |
+
- 1
|
| 216 |
+
- 1
|
| 217 |
+
- 1
|
| 218 |
+
efficient_sample: false
|
| 219 |
+
# ---- Stage 3 VRAM Parameters ----
|
| 220 |
+
dmd_is_low_vram_mode: true
|
| 221 |
+
is_gan_low_vram_mode: true
|
| 222 |
+
dmd_is_offload_grad: false
|
| 223 |
+
# ---- Stage 3 Parameters ----
|
| 224 |
+
log_iters: 125
|
| 225 |
+
no_visualize: false
|
| 226 |
+
is_train_dmd: true
|
| 227 |
+
max_grad_norm_critic: 10.0
|
| 228 |
+
dmd_generator_deepspeed_config: scripts/accelerate_configs/zero2.json
|
| 229 |
+
dmd_critic_deepspeed_config: scripts/accelerate_configs/zero2.json
|
| 230 |
+
critic_learning_rate: 4.0e-07
|
| 231 |
+
dfake_gen_update_ratio: 5
|
| 232 |
+
dmd_denoising_step_list:
|
| 233 |
+
- 1000
|
| 234 |
+
- 750
|
| 235 |
+
- 500
|
| 236 |
+
- 250
|
| 237 |
+
num_critic_input_frames: 9
|
| 238 |
+
dmd_timestep_shift: 5.0
|
| 239 |
+
dmd_last_step_only: false
|
| 240 |
+
dmd_last_section_grad_only: false
|
| 241 |
+
dmd_teacher_forcing: false
|
| 242 |
+
dmd_teacher_forcing_ratio: 0.2
|
| 243 |
+
fake_guidance_scale: 0.0
|
| 244 |
+
real_guidance_scale: 3.0
|
| 245 |
+
# ---- GT History Parameters ----
|
| 246 |
+
is_use_gt_history: true
|
| 247 |
+
use_gt_history_ratio: 1.0
|
| 248 |
+
# ---- VAE Re-Encode ----
|
| 249 |
+
is_dmd_vae_decode: false
|
| 250 |
+
# ---- Multi Stage Backward Simulated ----
|
| 251 |
+
is_multi_pyramid_stage_backward_simulated: false
|
| 252 |
+
is_amplify_first_chunk: true
|
| 253 |
+
# ---- GAN Parameters ----
|
| 254 |
+
is_use_gan: true
|
| 255 |
+
gan_start_step: 1000
|
| 256 |
+
is_separate_gan_grad: false
|
| 257 |
+
is_use_gan_hooks: true
|
| 258 |
+
is_use_gan_final: true
|
| 259 |
+
gan_cond_map_dim: 768
|
| 260 |
+
gan_hooks:
|
| 261 |
+
- 5
|
| 262 |
+
- 15
|
| 263 |
+
- 25
|
| 264 |
+
- 35
|
| 265 |
+
gan_g_weight: 5e-2
|
| 266 |
+
gan_d_weight: 1e-2
|
| 267 |
+
aprox_r1: true
|
| 268 |
+
aprox_r2: true
|
| 269 |
+
r1_weight: 100.0
|
| 270 |
+
r2_weight: 0.0
|
| 271 |
+
r1_sigma: 0.1
|
| 272 |
+
r2_sigma: 0.1
|
| 273 |
+
# ---- Cold Start Parameters ----
|
| 274 |
+
is_enable_cold_start: false
|
| 275 |
+
cold_start_step: 2000
|
| 276 |
+
stage_cold_start_step: 2000
|
| 277 |
+
# ---- Dynamic Timestep ----
|
| 278 |
+
generator_is_forcing_low_renoise: false
|
| 279 |
+
generator_dynamic_alpha: 4.0
|
| 280 |
+
generator_dynamic_beta: 1.5
|
| 281 |
+
generator_dynamic_sample_type: "beta"
|
| 282 |
+
generator_dynamic_step: 500
|
| 283 |
+
critic_dynamic_alpha: 4.0
|
| 284 |
+
critic_dynamic_beta: 1.5
|
| 285 |
+
critic_dynamic_sample_type: "uniform"
|
| 286 |
+
critic_dynamic_step: 500
|
| 287 |
+
# ---- Dynamic DMD Section ----
|
| 288 |
+
dmd_num_latent_sections_min: 1
|
| 289 |
+
dmd_num_latent_sections_max: 1
|
| 290 |
+
dmd_dynamic_alpha: 1.5
|
| 291 |
+
dmd_dynamic_beta: 4.0
|
| 292 |
+
dmd_dynamic_sample_type: "uniform"
|
| 293 |
+
dmd_dynamic_step: 500
|
| 294 |
+
# ---- Dynamic ODE Section ----
|
| 295 |
+
ode_num_latent_sections_min: 3
|
| 296 |
+
ode_num_latent_sections_max: 3
|
| 297 |
+
ode_dynamic_alpha: 1.5
|
| 298 |
+
ode_dynamic_beta: 4.0
|
| 299 |
+
ode_dynamic_sample_type: "uniform"
|
| 300 |
+
ode_dynamic_step: 500
|
Helios-main/tools/gradio/comparison/gradio_compare_diff-ablation.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 = re.match(r".*?(\d+)_(\d+)\.mp4$", filename)
|
| 10 |
+
if match:
|
| 11 |
+
step = int(match.group(1))
|
| 12 |
+
idx = int(match.group(2))
|
| 13 |
+
return step, idx
|
| 14 |
+
return None, None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_video_list(folder_path):
|
| 18 |
+
"""Get all mp4 videos from the folder"""
|
| 19 |
+
if not os.path.exists(folder_path):
|
| 20 |
+
return []
|
| 21 |
+
|
| 22 |
+
videos = []
|
| 23 |
+
for file in os.listdir(folder_path):
|
| 24 |
+
if file.endswith(".mp4"):
|
| 25 |
+
step, idx = parse_video_name(file)
|
| 26 |
+
if step is not None:
|
| 27 |
+
videos.append({"filename": file, "step": step, "idx": idx, "path": os.path.join(folder_path, file)})
|
| 28 |
+
|
| 29 |
+
# Sort by step and idx
|
| 30 |
+
videos.sort(key=lambda x: (x["step"], x["idx"]))
|
| 31 |
+
return videos
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def create_video_mapping(videos):
|
| 35 |
+
"""Create mapping from (step, idx) to filename"""
|
| 36 |
+
mapping = {}
|
| 37 |
+
for video in videos:
|
| 38 |
+
key = (video["step"], video["idx"])
|
| 39 |
+
mapping[key] = video["filename"]
|
| 40 |
+
return mapping
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_step_idx_mapping(common_keys):
|
| 44 |
+
"""Extract step and idx mapping from common (step, idx) keys"""
|
| 45 |
+
step_idx_map = {} # {step: [idx1, idx2, ...]}
|
| 46 |
+
all_steps = set()
|
| 47 |
+
all_indices = set()
|
| 48 |
+
|
| 49 |
+
for step, idx in common_keys:
|
| 50 |
+
all_steps.add(step)
|
| 51 |
+
all_indices.add(idx)
|
| 52 |
+
if step not in step_idx_map:
|
| 53 |
+
step_idx_map[step] = []
|
| 54 |
+
step_idx_map[step].append(idx)
|
| 55 |
+
|
| 56 |
+
# Sort
|
| 57 |
+
for step in step_idx_map:
|
| 58 |
+
step_idx_map[step].sort()
|
| 59 |
+
|
| 60 |
+
return sorted(all_steps), sorted(all_indices), step_idx_map
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def load_videos(folder1, folder2):
|
| 64 |
+
"""Load videos from two folders and match them"""
|
| 65 |
+
if not folder1 or not folder2:
|
| 66 |
+
return (
|
| 67 |
+
None,
|
| 68 |
+
None,
|
| 69 |
+
"Please enter two folder paths",
|
| 70 |
+
gr.update(choices=[], value=None),
|
| 71 |
+
gr.update(choices=[], value=None),
|
| 72 |
+
gr.update(interactive=False),
|
| 73 |
+
gr.update(interactive=False),
|
| 74 |
+
gr.update(interactive=False),
|
| 75 |
+
gr.update(interactive=False),
|
| 76 |
+
"0 / 0",
|
| 77 |
+
{},
|
| 78 |
+
{},
|
| 79 |
+
{},
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
videos1 = get_video_list(folder1)
|
| 83 |
+
videos2 = get_video_list(folder2)
|
| 84 |
+
|
| 85 |
+
if not videos1:
|
| 86 |
+
return (
|
| 87 |
+
None,
|
| 88 |
+
None,
|
| 89 |
+
"No video files found in folder 1",
|
| 90 |
+
gr.update(choices=[], value=None),
|
| 91 |
+
gr.update(choices=[], value=None),
|
| 92 |
+
gr.update(interactive=False),
|
| 93 |
+
gr.update(interactive=False),
|
| 94 |
+
gr.update(interactive=False),
|
| 95 |
+
gr.update(interactive=False),
|
| 96 |
+
"0 / 0",
|
| 97 |
+
{},
|
| 98 |
+
{},
|
| 99 |
+
{},
|
| 100 |
+
)
|
| 101 |
+
if not videos2:
|
| 102 |
+
return (
|
| 103 |
+
None,
|
| 104 |
+
None,
|
| 105 |
+
"No video files found in folder 2",
|
| 106 |
+
gr.update(choices=[], value=None),
|
| 107 |
+
gr.update(choices=[], value=None),
|
| 108 |
+
gr.update(interactive=False),
|
| 109 |
+
gr.update(interactive=False),
|
| 110 |
+
gr.update(interactive=False),
|
| 111 |
+
gr.update(interactive=False),
|
| 112 |
+
"0 / 0",
|
| 113 |
+
{},
|
| 114 |
+
{},
|
| 115 |
+
{},
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# Create mapping from (step, idx) to filename
|
| 119 |
+
video_map1 = create_video_mapping(videos1)
|
| 120 |
+
video_map2 = create_video_mapping(videos2)
|
| 121 |
+
|
| 122 |
+
# Find common (step, idx) combinations
|
| 123 |
+
common_keys = sorted(set(video_map1.keys()) & set(video_map2.keys()))
|
| 124 |
+
|
| 125 |
+
if not common_keys:
|
| 126 |
+
# Show detailed info for debugging
|
| 127 |
+
steps1 = {v["step"] for v in videos1}
|
| 128 |
+
steps2 = {v["step"] for v in videos2}
|
| 129 |
+
info = "No matching videos found between the two folders\n"
|
| 130 |
+
info += f"Folder 1 steps: {sorted(steps1)}\n"
|
| 131 |
+
info += f"Folder 2 steps: {sorted(steps2)}\n"
|
| 132 |
+
info += f"Common steps: {sorted(steps1 & steps2)}"
|
| 133 |
+
return (
|
| 134 |
+
None,
|
| 135 |
+
None,
|
| 136 |
+
info,
|
| 137 |
+
gr.update(choices=[], value=None),
|
| 138 |
+
gr.update(choices=[], value=None),
|
| 139 |
+
gr.update(interactive=False),
|
| 140 |
+
gr.update(interactive=False),
|
| 141 |
+
gr.update(interactive=False),
|
| 142 |
+
gr.update(interactive=False),
|
| 143 |
+
"0 / 0",
|
| 144 |
+
{},
|
| 145 |
+
{},
|
| 146 |
+
{},
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Get all steps and indices
|
| 150 |
+
all_steps, all_indices, step_idx_map = get_step_idx_mapping(common_keys)
|
| 151 |
+
|
| 152 |
+
# Load first video
|
| 153 |
+
first_key = common_keys[0]
|
| 154 |
+
first_step, first_idx = first_key
|
| 155 |
+
|
| 156 |
+
filename1 = video_map1[first_key]
|
| 157 |
+
filename2 = video_map2[first_key]
|
| 158 |
+
|
| 159 |
+
video1_path = os.path.join(folder1, filename1)
|
| 160 |
+
video2_path = os.path.join(folder2, filename2)
|
| 161 |
+
|
| 162 |
+
info = f"Found {len(common_keys)} matching videos\n"
|
| 163 |
+
info += f"Current: Step {first_step}, Index {first_idx}\n"
|
| 164 |
+
info += f"Folder 1: {filename1}\n"
|
| 165 |
+
info += f"Folder 2: {filename2}"
|
| 166 |
+
|
| 167 |
+
# Get available indices for current step
|
| 168 |
+
available_indices = step_idx_map.get(first_step, [])
|
| 169 |
+
|
| 170 |
+
progress = f"1 / {len(common_keys)}"
|
| 171 |
+
|
| 172 |
+
return (
|
| 173 |
+
video1_path,
|
| 174 |
+
video2_path,
|
| 175 |
+
info,
|
| 176 |
+
gr.update(choices=all_steps, value=first_step),
|
| 177 |
+
gr.update(choices=available_indices, value=first_idx),
|
| 178 |
+
gr.update(interactive=first_step > all_steps[0]),
|
| 179 |
+
gr.update(interactive=first_step < all_steps[-1]),
|
| 180 |
+
gr.update(interactive=first_idx > available_indices[0] if available_indices else False),
|
| 181 |
+
gr.update(interactive=first_idx < available_indices[-1] if available_indices else False),
|
| 182 |
+
progress,
|
| 183 |
+
video_map1,
|
| 184 |
+
video_map2,
|
| 185 |
+
step_idx_map,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def update_available_indices(selected_step, step_idx_map):
|
| 190 |
+
"""Update available index list"""
|
| 191 |
+
if not step_idx_map or selected_step is None:
|
| 192 |
+
return gr.update(choices=[], value=None)
|
| 193 |
+
|
| 194 |
+
available_indices = step_idx_map.get(selected_step, [])
|
| 195 |
+
first_idx = available_indices[0] if available_indices else None
|
| 196 |
+
|
| 197 |
+
return gr.update(choices=available_indices, value=first_idx)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def update_videos_from_selectors(folder1, folder2, selected_step, selected_idx, video_map1, video_map2, step_idx_map):
|
| 201 |
+
"""Update videos based on selected step and idx"""
|
| 202 |
+
if selected_step is None or selected_idx is None:
|
| 203 |
+
return None, None, "Please select step and index", gr.update(), gr.update(), gr.update(), gr.update(), ""
|
| 204 |
+
|
| 205 |
+
key = (selected_step, selected_idx)
|
| 206 |
+
|
| 207 |
+
if key not in video_map1 or key not in video_map2:
|
| 208 |
+
return (
|
| 209 |
+
None,
|
| 210 |
+
None,
|
| 211 |
+
f"Video not found for Step {selected_step}, Index {selected_idx}",
|
| 212 |
+
gr.update(),
|
| 213 |
+
gr.update(),
|
| 214 |
+
gr.update(),
|
| 215 |
+
gr.update(),
|
| 216 |
+
"",
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
filename1 = video_map1[key]
|
| 220 |
+
filename2 = video_map2[key]
|
| 221 |
+
|
| 222 |
+
video1_path = os.path.join(folder1, filename1)
|
| 223 |
+
video2_path = os.path.join(folder2, filename2)
|
| 224 |
+
|
| 225 |
+
info = f"Current: Step {selected_step}, Index {selected_idx}\n"
|
| 226 |
+
info += f"Folder 1: {filename1}\n"
|
| 227 |
+
info += f"Folder 2: {filename2}"
|
| 228 |
+
|
| 229 |
+
# Get all steps and indices for current step
|
| 230 |
+
all_steps = sorted(step_idx_map.keys())
|
| 231 |
+
available_indices = step_idx_map.get(selected_step, [])
|
| 232 |
+
|
| 233 |
+
# Update button states
|
| 234 |
+
prev_step_interactive = selected_step > all_steps[0]
|
| 235 |
+
next_step_interactive = selected_step < all_steps[-1]
|
| 236 |
+
prev_idx_interactive = selected_idx > available_indices[0] if available_indices else False
|
| 237 |
+
next_idx_interactive = selected_idx < available_indices[-1] if available_indices else False
|
| 238 |
+
|
| 239 |
+
# Calculate current video number
|
| 240 |
+
all_keys = sorted(set(video_map1.keys()) & set(video_map2.keys()))
|
| 241 |
+
current_idx = all_keys.index(key) + 1
|
| 242 |
+
progress = f"{current_idx} / {len(all_keys)}"
|
| 243 |
+
|
| 244 |
+
return (
|
| 245 |
+
video1_path,
|
| 246 |
+
video2_path,
|
| 247 |
+
info,
|
| 248 |
+
gr.update(interactive=prev_step_interactive),
|
| 249 |
+
gr.update(interactive=next_step_interactive),
|
| 250 |
+
gr.update(interactive=prev_idx_interactive),
|
| 251 |
+
gr.update(interactive=next_idx_interactive),
|
| 252 |
+
progress,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def navigate_step(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction):
|
| 257 |
+
"""Navigate to previous or next step"""
|
| 258 |
+
if not step_idx_map or current_step is None:
|
| 259 |
+
return (
|
| 260 |
+
None,
|
| 261 |
+
None,
|
| 262 |
+
"Please load videos first",
|
| 263 |
+
current_step,
|
| 264 |
+
current_idx,
|
| 265 |
+
gr.update(),
|
| 266 |
+
gr.update(),
|
| 267 |
+
gr.update(),
|
| 268 |
+
gr.update(),
|
| 269 |
+
"",
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
all_steps = sorted(step_idx_map.keys())
|
| 273 |
+
current_step_idx = all_steps.index(current_step)
|
| 274 |
+
|
| 275 |
+
if direction == "prev":
|
| 276 |
+
new_step_idx = max(0, current_step_idx - 1)
|
| 277 |
+
else: # next
|
| 278 |
+
new_step_idx = min(len(all_steps) - 1, current_step_idx + 1)
|
| 279 |
+
|
| 280 |
+
new_step = all_steps[new_step_idx]
|
| 281 |
+
|
| 282 |
+
# Get first available index for new step
|
| 283 |
+
available_indices = step_idx_map.get(new_step, [])
|
| 284 |
+
new_idx = available_indices[0] if available_indices else current_idx
|
| 285 |
+
|
| 286 |
+
return update_videos_from_selectors(folder1, folder2, new_step, new_idx, video_map1, video_map2, step_idx_map) + (
|
| 287 |
+
new_step,
|
| 288 |
+
new_idx,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def navigate_idx(folder1, folder2, current_step, current_idx, video_map1, video_map2, step_idx_map, direction):
|
| 293 |
+
"""Navigate to previous or next index"""
|
| 294 |
+
if not step_idx_map or current_step is None or current_idx is None:
|
| 295 |
+
return (
|
| 296 |
+
None,
|
| 297 |
+
None,
|
| 298 |
+
"Please load videos first",
|
| 299 |
+
current_step,
|
| 300 |
+
current_idx,
|
| 301 |
+
gr.update(),
|
| 302 |
+
gr.update(),
|
| 303 |
+
gr.update(),
|
| 304 |
+
gr.update(),
|
| 305 |
+
"",
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
available_indices = step_idx_map.get(current_step, [])
|
| 309 |
+
if not available_indices or current_idx not in available_indices:
|
| 310 |
+
return (
|
| 311 |
+
None,
|
| 312 |
+
None,
|
| 313 |
+
"Index not in list",
|
| 314 |
+
current_step,
|
| 315 |
+
current_idx,
|
| 316 |
+
gr.update(),
|
| 317 |
+
gr.update(),
|
| 318 |
+
gr.update(),
|
| 319 |
+
gr.update(),
|
| 320 |
+
"",
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
current_idx_pos = available_indices.index(current_idx)
|
| 324 |
+
|
| 325 |
+
if direction == "prev":
|
| 326 |
+
new_idx_pos = max(0, current_idx_pos - 1)
|
| 327 |
+
else: # next
|
| 328 |
+
new_idx_pos = min(len(available_indices) - 1, current_idx_pos + 1)
|
| 329 |
+
|
| 330 |
+
new_idx = available_indices[new_idx_pos]
|
| 331 |
+
|
| 332 |
+
return update_videos_from_selectors(
|
| 333 |
+
folder1, folder2, current_step, new_idx, video_map1, video_map2, step_idx_map
|
| 334 |
+
) + (current_step, new_idx)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# Create Gradio interface
|
| 338 |
+
with gr.Blocks(title="Video Comparison Tool") as demo:
|
| 339 |
+
gr.Markdown("# Video Comparison Tool")
|
| 340 |
+
gr.Markdown(
|
| 341 |
+
"Enter two folder paths to automatically match and compare videos with the same naming (matched by step and index, ignoring filename prefix)"
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
# Store state
|
| 345 |
+
video_map1_state = gr.State({})
|
| 346 |
+
video_map2_state = gr.State({})
|
| 347 |
+
step_idx_map_state = gr.State({})
|
| 348 |
+
|
| 349 |
+
with gr.Row():
|
| 350 |
+
folder1_input = gr.Textbox(label="Folder 1 Path", placeholder="/path/to/folder1", scale=2)
|
| 351 |
+
folder2_input = gr.Textbox(label="Folder 2 Path", placeholder="/path/to/folder2", scale=2)
|
| 352 |
+
|
| 353 |
+
load_btn = gr.Button("Load Videos", variant="primary")
|
| 354 |
+
|
| 355 |
+
info_text = gr.Textbox(label="Info", interactive=False, lines=4)
|
| 356 |
+
|
| 357 |
+
# Step navigation controls
|
| 358 |
+
with gr.Row():
|
| 359 |
+
prev_step_btn = gr.Button("⬅️ Previous Step", interactive=False, scale=1)
|
| 360 |
+
step_selector = gr.Dropdown(label="Select Step", choices=[], interactive=True, scale=2)
|
| 361 |
+
next_step_btn = gr.Button("Next Step ➡️", interactive=False, scale=1)
|
| 362 |
+
|
| 363 |
+
# Index navigation controls
|
| 364 |
+
with gr.Row():
|
| 365 |
+
prev_idx_btn = gr.Button("⬅️ Previous Index", interactive=False, scale=1)
|
| 366 |
+
idx_selector = gr.Dropdown(label="Select Index", choices=[], interactive=True, scale=2)
|
| 367 |
+
next_idx_btn = gr.Button("Next Index ➡️", interactive=False, scale=1)
|
| 368 |
+
|
| 369 |
+
progress_text = gr.Textbox(label="Progress", value="0 / 0", interactive=False)
|
| 370 |
+
|
| 371 |
+
with gr.Row():
|
| 372 |
+
with gr.Column():
|
| 373 |
+
gr.Markdown("### Folder 1")
|
| 374 |
+
video1 = gr.Video(label="Video 1", autoplay=True, loop=True)
|
| 375 |
+
|
| 376 |
+
with gr.Column():
|
| 377 |
+
gr.Markdown("### Folder 2")
|
| 378 |
+
video2 = gr.Video(label="Video 2", autoplay=True, loop=True)
|
| 379 |
+
|
| 380 |
+
# Event bindings
|
| 381 |
+
load_btn.click(
|
| 382 |
+
fn=load_videos,
|
| 383 |
+
inputs=[folder1_input, folder2_input],
|
| 384 |
+
outputs=[
|
| 385 |
+
video1,
|
| 386 |
+
video2,
|
| 387 |
+
info_text,
|
| 388 |
+
step_selector,
|
| 389 |
+
idx_selector,
|
| 390 |
+
prev_step_btn,
|
| 391 |
+
next_step_btn,
|
| 392 |
+
prev_idx_btn,
|
| 393 |
+
next_idx_btn,
|
| 394 |
+
progress_text,
|
| 395 |
+
video_map1_state,
|
| 396 |
+
video_map2_state,
|
| 397 |
+
step_idx_map_state,
|
| 398 |
+
],
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# When step changes, update available indices
|
| 402 |
+
step_selector.change(
|
| 403 |
+
fn=update_available_indices, inputs=[step_selector, step_idx_map_state], outputs=[idx_selector]
|
| 404 |
+
).then(
|
| 405 |
+
fn=update_videos_from_selectors,
|
| 406 |
+
inputs=[
|
| 407 |
+
folder1_input,
|
| 408 |
+
folder2_input,
|
| 409 |
+
step_selector,
|
| 410 |
+
idx_selector,
|
| 411 |
+
video_map1_state,
|
| 412 |
+
video_map2_state,
|
| 413 |
+
step_idx_map_state,
|
| 414 |
+
],
|
| 415 |
+
outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text],
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# When index changes, update videos
|
| 419 |
+
idx_selector.change(
|
| 420 |
+
fn=update_videos_from_selectors,
|
| 421 |
+
inputs=[
|
| 422 |
+
folder1_input,
|
| 423 |
+
folder2_input,
|
| 424 |
+
step_selector,
|
| 425 |
+
idx_selector,
|
| 426 |
+
video_map1_state,
|
| 427 |
+
video_map2_state,
|
| 428 |
+
step_idx_map_state,
|
| 429 |
+
],
|
| 430 |
+
outputs=[video1, video2, info_text, prev_step_btn, next_step_btn, prev_idx_btn, next_idx_btn, progress_text],
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
# Step navigation buttons
|
| 434 |
+
prev_step_btn.click(
|
| 435 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "prev"),
|
| 436 |
+
inputs=[
|
| 437 |
+
folder1_input,
|
| 438 |
+
folder2_input,
|
| 439 |
+
step_selector,
|
| 440 |
+
idx_selector,
|
| 441 |
+
video_map1_state,
|
| 442 |
+
video_map2_state,
|
| 443 |
+
step_idx_map_state,
|
| 444 |
+
],
|
| 445 |
+
outputs=[
|
| 446 |
+
video1,
|
| 447 |
+
video2,
|
| 448 |
+
info_text,
|
| 449 |
+
prev_step_btn,
|
| 450 |
+
next_step_btn,
|
| 451 |
+
prev_idx_btn,
|
| 452 |
+
next_idx_btn,
|
| 453 |
+
progress_text,
|
| 454 |
+
step_selector,
|
| 455 |
+
idx_selector,
|
| 456 |
+
],
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
next_step_btn.click(
|
| 460 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_step(f1, f2, s, i, vm1, vm2, sim, "next"),
|
| 461 |
+
inputs=[
|
| 462 |
+
folder1_input,
|
| 463 |
+
folder2_input,
|
| 464 |
+
step_selector,
|
| 465 |
+
idx_selector,
|
| 466 |
+
video_map1_state,
|
| 467 |
+
video_map2_state,
|
| 468 |
+
step_idx_map_state,
|
| 469 |
+
],
|
| 470 |
+
outputs=[
|
| 471 |
+
video1,
|
| 472 |
+
video2,
|
| 473 |
+
info_text,
|
| 474 |
+
prev_step_btn,
|
| 475 |
+
next_step_btn,
|
| 476 |
+
prev_idx_btn,
|
| 477 |
+
next_idx_btn,
|
| 478 |
+
progress_text,
|
| 479 |
+
step_selector,
|
| 480 |
+
idx_selector,
|
| 481 |
+
],
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
# Index navigation buttons
|
| 485 |
+
prev_idx_btn.click(
|
| 486 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "prev"),
|
| 487 |
+
inputs=[
|
| 488 |
+
folder1_input,
|
| 489 |
+
folder2_input,
|
| 490 |
+
step_selector,
|
| 491 |
+
idx_selector,
|
| 492 |
+
video_map1_state,
|
| 493 |
+
video_map2_state,
|
| 494 |
+
step_idx_map_state,
|
| 495 |
+
],
|
| 496 |
+
outputs=[
|
| 497 |
+
video1,
|
| 498 |
+
video2,
|
| 499 |
+
info_text,
|
| 500 |
+
prev_step_btn,
|
| 501 |
+
next_step_btn,
|
| 502 |
+
prev_idx_btn,
|
| 503 |
+
next_idx_btn,
|
| 504 |
+
progress_text,
|
| 505 |
+
step_selector,
|
| 506 |
+
idx_selector,
|
| 507 |
+
],
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
next_idx_btn.click(
|
| 511 |
+
fn=lambda f1, f2, s, i, vm1, vm2, sim: navigate_idx(f1, f2, s, i, vm1, vm2, sim, "next"),
|
| 512 |
+
inputs=[
|
| 513 |
+
folder1_input,
|
| 514 |
+
folder2_input,
|
| 515 |
+
step_selector,
|
| 516 |
+
idx_selector,
|
| 517 |
+
video_map1_state,
|
| 518 |
+
video_map2_state,
|
| 519 |
+
step_idx_map_state,
|
| 520 |
+
],
|
| 521 |
+
outputs=[
|
| 522 |
+
video1,
|
| 523 |
+
video2,
|
| 524 |
+
info_text,
|
| 525 |
+
prev_step_btn,
|
| 526 |
+
next_step_btn,
|
| 527 |
+
prev_idx_btn,
|
| 528 |
+
next_idx_btn,
|
| 529 |
+
progress_text,
|
| 530 |
+
step_selector,
|
| 531 |
+
idx_selector,
|
| 532 |
+
],
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
if __name__ == "__main__":
|
| 536 |
+
demo.launch(share=True, allowed_paths=["0_ablation_videos"])
|
Helios-main/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-main/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-main/tools/offload_data/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# <u>Data Preprocessing Pipeline</u> by *Helios*
|
| 2 |
+
This repository describes the data preprocessing pipeline used in the [Helios](https://arxiv.org/abs/2603.04379) paper. And we prepare a toy training data [here](https://huggingface.co/BestWishYsh/HeliosBench-Weights/tree/main/demo_data).
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
## ⚙️ Requirements and Installation
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
### Environment
|
| 9 |
+
|
| 10 |
+
```bash
|
| 11 |
+
# Activate conda environment
|
| 12 |
+
conda activate helios
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## 🗝️ Usage
|
| 16 |
+
|
| 17 |
+
### Step 1 - Prepare Metadata and Organize Videos
|
| 18 |
+
|
| 19 |
+
To train your own video generation model, create JSON files following this [format](./example/toy_data/toy_filter.json):
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
[
|
| 23 |
+
{
|
| 24 |
+
"cut": [0, 81],
|
| 25 |
+
"crop": [0, 832, 0, 480],
|
| 26 |
+
"fps": 24.0,
|
| 27 |
+
"num_frames": 81,
|
| 28 |
+
"resolution": {
|
| 29 |
+
"height": 480,
|
| 30 |
+
"width": 832
|
| 31 |
+
},
|
| 32 |
+
"cap": [
|
| 33 |
+
"A stunning mid-afternoon ..."
|
| 34 |
+
],
|
| 35 |
+
"path": "videos/2_240_ori81.mp4"
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"cut": [0, 81],
|
| 39 |
+
...
|
| 40 |
+
}
|
| 41 |
+
...
|
| 42 |
+
]
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
and arrange video files following this [structure](./example):
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
📦 example/
|
| 49 |
+
├── 📂 toy_data/
|
| 50 |
+
│ ├── 📂 videos
|
| 51 |
+
│ │ ├── 2_240_ori81.mp4
|
| 52 |
+
│ │ ├── 239_120_ori129.mp4.mp4
|
| 53 |
+
│ │ └── ...
|
| 54 |
+
│ └── 📄 toy_data_1.json
|
| 55 |
+
│
|
| 56 |
+
├── 📂 toy_data_2/
|
| 57 |
+
│ │ ├── A.mp4
|
| 58 |
+
│ │ ├── B.mp4
|
| 59 |
+
│ │ └── ...
|
| 60 |
+
│ └── 📄 toy_data_2.json
|
| 61 |
+
...
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
### Step 2 - Prepare Autoregressive Real Data
|
| 65 |
+
|
| 66 |
+
These data can be used for training Stage-1, Stage-2, and Stage-3.
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
# Remember to modify the input and output paths before running
|
| 70 |
+
bash get_short-latents.py
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### Step 3 - Prepare Autoregressive ODE Data
|
| 74 |
+
|
| 75 |
+
These data can only be used for training Stage-3.
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
# Remember to modify the input and output paths before running
|
| 79 |
+
bash get_ode-pairs.sh
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
### (Optional) Step 4 - Prepare Text Data
|
| 83 |
+
|
| 84 |
+
If you want to use the [Self-Forcing](https://github.com/guandeh17/Self-Forcing) training approach, prepare text embeddings:
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
# Remember to modify the input and output paths before running
|
| 88 |
+
bash get_text-embedding.sh
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## 🔒 Acknowledgement
|
| 92 |
+
|
| 93 |
+
* This project wouldn't be possible without the following open-sourced repositories: [OpenSora Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan), [OpenSora](https://github.com/hpcaitech/Open-Sora), [Video-Dataset-Scripts](https://github.com/huggingface/video-dataset-scripts)
|
Helios-main/tools/offload_data/get_long-latents.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
import torchvision.transforms as transforms
|
| 7 |
+
from accelerate import Accelerator
|
| 8 |
+
from helios.dataset.dataloader_mp4_dist import BucketedFeatureDataset, BucketedSampler, collate_fn
|
| 9 |
+
from helios.utils.utils_base import encode_prompt
|
| 10 |
+
from torch.utils.data import DataLoader
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 13 |
+
|
| 14 |
+
from diffusers import AutoencoderKLWan
|
| 15 |
+
from diffusers.training_utils import free_memory
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def setup_distributed_env():
|
| 19 |
+
dist.init_process_group(backend="nccl")
|
| 20 |
+
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def cleanup_distributed_env():
|
| 24 |
+
dist.destroy_process_group()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main(
|
| 28 |
+
rank,
|
| 29 |
+
world_size,
|
| 30 |
+
global_rank,
|
| 31 |
+
stride,
|
| 32 |
+
batch_size,
|
| 33 |
+
dataloader_num_workers,
|
| 34 |
+
json_file,
|
| 35 |
+
video_folder,
|
| 36 |
+
output_latent_folder,
|
| 37 |
+
pretrained_model_name_or_path,
|
| 38 |
+
resolution=640,
|
| 39 |
+
):
|
| 40 |
+
weight_dtype = torch.bfloat16
|
| 41 |
+
device = rank
|
| 42 |
+
seed = 42
|
| 43 |
+
|
| 44 |
+
# Load the tokenizers
|
| 45 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 46 |
+
pretrained_model_name_or_path,
|
| 47 |
+
subfolder="tokenizer",
|
| 48 |
+
)
|
| 49 |
+
text_encoder = UMT5EncoderModel.from_pretrained(
|
| 50 |
+
pretrained_model_name_or_path,
|
| 51 |
+
subfolder="text_encoder",
|
| 52 |
+
torch_dtype=weight_dtype,
|
| 53 |
+
)
|
| 54 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 55 |
+
pretrained_model_name_or_path,
|
| 56 |
+
subfolder="vae",
|
| 57 |
+
torch_dtype=torch.float32,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(device, weight_dtype)
|
| 61 |
+
latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to(
|
| 62 |
+
device, weight_dtype
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
vae.eval()
|
| 66 |
+
vae.requires_grad_(False)
|
| 67 |
+
text_encoder.eval()
|
| 68 |
+
text_encoder.requires_grad_(False)
|
| 69 |
+
|
| 70 |
+
vae = vae.to(device)
|
| 71 |
+
text_encoder = text_encoder.to(device)
|
| 72 |
+
|
| 73 |
+
# dist.barrier()
|
| 74 |
+
dataset = BucketedFeatureDataset(
|
| 75 |
+
json_files=json_file,
|
| 76 |
+
video_folders=video_folder,
|
| 77 |
+
stride=stride,
|
| 78 |
+
force_rebuild=False,
|
| 79 |
+
resolution=resolution,
|
| 80 |
+
single_res=True,
|
| 81 |
+
single_height=384,
|
| 82 |
+
single_width=640,
|
| 83 |
+
single_length=True,
|
| 84 |
+
single_num_frame=81,
|
| 85 |
+
)
|
| 86 |
+
sampler = BucketedSampler(dataset, batch_size=batch_size, drop_last=False, shuffle=True, seed=seed)
|
| 87 |
+
dataloader = DataLoader(
|
| 88 |
+
dataset,
|
| 89 |
+
batch_sampler=sampler,
|
| 90 |
+
collate_fn=collate_fn,
|
| 91 |
+
num_workers=dataloader_num_workers,
|
| 92 |
+
pin_memory=True,
|
| 93 |
+
prefetch_factor=2 if dataloader_num_workers != 0 else None,
|
| 94 |
+
# persistent_workers=True if dataloader_num_workers > 0 else False,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
print(len(dataset), len(dataloader))
|
| 98 |
+
accelerator = Accelerator()
|
| 99 |
+
dataloader = accelerator.prepare(dataloader)
|
| 100 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 101 |
+
print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}")
|
| 102 |
+
|
| 103 |
+
sampler.set_epoch(0)
|
| 104 |
+
if rank == 0:
|
| 105 |
+
pbar = tqdm(total=len(dataloader), desc="Processing")
|
| 106 |
+
# dist.barrier()
|
| 107 |
+
for idx, batch in enumerate(dataloader):
|
| 108 |
+
if batch is None or batch["videos"] is None:
|
| 109 |
+
print("None batch, continuing")
|
| 110 |
+
continue
|
| 111 |
+
free_memory()
|
| 112 |
+
|
| 113 |
+
valid_indices = []
|
| 114 |
+
valid_uttids = []
|
| 115 |
+
valid_num_frames = []
|
| 116 |
+
valid_heights = []
|
| 117 |
+
valid_widths = []
|
| 118 |
+
valid_videos = []
|
| 119 |
+
valid_prompts = []
|
| 120 |
+
valid_first_frames_images = []
|
| 121 |
+
|
| 122 |
+
if batch["uttid"] is None:
|
| 123 |
+
print("None batch, contiuning")
|
| 124 |
+
continue
|
| 125 |
+
|
| 126 |
+
for i, (uttid, num_frame, height, width) in enumerate(
|
| 127 |
+
zip(
|
| 128 |
+
batch["uttid"],
|
| 129 |
+
batch["video_metadata"]["num_frames"],
|
| 130 |
+
batch["video_metadata"]["height"],
|
| 131 |
+
batch["video_metadata"]["width"],
|
| 132 |
+
)
|
| 133 |
+
):
|
| 134 |
+
os.makedirs(output_latent_folder, exist_ok=True)
|
| 135 |
+
output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt")
|
| 136 |
+
if not os.path.exists(output_path):
|
| 137 |
+
valid_indices.append(i)
|
| 138 |
+
valid_uttids.append(uttid)
|
| 139 |
+
valid_num_frames.append(num_frame)
|
| 140 |
+
valid_heights.append(height)
|
| 141 |
+
valid_widths.append(width)
|
| 142 |
+
valid_videos.append(batch["videos"][i])
|
| 143 |
+
valid_prompts.append(batch["prompts"][i])
|
| 144 |
+
valid_first_frames_images.append(batch["first_frames_images"][i])
|
| 145 |
+
else:
|
| 146 |
+
print(f"skipping {uttid}")
|
| 147 |
+
|
| 148 |
+
if not valid_indices:
|
| 149 |
+
print("skipping entire batch!")
|
| 150 |
+
if rank == 0:
|
| 151 |
+
pbar.update(1)
|
| 152 |
+
pbar.set_postfix({"batch": idx})
|
| 153 |
+
continue
|
| 154 |
+
|
| 155 |
+
batch = None
|
| 156 |
+
del batch
|
| 157 |
+
free_memory()
|
| 158 |
+
|
| 159 |
+
batch = {
|
| 160 |
+
"uttid": valid_uttids,
|
| 161 |
+
"video_metadata": {"num_frames": valid_num_frames, "height": valid_heights, "width": valid_widths},
|
| 162 |
+
"videos": torch.stack(valid_videos),
|
| 163 |
+
"prompts": valid_prompts,
|
| 164 |
+
"first_frames_images": torch.stack(valid_first_frames_images),
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
if len(batch["uttid"]) == 0:
|
| 168 |
+
print("All samples in this batch are already processed, skipping!")
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
with torch.no_grad():
|
| 172 |
+
# Get Vae feature
|
| 173 |
+
pixel_values = batch["videos"].permute(0, 2, 1, 3, 4).to(dtype=vae.dtype, device=device)
|
| 174 |
+
vae_latents = vae.encode(pixel_values).latent_dist.sample()
|
| 175 |
+
vae_latents = (vae_latents - latents_mean) * latents_std
|
| 176 |
+
|
| 177 |
+
# Encode prompts
|
| 178 |
+
prompts = batch["prompts"]
|
| 179 |
+
prompt_embeds, prompt_attention_mask = encode_prompt(
|
| 180 |
+
tokenizer=tokenizer,
|
| 181 |
+
text_encoder=text_encoder,
|
| 182 |
+
prompt=prompts,
|
| 183 |
+
device=device,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
image_tensor = batch["first_frames_images"]
|
| 187 |
+
images = [transforms.ToPILImage()(x.to(torch.uint8)) for x in image_tensor]
|
| 188 |
+
|
| 189 |
+
for (
|
| 190 |
+
uttid,
|
| 191 |
+
num_frame,
|
| 192 |
+
height,
|
| 193 |
+
width,
|
| 194 |
+
cur_vae_latent,
|
| 195 |
+
cur_prompt_embed,
|
| 196 |
+
cur_prompt_attention_mask,
|
| 197 |
+
cur_first_frames_image,
|
| 198 |
+
cur_prompt,
|
| 199 |
+
) in zip(
|
| 200 |
+
batch["uttid"],
|
| 201 |
+
batch["video_metadata"]["num_frames"],
|
| 202 |
+
batch["video_metadata"]["height"],
|
| 203 |
+
batch["video_metadata"]["width"],
|
| 204 |
+
vae_latents,
|
| 205 |
+
prompt_embeds,
|
| 206 |
+
prompt_attention_mask,
|
| 207 |
+
images,
|
| 208 |
+
prompts,
|
| 209 |
+
):
|
| 210 |
+
output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt")
|
| 211 |
+
temp_to_save = {
|
| 212 |
+
"vae_latent": cur_vae_latent.cpu().detach(),
|
| 213 |
+
"prompt_embed": cur_prompt_embed.cpu().detach(),
|
| 214 |
+
# "prompt_attention_mask": cur_prompt_attention_mask.cpu().detach(),
|
| 215 |
+
"first_frames_image": cur_first_frames_image,
|
| 216 |
+
"prompt_raw": cur_prompt,
|
| 217 |
+
}
|
| 218 |
+
try:
|
| 219 |
+
torch.save(temp_to_save, output_path)
|
| 220 |
+
except Exception:
|
| 221 |
+
continue
|
| 222 |
+
print(f"save latent to: {output_path}")
|
| 223 |
+
|
| 224 |
+
if rank == 0:
|
| 225 |
+
pbar.update(1)
|
| 226 |
+
pbar.set_postfix({"batch": idx})
|
| 227 |
+
|
| 228 |
+
pixel_values = None
|
| 229 |
+
prompts = None
|
| 230 |
+
image_tensor = None
|
| 231 |
+
images = None
|
| 232 |
+
vae_latents = None
|
| 233 |
+
vae_latents_2 = None
|
| 234 |
+
image_embeds = None
|
| 235 |
+
prompt_embeds = None
|
| 236 |
+
batch = None
|
| 237 |
+
valid_indices = None
|
| 238 |
+
valid_uttids = None
|
| 239 |
+
valid_num_frames = None
|
| 240 |
+
valid_heights = None
|
| 241 |
+
valid_widths = None
|
| 242 |
+
valid_videos = None
|
| 243 |
+
valid_prompts = None
|
| 244 |
+
valid_first_frames_images = None
|
| 245 |
+
temp_to_save = None
|
| 246 |
+
|
| 247 |
+
del pixel_values
|
| 248 |
+
del prompts
|
| 249 |
+
del image_tensor
|
| 250 |
+
del images
|
| 251 |
+
del vae_latents
|
| 252 |
+
del vae_latents_2
|
| 253 |
+
del image_embeds
|
| 254 |
+
del batch
|
| 255 |
+
del valid_indices
|
| 256 |
+
del valid_uttids
|
| 257 |
+
del valid_num_frames
|
| 258 |
+
del valid_heights
|
| 259 |
+
del valid_widths
|
| 260 |
+
del valid_videos
|
| 261 |
+
del valid_prompts
|
| 262 |
+
del valid_first_frames_images
|
| 263 |
+
del temp_to_save
|
| 264 |
+
|
| 265 |
+
free_memory()
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
if __name__ == "__main__":
|
| 269 |
+
parser = argparse.ArgumentParser(description="Script for running model training and data processing.")
|
| 270 |
+
parser.add_argument("--dataloader_num_workers", type=int, default=8, help="Number of workers for data loading")
|
| 271 |
+
parser.add_argument(
|
| 272 |
+
"--pretrained_model_name_or_path",
|
| 273 |
+
type=str,
|
| 274 |
+
default="BestWishYsh/Helios-Base",
|
| 275 |
+
help="Pretrained model path",
|
| 276 |
+
)
|
| 277 |
+
args = parser.parse_args()
|
| 278 |
+
|
| 279 |
+
setup_distributed_env()
|
| 280 |
+
|
| 281 |
+
global_rank = dist.get_rank()
|
| 282 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 283 |
+
device = torch.cuda.current_device()
|
| 284 |
+
world_size = dist.get_world_size()
|
| 285 |
+
|
| 286 |
+
base_video_path = "example"
|
| 287 |
+
video_paths = [
|
| 288 |
+
"toy_data",
|
| 289 |
+
]
|
| 290 |
+
|
| 291 |
+
base_output_latent_path = "example/toy_data/latents_long"
|
| 292 |
+
output_latent_paths = [
|
| 293 |
+
"toy_data",
|
| 294 |
+
]
|
| 295 |
+
|
| 296 |
+
base_csv_paths = [
|
| 297 |
+
"example",
|
| 298 |
+
]
|
| 299 |
+
csv_paths = [
|
| 300 |
+
"toy_data/toy_filter.json",
|
| 301 |
+
]
|
| 302 |
+
|
| 303 |
+
resolutions = [640]
|
| 304 |
+
strides = [1]
|
| 305 |
+
batch_sizes = [4]
|
| 306 |
+
|
| 307 |
+
for stride, batch_size, base_csv_path, csv_path, video_path, output_latent_path, cur_resolution in zip(
|
| 308 |
+
strides, batch_sizes, base_csv_paths, csv_paths, video_paths, output_latent_paths, resolutions
|
| 309 |
+
):
|
| 310 |
+
json_file = os.path.join(base_csv_path, csv_path)
|
| 311 |
+
video_folder = os.path.join(base_video_path, video_path)
|
| 312 |
+
output_latent_folder = os.path.join(base_output_latent_path, output_latent_path)
|
| 313 |
+
|
| 314 |
+
main(
|
| 315 |
+
rank=device,
|
| 316 |
+
world_size=world_size,
|
| 317 |
+
global_rank=global_rank,
|
| 318 |
+
stride=stride,
|
| 319 |
+
batch_size=batch_size,
|
| 320 |
+
dataloader_num_workers=args.dataloader_num_workers,
|
| 321 |
+
json_file=json_file,
|
| 322 |
+
video_folder=video_folder,
|
| 323 |
+
output_latent_folder=output_latent_folder,
|
| 324 |
+
pretrained_model_name_or_path=args.pretrained_model_name_or_path,
|
| 325 |
+
resolution=cur_resolution,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
dist.barrier()
|
| 329 |
+
dist.destroy_process_group()
|
Helios-main/tools/offload_data/get_long-latents.sh
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export OMNISTORE_LOAD_STRICT_MODE=0
|
| 2 |
+
export OMNISTORE_LOGGING_LEVEL=ERROR
|
| 3 |
+
#################################################################
|
| 4 |
+
## Torch
|
| 5 |
+
#################################################################
|
| 6 |
+
export TOKENIZERS_PARALLELISM=false
|
| 7 |
+
export TORCH_LOGS="+dynamo,recompiles,graph_breaks"
|
| 8 |
+
export TORCHDYNAMO_VERBOSE=1
|
| 9 |
+
export TORCH_NCCL_ENABLE_MONITORING=1
|
| 10 |
+
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9"
|
| 11 |
+
#################################################################
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
#################################################################
|
| 15 |
+
## NCCL
|
| 16 |
+
#################################################################
|
| 17 |
+
export NCCL_IB_GID_INDEX=3
|
| 18 |
+
export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE
|
| 19 |
+
export NCCL_SOCKET_IFNAME=eth0
|
| 20 |
+
export NCCL_SOCKET_TIMEOUT=3600000
|
| 21 |
+
|
| 22 |
+
export NCCL_DEBUG=WARN # disable the verbose NCCL logs
|
| 23 |
+
export NCCL_P2P_DISABLE=0
|
| 24 |
+
export NCCL_IB_DISABLE=0 # was 1
|
| 25 |
+
export NCCL_SHM_DISABLE=0 # was 1
|
| 26 |
+
export NCCL_P2P_LEVEL=NVL
|
| 27 |
+
|
| 28 |
+
export NCCL_PXN_DISABLE=0
|
| 29 |
+
export NCCL_NET_GDR_LEVEL=2
|
| 30 |
+
export NCCL_IB_QPS_PER_CONNECTION=4
|
| 31 |
+
export NCCL_IB_TC=160
|
| 32 |
+
export NCCL_IB_TIMEOUT=22
|
| 33 |
+
#################################################################
|
| 34 |
+
|
| 35 |
+
#################################################################
|
| 36 |
+
## DIST
|
| 37 |
+
#################################################################
|
| 38 |
+
MASTER_ADDR=$ARNOLD_WORKER_0_HOST
|
| 39 |
+
ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
|
| 40 |
+
MASTER_PORT=${ports[0]}
|
| 41 |
+
NNODES=$ARNOLD_WORKER_NUM
|
| 42 |
+
NODE_RANK=$ARNOLD_ID
|
| 43 |
+
GPUS_PER_NODE=$ARNOLD_WORKER_GPU
|
| 44 |
+
|
| 45 |
+
# export CUDA_VISIBLE_DEVICES=1
|
| 46 |
+
# MASTER_PORT=12345
|
| 47 |
+
# GPUS_PER_NODE=1
|
| 48 |
+
# NNODES=1
|
| 49 |
+
# NODE_RANK=0
|
| 50 |
+
|
| 51 |
+
WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
|
| 52 |
+
|
| 53 |
+
DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
|
| 54 |
+
if [ ! -z $RDZV_BACKEND ]; then
|
| 55 |
+
DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d"
|
| 56 |
+
export NCCL_SHM_DISABLE=1
|
| 57 |
+
fi
|
| 58 |
+
|
| 59 |
+
echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m"
|
| 60 |
+
|
| 61 |
+
#################################################################
|
| 62 |
+
#
|
| 63 |
+
torchrun $DISTRIBUTED_ARGS \
|
| 64 |
+
tools/offload_data/get_long-latents.py
|
Helios-main/tools/offload_data/get_ode-pairs.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 argparse
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.distributed as dist
|
| 12 |
+
from accelerate import Accelerator
|
| 13 |
+
from helios.modules.helios_kernels import (
|
| 14 |
+
replace_all_norms_with_flash_norms,
|
| 15 |
+
replace_rmsnorm_with_fp32,
|
| 16 |
+
replace_rope_with_flash_rope,
|
| 17 |
+
)
|
| 18 |
+
from helios.modules.transformer_helios import HeliosTransformer3DModel
|
| 19 |
+
from helios.pipelines.pipeline_helios_ode import HeliosPipeline
|
| 20 |
+
from helios.scheduler.scheduling_helios import HeliosScheduler
|
| 21 |
+
from helios.utils.utils_base import encode_prompt, load_extra_components
|
| 22 |
+
from torch.utils.data import DataLoader, Dataset
|
| 23 |
+
from tqdm import tqdm
|
| 24 |
+
|
| 25 |
+
from diffusers.models import AutoencoderKLWan
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def setup_distributed_env():
|
| 29 |
+
dist.init_process_group(backend="nccl")
|
| 30 |
+
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def check_file_exists(args):
|
| 34 |
+
basename, idx, line, output_folder = args
|
| 35 |
+
uttid = f"{basename}_{idx:05d}"
|
| 36 |
+
output_path = os.path.join(output_folder, f"{uttid}.pt")
|
| 37 |
+
if os.path.exists(output_path):
|
| 38 |
+
return None, None
|
| 39 |
+
return line.strip(), uttid
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def prepare_dataset_on_rank0(txt_file, output_folder, rank):
|
| 43 |
+
while True:
|
| 44 |
+
try:
|
| 45 |
+
if rank == 0:
|
| 46 |
+
basename = Path(txt_file).stem
|
| 47 |
+
output_dir = Path(output_folder)
|
| 48 |
+
|
| 49 |
+
existing_files = set()
|
| 50 |
+
if output_dir.exists():
|
| 51 |
+
existing_files = {f.name for f in output_dir.iterdir() if f.is_file()}
|
| 52 |
+
|
| 53 |
+
prompts = []
|
| 54 |
+
uttids = []
|
| 55 |
+
|
| 56 |
+
with open(txt_file, "r") as f:
|
| 57 |
+
for idx, line in enumerate(f):
|
| 58 |
+
if not line.strip():
|
| 59 |
+
continue
|
| 60 |
+
|
| 61 |
+
uttid = f"{basename}_{idx:05d}"
|
| 62 |
+
filename = f"{uttid}.pt"
|
| 63 |
+
|
| 64 |
+
if filename not in existing_files:
|
| 65 |
+
prompts.append(line.strip())
|
| 66 |
+
uttids.append(uttid)
|
| 67 |
+
|
| 68 |
+
data_to_broadcast = [prompts, uttids]
|
| 69 |
+
else:
|
| 70 |
+
data_to_broadcast = [None, None]
|
| 71 |
+
|
| 72 |
+
dist.broadcast_object_list(data_to_broadcast, src=0)
|
| 73 |
+
break
|
| 74 |
+
except Exception:
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
return data_to_broadcast[0], data_to_broadcast[1]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class PromptDataset(Dataset):
|
| 81 |
+
def __init__(self, prompts, uttids):
|
| 82 |
+
self.prompts = prompts
|
| 83 |
+
self.uttids = uttids
|
| 84 |
+
|
| 85 |
+
def __len__(self):
|
| 86 |
+
return len(self.prompts)
|
| 87 |
+
|
| 88 |
+
def __getitem__(self, idx):
|
| 89 |
+
return {"prompt": self.prompts[idx], "uttid": self.uttids[idx]}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def main():
|
| 93 |
+
args = parse_args()
|
| 94 |
+
|
| 95 |
+
# =============== Environment ===============
|
| 96 |
+
batch_size = 1
|
| 97 |
+
dataloader_num_workers = 8
|
| 98 |
+
feature_folders = [
|
| 99 |
+
"example/vidprom_first_1k.txt",
|
| 100 |
+
]
|
| 101 |
+
output_folders = [
|
| 102 |
+
"example/toy_data/ode_pairs/vidprom_filtered_extended",
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
if args.weight_dtype == "fp32":
|
| 106 |
+
args.weight_dtype = torch.float32
|
| 107 |
+
elif args.weight_dtype == "fp16":
|
| 108 |
+
args.weight_dtype = torch.float16
|
| 109 |
+
else:
|
| 110 |
+
args.weight_dtype = torch.bfloat16
|
| 111 |
+
|
| 112 |
+
setup_distributed_env()
|
| 113 |
+
|
| 114 |
+
rank = int(os.environ["LOCAL_RANK"])
|
| 115 |
+
device = torch.cuda.current_device()
|
| 116 |
+
|
| 117 |
+
accelerator = Accelerator()
|
| 118 |
+
|
| 119 |
+
# =============== Prepare Model ===============
|
| 120 |
+
transformer = HeliosTransformer3DModel.from_pretrained(
|
| 121 |
+
args.transformer_path,
|
| 122 |
+
subfolder="transformer",
|
| 123 |
+
torch_dtype=args.weight_dtype,
|
| 124 |
+
use_default_loader=args.use_default_loader,
|
| 125 |
+
)
|
| 126 |
+
transformer = replace_rmsnorm_with_fp32(transformer)
|
| 127 |
+
transformer = replace_all_norms_with_flash_norms(transformer)
|
| 128 |
+
replace_rope_with_flash_rope()
|
| 129 |
+
vae = AutoencoderKLWan.from_pretrained(args.base_model_path, subfolder="vae", torch_dtype=torch.float32)
|
| 130 |
+
if args.is_enable_stage2:
|
| 131 |
+
scheduler = HeliosScheduler(
|
| 132 |
+
shift=args.stage2_timestep_shift,
|
| 133 |
+
stages=args.stage2_num_stages,
|
| 134 |
+
stage_range=args.stage2_stage_range,
|
| 135 |
+
gamma=args.stage2_scheduler_gamma,
|
| 136 |
+
)
|
| 137 |
+
pipe = HeliosPipeline.from_pretrained(
|
| 138 |
+
args.base_model_path,
|
| 139 |
+
transformer=transformer,
|
| 140 |
+
vae=vae,
|
| 141 |
+
scheduler=scheduler,
|
| 142 |
+
torch_dtype=args.weight_dtype,
|
| 143 |
+
)
|
| 144 |
+
else:
|
| 145 |
+
pipe = HeliosPipeline.from_pretrained(
|
| 146 |
+
args.base_model_path, transformer=transformer, vae=vae, torch_dtype=args.weight_dtype
|
| 147 |
+
)
|
| 148 |
+
pipe = pipe.to(device)
|
| 149 |
+
|
| 150 |
+
if args.lora_path is not None:
|
| 151 |
+
pipe.load_lora_weights(args.lora_path, adapter_name="default")
|
| 152 |
+
pipe.set_adapters(["default"], adapter_weights=[1.0])
|
| 153 |
+
|
| 154 |
+
if args.partial_path is not None:
|
| 155 |
+
if not hasattr(args, "training_config"):
|
| 156 |
+
from argparse import Namespace
|
| 157 |
+
|
| 158 |
+
args.training_config = Namespace()
|
| 159 |
+
args.training_config.is_enable_stage1 = True
|
| 160 |
+
args.training_config.restrict_self_attn = True
|
| 161 |
+
args.training_config.is_amplify_history = True
|
| 162 |
+
args.training_config.is_use_gan = True
|
| 163 |
+
load_extra_components(args, transformer, args.partial_path)
|
| 164 |
+
|
| 165 |
+
if args.vae_decode_type == "once":
|
| 166 |
+
pipe.vae.enable_tiling()
|
| 167 |
+
|
| 168 |
+
transformer.eval()
|
| 169 |
+
transformer.requires_grad_(False)
|
| 170 |
+
vae.eval()
|
| 171 |
+
vae.requires_grad_(False)
|
| 172 |
+
|
| 173 |
+
transformer.to(device)
|
| 174 |
+
vae.to(device)
|
| 175 |
+
pipe.to(device)
|
| 176 |
+
|
| 177 |
+
for feature_folder, output_folder in zip(feature_folders, output_folders):
|
| 178 |
+
print(f"Process {feature_folder} !")
|
| 179 |
+
|
| 180 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 181 |
+
prompts, uttids = prepare_dataset_on_rank0(feature_folder, output_folder, rank)
|
| 182 |
+
dataset = PromptDataset(prompts, uttids)
|
| 183 |
+
dataloader = DataLoader(
|
| 184 |
+
dataset,
|
| 185 |
+
batch_size=batch_size,
|
| 186 |
+
shuffle=False,
|
| 187 |
+
num_workers=dataloader_num_workers,
|
| 188 |
+
prefetch_factor=2 if dataloader_num_workers > 0 else None,
|
| 189 |
+
pin_memory=True,
|
| 190 |
+
drop_last=False,
|
| 191 |
+
)
|
| 192 |
+
dataloader = accelerator.prepare(dataloader)
|
| 193 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 194 |
+
print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}")
|
| 195 |
+
|
| 196 |
+
if len(dataloader) == 0:
|
| 197 |
+
continue
|
| 198 |
+
|
| 199 |
+
# =============== Main Loop ===============
|
| 200 |
+
if rank == 0:
|
| 201 |
+
pbar = tqdm(total=len(dataloader), desc="Processing")
|
| 202 |
+
|
| 203 |
+
for i, batch in enumerate(dataloader):
|
| 204 |
+
assert len(batch["uttid"]) == 1
|
| 205 |
+
uttid = batch["uttid"][0]
|
| 206 |
+
prompt_raw = batch["prompt"][0]
|
| 207 |
+
|
| 208 |
+
output_path = os.path.join(output_folder, f"{uttid}.pt")
|
| 209 |
+
if os.path.exists(output_path):
|
| 210 |
+
if rank == 0:
|
| 211 |
+
print(f"Skipping existing file: {output_path}")
|
| 212 |
+
pbar.update(1)
|
| 213 |
+
continue
|
| 214 |
+
|
| 215 |
+
with torch.no_grad():
|
| 216 |
+
prompt_embed, _ = encode_prompt(
|
| 217 |
+
tokenizer=pipe.tokenizer,
|
| 218 |
+
text_encoder=pipe.text_encoder,
|
| 219 |
+
prompt=prompt_raw,
|
| 220 |
+
device=device,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
all_sections_ode = pipe(
|
| 224 |
+
prompt=prompt_raw,
|
| 225 |
+
negative_prompt=args.negative_prompt,
|
| 226 |
+
height=args.height,
|
| 227 |
+
width=args.width,
|
| 228 |
+
num_frames=args.num_frames, # 73 109 145 181 215
|
| 229 |
+
num_inference_steps=50,
|
| 230 |
+
guidance_scale=args.guidance_scale,
|
| 231 |
+
generator=torch.Generator(device="cuda").manual_seed(args.seed),
|
| 232 |
+
output_type="latent",
|
| 233 |
+
vae_decode_type=args.vae_decode_type,
|
| 234 |
+
# stage 1
|
| 235 |
+
history_sizes=[16, 2, 1],
|
| 236 |
+
latent_window_size=args.latent_window_size,
|
| 237 |
+
is_keep_x0=True,
|
| 238 |
+
use_dynamic_shifting=args.use_dynamic_shifting,
|
| 239 |
+
time_shift_type=args.time_shift_type,
|
| 240 |
+
# stage 2
|
| 241 |
+
is_enable_stage2=args.is_enable_stage2,
|
| 242 |
+
stage2_num_stages=args.stage2_num_stages,
|
| 243 |
+
stage2_num_inference_steps_list=args.stage2_num_inference_steps_list,
|
| 244 |
+
scheduler_type="unipc",
|
| 245 |
+
# cfg zero
|
| 246 |
+
use_cfg_zero_star=args.use_cfg_zero_star,
|
| 247 |
+
use_zero_init=args.use_zero_init,
|
| 248 |
+
zero_steps=args.zero_steps,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# (Pdb) len(all_sections_ode)
|
| 252 |
+
# 264 -> % 8 == 0
|
| 253 |
+
# 231 -> % 7 == 0
|
| 254 |
+
# 198 -> % 6 == 0
|
| 255 |
+
# 165 -> % 5 == 0
|
| 256 |
+
# (Pdb) len(all_sections_ode[0])
|
| 257 |
+
# 3
|
| 258 |
+
# (Pdb) all_sections_ode[0][0].keys()
|
| 259 |
+
# dict_keys(['latents', 'timesteps', 'noise_pred'])
|
| 260 |
+
# (Pdb) all_sections_ode[0][0]["timesteps"].shape
|
| 261 |
+
# torch.Size([20]
|
| 262 |
+
# (Pdb) all_sections_ode[0][0]["latents"].shape
|
| 263 |
+
# torch.Size([20, 1, 16, 9, 12, 20])
|
| 264 |
+
# (Pdb) all_sections_ode[0][0]["noise_pred"].shape
|
| 265 |
+
# torch.Size([20, 1, 16, 9, 12, 20])
|
| 266 |
+
|
| 267 |
+
processed_sections_ode = []
|
| 268 |
+
for idx, section in enumerate(all_sections_ode):
|
| 269 |
+
processed_section = []
|
| 270 |
+
for iidx, item in enumerate(section):
|
| 271 |
+
if idx == 0:
|
| 272 |
+
if iidx == 0:
|
| 273 |
+
selected_target_timesteps = [998.5342, 902.2183, 833.9636, 783.0660]
|
| 274 |
+
elif iidx == 1:
|
| 275 |
+
selected_target_timesteps = [742.8216, 640.0038, 547.1926, 462.9951]
|
| 276 |
+
elif iidx == 2:
|
| 277 |
+
selected_target_timesteps = [385.4137, 328.6249, 253.9905, 151.5308]
|
| 278 |
+
else:
|
| 279 |
+
if iidx == 0:
|
| 280 |
+
selected_target_timesteps = [998.5342, 833.9636]
|
| 281 |
+
elif iidx == 1:
|
| 282 |
+
selected_target_timesteps = [742.8216, 547.1926]
|
| 283 |
+
elif iidx == 2:
|
| 284 |
+
selected_target_timesteps = [385.4137, 253.9905]
|
| 285 |
+
|
| 286 |
+
indices = []
|
| 287 |
+
actual_timesteps = item["timesteps"]
|
| 288 |
+
for target_t in selected_target_timesteps:
|
| 289 |
+
diffs = torch.abs(actual_timesteps - target_t)
|
| 290 |
+
closest_idx = torch.argmin(diffs).item()
|
| 291 |
+
indices.append(closest_idx)
|
| 292 |
+
latents_indices = indices + [-1]
|
| 293 |
+
|
| 294 |
+
rocessed_item = {
|
| 295 |
+
"latents": item["latents"][latents_indices],
|
| 296 |
+
"timesteps": item["timesteps"][indices],
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
processed_section.append(rocessed_item)
|
| 300 |
+
processed_sections_ode.append(processed_section)
|
| 301 |
+
all_sections_ode = processed_sections_ode
|
| 302 |
+
|
| 303 |
+
temp_to_save = {
|
| 304 |
+
"latent_window_size": args.latent_window_size,
|
| 305 |
+
"prompt_raw": prompt_raw,
|
| 306 |
+
"prompt_embed": prompt_embed,
|
| 307 |
+
"ode_latents": all_sections_ode,
|
| 308 |
+
}
|
| 309 |
+
torch.save(temp_to_save, output_path)
|
| 310 |
+
print(f"save latent to: {output_path}")
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def parse_args():
|
| 314 |
+
parser = argparse.ArgumentParser(description="Generate video with model")
|
| 315 |
+
|
| 316 |
+
# === Model paths ===
|
| 317 |
+
parser.add_argument("--base_model_path", type=str, default="BestWishYsh/Helios-Base")
|
| 318 |
+
parser.add_argument(
|
| 319 |
+
"--transformer_path",
|
| 320 |
+
type=str,
|
| 321 |
+
default="BestWishYsh/Helios-Mid",
|
| 322 |
+
)
|
| 323 |
+
parser.add_argument(
|
| 324 |
+
"--lora_path",
|
| 325 |
+
type=str,
|
| 326 |
+
default=None,
|
| 327 |
+
)
|
| 328 |
+
parser.add_argument(
|
| 329 |
+
"--partial_path",
|
| 330 |
+
type=str,
|
| 331 |
+
default=None,
|
| 332 |
+
)
|
| 333 |
+
parser.add_argument("--use_default_loader", action="store_true")
|
| 334 |
+
|
| 335 |
+
# === Generation parameters ===
|
| 336 |
+
# environment
|
| 337 |
+
parser.add_argument(
|
| 338 |
+
"--sample_type",
|
| 339 |
+
type=str,
|
| 340 |
+
default="t2v",
|
| 341 |
+
choices=["t2v", "i2v", "v2v"],
|
| 342 |
+
)
|
| 343 |
+
parser.add_argument(
|
| 344 |
+
"--weight_dtype",
|
| 345 |
+
type=str,
|
| 346 |
+
default="bf16",
|
| 347 |
+
choices=["bf16", "fp16", "fp32"],
|
| 348 |
+
help="Data type for model weights.",
|
| 349 |
+
)
|
| 350 |
+
parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.")
|
| 351 |
+
# base
|
| 352 |
+
parser.add_argument("--height", type=int, default=384)
|
| 353 |
+
parser.add_argument("--width", type=int, default=640)
|
| 354 |
+
parser.add_argument("--num_frames", type=int, default=165)
|
| 355 |
+
parser.add_argument("--num_inference_steps", type=int, default=50)
|
| 356 |
+
parser.add_argument("--guidance_scale", type=float, default=5.0)
|
| 357 |
+
parser.add_argument("--use_dynamic_shifting", action="store_true")
|
| 358 |
+
parser.add_argument(
|
| 359 |
+
"--time_shift_type",
|
| 360 |
+
type=str,
|
| 361 |
+
default="linear",
|
| 362 |
+
choices=["exponential", "linear"],
|
| 363 |
+
)
|
| 364 |
+
parser.add_argument("--vae_decode_type", type=str, default="default", choices=["default", "once", "default_fast"])
|
| 365 |
+
# stage 1
|
| 366 |
+
parser.add_argument("--latent_window_size", type=int, default=9)
|
| 367 |
+
# stage 2
|
| 368 |
+
parser.add_argument("--is_enable_stage2", action="store_true")
|
| 369 |
+
parser.add_argument("--stage2_timestep_shift", type=float, default=1.0)
|
| 370 |
+
parser.add_argument("--stage2_scheduler_gamma", type=float, default=1 / 3)
|
| 371 |
+
parser.add_argument("--stage2_stage_range", type=int, nargs="+", default=[0, 1 / 3, 2 / 3, 1])
|
| 372 |
+
parser.add_argument("--stage2_num_stages", type=int, default=3)
|
| 373 |
+
parser.add_argument("--stage2_num_inference_steps_list", type=int, nargs="+", default=[20, 20, 20])
|
| 374 |
+
# cfg zero
|
| 375 |
+
parser.add_argument("--use_cfg_zero_star", action="store_true")
|
| 376 |
+
parser.add_argument("--use_zero_init", action="store_true")
|
| 377 |
+
parser.add_argument("--zero_steps", type=int, default=1)
|
| 378 |
+
|
| 379 |
+
# === Prompts ===
|
| 380 |
+
parser.add_argument(
|
| 381 |
+
"--negative_prompt",
|
| 382 |
+
type=str,
|
| 383 |
+
default="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",
|
| 384 |
+
)
|
| 385 |
+
parser.add_argument(
|
| 386 |
+
"--prompt_txt_path",
|
| 387 |
+
type=str,
|
| 388 |
+
default=None,
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
return parser.parse_args()
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
if __name__ == "__main__":
|
| 395 |
+
# from diffusers import AutoencoderKLWan
|
| 396 |
+
# from diffusers.video_processor import VideoProcessor
|
| 397 |
+
# from diffusers.utils import export_to_video
|
| 398 |
+
|
| 399 |
+
# device = "cuda"
|
| 400 |
+
# pretrained_model_name_or_path = "BestWishYsh/Helios-Base"
|
| 401 |
+
# vae = AutoencoderKLWan.from_pretrained(
|
| 402 |
+
# pretrained_model_name_or_path,
|
| 403 |
+
# subfolder="vae",
|
| 404 |
+
# torch_dtype=torch.float32,
|
| 405 |
+
# ).to(device)
|
| 406 |
+
# vae.eval()
|
| 407 |
+
# vae.requires_grad_(False)
|
| 408 |
+
|
| 409 |
+
# vae_scale_factor_spatial = vae.spatial_compression_ratio
|
| 410 |
+
# video_processor = VideoProcessor(vae_scale_factor=vae_scale_factor_spatial)
|
| 411 |
+
# latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1)
|
| 412 |
+
# latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1)
|
| 413 |
+
|
| 414 |
+
# x1 = torch.load("/mnt/hdfs/data/ysh_new/userful_things_wan/ode_pairs/vidprom_filtered_extended/vidprom_filtered_extended_00011.pt", map_location="cpu")
|
| 415 |
+
# vae_latents = x1["ode_latents"][-1][-1]["latents"][-1] / latents_std + latents_mean
|
| 416 |
+
# vae_latents = vae_latents.to(device=device, dtype=vae.dtype)
|
| 417 |
+
# video = vae.decode(vae_latents, return_dict=False)[0]
|
| 418 |
+
# video = video_processor.postprocess_video(video, output_type="pil")
|
| 419 |
+
# export_to_video(video[0], "output_wan.mp4", fps=30)
|
| 420 |
+
|
| 421 |
+
main()
|
Helios-main/tools/offload_data/get_ode-pairs.sh
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export OMNISTORE_LOAD_STRICT_MODE=0
|
| 2 |
+
export OMNISTORE_LOGGING_LEVEL=ERROR
|
| 3 |
+
#################################################################
|
| 4 |
+
## Torch
|
| 5 |
+
#################################################################
|
| 6 |
+
export TOKENIZERS_PARALLELISM=false
|
| 7 |
+
export TORCH_LOGS="+dynamo,recompiles,graph_breaks"
|
| 8 |
+
export TORCHDYNAMO_VERBOSE=1
|
| 9 |
+
export TORCH_NCCL_ENABLE_MONITORING=1
|
| 10 |
+
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9"
|
| 11 |
+
#################################################################
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
#################################################################
|
| 15 |
+
## NCCL
|
| 16 |
+
#################################################################
|
| 17 |
+
export NCCL_IB_GID_INDEX=3
|
| 18 |
+
export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE
|
| 19 |
+
export NCCL_SOCKET_IFNAME=eth0
|
| 20 |
+
export NCCL_SOCKET_TIMEOUT=3600000
|
| 21 |
+
|
| 22 |
+
export NCCL_DEBUG=WARN # disable the verbose NCCL logs
|
| 23 |
+
export NCCL_P2P_DISABLE=0
|
| 24 |
+
export NCCL_IB_DISABLE=0 # was 1
|
| 25 |
+
export NCCL_SHM_DISABLE=0 # was 1
|
| 26 |
+
export NCCL_P2P_LEVEL=NVL
|
| 27 |
+
|
| 28 |
+
export NCCL_PXN_DISABLE=0
|
| 29 |
+
export NCCL_NET_GDR_LEVEL=2
|
| 30 |
+
export NCCL_IB_QPS_PER_CONNECTION=4
|
| 31 |
+
export NCCL_IB_TC=160
|
| 32 |
+
export NCCL_IB_TIMEOUT=22
|
| 33 |
+
#################################################################
|
| 34 |
+
|
| 35 |
+
#################################################################
|
| 36 |
+
## DIST
|
| 37 |
+
#################################################################
|
| 38 |
+
MASTER_ADDR=$ARNOLD_WORKER_0_HOST
|
| 39 |
+
ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
|
| 40 |
+
MASTER_PORT=${ports[0]}
|
| 41 |
+
NNODES=$ARNOLD_WORKER_NUM
|
| 42 |
+
NODE_RANK=$ARNOLD_ID
|
| 43 |
+
GPUS_PER_NODE=$ARNOLD_WORKER_GPU
|
| 44 |
+
|
| 45 |
+
# export CUDA_VISIBLE_DEVICES=1
|
| 46 |
+
# MASTER_PORT=12345
|
| 47 |
+
# GPUS_PER_NODE=1
|
| 48 |
+
# NNODES=1
|
| 49 |
+
# NODE_RANK=0
|
| 50 |
+
|
| 51 |
+
WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
|
| 52 |
+
|
| 53 |
+
DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
|
| 54 |
+
if [ ! -z $RDZV_BACKEND ]; then
|
| 55 |
+
DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d"
|
| 56 |
+
export NCCL_SHM_DISABLE=1
|
| 57 |
+
fi
|
| 58 |
+
|
| 59 |
+
echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m"
|
| 60 |
+
|
| 61 |
+
#################################################################
|
| 62 |
+
#
|
| 63 |
+
torchrun $DISTRIBUTED_ARGS \
|
| 64 |
+
tools/offload_data/get_ode-pairs.py \
|
| 65 |
+
--use_dynamic_shifting \
|
| 66 |
+
--time_shift_type "linear" \
|
| 67 |
+
--use_default_loader \
|
| 68 |
+
--is_enable_stage2 \
|
| 69 |
+
--num_frames 165
|
Helios-main/tools/offload_data/get_short-latents.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
import torchvision.transforms as transforms
|
| 7 |
+
from accelerate import Accelerator
|
| 8 |
+
from helios.dataset.dataloader_mp4_dist import BucketedFeatureDataset, BucketedSampler, collate_fn
|
| 9 |
+
from helios.utils.utils_base import encode_prompt
|
| 10 |
+
from torch.utils.data import DataLoader
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 13 |
+
|
| 14 |
+
from diffusers import AutoencoderKLWan
|
| 15 |
+
from diffusers.training_utils import free_memory
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def setup_distributed_env():
|
| 19 |
+
dist.init_process_group(backend="nccl")
|
| 20 |
+
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def cleanup_distributed_env():
|
| 24 |
+
dist.destroy_process_group()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main(
|
| 28 |
+
rank,
|
| 29 |
+
world_size,
|
| 30 |
+
global_rank,
|
| 31 |
+
stride,
|
| 32 |
+
batch_size,
|
| 33 |
+
dataloader_num_workers,
|
| 34 |
+
json_file,
|
| 35 |
+
video_folder,
|
| 36 |
+
output_latent_folder,
|
| 37 |
+
pretrained_model_name_or_path,
|
| 38 |
+
resolution=640,
|
| 39 |
+
):
|
| 40 |
+
weight_dtype = torch.bfloat16
|
| 41 |
+
device = rank
|
| 42 |
+
seed = 42
|
| 43 |
+
|
| 44 |
+
# Load the tokenizers
|
| 45 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 46 |
+
pretrained_model_name_or_path,
|
| 47 |
+
subfolder="tokenizer",
|
| 48 |
+
)
|
| 49 |
+
text_encoder = UMT5EncoderModel.from_pretrained(
|
| 50 |
+
pretrained_model_name_or_path,
|
| 51 |
+
subfolder="text_encoder",
|
| 52 |
+
torch_dtype=weight_dtype,
|
| 53 |
+
)
|
| 54 |
+
vae = AutoencoderKLWan.from_pretrained(
|
| 55 |
+
pretrained_model_name_or_path,
|
| 56 |
+
subfolder="vae",
|
| 57 |
+
torch_dtype=torch.float32,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
latents_mean = torch.tensor(vae.config.latents_mean).view(1, vae.config.z_dim, 1, 1, 1).to(device, weight_dtype)
|
| 61 |
+
latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(1, vae.config.z_dim, 1, 1, 1).to(
|
| 62 |
+
device, weight_dtype
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
vae.eval()
|
| 66 |
+
vae.requires_grad_(False)
|
| 67 |
+
text_encoder.eval()
|
| 68 |
+
text_encoder.requires_grad_(False)
|
| 69 |
+
|
| 70 |
+
vae = vae.to(device)
|
| 71 |
+
text_encoder = text_encoder.to(device)
|
| 72 |
+
|
| 73 |
+
# dist.barrier()
|
| 74 |
+
dataset = BucketedFeatureDataset(
|
| 75 |
+
json_files=json_file,
|
| 76 |
+
video_folders=video_folder,
|
| 77 |
+
stride=stride,
|
| 78 |
+
force_rebuild=False,
|
| 79 |
+
resolution=resolution,
|
| 80 |
+
single_res=True,
|
| 81 |
+
single_height=384,
|
| 82 |
+
single_width=640,
|
| 83 |
+
)
|
| 84 |
+
sampler = BucketedSampler(dataset, batch_size=batch_size, drop_last=False, shuffle=True, seed=seed)
|
| 85 |
+
dataloader = DataLoader(
|
| 86 |
+
dataset,
|
| 87 |
+
batch_sampler=sampler,
|
| 88 |
+
collate_fn=collate_fn,
|
| 89 |
+
num_workers=dataloader_num_workers,
|
| 90 |
+
pin_memory=True,
|
| 91 |
+
prefetch_factor=2 if dataloader_num_workers != 0 else None,
|
| 92 |
+
# persistent_workers=True if dataloader_num_workers > 0 else False,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
print(len(dataset), len(dataloader))
|
| 96 |
+
accelerator = Accelerator()
|
| 97 |
+
dataloader = accelerator.prepare(dataloader)
|
| 98 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 99 |
+
print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}")
|
| 100 |
+
|
| 101 |
+
sampler.set_epoch(0)
|
| 102 |
+
if rank == 0:
|
| 103 |
+
pbar = tqdm(total=len(dataloader), desc="Processing")
|
| 104 |
+
# dist.barrier()
|
| 105 |
+
for idx, batch in enumerate(dataloader):
|
| 106 |
+
if batch is None or batch["videos"] is None:
|
| 107 |
+
print("None batch, continuing")
|
| 108 |
+
continue
|
| 109 |
+
free_memory()
|
| 110 |
+
|
| 111 |
+
valid_indices = []
|
| 112 |
+
valid_uttids = []
|
| 113 |
+
valid_num_frames = []
|
| 114 |
+
valid_heights = []
|
| 115 |
+
valid_widths = []
|
| 116 |
+
valid_videos = []
|
| 117 |
+
valid_prompts = []
|
| 118 |
+
valid_first_frames_images = []
|
| 119 |
+
|
| 120 |
+
if batch["uttid"] is None:
|
| 121 |
+
print("None batch, contiuning")
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
for i, (uttid, num_frame, height, width) in enumerate(
|
| 125 |
+
zip(
|
| 126 |
+
batch["uttid"],
|
| 127 |
+
batch["video_metadata"]["num_frames"],
|
| 128 |
+
batch["video_metadata"]["height"],
|
| 129 |
+
batch["video_metadata"]["width"],
|
| 130 |
+
)
|
| 131 |
+
):
|
| 132 |
+
os.makedirs(output_latent_folder, exist_ok=True)
|
| 133 |
+
output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt")
|
| 134 |
+
if not os.path.exists(output_path):
|
| 135 |
+
valid_indices.append(i)
|
| 136 |
+
valid_uttids.append(uttid)
|
| 137 |
+
valid_num_frames.append(num_frame)
|
| 138 |
+
valid_heights.append(height)
|
| 139 |
+
valid_widths.append(width)
|
| 140 |
+
valid_videos.append(batch["videos"][i])
|
| 141 |
+
valid_prompts.append(batch["prompts"][i])
|
| 142 |
+
valid_first_frames_images.append(batch["first_frames_images"][i])
|
| 143 |
+
else:
|
| 144 |
+
print(f"skipping {uttid}")
|
| 145 |
+
|
| 146 |
+
if not valid_indices:
|
| 147 |
+
print("skipping entire batch!")
|
| 148 |
+
if rank == 0:
|
| 149 |
+
pbar.update(1)
|
| 150 |
+
pbar.set_postfix({"batch": idx})
|
| 151 |
+
continue
|
| 152 |
+
|
| 153 |
+
batch = None
|
| 154 |
+
del batch
|
| 155 |
+
free_memory()
|
| 156 |
+
|
| 157 |
+
batch = {
|
| 158 |
+
"uttid": valid_uttids,
|
| 159 |
+
"video_metadata": {"num_frames": valid_num_frames, "height": valid_heights, "width": valid_widths},
|
| 160 |
+
"videos": torch.stack(valid_videos),
|
| 161 |
+
"prompts": valid_prompts,
|
| 162 |
+
"first_frames_images": torch.stack(valid_first_frames_images),
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
if len(batch["uttid"]) == 0:
|
| 166 |
+
print("All samples in this batch are already processed, skipping!")
|
| 167 |
+
continue
|
| 168 |
+
|
| 169 |
+
with torch.no_grad():
|
| 170 |
+
# Get Vae feature
|
| 171 |
+
pixel_values = batch["videos"].permute(0, 2, 1, 3, 4).to(dtype=vae.dtype, device=device)
|
| 172 |
+
|
| 173 |
+
latent_window_size = 9
|
| 174 |
+
frame_window_size = (latent_window_size - 1) * 4 + 1
|
| 175 |
+
num_latent_frames = pixel_values.shape[2]
|
| 176 |
+
num_chunk_to_encode = num_latent_frames // frame_window_size
|
| 177 |
+
|
| 178 |
+
history_latent_list = []
|
| 179 |
+
for i in range(num_chunk_to_encode):
|
| 180 |
+
start_idx = i * frame_window_size
|
| 181 |
+
end_idx = start_idx + frame_window_size
|
| 182 |
+
cur_pixel_values = pixel_values[:, :, start_idx:end_idx, :, :]
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
cur_latent = vae.encode(cur_pixel_values).latent_dist.sample()
|
| 185 |
+
cur_latent = (cur_latent - latents_mean) * latents_std
|
| 186 |
+
history_latent_list.append(cur_latent)
|
| 187 |
+
vae_latents = torch.stack(history_latent_list, dim=1)
|
| 188 |
+
|
| 189 |
+
# Encode prompts
|
| 190 |
+
prompts = batch["prompts"]
|
| 191 |
+
prompt_embeds, prompt_attention_mask = encode_prompt(
|
| 192 |
+
tokenizer=tokenizer,
|
| 193 |
+
text_encoder=text_encoder,
|
| 194 |
+
prompt=prompts,
|
| 195 |
+
device=device,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
image_tensor = batch["first_frames_images"]
|
| 199 |
+
images = [transforms.ToPILImage()(x.to(torch.uint8)) for x in image_tensor]
|
| 200 |
+
|
| 201 |
+
for (
|
| 202 |
+
uttid,
|
| 203 |
+
num_frame,
|
| 204 |
+
height,
|
| 205 |
+
width,
|
| 206 |
+
cur_vae_latent,
|
| 207 |
+
cur_prompt_embed,
|
| 208 |
+
cur_prompt_attention_mask,
|
| 209 |
+
cur_first_frames_image,
|
| 210 |
+
cur_prompt,
|
| 211 |
+
) in zip(
|
| 212 |
+
batch["uttid"],
|
| 213 |
+
batch["video_metadata"]["num_frames"],
|
| 214 |
+
batch["video_metadata"]["height"],
|
| 215 |
+
batch["video_metadata"]["width"],
|
| 216 |
+
vae_latents,
|
| 217 |
+
prompt_embeds,
|
| 218 |
+
prompt_attention_mask,
|
| 219 |
+
images,
|
| 220 |
+
prompts,
|
| 221 |
+
):
|
| 222 |
+
output_path = os.path.join(output_latent_folder, f"{uttid}_{num_frame}_{height}_{width}.pt")
|
| 223 |
+
temp_to_save = {
|
| 224 |
+
"vae_latent": cur_vae_latent.cpu().detach(),
|
| 225 |
+
"prompt_embed": cur_prompt_embed.cpu().detach(),
|
| 226 |
+
# "prompt_attention_mask": cur_prompt_attention_mask.cpu().detach(),
|
| 227 |
+
"first_frames_image": cur_first_frames_image,
|
| 228 |
+
"prompt_raw": cur_prompt,
|
| 229 |
+
}
|
| 230 |
+
try:
|
| 231 |
+
torch.save(temp_to_save, output_path)
|
| 232 |
+
except Exception:
|
| 233 |
+
continue
|
| 234 |
+
print(f"save latent to: {output_path}")
|
| 235 |
+
|
| 236 |
+
if rank == 0:
|
| 237 |
+
pbar.update(1)
|
| 238 |
+
pbar.set_postfix({"batch": idx})
|
| 239 |
+
|
| 240 |
+
pixel_values = None
|
| 241 |
+
prompts = None
|
| 242 |
+
image_tensor = None
|
| 243 |
+
images = None
|
| 244 |
+
vae_latents = None
|
| 245 |
+
vae_latents_2 = None
|
| 246 |
+
image_embeds = None
|
| 247 |
+
prompt_embeds = None
|
| 248 |
+
batch = None
|
| 249 |
+
valid_indices = None
|
| 250 |
+
valid_uttids = None
|
| 251 |
+
valid_num_frames = None
|
| 252 |
+
valid_heights = None
|
| 253 |
+
valid_widths = None
|
| 254 |
+
valid_videos = None
|
| 255 |
+
valid_prompts = None
|
| 256 |
+
valid_first_frames_images = None
|
| 257 |
+
temp_to_save = None
|
| 258 |
+
|
| 259 |
+
del pixel_values
|
| 260 |
+
del prompts
|
| 261 |
+
del image_tensor
|
| 262 |
+
del images
|
| 263 |
+
del vae_latents
|
| 264 |
+
del vae_latents_2
|
| 265 |
+
del image_embeds
|
| 266 |
+
del batch
|
| 267 |
+
del valid_indices
|
| 268 |
+
del valid_uttids
|
| 269 |
+
del valid_num_frames
|
| 270 |
+
del valid_heights
|
| 271 |
+
del valid_widths
|
| 272 |
+
del valid_videos
|
| 273 |
+
del valid_prompts
|
| 274 |
+
del valid_first_frames_images
|
| 275 |
+
del temp_to_save
|
| 276 |
+
|
| 277 |
+
free_memory()
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
if __name__ == "__main__":
|
| 281 |
+
parser = argparse.ArgumentParser(description="Script for running model training and data processing.")
|
| 282 |
+
parser.add_argument("--dataloader_num_workers", type=int, default=8, help="Number of workers for data loading")
|
| 283 |
+
parser.add_argument(
|
| 284 |
+
"--pretrained_model_name_or_path",
|
| 285 |
+
type=str,
|
| 286 |
+
default="BestWishYsh/Helios-Base",
|
| 287 |
+
help="Pretrained model path",
|
| 288 |
+
)
|
| 289 |
+
args = parser.parse_args()
|
| 290 |
+
|
| 291 |
+
setup_distributed_env()
|
| 292 |
+
|
| 293 |
+
global_rank = dist.get_rank()
|
| 294 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 295 |
+
device = torch.cuda.current_device()
|
| 296 |
+
world_size = dist.get_world_size()
|
| 297 |
+
|
| 298 |
+
base_video_path = "example"
|
| 299 |
+
video_paths = [
|
| 300 |
+
"toy_data",
|
| 301 |
+
]
|
| 302 |
+
|
| 303 |
+
base_output_latent_path = "example/toy_data/latents_short"
|
| 304 |
+
output_latent_paths = [
|
| 305 |
+
"toy_data",
|
| 306 |
+
]
|
| 307 |
+
|
| 308 |
+
base_csv_paths = [
|
| 309 |
+
"example",
|
| 310 |
+
]
|
| 311 |
+
csv_paths = [
|
| 312 |
+
"toy_data/toy_filter.json",
|
| 313 |
+
]
|
| 314 |
+
|
| 315 |
+
resolutions = [640]
|
| 316 |
+
strides = [1]
|
| 317 |
+
batch_sizes = [4]
|
| 318 |
+
|
| 319 |
+
for stride, batch_size, base_csv_path, csv_path, video_path, output_latent_path, cur_resolution in zip(
|
| 320 |
+
strides, batch_sizes, base_csv_paths, csv_paths, video_paths, output_latent_paths, resolutions
|
| 321 |
+
):
|
| 322 |
+
json_file = os.path.join(base_csv_path, csv_path)
|
| 323 |
+
video_folder = os.path.join(base_video_path, video_path)
|
| 324 |
+
output_latent_folder = os.path.join(base_output_latent_path, output_latent_path)
|
| 325 |
+
|
| 326 |
+
main(
|
| 327 |
+
rank=device,
|
| 328 |
+
world_size=world_size,
|
| 329 |
+
global_rank=global_rank,
|
| 330 |
+
stride=stride,
|
| 331 |
+
batch_size=batch_size,
|
| 332 |
+
dataloader_num_workers=args.dataloader_num_workers,
|
| 333 |
+
json_file=json_file,
|
| 334 |
+
video_folder=video_folder,
|
| 335 |
+
output_latent_folder=output_latent_folder,
|
| 336 |
+
pretrained_model_name_or_path=args.pretrained_model_name_or_path,
|
| 337 |
+
resolution=cur_resolution,
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
dist.barrier()
|
| 341 |
+
dist.destroy_process_group()
|
Helios-main/tools/offload_data/get_short-latents.sh
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export OMNISTORE_LOAD_STRICT_MODE=0
|
| 2 |
+
export OMNISTORE_LOGGING_LEVEL=ERROR
|
| 3 |
+
#################################################################
|
| 4 |
+
## Torch
|
| 5 |
+
#################################################################
|
| 6 |
+
export TOKENIZERS_PARALLELISM=false
|
| 7 |
+
export TORCH_LOGS="+dynamo,recompiles,graph_breaks"
|
| 8 |
+
export TORCHDYNAMO_VERBOSE=1
|
| 9 |
+
export TORCH_NCCL_ENABLE_MONITORING=1
|
| 10 |
+
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9"
|
| 11 |
+
#################################################################
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
#################################################################
|
| 15 |
+
## NCCL
|
| 16 |
+
#################################################################
|
| 17 |
+
export NCCL_IB_GID_INDEX=3
|
| 18 |
+
export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE
|
| 19 |
+
export NCCL_SOCKET_IFNAME=eth0
|
| 20 |
+
export NCCL_SOCKET_TIMEOUT=3600000
|
| 21 |
+
|
| 22 |
+
export NCCL_DEBUG=WARN # disable the verbose NCCL logs
|
| 23 |
+
export NCCL_P2P_DISABLE=0
|
| 24 |
+
export NCCL_IB_DISABLE=0 # was 1
|
| 25 |
+
export NCCL_SHM_DISABLE=0 # was 1
|
| 26 |
+
export NCCL_P2P_LEVEL=NVL
|
| 27 |
+
|
| 28 |
+
export NCCL_PXN_DISABLE=0
|
| 29 |
+
export NCCL_NET_GDR_LEVEL=2
|
| 30 |
+
export NCCL_IB_QPS_PER_CONNECTION=4
|
| 31 |
+
export NCCL_IB_TC=160
|
| 32 |
+
export NCCL_IB_TIMEOUT=22
|
| 33 |
+
#################################################################
|
| 34 |
+
|
| 35 |
+
#################################################################
|
| 36 |
+
## DIST
|
| 37 |
+
#################################################################
|
| 38 |
+
MASTER_ADDR=$ARNOLD_WORKER_0_HOST
|
| 39 |
+
ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
|
| 40 |
+
MASTER_PORT=${ports[0]}
|
| 41 |
+
NNODES=$ARNOLD_WORKER_NUM
|
| 42 |
+
NODE_RANK=$ARNOLD_ID
|
| 43 |
+
GPUS_PER_NODE=$ARNOLD_WORKER_GPU
|
| 44 |
+
|
| 45 |
+
# export CUDA_VISIBLE_DEVICES=1
|
| 46 |
+
# MASTER_PORT=12345
|
| 47 |
+
# GPUS_PER_NODE=1
|
| 48 |
+
# NNODES=1
|
| 49 |
+
# NODE_RANK=0
|
| 50 |
+
|
| 51 |
+
WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
|
| 52 |
+
|
| 53 |
+
DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
|
| 54 |
+
if [ ! -z $RDZV_BACKEND ]; then
|
| 55 |
+
DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d"
|
| 56 |
+
export NCCL_SHM_DISABLE=1
|
| 57 |
+
fi
|
| 58 |
+
|
| 59 |
+
echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m"
|
| 60 |
+
|
| 61 |
+
#################################################################
|
| 62 |
+
#
|
| 63 |
+
torchrun $DISTRIBUTED_ARGS \
|
| 64 |
+
tools/offload_data/get_short-latents.py
|
Helios-main/tools/offload_data/get_text-embedding.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 argparse
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.distributed as dist
|
| 13 |
+
from accelerate import Accelerator
|
| 14 |
+
from helios.utils.utils_base import encode_prompt
|
| 15 |
+
from torch.utils.data import DataLoader, Dataset
|
| 16 |
+
from tqdm import tqdm
|
| 17 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def setup_distributed_env():
|
| 21 |
+
dist.init_process_group(backend="nccl")
|
| 22 |
+
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def check_file_exists(args):
|
| 26 |
+
basename, idx, line, output_folder = args
|
| 27 |
+
uttid = f"{basename}_{idx:05d}"
|
| 28 |
+
output_path = os.path.join(output_folder, f"{uttid}.pt")
|
| 29 |
+
if os.path.exists(output_path):
|
| 30 |
+
return None, None
|
| 31 |
+
return line.strip(), uttid
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def prepare_dataset_on_rank0(txt_file, output_folder, rank):
|
| 35 |
+
while True:
|
| 36 |
+
try:
|
| 37 |
+
if rank == 0:
|
| 38 |
+
basename = Path(txt_file).stem
|
| 39 |
+
output_dir = Path(output_folder)
|
| 40 |
+
|
| 41 |
+
existing_files = set()
|
| 42 |
+
if output_dir.exists():
|
| 43 |
+
existing_files = {f.name for f in output_dir.iterdir() if f.is_file()}
|
| 44 |
+
|
| 45 |
+
prompts = []
|
| 46 |
+
uttids = []
|
| 47 |
+
|
| 48 |
+
with open(txt_file, "r") as f:
|
| 49 |
+
for idx, line in enumerate(f):
|
| 50 |
+
if not line.strip():
|
| 51 |
+
continue
|
| 52 |
+
|
| 53 |
+
uttid = f"{basename}_{idx:05d}"
|
| 54 |
+
filename = f"{uttid}.pt"
|
| 55 |
+
|
| 56 |
+
if filename not in existing_files:
|
| 57 |
+
prompts.append(line.strip())
|
| 58 |
+
uttids.append(uttid)
|
| 59 |
+
|
| 60 |
+
data_to_broadcast = [prompts, uttids]
|
| 61 |
+
else:
|
| 62 |
+
data_to_broadcast = [None, None]
|
| 63 |
+
|
| 64 |
+
dist.broadcast_object_list(data_to_broadcast, src=0)
|
| 65 |
+
break
|
| 66 |
+
except Exception:
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
return data_to_broadcast[0], data_to_broadcast[1]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class PromptDataset(Dataset):
|
| 73 |
+
def __init__(self, prompts, uttids):
|
| 74 |
+
self.prompts = prompts
|
| 75 |
+
self.uttids = uttids
|
| 76 |
+
|
| 77 |
+
def __len__(self):
|
| 78 |
+
return len(self.prompts)
|
| 79 |
+
|
| 80 |
+
def __getitem__(self, idx):
|
| 81 |
+
return {"prompt": self.prompts[idx], "uttid": self.uttids[idx]}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def save_single_file(uttid, output_path, prompt_raw, prompt_embed):
|
| 85 |
+
temp_to_save = {
|
| 86 |
+
"prompt_raw": prompt_raw,
|
| 87 |
+
"prompt_embed": prompt_embed,
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
torch.save(temp_to_save, output_path, pickle_protocol=4)
|
| 92 |
+
return f"✓ Saved: {output_path}"
|
| 93 |
+
except Exception as e:
|
| 94 |
+
return f"✗ Failed to save {uttid}: {str(e)}"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def main():
|
| 98 |
+
save_executor = ThreadPoolExecutor(max_workers=8)
|
| 99 |
+
save_futures = []
|
| 100 |
+
|
| 101 |
+
args = parse_args()
|
| 102 |
+
|
| 103 |
+
# =============== Environment ===============
|
| 104 |
+
batch_size = 16
|
| 105 |
+
dataloader_num_workers = 8
|
| 106 |
+
feature_folders = [
|
| 107 |
+
"example/vidprom_first_1k.txt",
|
| 108 |
+
]
|
| 109 |
+
output_folders = [
|
| 110 |
+
"example/toy_data/text-embedding/vidprom_filtered_extended",
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
if args.weight_dtype == "fp32":
|
| 114 |
+
args.weight_dtype = torch.float32
|
| 115 |
+
elif args.weight_dtype == "fp16":
|
| 116 |
+
args.weight_dtype = torch.float16
|
| 117 |
+
else:
|
| 118 |
+
args.weight_dtype = torch.bfloat16
|
| 119 |
+
|
| 120 |
+
setup_distributed_env()
|
| 121 |
+
|
| 122 |
+
rank = int(os.environ["LOCAL_RANK"])
|
| 123 |
+
device = torch.cuda.current_device()
|
| 124 |
+
|
| 125 |
+
accelerator = Accelerator()
|
| 126 |
+
|
| 127 |
+
# =============== Prepare Model ===============
|
| 128 |
+
weight_dtype = torch.bfloat16
|
| 129 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 130 |
+
args.base_model_path,
|
| 131 |
+
subfolder="tokenizer",
|
| 132 |
+
)
|
| 133 |
+
text_encoder = UMT5EncoderModel.from_pretrained(
|
| 134 |
+
args.base_model_path,
|
| 135 |
+
subfolder="text_encoder",
|
| 136 |
+
dtype=weight_dtype,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
text_encoder.eval()
|
| 140 |
+
text_encoder.requires_grad_(False)
|
| 141 |
+
text_encoder = text_encoder.to(device)
|
| 142 |
+
|
| 143 |
+
for feature_folder, output_folder in zip(feature_folders, output_folders):
|
| 144 |
+
print(f"Process {feature_folder} !")
|
| 145 |
+
|
| 146 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 147 |
+
prompts, uttids = prepare_dataset_on_rank0(feature_folder, output_folder, rank)
|
| 148 |
+
dataset = PromptDataset(prompts, uttids)
|
| 149 |
+
dataloader = DataLoader(
|
| 150 |
+
dataset,
|
| 151 |
+
batch_size=batch_size,
|
| 152 |
+
shuffle=False,
|
| 153 |
+
num_workers=dataloader_num_workers,
|
| 154 |
+
prefetch_factor=2 if dataloader_num_workers > 0 else None,
|
| 155 |
+
pin_memory=True,
|
| 156 |
+
drop_last=False,
|
| 157 |
+
)
|
| 158 |
+
dataloader = accelerator.prepare(dataloader)
|
| 159 |
+
print(f"Dataset size: {len(dataset)}, Dataloader batches: {len(dataloader)}")
|
| 160 |
+
print(f"Process index: {accelerator.process_index}, World size: {accelerator.num_processes}")
|
| 161 |
+
|
| 162 |
+
if len(dataloader) == 0:
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
# =============== Main Loop ===============
|
| 166 |
+
if rank == 0:
|
| 167 |
+
pbar = tqdm(total=len(dataloader), desc="Processing")
|
| 168 |
+
|
| 169 |
+
for i, batch in enumerate(dataloader):
|
| 170 |
+
batch_size = len(batch["uttid"])
|
| 171 |
+
uttids = batch["uttid"]
|
| 172 |
+
prompts_raw = batch["prompt"]
|
| 173 |
+
|
| 174 |
+
files_to_process = []
|
| 175 |
+
indices_to_process = []
|
| 176 |
+
|
| 177 |
+
for idx, uttid in enumerate(uttids):
|
| 178 |
+
output_path = os.path.join(output_folder, f"{uttid}.pt")
|
| 179 |
+
if os.path.exists(output_path):
|
| 180 |
+
if rank == 0:
|
| 181 |
+
print(f"Skipping existing file: {output_path}")
|
| 182 |
+
else:
|
| 183 |
+
files_to_process.append((uttid, output_path))
|
| 184 |
+
indices_to_process.append(idx)
|
| 185 |
+
|
| 186 |
+
if len(files_to_process) == 0:
|
| 187 |
+
if rank == 0:
|
| 188 |
+
pbar.update(1)
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
prompts_to_encode = [prompts_raw[idx] for idx in indices_to_process]
|
| 192 |
+
|
| 193 |
+
with torch.no_grad():
|
| 194 |
+
prompt_embeds, _ = encode_prompt(
|
| 195 |
+
tokenizer=tokenizer,
|
| 196 |
+
text_encoder=text_encoder,
|
| 197 |
+
prompt=prompts_to_encode,
|
| 198 |
+
device=device,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
for idx, (uttid, output_path) in enumerate(files_to_process):
|
| 202 |
+
prompt_embed_cpu = prompt_embeds[idx].cpu().clone()
|
| 203 |
+
|
| 204 |
+
future = save_executor.submit(
|
| 205 |
+
save_single_file, uttid, output_path, prompts_to_encode[idx], prompt_embed_cpu
|
| 206 |
+
)
|
| 207 |
+
save_futures.append(future)
|
| 208 |
+
|
| 209 |
+
if len(save_futures) > 100:
|
| 210 |
+
completed_futures = [f for f in save_futures if f.done()]
|
| 211 |
+
|
| 212 |
+
if rank == 0:
|
| 213 |
+
for future in completed_futures:
|
| 214 |
+
try:
|
| 215 |
+
result = future.result()
|
| 216 |
+
print(result)
|
| 217 |
+
except Exception as e:
|
| 218 |
+
print(f"Save task error: {e}")
|
| 219 |
+
|
| 220 |
+
save_futures = [f for f in save_futures if not f.done()]
|
| 221 |
+
|
| 222 |
+
if rank == 0:
|
| 223 |
+
pbar.update(1)
|
| 224 |
+
|
| 225 |
+
if rank == 0:
|
| 226 |
+
pbar.close()
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def parse_args():
|
| 230 |
+
parser = argparse.ArgumentParser(description="Generate video with model")
|
| 231 |
+
|
| 232 |
+
# === Model paths ===
|
| 233 |
+
parser.add_argument("--base_model_path", type=str, default="BestWishYsh/Helios-Base")
|
| 234 |
+
|
| 235 |
+
# === Generation parameters ===
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--weight_dtype",
|
| 238 |
+
type=str,
|
| 239 |
+
default="bf16",
|
| 240 |
+
choices=["bf16", "fp16", "fp32"],
|
| 241 |
+
help="Data type for model weights.",
|
| 242 |
+
)
|
| 243 |
+
parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.")
|
| 244 |
+
|
| 245 |
+
# === Prompts ===
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--negative_prompt",
|
| 248 |
+
type=str,
|
| 249 |
+
default="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",
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
return parser.parse_args()
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
main()
|
Helios-main/tools/offload_data/get_text-embedding.sh
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export OMNISTORE_LOAD_STRICT_MODE=0
|
| 2 |
+
export OMNISTORE_LOGGING_LEVEL=ERROR
|
| 3 |
+
#################################################################
|
| 4 |
+
## Torch
|
| 5 |
+
#################################################################
|
| 6 |
+
export TOKENIZERS_PARALLELISM=false
|
| 7 |
+
export TORCH_LOGS="+dynamo,recompiles,graph_breaks"
|
| 8 |
+
export TORCHDYNAMO_VERBOSE=1
|
| 9 |
+
export TORCH_NCCL_ENABLE_MONITORING=1
|
| 10 |
+
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True,garbage_collection_threshold:0.9"
|
| 11 |
+
#################################################################
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
#################################################################
|
| 15 |
+
## NCCL
|
| 16 |
+
#################################################################
|
| 17 |
+
export NCCL_IB_GID_INDEX=3
|
| 18 |
+
export NCCL_IB_HCA=$ARNOLD_RDMA_DEVICE
|
| 19 |
+
export NCCL_SOCKET_IFNAME=eth0
|
| 20 |
+
export NCCL_SOCKET_TIMEOUT=3600000
|
| 21 |
+
|
| 22 |
+
export NCCL_DEBUG=WARN # disable the verbose NCCL logs
|
| 23 |
+
export NCCL_P2P_DISABLE=0
|
| 24 |
+
export NCCL_IB_DISABLE=0 # was 1
|
| 25 |
+
export NCCL_SHM_DISABLE=0 # was 1
|
| 26 |
+
export NCCL_P2P_LEVEL=NVL
|
| 27 |
+
|
| 28 |
+
export NCCL_PXN_DISABLE=0
|
| 29 |
+
export NCCL_NET_GDR_LEVEL=2
|
| 30 |
+
export NCCL_IB_QPS_PER_CONNECTION=4
|
| 31 |
+
export NCCL_IB_TC=160
|
| 32 |
+
export NCCL_IB_TIMEOUT=22
|
| 33 |
+
#################################################################
|
| 34 |
+
|
| 35 |
+
#################################################################
|
| 36 |
+
## DIST
|
| 37 |
+
#################################################################
|
| 38 |
+
MASTER_ADDR=$ARNOLD_WORKER_0_HOST
|
| 39 |
+
ports=(`echo $METIS_WORKER_0_PORT | tr ',' ' '`)
|
| 40 |
+
MASTER_PORT=${ports[0]}
|
| 41 |
+
NNODES=$ARNOLD_WORKER_NUM
|
| 42 |
+
NODE_RANK=$ARNOLD_ID
|
| 43 |
+
GPUS_PER_NODE=$ARNOLD_WORKER_GPU
|
| 44 |
+
|
| 45 |
+
# export CUDA_VISIBLE_DEVICES=1
|
| 46 |
+
# MASTER_PORT=12345
|
| 47 |
+
# GPUS_PER_NODE=1
|
| 48 |
+
# NNODES=1
|
| 49 |
+
# NODE_RANK=0
|
| 50 |
+
|
| 51 |
+
WORLD_SIZE=$(($GPUS_PER_NODE*$NNODES))
|
| 52 |
+
|
| 53 |
+
DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES --node_rank $NODE_RANK --master_addr $MASTER_ADDR --master_port $MASTER_PORT"
|
| 54 |
+
if [ ! -z $RDZV_BACKEND ]; then
|
| 55 |
+
DISTRIBUTED_ARGS="${DISTRIBUTED_ARGS} --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_id 9863 --rdzv_backend c10d"
|
| 56 |
+
export NCCL_SHM_DISABLE=1
|
| 57 |
+
fi
|
| 58 |
+
|
| 59 |
+
echo -e "\033[31mDISTRIBUTED_ARGS: ${DISTRIBUTED_ARGS}\033[0m"
|
| 60 |
+
|
| 61 |
+
#################################################################
|
| 62 |
+
#
|
| 63 |
+
torchrun $DISTRIBUTED_ARGS \
|
| 64 |
+
tools/offload_data/get_text-embedding.py
|
Helios-main/tools/others/benchmark/benchmark_compile_performance.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 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-main/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-main/tools/others/benchmark/benchmark_patchification_performance.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
os.environ["DIFFUSERS_ENABLE_HUB_KERNELS"] = "yes"
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import time
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
|
| 12 |
+
from diffusers import WanTransformer3DModel
|
| 13 |
+
|
| 14 |
+
|
| 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-main/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.386,
|
| 303 |
+
"training_peak_gb": 71.118,
|
| 304 |
+
"training_mem_diff_gb": 44.298
|
| 305 |
+
}
|
| 306 |
+
]
|
| 307 |
+
}
|
| 308 |
+
]
|
| 309 |
+
}
|
Helios-main/tools/others/benchmark/benchmark_triton_performance.py
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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-main/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 |
+
}
|