Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Helios/_DEV/helios/diffusers_version/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-311.pyc +0 -0
- Helios/_DEV/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-312.pyc +0 -0
- Helios/_DEV/helios/diffusers_version/__pycache__/scheduling_helios_diffusers.cpython-311.pyc +0 -0
- Helios/_DEV/helios/diffusers_version/__pycache__/transformer_helios_diffusers.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/__init__.py +5 -0
- Helios/_DEV/helios/modules/helios_kernels/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/__pycache__/attention_dispatch.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/__pycache__/fp32_rmsnorm.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/__pycache__/tiled_linear.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/__pycache__/triton_norm.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/__pycache__/triton_rope.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/__pycache__/utils.cpython-311.pyc +0 -0
- Helios/_DEV/helios/modules/helios_kernels/attention_dispatch.py +167 -0
- Helios/_DEV/helios/modules/helios_kernels/fp32_rmsnorm.py +48 -0
- Helios/_DEV/helios/modules/helios_kernels/tiled_linear.py +399 -0
- Helios/_DEV/helios/modules/helios_kernels/triton_norm.py +413 -0
- Helios/_DEV/helios/modules/helios_kernels/triton_rope.py +392 -0
- Helios/_DEV/helios/modules/helios_kernels/utils.py +70 -0
- Helios/_DEV/helios/pipelines/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV/helios/pipelines/__pycache__/pipeline_output.cpython-311.pyc +0 -0
- Helios/_DEV/helios/pipelines/__pycache__/pipeline_output.cpython-312.pyc +0 -0
- Helios/_DEV/helios/utils/__init__.py +0 -0
- Helios/_DEV/helios/utils/__pycache__/__init__.cpython-311.pyc +0 -0
- Helios/_DEV/helios/utils/__pycache__/utils_base.cpython-311.pyc +0 -0
- Helios/_DEV/helios/utils/train_config.py +443 -0
- Helios/_DEV/helios/utils/utils_base.py +745 -0
- Helios/_DEV/helios/utils/utils_helios_base.py +1091 -0
- Helios/_DEV/helios/utils/utils_helios_post.py +0 -0
- Helios/_DEV/helios/utils/utils_recycle_batch.py +724 -0
- Helios/_DEV/helios/utils/utils_recycle_single.py +437 -0
- Helios/_DEV/helios/videoalign/__init__.py +0 -0
- Helios/_DEV/helios/videoalign/data.py +278 -0
- Helios/_DEV/helios/videoalign/inference.py +321 -0
- Helios/_DEV/helios/videoalign/prompt_template.py +129 -0
- Helios/_DEV/helios/videoalign/train_reward.py +118 -0
- Helios/_DEV/helios/videoalign/trainer.py +133 -0
- Helios/_DEV/helios/videoalign/utils.py +236 -0
- Helios/_DEV/helios/videoalign/vision_process.py +396 -0
- Helios/_DEV/output_helios/helios-base/A_beautifully_crafted_green_ceramic_vase_adorned_with_intricate_patterns_and_det_1779441980/relative_l1.csv +0 -0
- Helios/_DEV/output_helios/helios-base/A_close_up_of_a_sleek_black_bicycle_parked_on_a_clean_paved_street_The_bicycle_h_1779439971/relative_l1.csv +0 -0
- Helios/_DEV/output_helios/helios-base/A_close_up_view_of_a_vibrant_pink_ceramic_bowl_with_intricate_floral_patterns_pa_1779441890/relative_l1.csv +0 -0
- Helios/_DEV/output_helios/helios-base/A_detailed_close_up_of_a_sleek_glossy_purple_suitcase_with_silver_hardware_The_s_1779445728/relative_l1.csv +0 -0
- Helios/_DEV/output_helios/helios-base/A_front_view_of_a_colorful_kite_lying_flat_on_the_bottom_of_a_skateboard_The_ska_1779440072/relative_l1.csv +0 -0
- Helios/_DEV/output_helios/helios-base/A_front_view_of_a_creative_culinary_fusion_dish_featuring_a_hot_dog_placed_atop__1779438168/relative_l1.csv +0 -0
- Helios/_DEV/output_helios/helios-base/A_vibrant_underwater_coral_reef_teeming_with_life_The_corals_are_in_various_shap_1779445801/relative_l1.csv +0 -0
- Helios/_DEV/output_helios/helios-base/A_woman_dancing_1779378268/relative_l1.csv +151 -0
- Helios/_DEV/output_helios/helios-base/A_woman_dancing_1779378754/relative_l1.csv +151 -0
- Helios/_DEV/output_helios/helios-base/Animated_style_a_well_dressed_couple_in_formal_evening_wear_is_walking_down_a_bu_1779443890/relative_l1.csv +0 -0
Helios/_DEV/helios/diffusers_version/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (200 Bytes). View file
|
|
|
Helios/_DEV/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-311.pyc
ADDED
|
Binary file (63.2 kB). View file
|
|
|
Helios/_DEV/helios/diffusers_version/__pycache__/pipeline_helios_diffusers.cpython-312.pyc
ADDED
|
Binary file (59.7 kB). View file
|
|
|
Helios/_DEV/helios/diffusers_version/__pycache__/scheduling_helios_diffusers.cpython-311.pyc
ADDED
|
Binary file (39.9 kB). View file
|
|
|
Helios/_DEV/helios/diffusers_version/__pycache__/transformer_helios_diffusers.cpython-311.pyc
ADDED
|
Binary file (44.1 kB). View file
|
|
|
Helios/_DEV/helios/modules/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (190 Bytes). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .attention_dispatch import attn_varlen_func, create_navit_attention_masks
|
| 2 |
+
from .fp32_rmsnorm import replace_rmsnorm_with_fp32
|
| 3 |
+
from .tiled_linear import replace_linear_with_tiled_linear
|
| 4 |
+
from .triton_norm import replace_all_norms_with_flash_norms
|
| 5 |
+
from .triton_rope import replace_rope_with_flash_rope
|
Helios/_DEV/helios/modules/helios_kernels/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (652 Bytes). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/__pycache__/attention_dispatch.cpython-311.pyc
ADDED
|
Binary file (7.4 kB). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/__pycache__/fp32_rmsnorm.cpython-311.pyc
ADDED
|
Binary file (2.67 kB). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/__pycache__/tiled_linear.cpython-311.pyc
ADDED
|
Binary file (20.1 kB). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/__pycache__/triton_norm.cpython-311.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/__pycache__/triton_rope.cpython-311.pyc
ADDED
|
Binary file (24.2 kB). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (2.77 kB). View file
|
|
|
Helios/_DEV/helios/modules/helios_kernels/attention_dispatch.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from kernels import get_kernel
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
try:
|
| 6 |
+
# FA3 Only support Hopper (SM90, H100/H800)
|
| 7 |
+
major, _ = torch.cuda.get_device_capability()
|
| 8 |
+
if major < 9:
|
| 9 |
+
raise RuntimeError("FA3 requires Hopper (SM90+), current GPU not supported")
|
| 10 |
+
flash_attn3 = get_kernel("kernels-community/flash-attn3")
|
| 11 |
+
flash_attn_func = flash_attn3.flash_attn_func
|
| 12 |
+
flash_attn_varlen_func = flash_attn3.flash_attn_varlen_func
|
| 13 |
+
print("Flash Attn 3 is installed!")
|
| 14 |
+
except (ImportError, RuntimeError):
|
| 15 |
+
try:
|
| 16 |
+
flash_attn2 = get_kernel("kernels-community/flash-attn2")
|
| 17 |
+
flash_attn_func = flash_attn2.flash_attn_func
|
| 18 |
+
flash_attn_varlen_func = flash_attn2.flash_attn_varlen_func
|
| 19 |
+
print("Flash Attn 2 is installed!")
|
| 20 |
+
except ImportError:
|
| 21 |
+
print("Flash Attn 2 / 3 is not installed!")
|
| 22 |
+
flash_attn_varlen_func = None
|
| 23 |
+
flash_attn_func = None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
# raise NotImplementedError
|
| 28 |
+
from sageattention import sageattn, sageattn_varlen
|
| 29 |
+
|
| 30 |
+
print("Sage Attn is installed!")
|
| 31 |
+
except ImportError:
|
| 32 |
+
print("Sage Attn is not installed!")
|
| 33 |
+
sageattn_varlen = None
|
| 34 |
+
sageattn = None
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
# raise NotImplementedError
|
| 38 |
+
from xformers.ops import memory_efficient_attention as xformers_attn_func
|
| 39 |
+
|
| 40 |
+
print("Xformers is installed!")
|
| 41 |
+
except ImportError:
|
| 42 |
+
print("Xformers is not installed!")
|
| 43 |
+
xformers_attn_func = None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def create_navit_attention_masks(
|
| 47 |
+
batch_size: int,
|
| 48 |
+
original_context_length_list: list,
|
| 49 |
+
history_context_length: int,
|
| 50 |
+
encoder_hidden_states_seq_len: int,
|
| 51 |
+
device: torch.device,
|
| 52 |
+
restrict_self_attn: bool = False,
|
| 53 |
+
guidance_cross_attn: bool = False,
|
| 54 |
+
):
|
| 55 |
+
# For navit_hidden_attention_mask
|
| 56 |
+
if restrict_self_attn:
|
| 57 |
+
cu_seqlens_q = [0]
|
| 58 |
+
for _ in range(batch_size):
|
| 59 |
+
for length in original_context_length_list:
|
| 60 |
+
cu_seqlens_q.append(cu_seqlens_q[-1] + length)
|
| 61 |
+
cu_seqlens_q = torch.tensor(cu_seqlens_q, device=device, dtype=torch.int32)
|
| 62 |
+
max_seqlen_q = max(original_context_length_list)
|
| 63 |
+
|
| 64 |
+
cu_seqlens_kv = [0]
|
| 65 |
+
for _ in range(batch_size):
|
| 66 |
+
for length in original_context_length_list:
|
| 67 |
+
cu_seqlens_kv.append(cu_seqlens_kv[-1] + length + history_context_length)
|
| 68 |
+
cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
|
| 69 |
+
max_seqlen_kv = max(original_context_length_list) + history_context_length
|
| 70 |
+
else:
|
| 71 |
+
cu_seqlens_kv = [0]
|
| 72 |
+
for _ in range(batch_size):
|
| 73 |
+
for length in original_context_length_list:
|
| 74 |
+
cu_seqlens_kv.append(cu_seqlens_kv[-1] + length + history_context_length)
|
| 75 |
+
cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
|
| 76 |
+
max_seqlen_kv = max(original_context_length_list) + history_context_length
|
| 77 |
+
cu_seqlens_q = cu_seqlens_kv
|
| 78 |
+
max_seqlen_q = max_seqlen_kv
|
| 79 |
+
navit_hidden_attention_mask = cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv
|
| 80 |
+
|
| 81 |
+
# For navit_history_hidden_attention_mask
|
| 82 |
+
navit_history_hidden_attention_mask = None
|
| 83 |
+
if restrict_self_attn:
|
| 84 |
+
cu_seqlens_kv = [0]
|
| 85 |
+
for _ in range(batch_size):
|
| 86 |
+
for length in original_context_length_list:
|
| 87 |
+
cu_seqlens_kv.append(cu_seqlens_kv[-1] + history_context_length)
|
| 88 |
+
cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
|
| 89 |
+
max_seqlen_kv = history_context_length
|
| 90 |
+
cu_seqlens_q = cu_seqlens_kv
|
| 91 |
+
max_seqlen_q = max_seqlen_kv
|
| 92 |
+
navit_history_hidden_attention_mask = cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv
|
| 93 |
+
|
| 94 |
+
# For navit_encoder_attention_mask
|
| 95 |
+
if guidance_cross_attn:
|
| 96 |
+
cross_cu_seqlens_q = [0]
|
| 97 |
+
for _ in range(batch_size):
|
| 98 |
+
for length in original_context_length_list:
|
| 99 |
+
cross_cu_seqlens_q.append(cross_cu_seqlens_q[-1] + length)
|
| 100 |
+
cross_cu_seqlens_q = torch.tensor(cross_cu_seqlens_q, device=device, dtype=torch.int32)
|
| 101 |
+
cross_max_seqlen_q = max(original_context_length_list)
|
| 102 |
+
else:
|
| 103 |
+
cross_cu_seqlens_q = [0]
|
| 104 |
+
for _ in range(batch_size):
|
| 105 |
+
for length in original_context_length_list:
|
| 106 |
+
cross_cu_seqlens_q.append(cross_cu_seqlens_q[-1] + length + history_context_length)
|
| 107 |
+
cross_cu_seqlens_q = torch.tensor(cross_cu_seqlens_q, device=device, dtype=torch.int32)
|
| 108 |
+
cross_cu_seqlens_q[0] = 0
|
| 109 |
+
cross_max_seqlen_q = max(original_context_length_list) + history_context_length
|
| 110 |
+
|
| 111 |
+
cu_seqlens_kv = [0]
|
| 112 |
+
for _ in range(batch_size):
|
| 113 |
+
for length in original_context_length_list:
|
| 114 |
+
cu_seqlens_kv.append(cu_seqlens_kv[-1] + encoder_hidden_states_seq_len)
|
| 115 |
+
cu_seqlens_kv = torch.tensor(cu_seqlens_kv, device=device, dtype=torch.int32)
|
| 116 |
+
max_seqlen_kv = encoder_hidden_states_seq_len
|
| 117 |
+
navit_encoder_attention_mask = cross_cu_seqlens_q, cu_seqlens_kv, cross_max_seqlen_q, max_seqlen_kv
|
| 118 |
+
|
| 119 |
+
return navit_hidden_attention_mask, navit_encoder_attention_mask, navit_history_hidden_attention_mask
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@torch.compiler.disable
|
| 123 |
+
def _flash_attn_wrapper(q, k, v):
|
| 124 |
+
return flash_attn_func(q, k, v)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@torch.compiler.disable
|
| 128 |
+
def _flash_attn_varlen_wrapper(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv):
|
| 129 |
+
return flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def attn_varlen_func(q, k, v, attention_mask=None):
|
| 133 |
+
if attention_mask is None:
|
| 134 |
+
if flash_attn_func is not None:
|
| 135 |
+
x = _flash_attn_wrapper(q, k, v)
|
| 136 |
+
return x
|
| 137 |
+
|
| 138 |
+
if sageattn is not None:
|
| 139 |
+
x = sageattn(q, k, v, tensor_layout="NHD")
|
| 140 |
+
return x
|
| 141 |
+
|
| 142 |
+
if xformers_attn_func is not None:
|
| 143 |
+
x = xformers_attn_func(q, k, v)
|
| 144 |
+
return x
|
| 145 |
+
|
| 146 |
+
x = torch.nn.functional.scaled_dot_product_attention(
|
| 147 |
+
q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
| 148 |
+
).transpose(1, 2)
|
| 149 |
+
return x
|
| 150 |
+
|
| 151 |
+
B, L, H, C = q.shape
|
| 152 |
+
|
| 153 |
+
q = q.flatten(0, 1)
|
| 154 |
+
k = k.flatten(0, 1)
|
| 155 |
+
v = v.flatten(0, 1)
|
| 156 |
+
|
| 157 |
+
cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv = attention_mask
|
| 158 |
+
if flash_attn_varlen_func is not None:
|
| 159 |
+
x = _flash_attn_varlen_wrapper(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)
|
| 160 |
+
elif sageattn_varlen is not None:
|
| 161 |
+
x = sageattn_varlen(q, k, v, cu_seqlens_q, cu_seqlens_kv, max_seqlen_q, max_seqlen_kv)
|
| 162 |
+
else:
|
| 163 |
+
raise NotImplementedError("No Attn Installed!")
|
| 164 |
+
|
| 165 |
+
x = x.unflatten(0, (B, L))
|
| 166 |
+
|
| 167 |
+
return x
|
Helios/_DEV/helios/modules/helios_kernels/fp32_rmsnorm.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from diffusers.models.normalization import RMSNorm
|
| 5 |
+
from diffusers.utils import is_torch_npu_available, is_torch_version
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# ------------------------------- replace funtion -------------------------------
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def replace_rmsnorm_with_fp32(model):
|
| 12 |
+
patched_count = 0
|
| 13 |
+
for name, module in model.named_modules():
|
| 14 |
+
if isinstance(module, (torch.nn.RMSNorm, RMSNorm)):
|
| 15 |
+
|
| 16 |
+
def new_forward(self, x):
|
| 17 |
+
return FP32RMSNorm.forward(self, x)
|
| 18 |
+
|
| 19 |
+
module.forward = new_forward.__get__(module, module.__class__)
|
| 20 |
+
patched_count += 1
|
| 21 |
+
print(f"Patched {patched_count} FP32_RMSNorm modules\n")
|
| 22 |
+
return model
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ------------------------------- Tiled MLP -------------------------------
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class FP32RMSNorm(RMSNorm):
|
| 29 |
+
def forward(self, hidden_states):
|
| 30 |
+
if is_torch_npu_available():
|
| 31 |
+
raise ValueError("FP32RMSNorm is not available on NPU")
|
| 32 |
+
|
| 33 |
+
if not is_torch_version(">=", "2.4"):
|
| 34 |
+
raise ValueError("FP32RMSNorm is only available in PyTorch 2.4 or higher")
|
| 35 |
+
|
| 36 |
+
original_dtype = hidden_states.dtype
|
| 37 |
+
hidden_states = nn.functional.rms_norm(
|
| 38 |
+
hidden_states.float(),
|
| 39 |
+
normalized_shape=(hidden_states.shape[-1],),
|
| 40 |
+
weight=self.weight.float(),
|
| 41 |
+
eps=self.eps,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
bias = getattr(self, "bias", None)
|
| 45 |
+
if bias is not None:
|
| 46 |
+
hidden_states = hidden_states + bias.float()
|
| 47 |
+
|
| 48 |
+
return hidden_states.to(original_dtype)
|
Helios/_DEV/helios/modules/helios_kernels/tiled_linear.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import math
|
| 3 |
+
from typing import Callable, List, Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
from diffusers.models.activations import GEGLU, GELU, ApproximateGELU, LinearActivation, SwiGLU
|
| 9 |
+
from diffusers.utils import deprecate
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# ------------------------------- replace funtion -------------------------------
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def replace_linear_with_tiled_linear(model, num_shards=None, patch_by_names=True, patch_by_types=True):
|
| 16 |
+
target_names = ["to_q", "to_k", "to_v", "add_k_proj", "add_v_proj"]
|
| 17 |
+
target_types = ["FeedForward"]
|
| 18 |
+
|
| 19 |
+
patched_count = 0
|
| 20 |
+
|
| 21 |
+
def tiled_forward(self, x):
|
| 22 |
+
compute_params = list(self.parameters())
|
| 23 |
+
return apply_tiled_linear(
|
| 24 |
+
fn=lambda module, input: module._original_forward(input),
|
| 25 |
+
mlp_module=self,
|
| 26 |
+
x=x,
|
| 27 |
+
num_shards=num_shards,
|
| 28 |
+
compute_params=compute_params,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
for name, module in model.named_modules():
|
| 32 |
+
layer_name = name.rsplit(".", 1)[-1] if "." in name else name
|
| 33 |
+
module_type = type(module).__name__
|
| 34 |
+
|
| 35 |
+
should_patch = False
|
| 36 |
+
if patch_by_types and module_type in target_types:
|
| 37 |
+
should_patch = True
|
| 38 |
+
if patch_by_names and layer_name in target_names and isinstance(module, torch.nn.Linear):
|
| 39 |
+
should_patch = True
|
| 40 |
+
|
| 41 |
+
if should_patch:
|
| 42 |
+
module._original_forward = module.forward
|
| 43 |
+
module.forward = tiled_forward.__get__(module, module.__class__)
|
| 44 |
+
patched_count += 1
|
| 45 |
+
# print(f" Patched {module_type}: {name}")
|
| 46 |
+
|
| 47 |
+
print(f"Patched {patched_count} FeedForward modules with TiledMLP\n")
|
| 48 |
+
return model
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# ------------------------------- Tiled MLP -------------------------------
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def ensure_contiguous(fn):
|
| 55 |
+
@functools.wraps(fn)
|
| 56 |
+
def wrapper(ctx, *args, **kwargs):
|
| 57 |
+
def maybe_to_contiguous(x):
|
| 58 |
+
return x.contiguous() if isinstance(x, torch.Tensor) else x
|
| 59 |
+
|
| 60 |
+
args = [maybe_to_contiguous(arg) for arg in args]
|
| 61 |
+
kwargs = {k: maybe_to_contiguous(v) for k, v in kwargs.items()}
|
| 62 |
+
return fn(ctx, *args, **kwargs)
|
| 63 |
+
|
| 64 |
+
return wrapper
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class TiledLinear(torch.autograd.Function):
|
| 68 |
+
"""
|
| 69 |
+
Based on DeepSpeed's TiledMLP:
|
| 70 |
+
https://github.com/deepspeedai/DeepSpeed/blob/v0.18.2/deepspeed/runtime/sequence_parallel/ulysses_sp.py#L838
|
| 71 |
+
|
| 72 |
+
Perform a tiled MLP computation to massively reduce memory usage needed to compute MLP
|
| 73 |
+
when using very long sequence lengths.
|
| 74 |
+
|
| 75 |
+
This module re-computes `forward` in the `backward`. So the `forward` occurs twice each iteration.
|
| 76 |
+
And if you're using activation checkpointing it then occurs thrice.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
fn: the function to call on sharded inputs (e.g., mlp.forward)
|
| 80 |
+
mlp_module: the MLP nn.Module object
|
| 81 |
+
x: the input to MLP.forward (hidden_states)
|
| 82 |
+
shards: how many shards to use
|
| 83 |
+
compute_params: a list of weights engaged in the compute
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
the computed hidden_states
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
@staticmethod
|
| 90 |
+
@ensure_contiguous
|
| 91 |
+
def forward(
|
| 92 |
+
ctx,
|
| 93 |
+
fn: Callable,
|
| 94 |
+
mlp_module: torch.nn.Module,
|
| 95 |
+
x: torch.Tensor,
|
| 96 |
+
shards: int,
|
| 97 |
+
compute_params: Optional[List[torch.nn.Parameter]] = None,
|
| 98 |
+
) -> torch.Tensor:
|
| 99 |
+
ctx.fn = fn
|
| 100 |
+
ctx.mlp_module = mlp_module
|
| 101 |
+
ctx.shards = shards
|
| 102 |
+
ctx.save_for_backward(x)
|
| 103 |
+
|
| 104 |
+
# x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts)
|
| 105 |
+
x_shards = list(torch.chunk(x, chunks=shards, dim=-2))
|
| 106 |
+
with torch.no_grad():
|
| 107 |
+
output_shards = [fn(mlp_module, x_shard) for x_shard in x_shards]
|
| 108 |
+
output_unsharded = torch.cat(output_shards, dim=-2)
|
| 109 |
+
|
| 110 |
+
return output_unsharded
|
| 111 |
+
|
| 112 |
+
@staticmethod
|
| 113 |
+
@ensure_contiguous
|
| 114 |
+
def backward(ctx, *grads) -> tuple:
|
| 115 |
+
fn = ctx.fn
|
| 116 |
+
(x,) = ctx.saved_tensors
|
| 117 |
+
mlp_module = ctx.mlp_module
|
| 118 |
+
shards = ctx.shards
|
| 119 |
+
|
| 120 |
+
x_requires_grad = x.requires_grad
|
| 121 |
+
x = x.detach()
|
| 122 |
+
# detach() unsets x.requires_grad, so restore it
|
| 123 |
+
x.requires_grad_(x_requires_grad)
|
| 124 |
+
|
| 125 |
+
# x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts)
|
| 126 |
+
hidden_size = x.shape[-1]
|
| 127 |
+
x_shape_orig = x.shape
|
| 128 |
+
|
| 129 |
+
# flatten bs+seqlen to avoid having stride issues when narrowing into seqlen w/ bs>1
|
| 130 |
+
x = x.view(-1, hidden_size)
|
| 131 |
+
incoming_grad = grads[0].view(-1, hidden_size)
|
| 132 |
+
x_grad = torch.zeros_like(x)
|
| 133 |
+
|
| 134 |
+
x_shards = list(torch.chunk(x, chunks=shards, dim=0))
|
| 135 |
+
|
| 136 |
+
trainable_params = [p for p in mlp_module.parameters() if p.requires_grad]
|
| 137 |
+
|
| 138 |
+
for i, x_shard in enumerate(x_shards):
|
| 139 |
+
x_shard = x_shard.detach().requires_grad_(x_requires_grad)
|
| 140 |
+
|
| 141 |
+
shard_step = x_shards[i].shape[0]
|
| 142 |
+
shard_offset = i * x_shards[0].shape[0]
|
| 143 |
+
|
| 144 |
+
incoming_grad_shard = incoming_grad.narrow(0, shard_offset, shard_step).view_as(x_shard)
|
| 145 |
+
|
| 146 |
+
with torch.enable_grad():
|
| 147 |
+
output = fn(mlp_module, x_shard)
|
| 148 |
+
|
| 149 |
+
grads_tuple = torch.autograd.grad(
|
| 150 |
+
outputs=output,
|
| 151 |
+
inputs=[x_shard] + trainable_params,
|
| 152 |
+
grad_outputs=incoming_grad_shard,
|
| 153 |
+
allow_unused=True,
|
| 154 |
+
retain_graph=False,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
x_grad.narrow(0, shard_offset, shard_step).copy_(grads_tuple[0])
|
| 158 |
+
|
| 159 |
+
for param, grad in zip(trainable_params, grads_tuple[1:]):
|
| 160 |
+
if grad is not None:
|
| 161 |
+
if param.grad is None:
|
| 162 |
+
param.grad = grad
|
| 163 |
+
else:
|
| 164 |
+
param.grad.add_(grad)
|
| 165 |
+
|
| 166 |
+
# unflatten
|
| 167 |
+
x_grad = x_grad.view(x_shape_orig)
|
| 168 |
+
|
| 169 |
+
return (None, None, x_grad, None, None)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def apply_tiled_linear(
|
| 173 |
+
fn: Callable,
|
| 174 |
+
mlp_module: torch.nn.Module,
|
| 175 |
+
x: torch.Tensor,
|
| 176 |
+
num_shards: Optional[int] = None,
|
| 177 |
+
compute_params: Optional[List[torch.nn.Parameter]] = None,
|
| 178 |
+
) -> torch.Tensor:
|
| 179 |
+
"""
|
| 180 |
+
Apply tiled MLP computation for memory efficiency.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
fn: the function to call on sharded inputs (e.g., lambda module, x: module(x))
|
| 184 |
+
mlp_module: the MLP nn.Module object
|
| 185 |
+
x: the input tensor with shape [bs, seqlen, hidden_size] or [seqlen, hidden_size]
|
| 186 |
+
num_shards: number of shards to use. If None, automatically calculated as ceil(seqlen / hidden_size)
|
| 187 |
+
compute_params: list of parameters for DeepSpeed ZeRO optimization
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
output tensor with the same shape as input
|
| 191 |
+
"""
|
| 192 |
+
if num_shards is None:
|
| 193 |
+
# x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size]
|
| 194 |
+
hidden_size = x.shape[-1]
|
| 195 |
+
seqlen = x.shape[-2]
|
| 196 |
+
num_shards = math.ceil(seqlen / hidden_size)
|
| 197 |
+
|
| 198 |
+
# Ensure num_shards is at least 1
|
| 199 |
+
num_shards = max(1, num_shards)
|
| 200 |
+
|
| 201 |
+
return TiledLinear.apply(
|
| 202 |
+
fn,
|
| 203 |
+
mlp_module,
|
| 204 |
+
x,
|
| 205 |
+
num_shards,
|
| 206 |
+
compute_params,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# ------------------------------- Tiled FeedForward -------------------------------
|
| 211 |
+
class FeedForward(nn.Module):
|
| 212 |
+
r"""
|
| 213 |
+
A feed-forward layer.
|
| 214 |
+
|
| 215 |
+
Parameters:
|
| 216 |
+
dim (`int`): The number of channels in the input.
|
| 217 |
+
dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
|
| 218 |
+
mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
|
| 219 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
| 220 |
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
| 221 |
+
final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
|
| 222 |
+
bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
def __init__(
|
| 226 |
+
self,
|
| 227 |
+
dim: int,
|
| 228 |
+
dim_out: Optional[int] = None,
|
| 229 |
+
mult: int = 4,
|
| 230 |
+
dropout: float = 0.0,
|
| 231 |
+
activation_fn: str = "geglu",
|
| 232 |
+
final_dropout: bool = False,
|
| 233 |
+
inner_dim=None,
|
| 234 |
+
bias: bool = True,
|
| 235 |
+
):
|
| 236 |
+
super().__init__()
|
| 237 |
+
if inner_dim is None:
|
| 238 |
+
inner_dim = int(dim * mult)
|
| 239 |
+
dim_out = dim_out if dim_out is not None else dim
|
| 240 |
+
|
| 241 |
+
if activation_fn == "gelu":
|
| 242 |
+
act_fn = GELU(dim, inner_dim, bias=bias)
|
| 243 |
+
if activation_fn == "gelu-approximate":
|
| 244 |
+
act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
|
| 245 |
+
elif activation_fn == "geglu":
|
| 246 |
+
act_fn = GEGLU(dim, inner_dim, bias=bias)
|
| 247 |
+
elif activation_fn == "geglu-approximate":
|
| 248 |
+
act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
|
| 249 |
+
elif activation_fn == "swiglu":
|
| 250 |
+
act_fn = SwiGLU(dim, inner_dim, bias=bias)
|
| 251 |
+
elif activation_fn == "linear-silu":
|
| 252 |
+
act_fn = LinearActivation(dim, inner_dim, bias=bias, activation="silu")
|
| 253 |
+
|
| 254 |
+
self.net = nn.ModuleList([])
|
| 255 |
+
# project in
|
| 256 |
+
self.net.append(act_fn)
|
| 257 |
+
# project dropout
|
| 258 |
+
self.net.append(nn.Dropout(dropout))
|
| 259 |
+
# project out
|
| 260 |
+
self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
|
| 261 |
+
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
|
| 262 |
+
if final_dropout:
|
| 263 |
+
self.net.append(nn.Dropout(dropout))
|
| 264 |
+
|
| 265 |
+
def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
| 266 |
+
if len(args) > 0 or kwargs.get("scale", None) is not None:
|
| 267 |
+
deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
|
| 268 |
+
deprecate("scale", "1.0.0", deprecation_message)
|
| 269 |
+
for module in self.net:
|
| 270 |
+
hidden_states = module(hidden_states)
|
| 271 |
+
return hidden_states
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class TiledFeedForward(nn.Module):
|
| 275 |
+
"""
|
| 276 |
+
Memory-efficient FeedForward using tiled computation (diffusers compatible)
|
| 277 |
+
Args:
|
| 278 |
+
dim: Input dimension
|
| 279 |
+
dim_out: Output dimension (default: dim)
|
| 280 |
+
mult: Multiplier for inner dimension (default: 4)
|
| 281 |
+
dropout: Dropout probability
|
| 282 |
+
activation_fn: Activation function ('geglu', 'gelu', 'gelu-approximate')
|
| 283 |
+
final_dropout: Apply dropout at the end
|
| 284 |
+
inner_dim: Inner dimension (overrides mult if provided)
|
| 285 |
+
bias: Use bias in linear layers
|
| 286 |
+
num_shards: Number of shards for tiling (None = auto)
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
def __init__(
|
| 290 |
+
self,
|
| 291 |
+
dim: int,
|
| 292 |
+
dim_out: Optional[int] = None,
|
| 293 |
+
mult: int = 4,
|
| 294 |
+
dropout: float = 0.0,
|
| 295 |
+
activation_fn: str = "geglu",
|
| 296 |
+
final_dropout: bool = False,
|
| 297 |
+
inner_dim: Optional[int] = None,
|
| 298 |
+
bias: bool = True,
|
| 299 |
+
num_shards: Optional[int] = None,
|
| 300 |
+
):
|
| 301 |
+
super().__init__()
|
| 302 |
+
|
| 303 |
+
# Calculate dimensions
|
| 304 |
+
if inner_dim is None:
|
| 305 |
+
inner_dim = int(dim * mult)
|
| 306 |
+
dim_out = dim_out if dim_out is not None else dim
|
| 307 |
+
|
| 308 |
+
self.dim = dim
|
| 309 |
+
self.inner_dim = inner_dim
|
| 310 |
+
self.dim_out = dim_out
|
| 311 |
+
self.activation_fn = activation_fn
|
| 312 |
+
self.num_shards = num_shards
|
| 313 |
+
|
| 314 |
+
if activation_fn == "gelu":
|
| 315 |
+
act_fn = GELU(dim, inner_dim, bias=bias)
|
| 316 |
+
if activation_fn == "gelu-approximate":
|
| 317 |
+
act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
|
| 318 |
+
elif activation_fn == "geglu":
|
| 319 |
+
act_fn = GEGLU(dim, inner_dim, bias=bias)
|
| 320 |
+
elif activation_fn == "geglu-approximate":
|
| 321 |
+
act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
|
| 322 |
+
elif activation_fn == "swiglu":
|
| 323 |
+
act_fn = SwiGLU(dim, inner_dim, bias=bias)
|
| 324 |
+
elif activation_fn == "linear-silu":
|
| 325 |
+
act_fn = LinearActivation(dim, inner_dim, bias=bias, activation="silu")
|
| 326 |
+
|
| 327 |
+
self.net = nn.ModuleList([])
|
| 328 |
+
# project in
|
| 329 |
+
self.net.append(act_fn)
|
| 330 |
+
# project dropout
|
| 331 |
+
self.net.append(nn.Dropout(dropout))
|
| 332 |
+
# project out
|
| 333 |
+
self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
|
| 334 |
+
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
|
| 335 |
+
if final_dropout:
|
| 336 |
+
self.net.append(nn.Dropout(dropout))
|
| 337 |
+
|
| 338 |
+
def _mlp_forward(self, module, x):
|
| 339 |
+
"""Internal MLP forward for tiled computation"""
|
| 340 |
+
for layer in module.net:
|
| 341 |
+
x = layer(x)
|
| 342 |
+
return x
|
| 343 |
+
|
| 344 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 345 |
+
"""
|
| 346 |
+
Forward pass with tiled computation
|
| 347 |
+
Args:
|
| 348 |
+
hidden_states: [batch_size, seq_len, dim] or [seq_len, dim]
|
| 349 |
+
Returns:
|
| 350 |
+
Output tensor with same shape as input (but last dim = dim_out)
|
| 351 |
+
"""
|
| 352 |
+
# Collect compute parameters
|
| 353 |
+
compute_params = list(self.parameters())
|
| 354 |
+
|
| 355 |
+
return apply_tiled_linear(
|
| 356 |
+
fn=self._mlp_forward,
|
| 357 |
+
mlp_module=self,
|
| 358 |
+
x=hidden_states,
|
| 359 |
+
num_shards=self.num_shards,
|
| 360 |
+
compute_params=compute_params,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
if __name__ == "__main__":
|
| 365 |
+
import torch
|
| 366 |
+
import torch.nn as nn
|
| 367 |
+
|
| 368 |
+
# 设置随机种子保证可重复性
|
| 369 |
+
torch.manual_seed(42)
|
| 370 |
+
|
| 371 |
+
# 创建测试输入
|
| 372 |
+
batch_size, seq_len, hidden_dim = 2, 1024, 768
|
| 373 |
+
x = torch.randn(batch_size, seq_len, hidden_dim, requires_grad=True)
|
| 374 |
+
|
| 375 |
+
# 方法1: replace
|
| 376 |
+
model1 = FeedForward(dim=hidden_dim)
|
| 377 |
+
# model1 = replace_linear_with_tiled_linear(model1, num_shards=4)
|
| 378 |
+
out1 = model1(x)
|
| 379 |
+
loss1 = out1.sum()
|
| 380 |
+
loss1.backward()
|
| 381 |
+
grad1 = x.grad.clone()
|
| 382 |
+
|
| 383 |
+
# 方法2: TiledFeedForward
|
| 384 |
+
x.grad = None
|
| 385 |
+
# model2 = TiledFeedForward(dim=hidden_dim, num_shards=4)
|
| 386 |
+
model2 = FeedForward(dim=hidden_dim)
|
| 387 |
+
model2 = replace_linear_with_tiled_linear(model2, num_shards=4)
|
| 388 |
+
# 复制权重确保完全一致
|
| 389 |
+
model2.load_state_dict(model1.state_dict(), strict=True)
|
| 390 |
+
out2 = model2(x)
|
| 391 |
+
loss2 = out2.sum()
|
| 392 |
+
loss2.backward()
|
| 393 |
+
grad2 = x.grad.clone()
|
| 394 |
+
|
| 395 |
+
# 比较结果
|
| 396 |
+
print(f"Output diff: {(out1 - out2).abs().max().item()}")
|
| 397 |
+
print(f"Gradient diff: {(grad1 - grad2).abs().max().item()}")
|
| 398 |
+
print(f"Output allclose: {torch.allclose(out1, out2, atol=1e-6)}")
|
| 399 |
+
print(f"Gradient allclose: {torch.allclose(grad1, grad2, atol=1e-6)}")
|
Helios/_DEV/helios/modules/helios_kernels/triton_norm.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import triton
|
| 3 |
+
import triton.language as tl
|
| 4 |
+
|
| 5 |
+
from diffusers.models.normalization import FP32LayerNorm, LayerNorm, RMSNorm
|
| 6 |
+
|
| 7 |
+
from .fp32_rmsnorm import FP32RMSNorm
|
| 8 |
+
from .utils import calculate_settings, torch_gpu_device
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# ------------------------------- replace funtion -------------------------------
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def replace_all_norms_with_flash_norms(model):
|
| 15 |
+
patched_count = {"LayerNorm": 0, "RMSNorm": 0}
|
| 16 |
+
|
| 17 |
+
for name, module in model.named_modules():
|
| 18 |
+
if isinstance(module, (LayerNorm, FP32LayerNorm)):
|
| 19 |
+
if hasattr(module, "elementwise_affine") and module.elementwise_affine:
|
| 20 |
+
module.forward = (lambda self, x: flash_layernorm(self, x)).__get__(module, module.__class__)
|
| 21 |
+
patched_count["LayerNorm"] += 1
|
| 22 |
+
|
| 23 |
+
if isinstance(module, (torch.nn.RMSNorm, RMSNorm, FP32RMSNorm)):
|
| 24 |
+
module.forward = (lambda self, x: flash_rms_layernorm(self, x)).__get__(module, module.__class__)
|
| 25 |
+
patched_count["RMSNorm"] += 1
|
| 26 |
+
|
| 27 |
+
print(f"Patched {patched_count['LayerNorm']} Flash_LayerNorm modules\n")
|
| 28 |
+
print(f"Patched {patched_count['RMSNorm']} Flash_RMSNorm modules\n")
|
| 29 |
+
|
| 30 |
+
return model
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ------------------------------- layer norm -------------------------------
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@triton.jit
|
| 37 |
+
def layernorm_forward(
|
| 38 |
+
Y,
|
| 39 |
+
Y_row_stride,
|
| 40 |
+
X,
|
| 41 |
+
X_row_stride,
|
| 42 |
+
W,
|
| 43 |
+
b,
|
| 44 |
+
r,
|
| 45 |
+
mu,
|
| 46 |
+
n_cols: tl.constexpr,
|
| 47 |
+
eps: tl.constexpr,
|
| 48 |
+
BLOCK_SIZE: tl.constexpr,
|
| 49 |
+
):
|
| 50 |
+
row_idx = tl.program_id(0)
|
| 51 |
+
col_offsets = tl.arange(0, BLOCK_SIZE)
|
| 52 |
+
mask = col_offsets < n_cols
|
| 53 |
+
|
| 54 |
+
Y += row_idx * Y_row_stride
|
| 55 |
+
X += row_idx * X_row_stride
|
| 56 |
+
r += row_idx
|
| 57 |
+
mu += row_idx
|
| 58 |
+
|
| 59 |
+
# According to https://pytorch.org/torchtune/stable/_modules/torchtune/modules/layer_norm.html#Fp32LayerNorm, all modules
|
| 60 |
+
# are in float32!
|
| 61 |
+
X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 62 |
+
W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 63 |
+
b_row = tl.load(b + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 64 |
+
|
| 65 |
+
mean_X = tl.sum(X_row, axis=0) / n_cols
|
| 66 |
+
# (X[0] - mean) == -mean so we need to mask it out
|
| 67 |
+
XX = tl.where(mask, X_row - mean_X, 0)
|
| 68 |
+
row_var = tl.sum(XX * XX, axis=0) / n_cols
|
| 69 |
+
inv_var = tl.math.rsqrt(row_var + eps)
|
| 70 |
+
tl.store(r, inv_var)
|
| 71 |
+
tl.store(mu, mean_X)
|
| 72 |
+
output = (XX * inv_var) * W_row + b_row
|
| 73 |
+
tl.store(Y + col_offsets, output, mask=mask)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@triton.jit
|
| 77 |
+
def layernorm_backward(
|
| 78 |
+
dY,
|
| 79 |
+
dY_row_stride,
|
| 80 |
+
X,
|
| 81 |
+
X_row_stride,
|
| 82 |
+
W,
|
| 83 |
+
b,
|
| 84 |
+
r,
|
| 85 |
+
mu,
|
| 86 |
+
n_cols: tl.constexpr,
|
| 87 |
+
eps: tl.constexpr,
|
| 88 |
+
BLOCK_SIZE: tl.constexpr,
|
| 89 |
+
):
|
| 90 |
+
# Approximately follows https://github.com/karpathy/llm.c/blob/master/doc/layernorm/layernorm.md
|
| 91 |
+
row_idx = tl.program_id(0)
|
| 92 |
+
col_offsets = tl.arange(0, BLOCK_SIZE)
|
| 93 |
+
mask = col_offsets < n_cols
|
| 94 |
+
|
| 95 |
+
dY += row_idx * dY_row_stride
|
| 96 |
+
X += row_idx * X_row_stride
|
| 97 |
+
r += row_idx
|
| 98 |
+
mu += row_idx
|
| 99 |
+
|
| 100 |
+
# According to https://pytorch.org/torchtune/stable/_modules/torchtune/modules/layer_norm.html#Fp32LayerNorm, all modules
|
| 101 |
+
# are in float32!
|
| 102 |
+
dY_row = tl.load(dY + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 103 |
+
X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 104 |
+
W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 105 |
+
# b_row = tl.load(b + col_offsets, mask = mask, other = 0).to(tl.float32)
|
| 106 |
+
|
| 107 |
+
inv_var = tl.load(r).to(tl.float32)
|
| 108 |
+
mean = tl.load(mu).to(tl.float32)
|
| 109 |
+
normed = (X_row - mean) * inv_var
|
| 110 |
+
dY_W = dY_row * W_row
|
| 111 |
+
dX_row = dY_W - tl.sum(dY_W, axis=0) / n_cols - normed * tl.sum(dY_W * normed, axis=0) / n_cols
|
| 112 |
+
dX_row = dX_row * inv_var
|
| 113 |
+
tl.store(dY + col_offsets, dX_row, mask=mask)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Flash_Layernorm(torch.autograd.Function):
|
| 117 |
+
@staticmethod
|
| 118 |
+
def forward(ctx, X, W, b, eps):
|
| 119 |
+
shape = X.shape
|
| 120 |
+
dim = shape[-1]
|
| 121 |
+
X = X.view(-1, dim)
|
| 122 |
+
n_rows, n_cols = X.shape
|
| 123 |
+
BLOCK_SIZE, num_warps = calculate_settings(n_cols)
|
| 124 |
+
device = X.device
|
| 125 |
+
Y = torch.empty((n_rows, n_cols), dtype=X.dtype, device=device)
|
| 126 |
+
r = torch.empty(n_rows, dtype=torch.float32, device=device)
|
| 127 |
+
mu = torch.empty(n_rows, dtype=torch.float32, device=device)
|
| 128 |
+
|
| 129 |
+
with torch_gpu_device(device):
|
| 130 |
+
layernorm_forward[(n_rows,)](
|
| 131 |
+
Y,
|
| 132 |
+
Y.stride(0),
|
| 133 |
+
X,
|
| 134 |
+
X.stride(0),
|
| 135 |
+
W,
|
| 136 |
+
b,
|
| 137 |
+
r,
|
| 138 |
+
mu,
|
| 139 |
+
n_cols,
|
| 140 |
+
eps,
|
| 141 |
+
BLOCK_SIZE=BLOCK_SIZE,
|
| 142 |
+
num_warps=num_warps,
|
| 143 |
+
)
|
| 144 |
+
ctx.eps = eps
|
| 145 |
+
ctx.BLOCK_SIZE = BLOCK_SIZE
|
| 146 |
+
ctx.num_warps = num_warps
|
| 147 |
+
ctx.save_for_backward(X, W, b, r, mu)
|
| 148 |
+
return Y.view(*shape)
|
| 149 |
+
|
| 150 |
+
@staticmethod
|
| 151 |
+
def backward(ctx, dY):
|
| 152 |
+
shape = dY.shape
|
| 153 |
+
dim = shape[-1]
|
| 154 |
+
dY = dY.view(-1, dim)
|
| 155 |
+
X, W, b, r, mu = ctx.saved_tensors
|
| 156 |
+
n_rows, n_cols = dY.shape
|
| 157 |
+
|
| 158 |
+
with torch_gpu_device(dY.device):
|
| 159 |
+
layernorm_backward[(n_rows,)](
|
| 160 |
+
dY,
|
| 161 |
+
dY.stride(0),
|
| 162 |
+
X,
|
| 163 |
+
X.stride(0),
|
| 164 |
+
W,
|
| 165 |
+
b,
|
| 166 |
+
r,
|
| 167 |
+
mu,
|
| 168 |
+
n_cols,
|
| 169 |
+
ctx.eps,
|
| 170 |
+
BLOCK_SIZE=ctx.BLOCK_SIZE,
|
| 171 |
+
num_warps=ctx.num_warps,
|
| 172 |
+
)
|
| 173 |
+
dX = dY.view(*shape)
|
| 174 |
+
return dX, None, None, None, None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def flash_layernorm(layernorm, X):
|
| 178 |
+
assert layernorm.elementwise_affine is True
|
| 179 |
+
W = layernorm.weight
|
| 180 |
+
bias = layernorm.bias
|
| 181 |
+
eps = layernorm.variance_epsilon if hasattr(layernorm, "variance_epsilon") else layernorm.eps
|
| 182 |
+
out = Flash_Layernorm.apply(X, W, bias, eps)
|
| 183 |
+
return out
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ------------------------------- layer norm -------------------------------
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ------------------------------- rms norm -------------------------------
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@triton.jit
|
| 193 |
+
def _rms_layernorm_forward(
|
| 194 |
+
Y,
|
| 195 |
+
Y_row_stride: tl.constexpr,
|
| 196 |
+
X,
|
| 197 |
+
X_row_stride: tl.constexpr,
|
| 198 |
+
W,
|
| 199 |
+
W_row_stride: tl.constexpr,
|
| 200 |
+
r,
|
| 201 |
+
r_row_stride: tl.constexpr,
|
| 202 |
+
n_cols: tl.constexpr,
|
| 203 |
+
eps: tl.constexpr,
|
| 204 |
+
BLOCK_SIZE: tl.constexpr,
|
| 205 |
+
):
|
| 206 |
+
"""
|
| 207 |
+
Flash RMS Layernorm kernel
|
| 208 |
+
Inspiration from a Triton tutorial:
|
| 209 |
+
https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
|
| 210 |
+
"""
|
| 211 |
+
row_idx = tl.program_id(0)
|
| 212 |
+
col_offsets = tl.arange(0, BLOCK_SIZE)
|
| 213 |
+
mask = col_offsets < n_cols
|
| 214 |
+
|
| 215 |
+
Y += row_idx * Y_row_stride
|
| 216 |
+
X += row_idx * X_row_stride
|
| 217 |
+
r += row_idx * r_row_stride
|
| 218 |
+
|
| 219 |
+
X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 220 |
+
W_row = tl.load(W + col_offsets, mask=mask, other=0) # .to(tl.float32)
|
| 221 |
+
|
| 222 |
+
row_var = tl.sum(X_row * X_row, axis=0) / n_cols
|
| 223 |
+
inv_var = tl.math.rsqrt(row_var + eps)
|
| 224 |
+
tl.store(r, inv_var)
|
| 225 |
+
normed = X_row * inv_var
|
| 226 |
+
normed = normed.to(W_row.dtype) # Exact copy from HF
|
| 227 |
+
output = normed * W_row
|
| 228 |
+
tl.store(Y + col_offsets, output, mask=mask)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _rms_layernorm_backward(
|
| 232 |
+
dY,
|
| 233 |
+
dY_row_stride: tl.constexpr,
|
| 234 |
+
dX,
|
| 235 |
+
dX_row_stride: tl.constexpr,
|
| 236 |
+
X,
|
| 237 |
+
X_row_stride: tl.constexpr,
|
| 238 |
+
W,
|
| 239 |
+
W_row_stride: tl.constexpr,
|
| 240 |
+
r,
|
| 241 |
+
r_row_stride: tl.constexpr,
|
| 242 |
+
# dW, dW_row_stride,
|
| 243 |
+
n_cols: tl.constexpr,
|
| 244 |
+
eps: tl.constexpr,
|
| 245 |
+
GEMMA: tl.constexpr,
|
| 246 |
+
BLOCK_SIZE: tl.constexpr,
|
| 247 |
+
):
|
| 248 |
+
"""
|
| 249 |
+
Flash RMS Layernorm kernel for the backward pass
|
| 250 |
+
Inspiration from a Triton tutorial:
|
| 251 |
+
https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
|
| 252 |
+
"""
|
| 253 |
+
row_idx = tl.program_id(0)
|
| 254 |
+
col_offsets = tl.arange(0, BLOCK_SIZE)
|
| 255 |
+
mask = col_offsets < n_cols
|
| 256 |
+
|
| 257 |
+
dY += row_idx * dY_row_stride
|
| 258 |
+
X += row_idx * X_row_stride
|
| 259 |
+
r += row_idx * r_row_stride
|
| 260 |
+
|
| 261 |
+
if GEMMA:
|
| 262 |
+
dX += row_idx * dY_row_stride
|
| 263 |
+
else:
|
| 264 |
+
dX = dY
|
| 265 |
+
|
| 266 |
+
dY_row = tl.load(dY + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 267 |
+
X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 268 |
+
W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 269 |
+
|
| 270 |
+
# Get saved row variance
|
| 271 |
+
inv_var = tl.load(r).to(tl.float32)
|
| 272 |
+
normed = X_row * inv_var
|
| 273 |
+
|
| 274 |
+
if GEMMA:
|
| 275 |
+
dY_W = dY_row * (W_row + 1.0)
|
| 276 |
+
else:
|
| 277 |
+
dY_W = dY_row * W_row
|
| 278 |
+
|
| 279 |
+
rowsum_dY_normed = tl.sum(dY_W * normed, axis=0)
|
| 280 |
+
output = inv_var / n_cols * (n_cols * dY_W - normed * rowsum_dY_normed)
|
| 281 |
+
tl.store(dX + col_offsets, output, mask=mask)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
_rms_layernorm_backward = triton.jit(_rms_layernorm_backward)
|
| 285 |
+
_rms_layernorm_backward = triton.heuristics(
|
| 286 |
+
{
|
| 287 |
+
"GEMMA": lambda args: bool(args["GEMMA"]),
|
| 288 |
+
}
|
| 289 |
+
)(_rms_layernorm_backward)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@triton.jit
|
| 293 |
+
def _gemma_rms_layernorm_forward(
|
| 294 |
+
Y,
|
| 295 |
+
Y_row_stride: tl.constexpr,
|
| 296 |
+
X,
|
| 297 |
+
X_row_stride: tl.constexpr,
|
| 298 |
+
W,
|
| 299 |
+
W_row_stride: tl.constexpr,
|
| 300 |
+
r,
|
| 301 |
+
r_row_stride: tl.constexpr,
|
| 302 |
+
n_cols: tl.constexpr,
|
| 303 |
+
eps: tl.constexpr,
|
| 304 |
+
BLOCK_SIZE: tl.constexpr,
|
| 305 |
+
):
|
| 306 |
+
# Copies https://github.com/google-deepmind/gemma/blob/main/gemma/layers.py#L31
|
| 307 |
+
# and https://github.com/keras-team/keras-nlp/blob/v0.8.2/keras_nlp/models/gemma/rms_normalization.py#L33
|
| 308 |
+
# exactly. Essentially all in float32!
|
| 309 |
+
row_idx = tl.program_id(0)
|
| 310 |
+
col_offsets = tl.arange(0, BLOCK_SIZE)
|
| 311 |
+
mask = col_offsets < n_cols
|
| 312 |
+
|
| 313 |
+
Y += row_idx * Y_row_stride
|
| 314 |
+
X += row_idx * X_row_stride
|
| 315 |
+
r += row_idx * r_row_stride
|
| 316 |
+
|
| 317 |
+
X_row = tl.load(X + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 318 |
+
W_row = tl.load(W + col_offsets, mask=mask, other=0).to(tl.float32)
|
| 319 |
+
|
| 320 |
+
row_var = tl.sum(X_row * X_row, axis=0) / n_cols
|
| 321 |
+
inv_var = tl.math.rsqrt(row_var + eps)
|
| 322 |
+
tl.store(r, inv_var)
|
| 323 |
+
normed = X_row * inv_var
|
| 324 |
+
output = normed * (W_row + 1.0)
|
| 325 |
+
|
| 326 |
+
tl.store(Y + col_offsets, output, mask=mask)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class Flash_RMS_Layernorm(torch.autograd.Function):
|
| 330 |
+
@staticmethod
|
| 331 |
+
def forward(ctx, X: torch.Tensor, W: torch.Tensor, eps: float, gemma: bool = False):
|
| 332 |
+
shape = X.shape
|
| 333 |
+
dim: int = shape[-1]
|
| 334 |
+
X = X.reshape(-1, dim)
|
| 335 |
+
n_rows: int
|
| 336 |
+
n_cols: int
|
| 337 |
+
n_rows, n_cols = X.shape
|
| 338 |
+
BLOCK_SIZE: int
|
| 339 |
+
num_warps: int
|
| 340 |
+
BLOCK_SIZE, num_warps = calculate_settings(n_cols)
|
| 341 |
+
device = X.device
|
| 342 |
+
|
| 343 |
+
Y = torch.empty((n_rows, n_cols), dtype=X.dtype, device=device)
|
| 344 |
+
r = torch.empty(n_rows, dtype=torch.float32, device=device)
|
| 345 |
+
|
| 346 |
+
fx = _gemma_rms_layernorm_forward if gemma else _rms_layernorm_forward
|
| 347 |
+
with torch_gpu_device(device):
|
| 348 |
+
fx[(n_rows,)](
|
| 349 |
+
Y,
|
| 350 |
+
Y.stride(0),
|
| 351 |
+
X,
|
| 352 |
+
X.stride(0),
|
| 353 |
+
W,
|
| 354 |
+
W.stride(0),
|
| 355 |
+
r,
|
| 356 |
+
r.stride(0),
|
| 357 |
+
n_cols,
|
| 358 |
+
eps,
|
| 359 |
+
BLOCK_SIZE=BLOCK_SIZE,
|
| 360 |
+
num_warps=num_warps,
|
| 361 |
+
)
|
| 362 |
+
ctx.eps = eps
|
| 363 |
+
ctx.BLOCK_SIZE = BLOCK_SIZE
|
| 364 |
+
ctx.num_warps = num_warps
|
| 365 |
+
ctx.GEMMA = gemma
|
| 366 |
+
ctx.save_for_backward(X, W, r)
|
| 367 |
+
return Y.view(*shape)
|
| 368 |
+
|
| 369 |
+
@staticmethod
|
| 370 |
+
def backward(ctx, dY: torch.Tensor):
|
| 371 |
+
shape = dY.shape
|
| 372 |
+
dim: int = shape[-1]
|
| 373 |
+
dY = dY.reshape(-1, dim)
|
| 374 |
+
X, W, r = ctx.saved_tensors
|
| 375 |
+
n_rows: int
|
| 376 |
+
n_cols: int
|
| 377 |
+
n_rows, n_cols = dY.shape
|
| 378 |
+
# dW = X
|
| 379 |
+
dX = torch.empty_like(dY) if ctx.GEMMA else dY
|
| 380 |
+
|
| 381 |
+
with torch_gpu_device(dY.device):
|
| 382 |
+
_rms_layernorm_backward[(n_rows,)](
|
| 383 |
+
dY,
|
| 384 |
+
dY.stride(0),
|
| 385 |
+
dX,
|
| 386 |
+
dX.stride(0),
|
| 387 |
+
X,
|
| 388 |
+
X.stride(0),
|
| 389 |
+
W,
|
| 390 |
+
W.stride(0),
|
| 391 |
+
r,
|
| 392 |
+
r.stride(0),
|
| 393 |
+
# dW, dW.stride(0),
|
| 394 |
+
n_cols,
|
| 395 |
+
ctx.eps,
|
| 396 |
+
GEMMA=ctx.GEMMA,
|
| 397 |
+
BLOCK_SIZE=ctx.BLOCK_SIZE,
|
| 398 |
+
num_warps=ctx.num_warps,
|
| 399 |
+
)
|
| 400 |
+
dX = dX.view(*shape)
|
| 401 |
+
return dX, None, None, None
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
# [TODO] Unsure why RMS Layernorm is not torch.compiling properly
|
| 405 |
+
@torch.compiler.disable
|
| 406 |
+
def flash_rms_layernorm(layernorm, X: torch.Tensor, gemma: bool = False):
|
| 407 |
+
W: torch.Tensor = layernorm.weight
|
| 408 |
+
eps: float = layernorm.variance_epsilon if hasattr(layernorm, "variance_epsilon") else layernorm.eps
|
| 409 |
+
out = Flash_RMS_Layernorm.apply(X, W, eps, gemma)
|
| 410 |
+
return out
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
# ------------------------------- rms norm -------------------------------
|
Helios/_DEV/helios/modules/helios_kernels/triton_rope.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import triton
|
| 3 |
+
import triton.language as tl
|
| 4 |
+
|
| 5 |
+
from .utils import calculate_settings, torch_gpu_device
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# ------------------------------- replace funtion -------------------------------
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def apply_rotary_emb_transposed_flash(x, freqs_cis):
|
| 12 |
+
return Flash_RoPE_Transposed.apply(x, freqs_cis)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def replace_rope_with_flash_rope():
|
| 16 |
+
from ...diffusers_version import transformer_helios_diffusers
|
| 17 |
+
from .. import transformer_helios
|
| 18 |
+
|
| 19 |
+
transformer_helios_diffusers.apply_rotary_emb_transposed = apply_rotary_emb_transposed_flash
|
| 20 |
+
transformer_helios.apply_rotary_emb_transposed = apply_rotary_emb_transposed_flash
|
| 21 |
+
print("Patched Flash_RoPE globally\n")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ------------------------------- layer norm -------------------------------
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@triton.jit
|
| 28 |
+
def _apply_rope_transposed_kernel(
|
| 29 |
+
X,
|
| 30 |
+
Out,
|
| 31 |
+
cos,
|
| 32 |
+
sin,
|
| 33 |
+
n_heads: tl.constexpr,
|
| 34 |
+
stride_x: tl.constexpr,
|
| 35 |
+
stride_out: tl.constexpr,
|
| 36 |
+
stride_freq: tl.constexpr,
|
| 37 |
+
head_dim: tl.constexpr,
|
| 38 |
+
BLOCK_SIZE: tl.constexpr,
|
| 39 |
+
):
|
| 40 |
+
row_idx = tl.program_id(0)
|
| 41 |
+
freq_row_idx = row_idx // n_heads
|
| 42 |
+
|
| 43 |
+
half_head_dim = head_dim // 2
|
| 44 |
+
col_offsets = tl.arange(0, BLOCK_SIZE)
|
| 45 |
+
mask = col_offsets < half_head_dim
|
| 46 |
+
|
| 47 |
+
x_ptr = X + row_idx * stride_x
|
| 48 |
+
out_ptr = Out + row_idx * stride_out
|
| 49 |
+
cos_ptr = cos + freq_row_idx * stride_freq
|
| 50 |
+
sin_ptr = sin + freq_row_idx * stride_freq
|
| 51 |
+
|
| 52 |
+
x_real = tl.load(x_ptr + col_offsets * 2, mask=mask, other=0.0)
|
| 53 |
+
x_imag = tl.load(x_ptr + col_offsets * 2 + 1, mask=mask, other=0.0)
|
| 54 |
+
cos_even = tl.load(cos_ptr + col_offsets * 2, mask=mask, other=0.0)
|
| 55 |
+
sin_odd = tl.load(sin_ptr + col_offsets * 2 + 1, mask=mask, other=0.0)
|
| 56 |
+
|
| 57 |
+
out_even = x_real * cos_even - x_imag * sin_odd
|
| 58 |
+
out_odd = x_real * sin_odd + x_imag * cos_even
|
| 59 |
+
|
| 60 |
+
tl.store(out_ptr + col_offsets * 2, out_even, mask=mask)
|
| 61 |
+
tl.store(out_ptr + col_offsets * 2 + 1, out_odd, mask=mask)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Flash_RoPE_Transposed(torch.autograd.Function):
|
| 65 |
+
@staticmethod
|
| 66 |
+
def forward(ctx, x, freqs_cis):
|
| 67 |
+
# x: [B, seq_len, n_heads, head_dim]
|
| 68 |
+
# freqs_cis: [B, seq_len, head_dim*2]
|
| 69 |
+
|
| 70 |
+
B, seq_len, n_heads, head_dim = x.shape
|
| 71 |
+
|
| 72 |
+
x_flat = x.reshape(-1, head_dim).contiguous()
|
| 73 |
+
device = x_flat.device
|
| 74 |
+
out = torch.empty_like(x_flat)
|
| 75 |
+
|
| 76 |
+
freqs_flat = freqs_cis.reshape(B * seq_len, -1).contiguous()
|
| 77 |
+
half_dim = freqs_flat.shape[-1] // 2
|
| 78 |
+
cos = freqs_flat[:, :half_dim].contiguous() # [B*seq_len, head_dim]
|
| 79 |
+
sin = freqs_flat[:, half_dim:].contiguous() # [B*seq_len, head_dim]
|
| 80 |
+
|
| 81 |
+
n_rows = x_flat.shape[0] # B*seq_len*n_heads
|
| 82 |
+
BLOCK_SIZE, num_warps = calculate_settings(head_dim // 2)
|
| 83 |
+
|
| 84 |
+
with torch_gpu_device(device):
|
| 85 |
+
_apply_rope_transposed_kernel[(n_rows,)](
|
| 86 |
+
x_flat,
|
| 87 |
+
out,
|
| 88 |
+
cos,
|
| 89 |
+
sin,
|
| 90 |
+
n_heads,
|
| 91 |
+
x_flat.stride(0),
|
| 92 |
+
out.stride(0),
|
| 93 |
+
cos.stride(0),
|
| 94 |
+
head_dim,
|
| 95 |
+
BLOCK_SIZE=BLOCK_SIZE,
|
| 96 |
+
num_warps=num_warps,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
out = out.reshape(B, seq_len, n_heads, head_dim)
|
| 100 |
+
|
| 101 |
+
ctx.save_for_backward(cos, sin)
|
| 102 |
+
ctx.n_heads = n_heads
|
| 103 |
+
ctx.BLOCK_SIZE = BLOCK_SIZE
|
| 104 |
+
ctx.num_warps = num_warps
|
| 105 |
+
ctx.head_dim = head_dim
|
| 106 |
+
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def backward(ctx, grad_output):
|
| 111 |
+
cos, sin = ctx.saved_tensors
|
| 112 |
+
|
| 113 |
+
B, seq_len, n_heads, head_dim = grad_output.shape
|
| 114 |
+
grad_flat = grad_output.reshape(-1, head_dim).contiguous()
|
| 115 |
+
device = grad_flat.device
|
| 116 |
+
grad_x = torch.empty_like(grad_flat)
|
| 117 |
+
|
| 118 |
+
sin_neg = -sin
|
| 119 |
+
|
| 120 |
+
n_rows = grad_flat.shape[0]
|
| 121 |
+
|
| 122 |
+
with torch_gpu_device(device):
|
| 123 |
+
_apply_rope_transposed_kernel[(n_rows,)](
|
| 124 |
+
grad_flat,
|
| 125 |
+
grad_x,
|
| 126 |
+
cos,
|
| 127 |
+
sin_neg,
|
| 128 |
+
ctx.n_heads,
|
| 129 |
+
grad_flat.stride(0),
|
| 130 |
+
grad_x.stride(0),
|
| 131 |
+
cos.stride(0),
|
| 132 |
+
ctx.head_dim,
|
| 133 |
+
BLOCK_SIZE=ctx.BLOCK_SIZE,
|
| 134 |
+
num_warps=ctx.num_warps,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
grad_x = grad_x.reshape(B, seq_len, n_heads, head_dim)
|
| 138 |
+
return grad_x, None
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ------------------------------- For test -------------------------------
|
| 142 |
+
def test_zero_error():
|
| 143 |
+
def apply_rotary_emb_transposed_orig(x, freqs_cis):
|
| 144 |
+
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
| 145 |
+
x_real, x_imag = x.unflatten(-1, (-1, 2)).unbind(-1)
|
| 146 |
+
out = torch.empty_like(x)
|
| 147 |
+
out[..., 0::2] = x_real * cos[..., 0::2] - x_imag * sin[..., 1::2]
|
| 148 |
+
out[..., 1::2] = x_real * sin[..., 1::2] + x_imag * cos[..., 0::2]
|
| 149 |
+
return out
|
| 150 |
+
|
| 151 |
+
for dtype in [torch.float32, torch.float16, torch.bfloat16]:
|
| 152 |
+
x = torch.randn(1, 128, 12, 128, device="cuda", dtype=dtype)
|
| 153 |
+
freqs_cis = torch.randn(1, 128, 256, device="cuda", dtype=dtype)
|
| 154 |
+
|
| 155 |
+
out_orig = apply_rotary_emb_transposed_orig(x, freqs_cis)
|
| 156 |
+
out_fast = apply_rotary_emb_transposed_flash(x, freqs_cis)
|
| 157 |
+
|
| 158 |
+
diff = (out_orig - out_fast).abs().max()
|
| 159 |
+
|
| 160 |
+
eps = torch.finfo(dtype).eps
|
| 161 |
+
print(f"{dtype}: max_diff={diff.item():.2e}, machine_eps={eps:.2e}")
|
| 162 |
+
|
| 163 |
+
if diff < eps * 100:
|
| 164 |
+
print(f" ✅ Essentially zero error for {dtype}")
|
| 165 |
+
else:
|
| 166 |
+
print(f" ⚠️ Significant error: {diff / eps:.1f}x machine epsilon")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def test_comparison():
|
| 170 |
+
def apply_rotary_emb_transposed_orig(x, freqs_cis):
|
| 171 |
+
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
| 172 |
+
x_real, x_imag = x.unflatten(-1, (-1, 2)).unbind(-1)
|
| 173 |
+
out = torch.empty_like(x)
|
| 174 |
+
out[..., 0::2] = x_real * cos[..., 0::2] - x_imag * sin[..., 1::2]
|
| 175 |
+
out[..., 1::2] = x_real * sin[..., 1::2] + x_imag * cos[..., 0::2]
|
| 176 |
+
return out
|
| 177 |
+
|
| 178 |
+
x = torch.randn(1, 14040, 12, 128, device="cuda", dtype=torch.float32)
|
| 179 |
+
freqs_cis = torch.randn(1, 14040, 256, device="cuda", dtype=torch.float32)
|
| 180 |
+
|
| 181 |
+
out_orig = apply_rotary_emb_transposed_orig(x, freqs_cis)
|
| 182 |
+
out_fast = apply_rotary_emb_transposed_flash(x, freqs_cis)
|
| 183 |
+
|
| 184 |
+
diff = (out_orig - out_fast).abs().max()
|
| 185 |
+
print(f"Max difference: {diff.item():.6e}")
|
| 186 |
+
|
| 187 |
+
if diff < 1e-5:
|
| 188 |
+
print("✅ Test passed!")
|
| 189 |
+
print(f"Input shapes: x={x.shape}, freqs_cis={freqs_cis.shape}")
|
| 190 |
+
print(f"Output shape: {out_fast.shape}")
|
| 191 |
+
else:
|
| 192 |
+
print(f"❌ Test failed! Max diff: {diff.item()}")
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def test_backward_comparison():
|
| 196 |
+
def apply_rotary_emb_transposed_orig(x, freqs_cis):
|
| 197 |
+
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
| 198 |
+
x_real, x_imag = x.unflatten(-1, (-1, 2)).unbind(-1)
|
| 199 |
+
out = torch.empty_like(x)
|
| 200 |
+
out[..., 0::2] = x_real * cos[..., 0::2] - x_imag * sin[..., 1::2]
|
| 201 |
+
out[..., 1::2] = x_real * sin[..., 1::2] + x_imag * cos[..., 0::2]
|
| 202 |
+
return out
|
| 203 |
+
|
| 204 |
+
x1 = torch.randn(1, 128, 12, 128, device="cuda", requires_grad=True)
|
| 205 |
+
x2 = x1.clone().detach().requires_grad_(True)
|
| 206 |
+
freqs_cis = torch.randn(1, 128, 256, device="cuda")
|
| 207 |
+
|
| 208 |
+
out_orig = apply_rotary_emb_transposed_orig(x1, freqs_cis)
|
| 209 |
+
out_fast = apply_rotary_emb_transposed_flash(x2, freqs_cis)
|
| 210 |
+
|
| 211 |
+
grad_output = torch.randn_like(out_orig)
|
| 212 |
+
|
| 213 |
+
out_orig.backward(grad_output)
|
| 214 |
+
out_fast.backward(grad_output)
|
| 215 |
+
|
| 216 |
+
grad_diff = (x1.grad - x2.grad).abs()
|
| 217 |
+
max_diff = grad_diff.max().item()
|
| 218 |
+
mean_diff = grad_diff.mean().item()
|
| 219 |
+
|
| 220 |
+
print("Gradient comparison:")
|
| 221 |
+
print(f" Max difference: {max_diff:.6e}")
|
| 222 |
+
print(f" Mean difference: {mean_diff:.6e}")
|
| 223 |
+
|
| 224 |
+
if max_diff < 1e-5:
|
| 225 |
+
print("✅ Backward gradients match!")
|
| 226 |
+
else:
|
| 227 |
+
print(f"⚠️ Gradients differ by {max_diff:.6e}")
|
| 228 |
+
max_idx = grad_diff.argmax()
|
| 229 |
+
print(f" Max diff location: {torch.unravel_index(max_idx, grad_diff.shape)}")
|
| 230 |
+
print(f" Original grad: {x1.grad.flatten()[max_idx]:.6f}")
|
| 231 |
+
print(f" Fast grad: {x2.grad.flatten()[max_idx]:.6f}")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def test_backward():
|
| 235 |
+
from torch.autograd import gradcheck
|
| 236 |
+
|
| 237 |
+
B, seq_len, n_heads, head_dim = 2, 16, 4, 32
|
| 238 |
+
x = torch.randn(B, seq_len, n_heads, head_dim, device="cuda", dtype=torch.float64, requires_grad=True)
|
| 239 |
+
freqs_cis = torch.randn(B, seq_len, head_dim * 2, device="cuda", dtype=torch.float64)
|
| 240 |
+
|
| 241 |
+
test = gradcheck(
|
| 242 |
+
Flash_RoPE_Transposed.apply,
|
| 243 |
+
(x, freqs_cis),
|
| 244 |
+
eps=1e-6,
|
| 245 |
+
atol=1e-4,
|
| 246 |
+
rtol=1e-3,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
if test:
|
| 250 |
+
print("✅ Backward pass is correct (gradcheck passed)")
|
| 251 |
+
else:
|
| 252 |
+
print("❌ Backward pass has errors")
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def test_in_training_loop_comparison():
|
| 256 |
+
def apply_rotary_emb_transposed_orig(x, freqs_cis):
|
| 257 |
+
cos, sin = freqs_cis.unsqueeze(-2).chunk(2, dim=-1)
|
| 258 |
+
x_real, x_imag = x.unflatten(-1, (-1, 2)).unbind(-1)
|
| 259 |
+
out = torch.empty_like(x)
|
| 260 |
+
out[..., 0::2] = x_real * cos[..., 0::2] - x_imag * sin[..., 1::2]
|
| 261 |
+
out[..., 1::2] = x_real * sin[..., 1::2] + x_imag * cos[..., 0::2]
|
| 262 |
+
return out
|
| 263 |
+
|
| 264 |
+
class SimpleModel(torch.nn.Module):
|
| 265 |
+
def __init__(self, use_fast=False):
|
| 266 |
+
super().__init__()
|
| 267 |
+
self.linear = torch.nn.Linear(128, 128, device="cuda")
|
| 268 |
+
self.use_fast = use_fast
|
| 269 |
+
|
| 270 |
+
def forward(self, x, freqs_cis):
|
| 271 |
+
x = self.linear(x)
|
| 272 |
+
if self.use_fast:
|
| 273 |
+
x = apply_rotary_emb_transposed_flash(x, freqs_cis)
|
| 274 |
+
else:
|
| 275 |
+
x = apply_rotary_emb_transposed_orig(x, freqs_cis)
|
| 276 |
+
return x.mean()
|
| 277 |
+
|
| 278 |
+
torch.manual_seed(42)
|
| 279 |
+
torch.cuda.manual_seed(42)
|
| 280 |
+
|
| 281 |
+
model_orig = SimpleModel(use_fast=False)
|
| 282 |
+
model_fast = SimpleModel(use_fast=True)
|
| 283 |
+
|
| 284 |
+
model_fast.load_state_dict(model_orig.state_dict())
|
| 285 |
+
|
| 286 |
+
optimizer_orig = torch.optim.Adam(model_orig.parameters(), lr=1e-3)
|
| 287 |
+
optimizer_fast = torch.optim.Adam(model_fast.parameters(), lr=1e-3)
|
| 288 |
+
|
| 289 |
+
losses_orig = []
|
| 290 |
+
losses_fast = []
|
| 291 |
+
|
| 292 |
+
print("=" * 80)
|
| 293 |
+
print("Training comparison: Original vs Optimized RoPE")
|
| 294 |
+
print("=" * 80)
|
| 295 |
+
print(f"{'Step':<6} {'Original Loss':<15} {'Fast Loss':<15} {'Diff':<12} {'Status':<10}")
|
| 296 |
+
print("-" * 80)
|
| 297 |
+
|
| 298 |
+
torch.manual_seed(42)
|
| 299 |
+
inputs = [
|
| 300 |
+
(torch.randn(1, 128, 12, 128, device="cuda"), torch.randn(1, 128, 256, device="cuda")) for _ in range(10)
|
| 301 |
+
]
|
| 302 |
+
|
| 303 |
+
for step, (x, freqs_cis) in enumerate(inputs):
|
| 304 |
+
optimizer_orig.zero_grad()
|
| 305 |
+
loss_orig = model_orig(x.clone(), freqs_cis)
|
| 306 |
+
loss_orig.backward()
|
| 307 |
+
optimizer_orig.step()
|
| 308 |
+
|
| 309 |
+
optimizer_fast.zero_grad()
|
| 310 |
+
loss_fast = model_fast(x.clone(), freqs_cis)
|
| 311 |
+
loss_fast.backward()
|
| 312 |
+
optimizer_fast.step()
|
| 313 |
+
|
| 314 |
+
has_nan_orig = any(p.grad is not None and torch.isnan(p.grad).any() for p in model_orig.parameters())
|
| 315 |
+
has_nan_fast = any(p.grad is not None and torch.isnan(p.grad).any() for p in model_fast.parameters())
|
| 316 |
+
|
| 317 |
+
if has_nan_orig or has_nan_fast:
|
| 318 |
+
print(f"❌ Step {step}: Found NaN in gradients")
|
| 319 |
+
return False
|
| 320 |
+
|
| 321 |
+
loss_orig_val = loss_orig.item()
|
| 322 |
+
loss_fast_val = loss_fast.item()
|
| 323 |
+
losses_orig.append(loss_orig_val)
|
| 324 |
+
losses_fast.append(loss_fast_val)
|
| 325 |
+
|
| 326 |
+
diff = abs(loss_orig_val - loss_fast_val)
|
| 327 |
+
rel_diff = diff / abs(loss_orig_val) if abs(loss_orig_val) > 1e-10 else 0
|
| 328 |
+
|
| 329 |
+
if diff < 1e-6:
|
| 330 |
+
status = "✅ Match"
|
| 331 |
+
elif diff < 1e-4:
|
| 332 |
+
status = "✓ Close"
|
| 333 |
+
else:
|
| 334 |
+
status = "⚠️ Differ"
|
| 335 |
+
|
| 336 |
+
print(
|
| 337 |
+
f"{step:<6} {loss_orig_val:<15.6f} {loss_fast_val:<15.6f} "
|
| 338 |
+
f"{diff:<12.2e} {status:<10}"
|
| 339 |
+
f"{rel_diff:<12.2e} {status:<10}"
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
print("-" * 80)
|
| 343 |
+
|
| 344 |
+
avg_diff = sum(abs(o - f) for o, f in zip(losses_orig, losses_fast)) / len(losses_orig)
|
| 345 |
+
max_diff = max(abs(o - f) for o, f in zip(losses_orig, losses_fast))
|
| 346 |
+
|
| 347 |
+
print(f"\n{'Summary':<20} {'Original':<15} {'Optimized':<15} {'Difference':<15}")
|
| 348 |
+
print("-" * 65)
|
| 349 |
+
print(
|
| 350 |
+
f"{'Initial loss:':<20} {losses_orig[0]:<15.6f} {losses_fast[0]:<15.6f} "
|
| 351 |
+
f"{abs(losses_orig[0] - losses_fast[0]):<15.2e}"
|
| 352 |
+
)
|
| 353 |
+
print(
|
| 354 |
+
f"{'Final loss:':<20} {losses_orig[-1]:<15.6f} {losses_fast[-1]:<15.6f} "
|
| 355 |
+
f"{abs(losses_orig[-1] - losses_fast[-1]):<15.2e}"
|
| 356 |
+
)
|
| 357 |
+
print(
|
| 358 |
+
f"{'Average loss:':<20} {sum(losses_orig) / len(losses_orig):<15.6f} "
|
| 359 |
+
f"{sum(losses_fast) / len(losses_fast):<15.6f} {avg_diff:<15.2e}"
|
| 360 |
+
)
|
| 361 |
+
print(f"{'Max difference:':<20} {'':<15} {'':<15} {max_diff:<15.2e}")
|
| 362 |
+
|
| 363 |
+
weight_diffs = []
|
| 364 |
+
for (name_o, param_o), (name_f, param_f) in zip(model_orig.named_parameters(), model_fast.named_parameters()):
|
| 365 |
+
diff = (param_o - param_f).abs().max().item()
|
| 366 |
+
weight_diffs.append(diff)
|
| 367 |
+
|
| 368 |
+
max_weight_diff = max(weight_diffs)
|
| 369 |
+
print(f"{'Max weight diff:':<20} {'':<15} {'':<15} {max_weight_diff:<15.2e}")
|
| 370 |
+
|
| 371 |
+
print("=" * 80)
|
| 372 |
+
|
| 373 |
+
if max_diff < 1e-4 and max_weight_diff < 1e-4:
|
| 374 |
+
print("✅ Training consistency test PASSED")
|
| 375 |
+
print(" Original and optimized versions produce nearly identical results")
|
| 376 |
+
return True
|
| 377 |
+
elif max_diff < 1e-2:
|
| 378 |
+
print("✓ Training consistency test ACCEPTABLE")
|
| 379 |
+
print(" Small numerical differences detected (within tolerance)")
|
| 380 |
+
return True
|
| 381 |
+
else:
|
| 382 |
+
print("⚠️ Training consistency test WARNING")
|
| 383 |
+
print(f" Differences detected: loss_diff={max_diff:.2e}, weight_diff={max_weight_diff:.2e}")
|
| 384 |
+
return False
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
if __name__ == "__main__":
|
| 388 |
+
test_zero_error()
|
| 389 |
+
test_comparison()
|
| 390 |
+
test_backward_comparison()
|
| 391 |
+
test_in_training_loop_comparison()
|
| 392 |
+
# test_backward()
|
Helios/_DEV/helios/modules/helios_kernels/utils.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import nullcontext
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import triton
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def get_device_type():
|
| 8 |
+
if torch.cuda.is_available():
|
| 9 |
+
try:
|
| 10 |
+
if torch.version.hip is not None:
|
| 11 |
+
return "hip"
|
| 12 |
+
except AttributeError:
|
| 13 |
+
pass
|
| 14 |
+
return "cuda"
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
if hasattr(torch, "xpu") and torch.xpu.is_available():
|
| 18 |
+
return "xpu"
|
| 19 |
+
except (AttributeError, RuntimeError):
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
return "cpu"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_device_count(device_type):
|
| 26 |
+
if device_type == "cuda" or device_type == "hip":
|
| 27 |
+
return torch.cuda.device_count()
|
| 28 |
+
elif device_type == "xpu":
|
| 29 |
+
try:
|
| 30 |
+
return torch.xpu.device_count()
|
| 31 |
+
except (AttributeError, RuntimeError):
|
| 32 |
+
return 0
|
| 33 |
+
return 0
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
MAX_FUSED_SIZE: int = 65536
|
| 37 |
+
next_power_of_2 = triton.next_power_of_2
|
| 38 |
+
DEVICE_TYPE = get_device_type()
|
| 39 |
+
DEVICE_COUNT = get_device_count(DEVICE_TYPE)
|
| 40 |
+
|
| 41 |
+
if DEVICE_COUNT > 1:
|
| 42 |
+
if DEVICE_TYPE in ("cuda", "hip"):
|
| 43 |
+
torch_gpu_device = torch.cuda.device
|
| 44 |
+
elif DEVICE_TYPE == "xpu":
|
| 45 |
+
torch_gpu_device = torch.xpu.device
|
| 46 |
+
else:
|
| 47 |
+
|
| 48 |
+
def torch_gpu_device(device):
|
| 49 |
+
return nullcontext()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def calculate_settings(
|
| 53 |
+
n: int,
|
| 54 |
+
) -> (
|
| 55 |
+
int,
|
| 56 |
+
int,
|
| 57 |
+
):
|
| 58 |
+
BLOCK_SIZE: int = next_power_of_2(n)
|
| 59 |
+
if BLOCK_SIZE > MAX_FUSED_SIZE:
|
| 60 |
+
raise RuntimeError(
|
| 61 |
+
f"Cannot launch Triton kernel since n = {n} exceeds the maximum CUDA blocksize = {MAX_FUSED_SIZE}."
|
| 62 |
+
)
|
| 63 |
+
num_warps: int = 4
|
| 64 |
+
if BLOCK_SIZE >= 32768:
|
| 65 |
+
num_warps = 32
|
| 66 |
+
elif BLOCK_SIZE >= 8192:
|
| 67 |
+
num_warps = 16
|
| 68 |
+
elif BLOCK_SIZE >= 2048:
|
| 69 |
+
num_warps = 8
|
| 70 |
+
return BLOCK_SIZE, num_warps
|
Helios/_DEV/helios/pipelines/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (192 Bytes). View file
|
|
|
Helios/_DEV/helios/pipelines/__pycache__/pipeline_output.cpython-311.pyc
ADDED
|
Binary file (1.33 kB). View file
|
|
|
Helios/_DEV/helios/pipelines/__pycache__/pipeline_output.cpython-312.pyc
ADDED
|
Binary file (1.14 kB). View file
|
|
|
Helios/_DEV/helios/utils/__init__.py
ADDED
|
File without changes
|
Helios/_DEV/helios/utils/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (188 Bytes). View file
|
|
|
Helios/_DEV/helios/utils/__pycache__/utils_base.cpython-311.pyc
ADDED
|
Binary file (41.8 kB). View file
|
|
|
Helios/_DEV/helios/utils/train_config.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@dataclass
|
| 6 |
+
class ReportTo:
|
| 7 |
+
tracker_name: str = field(default="Spark-Wan")
|
| 8 |
+
wandb_name: str = field(default="test_run")
|
| 9 |
+
report_to: str = field(
|
| 10 |
+
default="wandb",
|
| 11 |
+
metadata={"choices": ["wandb", "tensorboard", "comet_ml", "all"]},
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass
|
| 16 |
+
class DataConfig:
|
| 17 |
+
# ---- Base ----
|
| 18 |
+
use_shuffle: bool = field(default=False)
|
| 19 |
+
pin_memory: bool = field(default=False)
|
| 20 |
+
persistent_workers: bool = field(default=False)
|
| 21 |
+
instance_data_root: list = field(default_factory=list)
|
| 22 |
+
instance_video_root: list = field(default_factory=list)
|
| 23 |
+
dataset_sampling_ratios: list = field(default_factory=list)
|
| 24 |
+
dataloader_num_workers: int = field(default=0)
|
| 25 |
+
prefetch_factor: int = field(default=2)
|
| 26 |
+
force_rebuild: bool = field(default=False)
|
| 27 |
+
stride: int = field(default=1)
|
| 28 |
+
resolution: int = field(default=640)
|
| 29 |
+
single_res: bool = field(default=False)
|
| 30 |
+
single_res: bool = field(default=False)
|
| 31 |
+
single_height: int = field(default=384)
|
| 32 |
+
single_width: int = field(default=640)
|
| 33 |
+
single_length: bool = field(default=False)
|
| 34 |
+
single_num_frame: int = field(default=81)
|
| 35 |
+
multi_res: bool = field(default=False)
|
| 36 |
+
caption_dropout_p: float = field(default=0.00)
|
| 37 |
+
id_token: str = field(default="")
|
| 38 |
+
negative_prompt: str = field(
|
| 39 |
+
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"
|
| 40 |
+
)
|
| 41 |
+
# ---- Stage 1 ----
|
| 42 |
+
use_stage1_dataset: bool = field(default=False)
|
| 43 |
+
# ---- Stage 3 ----
|
| 44 |
+
use_stage3_dataset: bool = field(default=False)
|
| 45 |
+
gan_data_root: Optional[list] = field(default_factory=list)
|
| 46 |
+
ode_data_root: Optional[list] = field(default_factory=list)
|
| 47 |
+
text_data_root: Optional[list] = field(default_factory=list)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class ModelConfig:
|
| 52 |
+
# ---- Path ----
|
| 53 |
+
pretrained_model_name_or_path: Optional[str] = field(default=None)
|
| 54 |
+
transformer_model_name_or_path: Optional[str] = field(default=None)
|
| 55 |
+
siglip_model_name_or_path: Optional[str] = field(default=None)
|
| 56 |
+
lora_paths: Optional[list[str]] = field(default_factory=list)
|
| 57 |
+
subfolder: Optional[str] = field(default=None)
|
| 58 |
+
revision: Optional[str] = field(default=None)
|
| 59 |
+
variant: Optional[str] = field(default=None)
|
| 60 |
+
load_checkpoints_custom: bool = field(default=False)
|
| 61 |
+
load_model_path: Optional[str] = field(default=None)
|
| 62 |
+
load_dcp: bool = field(default=False)
|
| 63 |
+
load_dcp_path: Optional[str] = field(default=None)
|
| 64 |
+
# ---- Vae ----
|
| 65 |
+
upcast_vae: bool = field(default=False)
|
| 66 |
+
enable_slicing: bool = field(default=False)
|
| 67 |
+
enable_tiling: bool = field(default=False)
|
| 68 |
+
# ---- Lora ----
|
| 69 |
+
lora_rank: int = field(default=128)
|
| 70 |
+
lora_alpha: float = field(default=128.0)
|
| 71 |
+
lora_dropout: float = field(default=0.0)
|
| 72 |
+
lora_layers: Optional[str] = field(default=None)
|
| 73 |
+
lora_target_modules: list = field(default_factory=list)
|
| 74 |
+
lora_exclude_modules: list = field(default_factory=list)
|
| 75 |
+
# ---- Other ----
|
| 76 |
+
train_norm_layers: bool = field(default=False)
|
| 77 |
+
bnb_quantization_config_path: Optional[str] = field(default=None)
|
| 78 |
+
# ----- Stage 3 -----
|
| 79 |
+
critic_lora_name_or_path: Optional[str] = field(default=None)
|
| 80 |
+
critic_subfolder: Optional[str] = field(default=None)
|
| 81 |
+
critic_lora_rank: int = field(default=128)
|
| 82 |
+
critic_lora_alpha: float = field(default=128.0)
|
| 83 |
+
critic_lora_dropout: float = field(default=0.0)
|
| 84 |
+
real_score_model_name_or_path: Optional[str] = field(default=None)
|
| 85 |
+
# ---- Reward Parameters ----
|
| 86 |
+
reward_model_name_or_path: Optional[str] = field(default=None)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass
|
| 90 |
+
class ValidationConfig:
|
| 91 |
+
validation_steps: int = field(default=100)
|
| 92 |
+
validation_height: int = field(default=480)
|
| 93 |
+
validation_width: int = field(default=832)
|
| 94 |
+
validation_max_num_frames: int = field(default=81)
|
| 95 |
+
validation_prompts: Optional[list[str]] = field(default_factory=lambda: ["A frog jumps on a lotus leaf."])
|
| 96 |
+
validation_images: Optional[list[str]] = field(default_factory=lambda: ["example/input_images/frog.jpg"])
|
| 97 |
+
validation_guidance_scale: float = field(default=9.0)
|
| 98 |
+
validation_latent_window_size: list[int] = field(default_factory=lambda: [9])
|
| 99 |
+
validation_stream_chunk_size: list[int] = field(default_factory=lambda: [3])
|
| 100 |
+
first_step_valid: bool = field(default=True)
|
| 101 |
+
num_validation_videos: int = field(default=1)
|
| 102 |
+
num_inference_steps: int = field(default=30)
|
| 103 |
+
# ---- Dynamic Shifting ----
|
| 104 |
+
use_dynamic_shifting: bool = field(default=False)
|
| 105 |
+
time_shift_type: str = field(
|
| 106 |
+
default="linear",
|
| 107 |
+
metadata={"choices": ["exponential", "linear"]},
|
| 108 |
+
)
|
| 109 |
+
# ---- Stage 1 ----
|
| 110 |
+
use_kv_cache: bool = field(default=False)
|
| 111 |
+
# ---- Stage 2 ----
|
| 112 |
+
stage2_simulated_inference_steps: list[int] = field(default_factory=lambda: [10, 10, 10])
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@dataclass
|
| 116 |
+
class TrainingConfig:
|
| 117 |
+
# ---- Environment ----
|
| 118 |
+
local_rank: int = field(default=-1)
|
| 119 |
+
allow_tf32: bool = field(default=False)
|
| 120 |
+
gradient_checkpointing: bool = field(default=True)
|
| 121 |
+
enable_xformers_memory_efficient_attention: bool = field(default=False)
|
| 122 |
+
enable_npu_flash_attention: bool = field(default=False)
|
| 123 |
+
upcast_before_saving: bool = field(default=False)
|
| 124 |
+
offload: bool = field(default=False)
|
| 125 |
+
mixed_precision: str = field(
|
| 126 |
+
default="bf16",
|
| 127 |
+
metadata={"choices": ["no", "fp16", "bf16"]},
|
| 128 |
+
)
|
| 129 |
+
profile_out_dir: Optional[str] = field(default=None)
|
| 130 |
+
# ---- Training Resource ----
|
| 131 |
+
num_train_epochs: int = field(default=1)
|
| 132 |
+
max_train_steps: Optional[int] = field(default=None)
|
| 133 |
+
train_batch_size: int = field(default=1)
|
| 134 |
+
gradient_accumulation_steps: int = field(default=1)
|
| 135 |
+
checkpointing_steps: int = field(default=500)
|
| 136 |
+
checkpoints_total_limit: Optional[int] = field(default=None)
|
| 137 |
+
resume_from_checkpoint: Optional[str] = field(default=None)
|
| 138 |
+
save_checkpoints_custom: bool = field(default=False)
|
| 139 |
+
# ---- Optimizer ----
|
| 140 |
+
learning_rate: float = field(default=2e-4)
|
| 141 |
+
scale_lr: bool = field(default=False)
|
| 142 |
+
lr_scheduler: str = field(
|
| 143 |
+
default="constant",
|
| 144 |
+
metadata={
|
| 145 |
+
"choices": [
|
| 146 |
+
"linear",
|
| 147 |
+
"cosine",
|
| 148 |
+
"cosine_with_restarts",
|
| 149 |
+
"polynomial",
|
| 150 |
+
"constant",
|
| 151 |
+
"constant_with_warmup",
|
| 152 |
+
]
|
| 153 |
+
},
|
| 154 |
+
)
|
| 155 |
+
lr_warmup_steps: int = field(default=500)
|
| 156 |
+
lr_num_cycles: int = field(default=1)
|
| 157 |
+
lr_power: float = field(default=1.0)
|
| 158 |
+
optimizer: str = field(
|
| 159 |
+
default="adamw",
|
| 160 |
+
metadata={
|
| 161 |
+
"choices": ["adam", "adamw", "prodigy"],
|
| 162 |
+
},
|
| 163 |
+
)
|
| 164 |
+
use_8bit_adam: bool = field(default=False)
|
| 165 |
+
adam_beta1: float = field(default=0.9)
|
| 166 |
+
adam_beta2: float = field(default=0.999)
|
| 167 |
+
prodigy_beta3: Optional[float] = field(default=None)
|
| 168 |
+
prodigy_decouple: bool = field(default=True)
|
| 169 |
+
prodigy_use_bias_correction: bool = field(default=True)
|
| 170 |
+
prodigy_safeguard_warmup: bool = field(default=True)
|
| 171 |
+
adam_weight_decay: float = field(default=1e-04)
|
| 172 |
+
adam_epsilon: float = field(default=1e-08)
|
| 173 |
+
max_grad_norm: float = field(default=1.0)
|
| 174 |
+
weighting_scheme: str = field(
|
| 175 |
+
default="logit_normal",
|
| 176 |
+
metadata={
|
| 177 |
+
"choices": ["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"],
|
| 178 |
+
},
|
| 179 |
+
)
|
| 180 |
+
logit_mean: float = field(default=0.0)
|
| 181 |
+
logit_std: float = field(default=1.0)
|
| 182 |
+
mode_scale: float = field(default=1.29)
|
| 183 |
+
# ---- Dynamic Shifting ----
|
| 184 |
+
use_dynamic_shifting: bool = field(default=False)
|
| 185 |
+
time_shift_type: str = field(
|
| 186 |
+
default="linear",
|
| 187 |
+
metadata={"choices": ["exponential", "linear"]},
|
| 188 |
+
)
|
| 189 |
+
base_seq_len: Optional[int] = field(default=256)
|
| 190 |
+
max_seq_len: Optional[int] = field(default=4096)
|
| 191 |
+
base_shift: Optional[float] = field(default=0.5)
|
| 192 |
+
max_shift: Optional[float] = field(default=1.15)
|
| 193 |
+
# ---- VAE Decode Parameters ----
|
| 194 |
+
vae_decode_type: str = field(
|
| 195 |
+
default="default",
|
| 196 |
+
metadata={
|
| 197 |
+
"choices": ["default", "dafault_batch"],
|
| 198 |
+
},
|
| 199 |
+
)
|
| 200 |
+
# ---- EMA ----
|
| 201 |
+
use_ema: bool = field(default=False)
|
| 202 |
+
use_ema_validation: bool = field(default=False)
|
| 203 |
+
ema_decay: float = field(default=0.999)
|
| 204 |
+
ema_start_step: int = field(default=0)
|
| 205 |
+
ema_zero3_port: int = field(default=10543)
|
| 206 |
+
ema_deepspeed_config_file: str = field(default="scripts/accelerate_configs/zero3.json")
|
| 207 |
+
# ---- Stage 1 Parameters ----
|
| 208 |
+
is_enable_stage1: bool = field(default=False)
|
| 209 |
+
history_sizes: list[int] = field(default_factory=lambda: [16, 2, 1])
|
| 210 |
+
latent_window_size: list[int] = field(default_factory=lambda: [9])
|
| 211 |
+
is_random_drop: bool = field(default=False)
|
| 212 |
+
random_drop_i2v_ratio: float = field(default=0)
|
| 213 |
+
random_drop_v2v_ratio: float = field(default=0)
|
| 214 |
+
random_drop_t2v_ratio: float = field(default=0)
|
| 215 |
+
is_amplify_history: bool = field(default=False)
|
| 216 |
+
history_scale_mode: str = field(
|
| 217 |
+
default="per_head",
|
| 218 |
+
metadata={
|
| 219 |
+
"choices": ["scalar", "per_head"],
|
| 220 |
+
},
|
| 221 |
+
)
|
| 222 |
+
#
|
| 223 |
+
has_multi_term_memory_patch: bool = field(default=False)
|
| 224 |
+
is_train_full_multi_term_memory_patchg: bool = field(default=False)
|
| 225 |
+
is_train_lora_multi_term_memory_patchg: bool = field(default=False)
|
| 226 |
+
is_train_full_patch_embedding: bool = field(default=False)
|
| 227 |
+
is_train_lora_patch_embedding: bool = field(default=False)
|
| 228 |
+
zero_history_timestep: bool = field(default=False)
|
| 229 |
+
restrict_self_attn: bool = field(default=False)
|
| 230 |
+
guidance_cross_attn: bool = field(default=False)
|
| 231 |
+
is_train_restrict_lora: bool = field(default=False)
|
| 232 |
+
restrict_lora: bool = field(default=False)
|
| 233 |
+
restrict_lora_rank: int = field(default=128)
|
| 234 |
+
# ---- Easy Anti-Drifting Parameters ----
|
| 235 |
+
corrupt_model_input: bool = field(default=False)
|
| 236 |
+
corrupt_mode_model_input: str = field(
|
| 237 |
+
default="noise",
|
| 238 |
+
metadata={
|
| 239 |
+
"choices": ["noise", "downsample", "random"],
|
| 240 |
+
},
|
| 241 |
+
)
|
| 242 |
+
corrupt_mode_prob_model_input: float = field(default=0.9)
|
| 243 |
+
is_frame_independent_corrupt_model_input: bool = field(default=False)
|
| 244 |
+
is_chunk_independent_corrupt_model_input: bool = field(default=False)
|
| 245 |
+
noise_corrupt_ratio_model_input: float = field(default=1 / 3)
|
| 246 |
+
noise_corrupt_clean_prob_model_input: float = field(default=0.1)
|
| 247 |
+
downsample_min_corrupt_ratio_model_input: float = field(default=0.9)
|
| 248 |
+
downsample_max_corrupt_ratio_model_input: float = field(default=1.0)
|
| 249 |
+
#
|
| 250 |
+
corrupt_history: bool = field(default=False)
|
| 251 |
+
corrupt_mode_history: str = field(
|
| 252 |
+
default="noise",
|
| 253 |
+
metadata={
|
| 254 |
+
"choices": ["noise", "downsample", "random"],
|
| 255 |
+
},
|
| 256 |
+
)
|
| 257 |
+
corrupt_mode_prob_history: float = field(default=0.9)
|
| 258 |
+
is_frame_independent_corrupt_history: bool = field(default=False)
|
| 259 |
+
is_chunk_independent_corrupt_history: bool = field(default=False)
|
| 260 |
+
noise_corrupt_ratio_history_short: float = field(default=1 / 3)
|
| 261 |
+
noise_corrupt_ratio_history_mid: float = field(default=1 / 3)
|
| 262 |
+
noise_corrupt_ratio_history_long: float = field(default=1 / 3)
|
| 263 |
+
noise_corrupt_clean_prob_history: float = field(default=0.1)
|
| 264 |
+
downsample_min_corrupt_ratio_history: float = field(default=0.9)
|
| 265 |
+
downsample_max_corrupt_ratio_history: float = field(default=1.0)
|
| 266 |
+
#
|
| 267 |
+
is_add_saturation: bool = field(default=False)
|
| 268 |
+
saturation_ratio_min: float = field(default=0.3)
|
| 269 |
+
saturation_ratio_max: float = field(default=1.7)
|
| 270 |
+
saturation_ratio_clean_prob: float = field(default=0.1)
|
| 271 |
+
# ---- Stage 2 Parameters ----
|
| 272 |
+
is_enable_stage2: bool = field(default=False)
|
| 273 |
+
is_navit_pyramid: bool = field(default=False)
|
| 274 |
+
stage2_num_stages: int = field(default=3)
|
| 275 |
+
stage2_timestep_shift: float = field(default=1.0)
|
| 276 |
+
stage2_scheduler_gamma: float = field(default=1 / 3)
|
| 277 |
+
stage2_stage_range: list[float] = field(default_factory=lambda: [0.0, 1 / 3, 2 / 3, 1])
|
| 278 |
+
stage2_sample_ratios: list[int] = field(default_factory=lambda: [1, 2, 1])
|
| 279 |
+
efficient_sample: bool = field(default=False)
|
| 280 |
+
# ---- Stage 3 VRAM Parameters ----
|
| 281 |
+
dmd_is_low_vram_mode: bool = field(default=False)
|
| 282 |
+
is_gan_low_vram_mode: bool = field(default=False)
|
| 283 |
+
dmd_is_offload_grad: bool = field(default=False)
|
| 284 |
+
# ---- Stage 3 Parameters ----
|
| 285 |
+
log_iters: int = field(default=200)
|
| 286 |
+
no_visualize: bool = field(default=False)
|
| 287 |
+
is_train_dmd: bool = field(default=False)
|
| 288 |
+
max_grad_norm_critic: float = field(default=1.0)
|
| 289 |
+
dmd_generator_deepspeed_config: Optional[str] = field(default=None)
|
| 290 |
+
dmd_critic_deepspeed_config: Optional[str] = field(default=None)
|
| 291 |
+
critic_learning_rate: Optional[float] = field(default=2e-6)
|
| 292 |
+
dfake_gen_update_ratio: Optional[int] = field(default=5)
|
| 293 |
+
dmd_denoising_step_list: list[int] = field(default_factory=lambda: [1000, 750, 500, 250])
|
| 294 |
+
num_critic_input_frames: Optional[int] = field(default=21)
|
| 295 |
+
dmd_timestep_shift: Optional[float] = field(default=5.0)
|
| 296 |
+
dmd_last_step_only: bool = field(default=False)
|
| 297 |
+
dmd_last_section_grad_only: bool = field(default=False)
|
| 298 |
+
dmd_teacher_forcing: bool = field(default=False)
|
| 299 |
+
dmd_teacher_forcing_ratio: float = field(default=0.2)
|
| 300 |
+
fake_guidance_scale: float = field(default=0.0)
|
| 301 |
+
real_guidance_scale: float = field(default=3.0)
|
| 302 |
+
is_skip_first_section: bool = field(default=False)
|
| 303 |
+
is_amplify_first_chunk: bool = field(default=False)
|
| 304 |
+
# ---- GT History Parameters ----
|
| 305 |
+
is_use_gt_history: bool = field(default=False)
|
| 306 |
+
use_gt_history_ratio: float = field(default=1.0)
|
| 307 |
+
is_use_gt_coherence_dmd: bool = field(default=False)
|
| 308 |
+
# ---- VAE Re-Encode ----
|
| 309 |
+
is_dmd_vae_decode: bool = field(default=False)
|
| 310 |
+
# ---- Multi Stage Backward Simulated ----
|
| 311 |
+
is_multi_pyramid_stage_backward_simulated: bool = field(default=False)
|
| 312 |
+
# ---- Consistency Align Parameters ----
|
| 313 |
+
is_consistency_align: bool = field(default=False)
|
| 314 |
+
consistentcy_align_weight: float = field(default=0.25)
|
| 315 |
+
# ---- Smoothness Parameters ----
|
| 316 |
+
is_smoothness_loss: bool = field(default=False)
|
| 317 |
+
smoothness_loss_weight: float = field(default=1e-2)
|
| 318 |
+
# ---- Mean-Variance Regularization Parameters ----
|
| 319 |
+
is_mean_var_regular: bool = field(default=False)
|
| 320 |
+
mean_var_regular_weight: float = field(default=1.0)
|
| 321 |
+
regular_mean: Optional[float] = field(default=0.00657021)
|
| 322 |
+
regular_var: Optional[float] = field(default=0.85126512)
|
| 323 |
+
is_x0_mean_var_regular: bool = field(default=False)
|
| 324 |
+
mean_var_regular_x0_weight: float = field(default=1.0)
|
| 325 |
+
regular_x0_mean: Optional[float] = field(default=-0.01618061)
|
| 326 |
+
regular_x0_var: Optional[float] = field(default=0.27996052)
|
| 327 |
+
#
|
| 328 |
+
is_chunk_mean_var_regular: bool = field(default=False)
|
| 329 |
+
chunk_mean_var_regular_weight: float = field(default=1.0)
|
| 330 |
+
chunk_regular_mean: Optional[float] = field(default=0.01906107)
|
| 331 |
+
chunk_regular_var: Optional[float] = field(default=0.81397036)
|
| 332 |
+
is_chunk_x0_mean_var_regular: bool = field(default=False)
|
| 333 |
+
chunk_mean_var_regular_x0_weight: float = field(default=1.0)
|
| 334 |
+
chunk_regular_x0_mean: Optional[float] = field(default=-0.01578601)
|
| 335 |
+
chunk_regular_x0_var: Optional[float] = field(default=0.29913200)
|
| 336 |
+
# ---- ODE Regression ----
|
| 337 |
+
is_use_ode_regression: bool = field(default=False)
|
| 338 |
+
is_only_ode_regression: bool = field(default=False)
|
| 339 |
+
ode_regression_weight: float = field(default=0.25)
|
| 340 |
+
ode_num_latent_sections_min: int = field(default=3)
|
| 341 |
+
ode_num_latent_sections_max: int = field(default=3)
|
| 342 |
+
# ---- GAN Parameters ----
|
| 343 |
+
is_use_gan: bool = field(default=False)
|
| 344 |
+
gan_start_step: int = field(default=0)
|
| 345 |
+
is_separate_gan_grad: bool = field(default=False)
|
| 346 |
+
is_use_gan_hooks: bool = field(default=False)
|
| 347 |
+
is_use_gan_final: bool = field(default=False)
|
| 348 |
+
gan_cond_map_dim: int = field(default=768)
|
| 349 |
+
gan_hooks: list[int] = field(default_factory=lambda: [5, 15, 25, 35])
|
| 350 |
+
gan_g_weight: float = field(default=1e-2)
|
| 351 |
+
gan_d_weight: float = field(default=1e-2)
|
| 352 |
+
aprox_r1: bool = field(default=False)
|
| 353 |
+
aprox_r2: bool = field(default=False)
|
| 354 |
+
r1_weight: float = field(default=0.0)
|
| 355 |
+
r2_weight: float = field(default=0.0)
|
| 356 |
+
r1_sigma: float = field(default=0.1)
|
| 357 |
+
r2_sigma: float = field(default=0.1)
|
| 358 |
+
# ---- Reward Parameters ----
|
| 359 |
+
is_use_reward_model: bool = field(default=False)
|
| 360 |
+
reward_start_step: int = field(default=0)
|
| 361 |
+
reward_weight_vq: float = field(default=2.0)
|
| 362 |
+
reward_weight_mq: float = field(default=2.0)
|
| 363 |
+
reward_weight_ta: float = field(default=2.0)
|
| 364 |
+
# ---- Decouple Parameters ----
|
| 365 |
+
is_decouple_dmd: bool = field(default=False)
|
| 366 |
+
decouple_ca_start_step: int = field(default=2000)
|
| 367 |
+
decouple_ca_end_step: int = field(default=3000)
|
| 368 |
+
# ---- Cold Start Parameters ----
|
| 369 |
+
is_enable_cold_start: bool = field(default=False)
|
| 370 |
+
cold_start_step: int = field(default=1000)
|
| 371 |
+
stage_cold_start_step: Optional[int] = field(default=None)
|
| 372 |
+
# ---- Dynamic Timestep ----
|
| 373 |
+
generator_is_forcing_low_renoise: bool = field(default=False)
|
| 374 |
+
generator_dynamic_alpha: float = field(default=4.0)
|
| 375 |
+
generator_dynamic_beta: float = field(default=1.5)
|
| 376 |
+
generator_dynamic_sample_type: str = field(
|
| 377 |
+
default="uniform",
|
| 378 |
+
metadata={
|
| 379 |
+
"choices": ["uniform", "beta"],
|
| 380 |
+
},
|
| 381 |
+
)
|
| 382 |
+
generator_dynamic_step: int = field(default=1000)
|
| 383 |
+
critic_dynamic_alpha: float = field(default=4.0)
|
| 384 |
+
critic_dynamic_beta: float = field(default=1.5)
|
| 385 |
+
critic_dynamic_sample_type: str = field(
|
| 386 |
+
default="uniform",
|
| 387 |
+
metadata={
|
| 388 |
+
"choices": ["uniform", "beta"],
|
| 389 |
+
},
|
| 390 |
+
)
|
| 391 |
+
critic_dynamic_step: int = field(default=1000)
|
| 392 |
+
# ---- Dynamic DMD Section ----
|
| 393 |
+
dmd_num_latent_sections_min: Optional[int] = field(default=3)
|
| 394 |
+
dmd_num_latent_sections_max: Optional[int] = field(default=3)
|
| 395 |
+
dmd_dynamic_alpha: float = field(default=1.5)
|
| 396 |
+
dmd_dynamic_beta: float = field(default=4.0)
|
| 397 |
+
dmd_dynamic_sample_type: str = field(
|
| 398 |
+
default="uniform",
|
| 399 |
+
metadata={
|
| 400 |
+
"choices": ["uniform", "beta"],
|
| 401 |
+
},
|
| 402 |
+
)
|
| 403 |
+
dmd_dynamic_step: int = field(default=1000)
|
| 404 |
+
# ---- Dynamic ODE Section ----
|
| 405 |
+
ode_dynamic_alpha: float = field(default=1.5)
|
| 406 |
+
ode_dynamic_beta: float = field(default=4.0)
|
| 407 |
+
ode_dynamic_sample_type: str = field(
|
| 408 |
+
default="uniform",
|
| 409 |
+
metadata={
|
| 410 |
+
"choices": ["uniform", "beta"],
|
| 411 |
+
},
|
| 412 |
+
)
|
| 413 |
+
ode_dynamic_step: int = field(default=1000)
|
| 414 |
+
# ---- Recycle ----
|
| 415 |
+
use_error_recycling: bool = field(default=False)
|
| 416 |
+
y_error_sample_from_all_grids: bool = field(default=True)
|
| 417 |
+
|
| 418 |
+
error_buffer_size: int = field(default=500)
|
| 419 |
+
buffer_replacement_strategy: str = field(default="l2_batch")
|
| 420 |
+
buffer_warmup_iter: int = field(default=50)
|
| 421 |
+
timestep_grid_size: int = field(default=25)
|
| 422 |
+
num_grids: int = field(default=50)
|
| 423 |
+
|
| 424 |
+
y_error_num: int = field(default=6)
|
| 425 |
+
error_modulate_factor: float = field(default=0.0)
|
| 426 |
+
error_setting: int = field(default=1)
|
| 427 |
+
noise_prob: float = field(default=0.01)
|
| 428 |
+
y_prob: float = field(default=0.9)
|
| 429 |
+
latent_prob: float = field(default=0.9)
|
| 430 |
+
clean_prob: float = field(default=0.2)
|
| 431 |
+
clean_buffer_update_prob: float = field(default=0.1)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
@dataclass
|
| 435 |
+
class Args:
|
| 436 |
+
output_dir: str = field(default="Helios")
|
| 437 |
+
seed: int = field(default=42)
|
| 438 |
+
report_to: ReportTo = field(default_factory=ReportTo)
|
| 439 |
+
data_config: DataConfig = field(default_factory=DataConfig)
|
| 440 |
+
model_config: ModelConfig = field(default_factory=ModelConfig)
|
| 441 |
+
validation_config: ValidationConfig = field(default_factory=ValidationConfig)
|
| 442 |
+
training_config: TrainingConfig = field(default_factory=TrainingConfig)
|
| 443 |
+
logging_dir: str = field(default="logs")
|
Helios/_DEV/helios/utils/utils_base.py
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import html
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
from typing import List, Literal, Optional, Union
|
| 7 |
+
|
| 8 |
+
import ftfy
|
| 9 |
+
import regex as re
|
| 10 |
+
import torch
|
| 11 |
+
from accelerate.logging import get_logger
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
logger = get_logger(__name__)
|
| 15 |
+
|
| 16 |
+
NORM_LAYER_PREFIXES = ["norm_q", "norm_k", "norm_added_q", "norm_added_k"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ======================================== memory monitoring ========================================
|
| 20 |
+
def get_memory_stats():
|
| 21 |
+
if torch.cuda.is_available():
|
| 22 |
+
allocated = torch.cuda.memory_allocated() / 1024**3 # GB
|
| 23 |
+
reserved = torch.cuda.memory_reserved() / 1024**3 # GB
|
| 24 |
+
max_allocated = torch.cuda.max_memory_allocated() / 1024**3
|
| 25 |
+
return {"allocated": allocated, "reserved": reserved, "max_allocated": max_allocated}
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def reset_memory_stats():
|
| 30 |
+
if torch.cuda.is_available():
|
| 31 |
+
torch.cuda.empty_cache()
|
| 32 |
+
torch.cuda.reset_peak_memory_stats()
|
| 33 |
+
gc.collect()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ======================================== initialize ========================================
|
| 37 |
+
def get_config_value(args, name):
|
| 38 |
+
if hasattr(args, name):
|
| 39 |
+
return getattr(args, name)
|
| 40 |
+
elif hasattr(args, "training_config") and hasattr(args.training_config, name):
|
| 41 |
+
return getattr(args.training_config, name)
|
| 42 |
+
else:
|
| 43 |
+
raise AttributeError(f"Neither args nor args.training_config has attribute '{name}'")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def compare_configs(existing_conf, current_conf, path="", ignore_keys=None):
|
| 47 |
+
if ignore_keys is None:
|
| 48 |
+
ignore_keys = set()
|
| 49 |
+
|
| 50 |
+
mismatches = []
|
| 51 |
+
|
| 52 |
+
all_keys = set(existing_conf.keys()) | set(current_conf.keys())
|
| 53 |
+
|
| 54 |
+
for key in all_keys:
|
| 55 |
+
current_path = f"{path}.{key}" if path else key
|
| 56 |
+
|
| 57 |
+
if current_path in ignore_keys or key in ignore_keys:
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
if key not in existing_conf:
|
| 61 |
+
mismatches.append(f"Key '{current_path}' missing in existing config")
|
| 62 |
+
elif key not in current_conf:
|
| 63 |
+
mismatches.append(f"Key '{current_path}' missing in current config")
|
| 64 |
+
else:
|
| 65 |
+
existing_val = existing_conf[key]
|
| 66 |
+
current_val = current_conf[key]
|
| 67 |
+
|
| 68 |
+
if isinstance(existing_val, dict) and isinstance(current_val, dict):
|
| 69 |
+
mismatches.extend(compare_configs(existing_val, current_val, current_path, ignore_keys))
|
| 70 |
+
elif existing_val != current_val:
|
| 71 |
+
mismatches.append(f"Key '{current_path}': existing={existing_val} vs current={current_val}")
|
| 72 |
+
|
| 73 |
+
return mismatches
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def get_optimizer(args, accelerator, params_to_optimize, use_deepspeed: bool = False):
|
| 77 |
+
# Use DeepSpeed optimizer
|
| 78 |
+
if use_deepspeed:
|
| 79 |
+
from accelerate.utils import DummyOptim
|
| 80 |
+
|
| 81 |
+
return DummyOptim(
|
| 82 |
+
params_to_optimize,
|
| 83 |
+
lr=args.training_config.learning_rate,
|
| 84 |
+
betas=(args.training_config.adam_beta1, args.training_config.adam_beta2),
|
| 85 |
+
eps=args.training_config.adam_epsilon,
|
| 86 |
+
weight_decay=args.training_config.adam_weight_decay,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Optimizer creation
|
| 90 |
+
supported_optimizers = ["adam", "adamw", "prodigy"]
|
| 91 |
+
if args.training_config.optimizer.lower() not in supported_optimizers:
|
| 92 |
+
accelerator.print(
|
| 93 |
+
f"Unsupported choice of optimizer: {args.training_config.optimizer}. Supported optimizers include {supported_optimizers}. Defaulting to AdamW"
|
| 94 |
+
)
|
| 95 |
+
args.training_config.optimizer = "adamw"
|
| 96 |
+
|
| 97 |
+
if args.training_config.use_8bit_adam and args.training_config.optimizer.lower() not in ["adam", "adamw"]:
|
| 98 |
+
accelerator.print(
|
| 99 |
+
f"use_8bit_adam is ignored when optimizer is not set to 'AdamW'. Optimizer was "
|
| 100 |
+
f"set to {args.training_config.optimizer.lower()}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if args.training_config.use_8bit_adam:
|
| 104 |
+
try:
|
| 105 |
+
import bitsandbytes as bnb
|
| 106 |
+
except ImportError:
|
| 107 |
+
raise ImportError(
|
| 108 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if args.training_config.optimizer.lower() == "adamw":
|
| 112 |
+
optimizer_class = bnb.optim.AdamW8bit if args.training_config.use_8bit_adam else torch.optim.AdamW
|
| 113 |
+
|
| 114 |
+
optimizer = optimizer_class(
|
| 115 |
+
params_to_optimize,
|
| 116 |
+
betas=(args.training_config.adam_beta1, args.training_config.adam_beta2),
|
| 117 |
+
eps=args.training_config.adam_epsilon,
|
| 118 |
+
weight_decay=args.training_config.adam_weight_decay,
|
| 119 |
+
)
|
| 120 |
+
elif args.training_config.optimizer.lower() == "adam":
|
| 121 |
+
optimizer_class = bnb.optim.Adam8bit if args.training_config.use_8bit_adam else torch.optim.Adam
|
| 122 |
+
|
| 123 |
+
optimizer = optimizer_class(
|
| 124 |
+
params_to_optimize,
|
| 125 |
+
betas=(args.training_config.adam_beta1, args.training_config.adam_beta2),
|
| 126 |
+
eps=args.training_config.adam_epsilon,
|
| 127 |
+
weight_decay=args.training_config.adam_weight_decay,
|
| 128 |
+
)
|
| 129 |
+
elif args.training_config.optimizer.lower() == "prodigy":
|
| 130 |
+
try:
|
| 131 |
+
import prodigyopt
|
| 132 |
+
except ImportError:
|
| 133 |
+
raise ImportError("To use Prodigy, please install the prodigyopt library: `pip install prodigyopt`")
|
| 134 |
+
|
| 135 |
+
optimizer_class = prodigyopt.Prodigy
|
| 136 |
+
|
| 137 |
+
if args.training_config.learning_rate <= 0.1:
|
| 138 |
+
accelerator.print(
|
| 139 |
+
"Learning rate is too low. When using prodigy, it's generally better to set learning rate around 1.0"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
optimizer = optimizer_class(
|
| 143 |
+
params_to_optimize,
|
| 144 |
+
betas=(args.training_config.adam_beta1, args.training_config.adam_beta2),
|
| 145 |
+
beta3=args.training_config.prodigy_beta3,
|
| 146 |
+
weight_decay=args.training_config.adam_weight_decay,
|
| 147 |
+
eps=args.training_config.adam_epsilon,
|
| 148 |
+
decouple=args.training_config.prodigy_decouple,
|
| 149 |
+
use_bias_correction=args.training_config.prodigy_use_bias_correction,
|
| 150 |
+
safeguard_warmup=args.training_config.prodigy_safeguard_warmup,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
return optimizer
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# ======================================== checkpoints related ========================================
|
| 157 |
+
def save_extra_components(args, model=None, model_state_dict=None, output_dir=None):
|
| 158 |
+
if model is None and model_state_dict is None:
|
| 159 |
+
raise ValueError("Either 'model' or 'model_state_dict' must be provided")
|
| 160 |
+
|
| 161 |
+
if output_dir is None:
|
| 162 |
+
raise ValueError("output_dir must be provided")
|
| 163 |
+
|
| 164 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 165 |
+
state_dict = {}
|
| 166 |
+
|
| 167 |
+
# Determine whether to use model or model_state_dict
|
| 168 |
+
use_state_dict = model_state_dict is not None
|
| 169 |
+
|
| 170 |
+
# 1. Save patch_short, patch_mid, patch_long (formerly multi_term_memory_patchg)
|
| 171 |
+
if args.training_config.is_enable_stage1 and (
|
| 172 |
+
args.training_config.is_train_full_multi_term_memory_patchg
|
| 173 |
+
or args.training_config.is_train_lora_multi_term_memory_patchg
|
| 174 |
+
):
|
| 175 |
+
patch_names = ["patch_short", "patch_mid", "patch_long"]
|
| 176 |
+
|
| 177 |
+
if use_state_dict:
|
| 178 |
+
# Extract from state_dict
|
| 179 |
+
for k, v in model_state_dict.items():
|
| 180 |
+
if any(k.startswith(f"{p}.") for p in patch_names):
|
| 181 |
+
state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v
|
| 182 |
+
else:
|
| 183 |
+
# Extract from model
|
| 184 |
+
for p in patch_names:
|
| 185 |
+
if hasattr(model, p):
|
| 186 |
+
patch_module = getattr(model, p)
|
| 187 |
+
for k, v in patch_module.state_dict().items():
|
| 188 |
+
state_dict[f"{p}.{k}"] = v.detach().clone().cpu()
|
| 189 |
+
|
| 190 |
+
# 2. Save LoRA layers from all transformer blocks
|
| 191 |
+
if args.training_config.restrict_self_attn and args.training_config.is_train_restrict_lora:
|
| 192 |
+
if use_state_dict:
|
| 193 |
+
# Extract LoRA parameters from state_dict
|
| 194 |
+
for k, v in model_state_dict.items():
|
| 195 |
+
if any(lora_key in k for lora_key in [".q_loras.", ".k_loras.", ".v_loras."]):
|
| 196 |
+
state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v
|
| 197 |
+
else:
|
| 198 |
+
# Extract from model
|
| 199 |
+
for block_idx, block in enumerate(model.blocks):
|
| 200 |
+
if hasattr(block.attn1, "q_loras"):
|
| 201 |
+
for k, v in block.attn1.q_loras.state_dict().items():
|
| 202 |
+
state_dict[f"blocks.{block_idx}.attn1.q_loras.{k}"] = v.detach().clone().cpu()
|
| 203 |
+
|
| 204 |
+
if hasattr(block.attn1, "k_loras"):
|
| 205 |
+
for k, v in block.attn1.k_loras.state_dict().items():
|
| 206 |
+
state_dict[f"blocks.{block_idx}.attn1.k_loras.{k}"] = v.detach().clone().cpu()
|
| 207 |
+
|
| 208 |
+
if hasattr(block.attn1, "v_loras"):
|
| 209 |
+
for k, v in block.attn1.v_loras.state_dict().items():
|
| 210 |
+
state_dict[f"blocks.{block_idx}.attn1.v_loras.{k}"] = v.detach().clone().cpu()
|
| 211 |
+
|
| 212 |
+
# 3. Save History Scale parameters
|
| 213 |
+
if args.training_config.is_amplify_history:
|
| 214 |
+
if use_state_dict:
|
| 215 |
+
# Extract history_key_scale from state_dict
|
| 216 |
+
for k, v in model_state_dict.items():
|
| 217 |
+
if "history_key_scale" in k:
|
| 218 |
+
state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v
|
| 219 |
+
else:
|
| 220 |
+
# Extract from model
|
| 221 |
+
for block_idx, block in enumerate(model.blocks):
|
| 222 |
+
if hasattr(block.attn1, "history_key_scale"):
|
| 223 |
+
state_dict[f"blocks.{block_idx}.attn1.history_key_scale"] = (
|
| 224 |
+
block.attn1.history_key_scale.detach().clone().cpu()
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# 4. Save GAN parameters
|
| 228 |
+
if args.training_config.is_use_gan:
|
| 229 |
+
if use_state_dict:
|
| 230 |
+
# Extract GAN parameters from state_dict
|
| 231 |
+
for k, v in model_state_dict.items():
|
| 232 |
+
if k.startswith("gan_heads.") or k.startswith("gan_final_head."):
|
| 233 |
+
state_dict[k] = v.detach().clone().cpu() if torch.is_tensor(v) else v
|
| 234 |
+
else:
|
| 235 |
+
# Extract from model
|
| 236 |
+
if hasattr(model, "gan_heads"):
|
| 237 |
+
for hook_name, gan_head in model.gan_heads.items():
|
| 238 |
+
for k, v in gan_head.state_dict().items():
|
| 239 |
+
state_dict[f"gan_heads.{hook_name}.{k}"] = v.detach().clone().cpu()
|
| 240 |
+
|
| 241 |
+
if hasattr(model, "gan_final_head"):
|
| 242 |
+
for k, v in model.gan_final_head.state_dict().items():
|
| 243 |
+
state_dict[f"gan_final_head.{k}"] = v.detach().clone().cpu()
|
| 244 |
+
|
| 245 |
+
torch.save(state_dict, os.path.join(output_dir, "transformer_partial.pth"))
|
| 246 |
+
print(f"Saved checkpoint with {len(state_dict)} parameters to {output_dir}/transformer_partial.pth")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def load_extra_components(args, model, checkpoint_path):
|
| 250 |
+
"""
|
| 251 |
+
Load patch_short, patch_mid, patch_long, q_loras, k_loras, v_loras into the model
|
| 252 |
+
"""
|
| 253 |
+
state_dict = torch.load(checkpoint_path, map_location="cpu")
|
| 254 |
+
loaded_keys = set()
|
| 255 |
+
|
| 256 |
+
# Load patch modules (formerly multi_term_memory_patchg)
|
| 257 |
+
if args.training_config.is_enable_stage1:
|
| 258 |
+
patch_names = ["patch_short", "patch_mid", "patch_long"]
|
| 259 |
+
|
| 260 |
+
for p_name in patch_names:
|
| 261 |
+
patch_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"{p_name}.")]
|
| 262 |
+
if patch_keys_in_sd and hasattr(model, p_name):
|
| 263 |
+
patch_state = {
|
| 264 |
+
k.replace(f"{p_name}.", ""): v for k, v in state_dict.items() if k.startswith(f"{p_name}.")
|
| 265 |
+
}
|
| 266 |
+
patch_module = getattr(model, p_name)
|
| 267 |
+
load_info = patch_module.load_state_dict(patch_state, strict=False)
|
| 268 |
+
loaded_keys.update(patch_keys_in_sd)
|
| 269 |
+
|
| 270 |
+
print(f"Loaded {len(patch_keys_in_sd)} parameters for {p_name}")
|
| 271 |
+
if load_info.missing_keys:
|
| 272 |
+
print(f" Missing keys in {p_name}: {load_info.missing_keys}")
|
| 273 |
+
if load_info.unexpected_keys:
|
| 274 |
+
print(f" Unexpected keys in {p_name}: {load_info.unexpected_keys}")
|
| 275 |
+
|
| 276 |
+
# Load LoRA layers
|
| 277 |
+
lora_keys_count = 0
|
| 278 |
+
if args.training_config.restrict_self_attn:
|
| 279 |
+
for block_idx, block in enumerate(model.blocks):
|
| 280 |
+
# Load q_loras
|
| 281 |
+
q_lora_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"blocks.{block_idx}.attn1.q_loras.")]
|
| 282 |
+
if q_lora_keys_in_sd:
|
| 283 |
+
q_lora_state = {
|
| 284 |
+
k.replace(f"blocks.{block_idx}.attn1.q_loras.", ""): v
|
| 285 |
+
for k, v in state_dict.items()
|
| 286 |
+
if k.startswith(f"blocks.{block_idx}.attn1.q_loras.")
|
| 287 |
+
}
|
| 288 |
+
load_info = block.attn1.q_loras.load_state_dict(q_lora_state, strict=False)
|
| 289 |
+
loaded_keys.update(q_lora_keys_in_sd)
|
| 290 |
+
lora_keys_count += len(q_lora_keys_in_sd)
|
| 291 |
+
if load_info.missing_keys:
|
| 292 |
+
print(f" Missing keys in blocks.{block_idx}.attn1.q_loras: {load_info.missing_keys}")
|
| 293 |
+
if load_info.unexpected_keys:
|
| 294 |
+
print(f" Unexpected keys in blocks.{block_idx}.attn1.q_loras: {load_info.unexpected_keys}")
|
| 295 |
+
|
| 296 |
+
# Load k_loras
|
| 297 |
+
k_lora_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"blocks.{block_idx}.attn1.k_loras.")]
|
| 298 |
+
if k_lora_keys_in_sd:
|
| 299 |
+
k_lora_state = {
|
| 300 |
+
k.replace(f"blocks.{block_idx}.attn1.k_loras.", ""): v
|
| 301 |
+
for k, v in state_dict.items()
|
| 302 |
+
if k.startswith(f"blocks.{block_idx}.attn1.k_loras.")
|
| 303 |
+
}
|
| 304 |
+
load_info = block.attn1.k_loras.load_state_dict(k_lora_state, strict=False)
|
| 305 |
+
loaded_keys.update(k_lora_keys_in_sd)
|
| 306 |
+
lora_keys_count += len(k_lora_keys_in_sd)
|
| 307 |
+
if load_info.missing_keys:
|
| 308 |
+
print(f" Missing keys in blocks.{block_idx}.attn1.k_loras: {load_info.missing_keys}")
|
| 309 |
+
if load_info.unexpected_keys:
|
| 310 |
+
print(f" Unexpected keys in blocks.{block_idx}.attn1.k_loras: {load_info.unexpected_keys}")
|
| 311 |
+
|
| 312 |
+
# Load v_loras
|
| 313 |
+
v_lora_keys_in_sd = [k for k in state_dict.keys() if k.startswith(f"blocks.{block_idx}.attn1.v_loras.")]
|
| 314 |
+
if v_lora_keys_in_sd:
|
| 315 |
+
v_lora_state = {
|
| 316 |
+
k.replace(f"blocks.{block_idx}.attn1.v_loras.", ""): v
|
| 317 |
+
for k, v in state_dict.items()
|
| 318 |
+
if k.startswith(f"blocks.{block_idx}.attn1.v_loras.")
|
| 319 |
+
}
|
| 320 |
+
load_info = block.attn1.v_loras.load_state_dict(v_lora_state, strict=False)
|
| 321 |
+
loaded_keys.update(v_lora_keys_in_sd)
|
| 322 |
+
lora_keys_count += len(v_lora_keys_in_sd)
|
| 323 |
+
if load_info.missing_keys:
|
| 324 |
+
print(f" Missing keys in blocks.{block_idx}.attn1.v_loras: {load_info.missing_keys}")
|
| 325 |
+
if load_info.unexpected_keys:
|
| 326 |
+
print(f" Unexpected keys in blocks.{block_idx}.attn1.v_loras: {load_info.unexpected_keys}")
|
| 327 |
+
|
| 328 |
+
print(f"Loaded {lora_keys_count} parameters for Restrict Self Attn LoRA")
|
| 329 |
+
|
| 330 |
+
# Load History Scale layers
|
| 331 |
+
history_keys_count = 0
|
| 332 |
+
if args.training_config.is_amplify_history:
|
| 333 |
+
for block_idx, block in enumerate(model.blocks):
|
| 334 |
+
history_key_scale_key = f"blocks.{block_idx}.attn1.history_key_scale"
|
| 335 |
+
if history_key_scale_key in state_dict:
|
| 336 |
+
block.attn1.history_key_scale.data = state_dict[history_key_scale_key].to(
|
| 337 |
+
block.attn1.history_key_scale.device
|
| 338 |
+
)
|
| 339 |
+
loaded_keys.add(history_key_scale_key)
|
| 340 |
+
history_keys_count += 1
|
| 341 |
+
|
| 342 |
+
print(f"Loaded {history_keys_count} parameters for History Scale")
|
| 343 |
+
|
| 344 |
+
# Load GAN
|
| 345 |
+
gan_keys_count = 0
|
| 346 |
+
if args.training_config.is_use_gan:
|
| 347 |
+
# Load intermediate gan_heads
|
| 348 |
+
if hasattr(model, "gan_heads"):
|
| 349 |
+
for hook_name, gan_head in model.gan_heads.items():
|
| 350 |
+
gan_head_prefix = f"gan_heads.{hook_name}."
|
| 351 |
+
gan_head_keys_in_sd = [k for k in state_dict.keys() if k.startswith(gan_head_prefix)]
|
| 352 |
+
|
| 353 |
+
if gan_head_keys_in_sd:
|
| 354 |
+
gan_head_state = {
|
| 355 |
+
k.replace(gan_head_prefix, ""): v
|
| 356 |
+
for k, v in state_dict.items()
|
| 357 |
+
if k.startswith(gan_head_prefix)
|
| 358 |
+
}
|
| 359 |
+
load_info = gan_head.load_state_dict(gan_head_state, strict=False)
|
| 360 |
+
loaded_keys.update(gan_head_keys_in_sd)
|
| 361 |
+
gan_keys_count += len(gan_head_keys_in_sd)
|
| 362 |
+
if load_info.missing_keys:
|
| 363 |
+
print(f" Missing keys in gan_heads.{hook_name}: {load_info.missing_keys}")
|
| 364 |
+
if load_info.unexpected_keys:
|
| 365 |
+
print(f" Unexpected keys in gan_heads.{hook_name}: {load_info.unexpected_keys}")
|
| 366 |
+
|
| 367 |
+
# Load final gan head
|
| 368 |
+
if hasattr(model, "gan_final_head"):
|
| 369 |
+
gan_final_keys_in_sd = [k for k in state_dict.keys() if k.startswith("gan_final_head.")]
|
| 370 |
+
|
| 371 |
+
if gan_final_keys_in_sd:
|
| 372 |
+
gan_final_state = {
|
| 373 |
+
k.replace("gan_final_head.", ""): v
|
| 374 |
+
for k, v in state_dict.items()
|
| 375 |
+
if k.startswith("gan_final_head.")
|
| 376 |
+
}
|
| 377 |
+
load_info = model.gan_final_head.load_state_dict(gan_final_state, strict=False)
|
| 378 |
+
loaded_keys.update(gan_final_keys_in_sd)
|
| 379 |
+
gan_keys_count += len(gan_final_keys_in_sd)
|
| 380 |
+
if load_info.missing_keys:
|
| 381 |
+
print(f" Missing keys in gan_final_head: {load_info.missing_keys}")
|
| 382 |
+
if load_info.unexpected_keys:
|
| 383 |
+
print(f" Unexpected keys in gan_final_head: {load_info.unexpected_keys}")
|
| 384 |
+
|
| 385 |
+
if gan_keys_count > 0:
|
| 386 |
+
print(f"Loaded {gan_keys_count} parameters for GAN components")
|
| 387 |
+
|
| 388 |
+
if not loaded_keys:
|
| 389 |
+
print("No extra components were loaded from the checkpoint.")
|
| 390 |
+
return
|
| 391 |
+
|
| 392 |
+
all_sd_keys = set(state_dict.keys())
|
| 393 |
+
unmatched_keys = all_sd_keys - loaded_keys
|
| 394 |
+
|
| 395 |
+
print("\nCheckpoint loading completed.")
|
| 396 |
+
print(f"Total loaded keys: {len(loaded_keys)}")
|
| 397 |
+
if unmatched_keys:
|
| 398 |
+
print(f"The following keys in the checkpoint were not loaded into the model: {sorted(unmatched_keys)}\n")
|
| 399 |
+
else:
|
| 400 |
+
print("Load extra module successfully! All keys in the checkpoint were successfully processed or matched.\n")
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def save_model_checkpoint(
|
| 404 |
+
transformer,
|
| 405 |
+
args,
|
| 406 |
+
save_path,
|
| 407 |
+
weight_dtype=None,
|
| 408 |
+
unwrap_model_fn=None,
|
| 409 |
+
get_peft_model_state_dict_fn=None,
|
| 410 |
+
collate_lora_metadata_fn=None,
|
| 411 |
+
save_extra_components_fn=None,
|
| 412 |
+
pipeline_class=None,
|
| 413 |
+
norm_layer_prefixes=None,
|
| 414 |
+
):
|
| 415 |
+
modules_to_save = {}
|
| 416 |
+
model_to_save = unwrap_model_fn(transformer) if unwrap_model_fn else transformer
|
| 417 |
+
|
| 418 |
+
transformer_lora_layers = get_peft_model_state_dict_fn(model_to_save)
|
| 419 |
+
|
| 420 |
+
if args.model_config.train_norm_layers:
|
| 421 |
+
norm_prefixes = norm_layer_prefixes or []
|
| 422 |
+
transformer_norm_layers = {
|
| 423 |
+
f"transformer.{name}": param
|
| 424 |
+
for name, param in model_to_save.named_parameters()
|
| 425 |
+
if any(k in name for k in norm_prefixes)
|
| 426 |
+
}
|
| 427 |
+
transformer_lora_layers = {
|
| 428 |
+
**transformer_lora_layers,
|
| 429 |
+
**transformer_norm_layers,
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
modules_to_save["transformer"] = model_to_save
|
| 433 |
+
|
| 434 |
+
if pipeline_class and hasattr(pipeline_class, "save_lora_weights"):
|
| 435 |
+
lora_metadata = collate_lora_metadata_fn(modules_to_save) if collate_lora_metadata_fn else {}
|
| 436 |
+
pipeline_class.save_lora_weights(
|
| 437 |
+
save_directory=save_path,
|
| 438 |
+
transformer_lora_layers=transformer_lora_layers,
|
| 439 |
+
**lora_metadata,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
if save_extra_components_fn:
|
| 443 |
+
save_extra_components_fn(args=args, model=model_to_save, output_dir=save_path)
|
| 444 |
+
|
| 445 |
+
modules_to_save = None
|
| 446 |
+
lora_metadata = None
|
| 447 |
+
transformer_norm_layers = None
|
| 448 |
+
transformer_lora_layers = None
|
| 449 |
+
del modules_to_save
|
| 450 |
+
del lora_metadata
|
| 451 |
+
del transformer_norm_layers
|
| 452 |
+
del transformer_lora_layers
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def load_model_checkpoint(
|
| 456 |
+
args,
|
| 457 |
+
checkpoint_path,
|
| 458 |
+
transformer,
|
| 459 |
+
pipeline_class=None,
|
| 460 |
+
norm_layer_prefixes=None,
|
| 461 |
+
convert_unet_state_dict_to_peft_fn=None,
|
| 462 |
+
set_peft_model_state_dict_fn=None,
|
| 463 |
+
cast_training_params_fn=None,
|
| 464 |
+
):
|
| 465 |
+
if not os.path.exists(checkpoint_path):
|
| 466 |
+
raise ValueError(f"Checkpoint path does not exist: {checkpoint_path}")
|
| 467 |
+
|
| 468 |
+
lora_state_dict = None
|
| 469 |
+
if pipeline_class and hasattr(pipeline_class, "load_lora_weights"):
|
| 470 |
+
lora_state_dict = pipeline_class.lora_state_dict(checkpoint_path)
|
| 471 |
+
|
| 472 |
+
transformer_state_dict = {
|
| 473 |
+
f"{k.replace('transformer.', '')}": v for k, v in lora_state_dict.items() if k.startswith("transformer.")
|
| 474 |
+
}
|
| 475 |
+
transformer_state_dict = convert_unet_state_dict_to_peft_fn(transformer_state_dict)
|
| 476 |
+
incompatible_keys = set_peft_model_state_dict_fn(transformer, transformer_state_dict, adapter_name="default")
|
| 477 |
+
if incompatible_keys is not None:
|
| 478 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
| 479 |
+
if unexpected_keys:
|
| 480 |
+
print(
|
| 481 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
| 482 |
+
f" {unexpected_keys}. "
|
| 483 |
+
)
|
| 484 |
+
print(f"load lora from {checkpoint_path} successfully!")
|
| 485 |
+
|
| 486 |
+
if args.model_config.train_norm_layers and lora_state_dict and norm_layer_prefixes:
|
| 487 |
+
transformer_norm_state_dict = {
|
| 488 |
+
k: v
|
| 489 |
+
for k, v in lora_state_dict.items()
|
| 490 |
+
if k.startswith("transformer.") and any(norm_k in k for norm_k in norm_layer_prefixes)
|
| 491 |
+
}
|
| 492 |
+
transformer._transformer_norm_layers = pipeline_class._load_norm_into_transformer(
|
| 493 |
+
transformer_norm_state_dict,
|
| 494 |
+
transformer=transformer,
|
| 495 |
+
discard_original_layers=False,
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
load_extra_components(args, transformer, os.path.join(checkpoint_path, "transformer_partial.pth"))
|
| 499 |
+
|
| 500 |
+
if args.training_config.mixed_precision != "fp32":
|
| 501 |
+
models = [transformer]
|
| 502 |
+
cast_training_params_fn(models)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# ======================================== sigmas & timesteps ========================================
|
| 506 |
+
def get_sigmas(noise_scheduler, timesteps, n_dim=4, device="cuda", dtype=torch.float32):
|
| 507 |
+
sigmas = noise_scheduler.sigmas.to(device=device, dtype=dtype)
|
| 508 |
+
schedule_timesteps = noise_scheduler.timesteps.to(device)
|
| 509 |
+
timesteps = timesteps.to(device)
|
| 510 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 511 |
+
|
| 512 |
+
sigma = sigmas[step_indices].flatten()
|
| 513 |
+
while len(sigma.shape) < n_dim:
|
| 514 |
+
sigma = sigma.unsqueeze(-1)
|
| 515 |
+
return sigma
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def calculate_shift(
|
| 519 |
+
image_seq_len,
|
| 520 |
+
base_seq_len: int = 256,
|
| 521 |
+
max_seq_len: int = 4096,
|
| 522 |
+
base_shift: float = 0.5,
|
| 523 |
+
max_shift: float = 1.15,
|
| 524 |
+
):
|
| 525 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
| 526 |
+
b = base_shift - m * base_seq_len
|
| 527 |
+
mu = image_seq_len * m + b
|
| 528 |
+
return mu
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def apply_schedule_shift(
|
| 532 |
+
sigmas,
|
| 533 |
+
noise,
|
| 534 |
+
sigmas_two=None,
|
| 535 |
+
base_seq_len: int = 256,
|
| 536 |
+
max_seq_len: int = 4096,
|
| 537 |
+
base_shift: float = 0.5,
|
| 538 |
+
max_shift: float = 1.15,
|
| 539 |
+
exp_max: float = 7.0,
|
| 540 |
+
time_shift_type: Literal["exponential", "linear"] = "linear",
|
| 541 |
+
mu: float = None,
|
| 542 |
+
return_mu: bool = False,
|
| 543 |
+
):
|
| 544 |
+
if mu is None:
|
| 545 |
+
# Resolution-dependent shifting of timestep schedules as per section 5.3.2 of SD3 paper
|
| 546 |
+
image_seq_len = (noise.shape[-1] * noise.shape[-2] * noise.shape[-3]) // 4 # patch size 1,2,2
|
| 547 |
+
mu = calculate_shift(
|
| 548 |
+
image_seq_len,
|
| 549 |
+
base_seq_len if base_seq_len is not None else 256,
|
| 550 |
+
max_seq_len if max_seq_len is not None else 4096,
|
| 551 |
+
base_shift if base_shift is not None else 0.5,
|
| 552 |
+
max_shift if max_shift is not None else 1.15,
|
| 553 |
+
)
|
| 554 |
+
if time_shift_type == "exponential":
|
| 555 |
+
mu = min(mu, math.log(exp_max))
|
| 556 |
+
mu = math.exp(mu)
|
| 557 |
+
|
| 558 |
+
if sigmas_two is not None:
|
| 559 |
+
sigmas = (sigmas * mu) / (1 + (mu - 1) * sigmas)
|
| 560 |
+
sigmas_two = (sigmas_two * mu) / (1 + (mu - 1) * sigmas_two)
|
| 561 |
+
if return_mu:
|
| 562 |
+
return sigmas, sigmas_two, mu
|
| 563 |
+
else:
|
| 564 |
+
return sigmas, sigmas_two
|
| 565 |
+
else:
|
| 566 |
+
sigmas = (sigmas * mu) / (1 + (mu - 1) * sigmas)
|
| 567 |
+
if return_mu:
|
| 568 |
+
return sigmas, mu
|
| 569 |
+
else:
|
| 570 |
+
return sigmas
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
# ======================================== clean prompt ========================================
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def basic_clean(text):
|
| 577 |
+
text = ftfy.fix_text(text)
|
| 578 |
+
text = html.unescape(html.unescape(text))
|
| 579 |
+
return text.strip()
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def whitespace_clean(text):
|
| 583 |
+
text = re.sub(r"\s+", " ", text)
|
| 584 |
+
text = text.strip()
|
| 585 |
+
return text
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def prompt_clean(text):
|
| 589 |
+
text = whitespace_clean(basic_clean(text))
|
| 590 |
+
return text
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _get_t5_prompt_embeds(
|
| 594 |
+
tokenizer,
|
| 595 |
+
text_encoder,
|
| 596 |
+
prompt: Union[str, List[str]] = None,
|
| 597 |
+
num_videos_per_prompt: int = 1,
|
| 598 |
+
max_sequence_length: int = 512,
|
| 599 |
+
caption_dropout_p: float = 0.0,
|
| 600 |
+
device: Optional[torch.device] = "cuda",
|
| 601 |
+
dtype: Optional[torch.dtype] = torch.bfloat16,
|
| 602 |
+
):
|
| 603 |
+
device = device
|
| 604 |
+
dtype = dtype
|
| 605 |
+
|
| 606 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 607 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 608 |
+
batch_size = len(prompt)
|
| 609 |
+
|
| 610 |
+
text_inputs = tokenizer(
|
| 611 |
+
prompt,
|
| 612 |
+
padding="max_length",
|
| 613 |
+
max_length=max_sequence_length,
|
| 614 |
+
truncation=True,
|
| 615 |
+
add_special_tokens=True,
|
| 616 |
+
return_attention_mask=True,
|
| 617 |
+
return_tensors="pt",
|
| 618 |
+
)
|
| 619 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 620 |
+
|
| 621 |
+
prompt_embeds = text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 622 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 623 |
+
|
| 624 |
+
if random.random() < caption_dropout_p:
|
| 625 |
+
prompt_embeds.fill_(0)
|
| 626 |
+
mask.fill_(False)
|
| 627 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 628 |
+
|
| 629 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 630 |
+
prompt_embeds = torch.stack(
|
| 631 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 635 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 636 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 637 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 638 |
+
|
| 639 |
+
return prompt_embeds, text_inputs.attention_mask
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def encode_prompt(
|
| 643 |
+
tokenizer,
|
| 644 |
+
text_encoder,
|
| 645 |
+
prompt: Union[str, List[str]],
|
| 646 |
+
num_videos_per_prompt: int = 1,
|
| 647 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 648 |
+
max_sequence_length: int = 512,
|
| 649 |
+
caption_dropout_p: float = 0.0,
|
| 650 |
+
device: Optional[torch.device] = "cuda",
|
| 651 |
+
dtype: Optional[torch.dtype] = torch.bfloat16,
|
| 652 |
+
):
|
| 653 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 654 |
+
|
| 655 |
+
if prompt_embeds is None:
|
| 656 |
+
prompt_embeds, prompt_attention_mask = _get_t5_prompt_embeds(
|
| 657 |
+
tokenizer,
|
| 658 |
+
text_encoder,
|
| 659 |
+
prompt=prompt,
|
| 660 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 661 |
+
max_sequence_length=max_sequence_length,
|
| 662 |
+
caption_dropout_p=caption_dropout_p,
|
| 663 |
+
device=device,
|
| 664 |
+
dtype=dtype,
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
return prompt_embeds, prompt_attention_mask
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
# ======================================== other techniques ========================================
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
class AdaptiveAntiDrifting:
|
| 674 |
+
def __init__(
|
| 675 |
+
self,
|
| 676 |
+
rho_mu: float = 0.9,
|
| 677 |
+
rho_sigma: float = 0.9,
|
| 678 |
+
delta_mu: float = 0.15,
|
| 679 |
+
delta_sigma: float = 0.15,
|
| 680 |
+
device: torch.device = None,
|
| 681 |
+
dtype: torch.dtype = torch.float32,
|
| 682 |
+
):
|
| 683 |
+
"""
|
| 684 |
+
Args:
|
| 685 |
+
rho_mu: EMA coefficient for mean (momentum parameter)
|
| 686 |
+
rho_sigma: EMA coefficient for variance (momentum parameter)
|
| 687 |
+
delta_mu: Threshold for mean drift detection
|
| 688 |
+
delta_sigma: Threshold for variance drift detection
|
| 689 |
+
device: Device for tensor operations
|
| 690 |
+
dtype: Data type for tensors
|
| 691 |
+
"""
|
| 692 |
+
self.rho_mu = rho_mu
|
| 693 |
+
self.rho_sigma = rho_sigma
|
| 694 |
+
self.delta_mu = delta_mu
|
| 695 |
+
self.delta_sigma = delta_sigma
|
| 696 |
+
self.device = device
|
| 697 |
+
self.dtype = dtype
|
| 698 |
+
|
| 699 |
+
# Global statistics (initialized on first chunk)
|
| 700 |
+
self.global_mean = None
|
| 701 |
+
self.global_var = None
|
| 702 |
+
self.is_initialized = False
|
| 703 |
+
|
| 704 |
+
def compute_latent_statistics(self, latent_chunk: torch.Tensor) -> tuple:
|
| 705 |
+
# Shape: (B, C, T, H, W) -> (B, C)
|
| 706 |
+
mean = latent_chunk.mean(dim=[2, 3, 4])
|
| 707 |
+
var = latent_chunk.var(dim=[2, 3, 4])
|
| 708 |
+
|
| 709 |
+
return mean, var
|
| 710 |
+
|
| 711 |
+
def update_global_statistics(self, current_mean: torch.Tensor, current_var: torch.Tensor):
|
| 712 |
+
if not self.is_initialized:
|
| 713 |
+
self.global_mean = current_mean.clone()
|
| 714 |
+
self.global_var = current_var.clone()
|
| 715 |
+
self.is_initialized = True
|
| 716 |
+
else:
|
| 717 |
+
self.global_mean = self.rho_mu * self.global_mean + (1 - self.rho_mu) * current_mean
|
| 718 |
+
self.global_var = self.rho_sigma * self.global_var + (1 - self.rho_sigma) * current_var
|
| 719 |
+
|
| 720 |
+
def detect_drift(self, current_mean: torch.Tensor, current_var: torch.Tensor) -> bool:
|
| 721 |
+
if not self.is_initialized:
|
| 722 |
+
return False
|
| 723 |
+
|
| 724 |
+
mean_drift = torch.norm(current_mean - self.global_mean, p=2, dim=-1).mean().item()
|
| 725 |
+
var_drift = torch.norm(current_var - self.global_var, p=2, dim=-1).mean().item()
|
| 726 |
+
|
| 727 |
+
has_drift = (mean_drift > self.delta_mu) and (var_drift > self.delta_sigma)
|
| 728 |
+
|
| 729 |
+
return has_drift
|
| 730 |
+
|
| 731 |
+
def apply_frame_aware_corruption(
|
| 732 |
+
self,
|
| 733 |
+
history_latents: torch.Tensor,
|
| 734 |
+
corruption_strength: float = 0.1,
|
| 735 |
+
generator: Optional[torch.Generator] = None,
|
| 736 |
+
) -> torch.Tensor:
|
| 737 |
+
noise = torch.randn_like(history_latents, generator=generator, device=history_latents.device)
|
| 738 |
+
corrupted_latents = history_latents + corruption_strength * noise
|
| 739 |
+
|
| 740 |
+
return corrupted_latents
|
| 741 |
+
|
| 742 |
+
def reset(self):
|
| 743 |
+
self.global_mean = None
|
| 744 |
+
self.global_var = None
|
| 745 |
+
self.is_initialized = False
|
Helios/_DEV/helios/utils/utils_helios_base.py
ADDED
|
@@ -0,0 +1,1091 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from accelerate.logging import get_logger
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
|
| 8 |
+
from diffusers.training_utils import compute_density_for_timestep_sampling, compute_loss_weighting_for_sd3, free_memory
|
| 9 |
+
|
| 10 |
+
from .utils_base import apply_schedule_shift, get_config_value
|
| 11 |
+
from .utils_recycle_batch import apply_error_injection, process_and_update_error_buffers
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
logger = get_logger(__name__)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# ======================================== flow loss ========================================
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _flow_loss(
|
| 21 |
+
args,
|
| 22 |
+
accelerator,
|
| 23 |
+
lr_scheduler,
|
| 24 |
+
transformer,
|
| 25 |
+
prompt_embeds,
|
| 26 |
+
prompt_attention_masks,
|
| 27 |
+
noisy_model_input_list,
|
| 28 |
+
sigmas_list,
|
| 29 |
+
timesteps_list,
|
| 30 |
+
targets_list,
|
| 31 |
+
indices_hidden_states,
|
| 32 |
+
latents_history_short,
|
| 33 |
+
indices_latents_history_short,
|
| 34 |
+
latents_history_mid,
|
| 35 |
+
indices_latents_history_mid,
|
| 36 |
+
latents_history_long,
|
| 37 |
+
indices_latents_history_long,
|
| 38 |
+
recycle_vars,
|
| 39 |
+
global_step,
|
| 40 |
+
noise_scheduler_copy,
|
| 41 |
+
use_clean_input,
|
| 42 |
+
):
|
| 43 |
+
assert len(noisy_model_input_list) == len(sigmas_list) == len(timesteps_list) == len(targets_list)
|
| 44 |
+
|
| 45 |
+
for noisy_model_input, sigmas, timesteps, target in zip(
|
| 46 |
+
noisy_model_input_list, sigmas_list, timesteps_list, targets_list
|
| 47 |
+
):
|
| 48 |
+
# ----- w/o mini batch ------
|
| 49 |
+
model_pred = transformer(
|
| 50 |
+
hidden_states=noisy_model_input,
|
| 51 |
+
timestep=timesteps,
|
| 52 |
+
encoder_hidden_states=prompt_embeds,
|
| 53 |
+
indices_hidden_states=indices_hidden_states, # torch.Size([2, 9])
|
| 54 |
+
indices_latents_history_short=indices_latents_history_short, # torch.Size([2, 2])
|
| 55 |
+
indices_latents_history_mid=indices_latents_history_mid, # torch.Size([2, 2])
|
| 56 |
+
indices_latents_history_long=indices_latents_history_long, # torch.Size([2, 16])
|
| 57 |
+
latents_history_short=latents_history_short, # torch.Size([2, 16, 2, 60, 104])
|
| 58 |
+
latents_history_mid=latents_history_mid, # torch.Size([2, 16, 2, 60, 104])
|
| 59 |
+
latents_history_long=latents_history_long, # torch.Size([2, 16, 16, 60, 104])
|
| 60 |
+
return_dict=False,
|
| 61 |
+
)[0]
|
| 62 |
+
|
| 63 |
+
# Compute regular loss.
|
| 64 |
+
if isinstance(model_pred, list):
|
| 65 |
+
loss_list = []
|
| 66 |
+
for cur_model_pred, cur_target, cur_sigmas in zip(model_pred, target, sigmas):
|
| 67 |
+
cur_weighting = compute_loss_weighting_for_sd3(
|
| 68 |
+
weighting_scheme=args.training_config.weighting_scheme, sigmas=cur_sigmas
|
| 69 |
+
)
|
| 70 |
+
loss = torch.mean(
|
| 71 |
+
(cur_weighting.float() * (cur_model_pred.float() - cur_target.float()) ** 2).reshape(
|
| 72 |
+
cur_target.shape[0], -1
|
| 73 |
+
),
|
| 74 |
+
1,
|
| 75 |
+
).mean()
|
| 76 |
+
loss_list.append(loss)
|
| 77 |
+
loss = torch.stack(loss_list, dim=0).mean()
|
| 78 |
+
del loss_list
|
| 79 |
+
else:
|
| 80 |
+
# these weighting schemes use a uniform timestep sampling
|
| 81 |
+
# and instead post-weight the loss
|
| 82 |
+
weighting = compute_loss_weighting_for_sd3(
|
| 83 |
+
weighting_scheme=args.training_config.weighting_scheme, sigmas=sigmas
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
loss = torch.mean(
|
| 87 |
+
(weighting.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1),
|
| 88 |
+
1,
|
| 89 |
+
).mean()
|
| 90 |
+
|
| 91 |
+
# loss = loss * (batch_size / total_sample_count)
|
| 92 |
+
assert loss.requires_grad, f"Loss should have gradient! Got {loss.requires_grad}"
|
| 93 |
+
assert loss.grad_fn is not None, "Loss should have grad_fn!"
|
| 94 |
+
accelerator.backward(loss)
|
| 95 |
+
|
| 96 |
+
if args.training_config.use_error_recycling:
|
| 97 |
+
if isinstance(model_pred, list):
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
for cur_model_pred, cur_target, cur_timesteps, cur_noisy_model_input in zip(
|
| 100 |
+
model_pred, target, timesteps, noisy_model_input
|
| 101 |
+
):
|
| 102 |
+
process_and_update_error_buffers(
|
| 103 |
+
args,
|
| 104 |
+
recycle_vars,
|
| 105 |
+
accelerator,
|
| 106 |
+
global_step,
|
| 107 |
+
noise_scheduler_copy,
|
| 108 |
+
cur_model_pred,
|
| 109 |
+
cur_target,
|
| 110 |
+
cur_timesteps,
|
| 111 |
+
cur_noisy_model_input,
|
| 112 |
+
use_clean_input,
|
| 113 |
+
)
|
| 114 |
+
else:
|
| 115 |
+
with torch.no_grad():
|
| 116 |
+
process_and_update_error_buffers(
|
| 117 |
+
args,
|
| 118 |
+
recycle_vars,
|
| 119 |
+
accelerator,
|
| 120 |
+
global_step,
|
| 121 |
+
noise_scheduler_copy,
|
| 122 |
+
model_pred,
|
| 123 |
+
target,
|
| 124 |
+
timesteps,
|
| 125 |
+
noisy_model_input,
|
| 126 |
+
use_clean_input,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Check if the gradient of each model parameter contains NaN
|
| 130 |
+
for name, param in transformer.named_parameters():
|
| 131 |
+
if param.grad is not None and torch.isnan(param.grad).any():
|
| 132 |
+
logger.error(f"Gradient for {name} contains NaN!")
|
| 133 |
+
|
| 134 |
+
grad_norm = None
|
| 135 |
+
if accelerator.sync_gradients:
|
| 136 |
+
params_to_clip = transformer.parameters()
|
| 137 |
+
grad_norm = accelerator.clip_grad_norm_(params_to_clip, args.training_config.max_grad_norm)
|
| 138 |
+
|
| 139 |
+
logs = {
|
| 140 |
+
"loss": loss.detach().item(),
|
| 141 |
+
"lr": lr_scheduler.get_last_lr()[0],
|
| 142 |
+
}
|
| 143 |
+
if grad_norm is not None:
|
| 144 |
+
logs["grad_norm"] = grad_norm.item() if hasattr(grad_norm, "item") else grad_norm
|
| 145 |
+
|
| 146 |
+
del noisy_model_input_list
|
| 147 |
+
del sigmas_list
|
| 148 |
+
del timesteps_list
|
| 149 |
+
del targets_list
|
| 150 |
+
del noisy_model_input
|
| 151 |
+
del timesteps
|
| 152 |
+
del prompt_embeds
|
| 153 |
+
del prompt_attention_masks
|
| 154 |
+
del indices_hidden_states
|
| 155 |
+
del latents_history_short
|
| 156 |
+
del indices_latents_history_short
|
| 157 |
+
del latents_history_mid
|
| 158 |
+
del indices_latents_history_mid
|
| 159 |
+
del latents_history_long
|
| 160 |
+
del indices_latents_history_long
|
| 161 |
+
del model_pred
|
| 162 |
+
del target
|
| 163 |
+
del loss
|
| 164 |
+
free_memory()
|
| 165 |
+
|
| 166 |
+
return logs
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# ======================================== easy anti-drifting ========================================
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def downsample_corrupt(model_input, downsample_min_corrupt_ratio, downsample_max_corrupt_ratio):
|
| 173 |
+
corrupt_ratio = random.uniform(downsample_min_corrupt_ratio, downsample_max_corrupt_ratio)
|
| 174 |
+
|
| 175 |
+
is_5d = model_input.ndim == 5
|
| 176 |
+
|
| 177 |
+
if is_5d:
|
| 178 |
+
B, C, T, H, W = model_input.shape
|
| 179 |
+
model_input = model_input.permute(0, 2, 1, 3, 4).reshape(B * T, C, H, W)
|
| 180 |
+
else:
|
| 181 |
+
B, C, H, W = model_input.shape
|
| 182 |
+
|
| 183 |
+
h0, w0 = model_input.shape[-2:]
|
| 184 |
+
|
| 185 |
+
h1 = max(1, int(round(h0 * corrupt_ratio)))
|
| 186 |
+
w1 = max(1, int(round(w0 * corrupt_ratio)))
|
| 187 |
+
|
| 188 |
+
model_input = F.interpolate(model_input, size=(h1, w1), mode="bilinear", align_corners=False, antialias=True)
|
| 189 |
+
|
| 190 |
+
model_input = F.interpolate(model_input, size=(h0, w0), mode="bilinear", align_corners=False, antialias=True)
|
| 191 |
+
|
| 192 |
+
if is_5d:
|
| 193 |
+
model_input = model_input.reshape(B, T, C, H, W).permute(0, 2, 1, 3, 4)
|
| 194 |
+
|
| 195 |
+
return model_input
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def get_corrupt_noise_sigma(model_input, batch_size, corrupt_ratio=1 / 3, num_frames=None, is_frame_independent=False):
|
| 199 |
+
if is_frame_independent:
|
| 200 |
+
noise_sigma_shape = (batch_size, 1, num_frames)
|
| 201 |
+
else:
|
| 202 |
+
noise_sigma_shape = (batch_size,)
|
| 203 |
+
noise_sigma = (
|
| 204 |
+
torch.rand(size=noise_sigma_shape, device=model_input.device, dtype=model_input.dtype) * corrupt_ratio
|
| 205 |
+
)
|
| 206 |
+
while len(noise_sigma.shape) < model_input.ndim:
|
| 207 |
+
noise_sigma = noise_sigma.unsqueeze(-1)
|
| 208 |
+
return noise_sigma
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def corrupt_model_input(
|
| 212 |
+
model_input,
|
| 213 |
+
# choose mode
|
| 214 |
+
corrupt_mode="noise", # "noise" | "downsample" | "random"
|
| 215 |
+
noise_mode_prob=0.9, # when corrupt_mode="random", select the probability of noise (select downsample for the remaining probability).
|
| 216 |
+
# for noise
|
| 217 |
+
is_frame_independent=False,
|
| 218 |
+
is_chunk_independent=False,
|
| 219 |
+
noise_corrupt_ratio=1 / 3,
|
| 220 |
+
noise_corrupt_clean_prob=0.1,
|
| 221 |
+
# for downsample
|
| 222 |
+
downsample_min_corrupt_ratio=0.9,
|
| 223 |
+
downsample_max_corrupt_ratio=1.0,
|
| 224 |
+
):
|
| 225 |
+
assert not (is_frame_independent and is_chunk_independent), (
|
| 226 |
+
"is_frame_independent and is_chunk_independent cannot both be True"
|
| 227 |
+
)
|
| 228 |
+
assert corrupt_mode in ("noise", "downsample", "random"), (
|
| 229 |
+
f"corrupt_mode must be 'noise', 'downsample', or 'random', got '{corrupt_mode}'"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
# ==================== choose mode ====================
|
| 233 |
+
if corrupt_mode == "random":
|
| 234 |
+
mode = "noise" if random.random() < noise_mode_prob else "downsample"
|
| 235 |
+
else:
|
| 236 |
+
mode = corrupt_mode
|
| 237 |
+
|
| 238 |
+
# ==================== downsample branch ====================
|
| 239 |
+
if mode == "downsample":
|
| 240 |
+
model_input = downsample_corrupt(
|
| 241 |
+
model_input=model_input,
|
| 242 |
+
downsample_min_corrupt_ratio=downsample_min_corrupt_ratio,
|
| 243 |
+
downsample_max_corrupt_ratio=downsample_max_corrupt_ratio,
|
| 244 |
+
)
|
| 245 |
+
return model_input
|
| 246 |
+
|
| 247 |
+
# ==================== noise branch ====================
|
| 248 |
+
clean_random = random.random()
|
| 249 |
+
if clean_random < noise_corrupt_clean_prob:
|
| 250 |
+
return model_input
|
| 251 |
+
|
| 252 |
+
noise_sigma = get_corrupt_noise_sigma(
|
| 253 |
+
model_input=model_input,
|
| 254 |
+
batch_size=model_input.shape[0],
|
| 255 |
+
corrupt_ratio=noise_corrupt_ratio,
|
| 256 |
+
num_frames=model_input.shape[2],
|
| 257 |
+
is_frame_independent=is_frame_independent,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
model_input = noise_sigma * torch.randn_like(model_input) + (1 - noise_sigma) * model_input
|
| 261 |
+
|
| 262 |
+
return model_input
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def corrupt_history_latents(
|
| 266 |
+
latents_history_short,
|
| 267 |
+
latents_history_mid,
|
| 268 |
+
latents_history_long,
|
| 269 |
+
latent_window_size,
|
| 270 |
+
is_keep_x0=True,
|
| 271 |
+
# choose mode
|
| 272 |
+
corrupt_mode="noise", # "noise" | "downsample" | "random"
|
| 273 |
+
noise_mode_prob=0.9, # when corrupt_mode="random", select the probability of noise (select downsample for the remaining probability).
|
| 274 |
+
# for noise
|
| 275 |
+
is_frame_independent=False,
|
| 276 |
+
is_chunk_independent=False,
|
| 277 |
+
corrupt_ratio_1x=1 / 3,
|
| 278 |
+
corrupt_ratio_2x=1 / 3,
|
| 279 |
+
corrupt_ratio_4x=1 / 3,
|
| 280 |
+
noise_corrupt_clean_prob=0.1,
|
| 281 |
+
# for downsample
|
| 282 |
+
downsample_min_corrupt_ratio=0.9,
|
| 283 |
+
downsample_max_corrupt_ratio=1.0,
|
| 284 |
+
):
|
| 285 |
+
assert not (is_frame_independent and is_chunk_independent), (
|
| 286 |
+
"is_frame_independent and is_chunk_independent cannot both be True"
|
| 287 |
+
)
|
| 288 |
+
assert corrupt_mode in ("noise", "downsample", "random"), (
|
| 289 |
+
f"corrupt_mode must be 'noise', 'downsample', or 'random', got '{corrupt_mode}'"
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
clean_random = random.random()
|
| 293 |
+
if clean_random < noise_corrupt_clean_prob:
|
| 294 |
+
return latents_history_short, latents_history_mid, latents_history_long
|
| 295 |
+
|
| 296 |
+
# ==================== choose mode ====================
|
| 297 |
+
if corrupt_mode == "random":
|
| 298 |
+
mode = "noise" if random.random() < noise_mode_prob else "downsample"
|
| 299 |
+
else:
|
| 300 |
+
mode = corrupt_mode
|
| 301 |
+
|
| 302 |
+
# ==================== noise branch ====================
|
| 303 |
+
if mode == "noise":
|
| 304 |
+
batch_size = latents_history_short.shape[0]
|
| 305 |
+
if not is_frame_independent and not is_chunk_independent:
|
| 306 |
+
noise_sigma = get_corrupt_noise_sigma(
|
| 307 |
+
model_input=latents_history_short, batch_size=batch_size, corrupt_ratio=corrupt_ratio_1x
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
len_4x = latents_history_long.shape[2]
|
| 311 |
+
len_2x = latents_history_mid.shape[2]
|
| 312 |
+
len_1x = latents_history_short.shape[2]
|
| 313 |
+
|
| 314 |
+
hist_seq_len = len_4x + len_2x + len_1x
|
| 315 |
+
hist_seq_len_copy = hist_seq_len
|
| 316 |
+
|
| 317 |
+
ori_len_1x = len_1x
|
| 318 |
+
if is_keep_x0:
|
| 319 |
+
len_1x -= 1
|
| 320 |
+
hist_seq_len -= 1
|
| 321 |
+
begin_num = 1
|
| 322 |
+
else:
|
| 323 |
+
begin_num = 0
|
| 324 |
+
|
| 325 |
+
max_windows = hist_seq_len // latent_window_size
|
| 326 |
+
tail_num = hist_seq_len % latent_window_size
|
| 327 |
+
|
| 328 |
+
assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num
|
| 329 |
+
|
| 330 |
+
tail_latents_history = None
|
| 331 |
+
begin_latents_history = None
|
| 332 |
+
|
| 333 |
+
if tail_num != 0:
|
| 334 |
+
tail_latents_history = latents_history_long[:, :, :tail_num, :, :]
|
| 335 |
+
latents_history_long = latents_history_long[:, :, tail_num:, :, :]
|
| 336 |
+
if tail_latents_history.sum() != 0:
|
| 337 |
+
if mode == "downsample":
|
| 338 |
+
tail_latents_history = downsample_corrupt(
|
| 339 |
+
model_input=tail_latents_history,
|
| 340 |
+
downsample_min_corrupt_ratio=downsample_min_corrupt_ratio,
|
| 341 |
+
downsample_max_corrupt_ratio=downsample_max_corrupt_ratio,
|
| 342 |
+
)
|
| 343 |
+
else:
|
| 344 |
+
noise_sigma = get_corrupt_noise_sigma(
|
| 345 |
+
model_input=latents_history_short,
|
| 346 |
+
batch_size=batch_size,
|
| 347 |
+
corrupt_ratio=corrupt_ratio_4x,
|
| 348 |
+
num_frames=tail_latents_history.shape[2],
|
| 349 |
+
is_frame_independent=is_frame_independent,
|
| 350 |
+
)
|
| 351 |
+
tail_latents_history = (
|
| 352 |
+
noise_sigma * torch.randn_like(tail_latents_history) + (1 - noise_sigma) * tail_latents_history
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
if begin_num != 0:
|
| 356 |
+
begin_latents_history = latents_history_short[:, :, :begin_num, :, :]
|
| 357 |
+
latents_history_short = latents_history_short[:, :, begin_num:, :, :]
|
| 358 |
+
if begin_latents_history.sum() != 0:
|
| 359 |
+
if mode == "downsample":
|
| 360 |
+
begin_latents_history = downsample_corrupt(
|
| 361 |
+
model_input=begin_latents_history,
|
| 362 |
+
downsample_min_corrupt_ratio=downsample_min_corrupt_ratio,
|
| 363 |
+
downsample_max_corrupt_ratio=downsample_max_corrupt_ratio,
|
| 364 |
+
)
|
| 365 |
+
else:
|
| 366 |
+
noise_sigma = get_corrupt_noise_sigma(
|
| 367 |
+
model_input=latents_history_short,
|
| 368 |
+
batch_size=batch_size,
|
| 369 |
+
corrupt_ratio=corrupt_ratio_1x,
|
| 370 |
+
num_frames=begin_latents_history.shape[2],
|
| 371 |
+
is_frame_independent=is_frame_independent,
|
| 372 |
+
)
|
| 373 |
+
begin_latents_history = (
|
| 374 |
+
noise_sigma * torch.randn_like(begin_latents_history) + (1 - noise_sigma) * begin_latents_history
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
mid_latents_history = torch.cat([latents_history_long, latents_history_mid, latents_history_short], dim=2)
|
| 378 |
+
window_num = mid_latents_history.shape[2] // latent_window_size
|
| 379 |
+
assert mid_latents_history.shape[2] % latent_window_size == 0, (
|
| 380 |
+
f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}"
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
seq_begin = 0
|
| 384 |
+
for idx in range(window_num):
|
| 385 |
+
seq_end = seq_begin + latent_window_size
|
| 386 |
+
if mid_latents_history[:, :, seq_begin:seq_end, :, :].sum() != 0:
|
| 387 |
+
if idx == window_num - 1:
|
| 388 |
+
len_2x_end = seq_begin + len_2x
|
| 389 |
+
if mode == "downsample":
|
| 390 |
+
mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = downsample_corrupt(
|
| 391 |
+
model_input=mid_latents_history[:, :, seq_begin:len_2x_end, :, :],
|
| 392 |
+
downsample_min_corrupt_ratio=downsample_min_corrupt_ratio,
|
| 393 |
+
downsample_max_corrupt_ratio=downsample_max_corrupt_ratio,
|
| 394 |
+
)
|
| 395 |
+
else:
|
| 396 |
+
noise_sigma_4x = get_corrupt_noise_sigma(
|
| 397 |
+
model_input=latents_history_short,
|
| 398 |
+
batch_size=batch_size,
|
| 399 |
+
corrupt_ratio=corrupt_ratio_4x,
|
| 400 |
+
num_frames=len_2x,
|
| 401 |
+
is_frame_independent=is_frame_independent,
|
| 402 |
+
)
|
| 403 |
+
mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = (
|
| 404 |
+
noise_sigma_4x * torch.randn_like(mid_latents_history[:, :, seq_begin:len_2x_end, :, :])
|
| 405 |
+
+ (1 - noise_sigma_4x) * mid_latents_history[:, :, seq_begin:len_2x_end, :, :]
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
remaining_frames = seq_end - len_2x_end
|
| 409 |
+
if mode == "downsample":
|
| 410 |
+
mid_latents_history[:, :, len_2x_end:seq_end, :, :] = downsample_corrupt(
|
| 411 |
+
model_input=mid_latents_history[:, :, len_2x_end:seq_end, :, :],
|
| 412 |
+
downsample_min_corrupt_ratio=downsample_min_corrupt_ratio,
|
| 413 |
+
downsample_max_corrupt_ratio=downsample_max_corrupt_ratio,
|
| 414 |
+
)
|
| 415 |
+
else:
|
| 416 |
+
noise_sigma_2x = get_corrupt_noise_sigma(
|
| 417 |
+
model_input=latents_history_short,
|
| 418 |
+
batch_size=batch_size,
|
| 419 |
+
corrupt_ratio=corrupt_ratio_2x,
|
| 420 |
+
num_frames=remaining_frames,
|
| 421 |
+
is_frame_independent=is_frame_independent,
|
| 422 |
+
)
|
| 423 |
+
mid_latents_history[:, :, len_2x_end:seq_end, :, :] = (
|
| 424 |
+
noise_sigma_2x * torch.randn_like(mid_latents_history[:, :, len_2x_end:seq_end, :, :])
|
| 425 |
+
+ (1 - noise_sigma_2x) * mid_latents_history[:, :, len_2x_end:seq_end, :, :]
|
| 426 |
+
)
|
| 427 |
+
else:
|
| 428 |
+
if mode == "downsample":
|
| 429 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :] = downsample_corrupt(
|
| 430 |
+
model_input=mid_latents_history[:, :, seq_begin:seq_end, :, :],
|
| 431 |
+
downsample_min_corrupt_ratio=downsample_min_corrupt_ratio,
|
| 432 |
+
downsample_max_corrupt_ratio=downsample_max_corrupt_ratio,
|
| 433 |
+
)
|
| 434 |
+
else:
|
| 435 |
+
noise_sigma = get_corrupt_noise_sigma(
|
| 436 |
+
model_input=latents_history_short,
|
| 437 |
+
batch_size=batch_size,
|
| 438 |
+
corrupt_ratio=corrupt_ratio_4x,
|
| 439 |
+
num_frames=latent_window_size,
|
| 440 |
+
is_frame_independent=is_frame_independent,
|
| 441 |
+
)
|
| 442 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :] = (
|
| 443 |
+
noise_sigma * torch.randn_like(mid_latents_history[:, :, seq_begin:seq_end, :, :])
|
| 444 |
+
+ (1 - noise_sigma) * mid_latents_history[:, :, seq_begin:seq_end, :, :]
|
| 445 |
+
)
|
| 446 |
+
seq_begin = seq_end
|
| 447 |
+
|
| 448 |
+
recovers = []
|
| 449 |
+
if tail_latents_history is not None:
|
| 450 |
+
recovers.append(tail_latents_history)
|
| 451 |
+
recovers.append(mid_latents_history[:, :, :-len_1x, :, :])
|
| 452 |
+
if begin_latents_history is not None:
|
| 453 |
+
recovers.append(begin_latents_history)
|
| 454 |
+
recovers.append(mid_latents_history[:, :, -len_1x:, :, :])
|
| 455 |
+
mid_latents_history = torch.cat(recovers, dim=2)
|
| 456 |
+
|
| 457 |
+
# Split and update back to original tensors
|
| 458 |
+
latents_4x_recovered, latents_2x_recovered, latents_history_short_recovered = mid_latents_history.split(
|
| 459 |
+
[len_4x, len_2x, ori_len_1x], dim=2
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
return (
|
| 463 |
+
latents_history_short_recovered,
|
| 464 |
+
latents_2x_recovered,
|
| 465 |
+
latents_4x_recovered,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def add_saturation_to_history_latents(
|
| 470 |
+
latents_history_short,
|
| 471 |
+
latents_history_mid,
|
| 472 |
+
latents_history_long,
|
| 473 |
+
latent_window_size,
|
| 474 |
+
is_keep_x0=False,
|
| 475 |
+
saturation_ratio_min=0.7,
|
| 476 |
+
saturation_ratio_max=2.0,
|
| 477 |
+
saturation_clean_prob=0.2,
|
| 478 |
+
):
|
| 479 |
+
# clean_random = random.random()
|
| 480 |
+
# if clean_random < saturation_clean_prob:
|
| 481 |
+
# return latents_history_short, latents_history_mid, latents_history_long
|
| 482 |
+
|
| 483 |
+
def get_saturation(x1, saturation_ratio_min, saturation_ratio_max):
|
| 484 |
+
if random.random() < 0.5:
|
| 485 |
+
sat_factor = random.uniform(saturation_ratio_min, 1.0 - 1e-3)
|
| 486 |
+
else:
|
| 487 |
+
sat_factor = random.uniform(1.0 + 1e-3, saturation_ratio_max)
|
| 488 |
+
latent_mean = torch.mean(x1, dim=1, keepdim=True)
|
| 489 |
+
x1_saturated = (x1 - latent_mean) * sat_factor + latent_mean
|
| 490 |
+
return x1_saturated
|
| 491 |
+
|
| 492 |
+
len_4x = latents_history_long.shape[2]
|
| 493 |
+
len_2x = latents_history_mid.shape[2]
|
| 494 |
+
len_1x = latents_history_short.shape[2]
|
| 495 |
+
|
| 496 |
+
hist_seq_len = len_4x + len_2x + len_1x
|
| 497 |
+
hist_seq_len_copy = hist_seq_len
|
| 498 |
+
|
| 499 |
+
ori_len_1x = len_1x
|
| 500 |
+
if is_keep_x0:
|
| 501 |
+
len_1x -= 1
|
| 502 |
+
hist_seq_len -= 1
|
| 503 |
+
begin_num = 1
|
| 504 |
+
else:
|
| 505 |
+
begin_num = 0
|
| 506 |
+
|
| 507 |
+
max_windows = hist_seq_len // latent_window_size
|
| 508 |
+
tail_num = hist_seq_len % latent_window_size
|
| 509 |
+
|
| 510 |
+
assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num
|
| 511 |
+
|
| 512 |
+
tail_latents_history = None
|
| 513 |
+
begin_latents_history = None
|
| 514 |
+
|
| 515 |
+
if tail_num != 0:
|
| 516 |
+
tail_latents_history = latents_history_long[:, :, :tail_num, :, :]
|
| 517 |
+
latents_history_long = latents_history_long[:, :, tail_num:, :, :]
|
| 518 |
+
if tail_latents_history.sum() != 0:
|
| 519 |
+
if random.random() < saturation_clean_prob:
|
| 520 |
+
tail_latents_history = tail_latents_history
|
| 521 |
+
else:
|
| 522 |
+
tail_latents_history = get_saturation(
|
| 523 |
+
tail_latents_history,
|
| 524 |
+
saturation_ratio_min=saturation_ratio_min,
|
| 525 |
+
saturation_ratio_max=saturation_ratio_max,
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
if begin_num != 0:
|
| 529 |
+
begin_latents_history = latents_history_short[:, :, :begin_num, :, :]
|
| 530 |
+
latents_history_short = latents_history_short[:, :, begin_num:, :, :]
|
| 531 |
+
# if begin_latents_history.sum() != 0:
|
| 532 |
+
# begin_latents_history = get_saturation(
|
| 533 |
+
# begin_latents_history,
|
| 534 |
+
# saturation_ratio_min=saturation_ratio_min,
|
| 535 |
+
# saturation_ratio_max=saturation_ratio_max,
|
| 536 |
+
# )
|
| 537 |
+
|
| 538 |
+
mid_latents_history = torch.cat([latents_history_long, latents_history_mid, latents_history_short], dim=2)
|
| 539 |
+
window_num = mid_latents_history.shape[2] // latent_window_size
|
| 540 |
+
assert mid_latents_history.shape[2] % latent_window_size == 0, (
|
| 541 |
+
f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
seq_begin = 0
|
| 545 |
+
for idx in range(window_num):
|
| 546 |
+
seq_end = seq_begin + latent_window_size
|
| 547 |
+
if mid_latents_history[:, :, seq_begin:seq_end, :, :].sum() != 0:
|
| 548 |
+
if idx == window_num - 1:
|
| 549 |
+
len_2x_end = seq_begin + len_2x
|
| 550 |
+
if random.random() < saturation_clean_prob:
|
| 551 |
+
mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = mid_latents_history[
|
| 552 |
+
:, :, seq_begin:len_2x_end, :, :
|
| 553 |
+
]
|
| 554 |
+
else:
|
| 555 |
+
mid_latents_history[:, :, seq_begin:len_2x_end, :, :] = get_saturation(
|
| 556 |
+
mid_latents_history[:, :, seq_begin:len_2x_end, :, :],
|
| 557 |
+
saturation_ratio_min=saturation_ratio_min,
|
| 558 |
+
saturation_ratio_max=saturation_ratio_max,
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
if random.random() < saturation_clean_prob:
|
| 562 |
+
mid_latents_history[:, :, len_2x_end:seq_end, :, :] = mid_latents_history[
|
| 563 |
+
:, :, len_2x_end:seq_end, :, :
|
| 564 |
+
]
|
| 565 |
+
else:
|
| 566 |
+
mid_latents_history[:, :, len_2x_end:seq_end, :, :] = get_saturation(
|
| 567 |
+
mid_latents_history[:, :, len_2x_end:seq_end, :, :],
|
| 568 |
+
saturation_ratio_min=saturation_ratio_min,
|
| 569 |
+
saturation_ratio_max=saturation_ratio_max,
|
| 570 |
+
)
|
| 571 |
+
else:
|
| 572 |
+
if random.random() < saturation_clean_prob:
|
| 573 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :] = mid_latents_history[
|
| 574 |
+
:, :, seq_begin:seq_end, :, :
|
| 575 |
+
]
|
| 576 |
+
else:
|
| 577 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :] = get_saturation(
|
| 578 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :],
|
| 579 |
+
saturation_ratio_min=saturation_ratio_min,
|
| 580 |
+
saturation_ratio_max=saturation_ratio_max,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
seq_begin = seq_end
|
| 584 |
+
|
| 585 |
+
recovers = []
|
| 586 |
+
if tail_latents_history is not None:
|
| 587 |
+
recovers.append(tail_latents_history)
|
| 588 |
+
recovers.append(mid_latents_history[:, :, :-len_1x, :, :])
|
| 589 |
+
if begin_latents_history is not None:
|
| 590 |
+
recovers.append(begin_latents_history)
|
| 591 |
+
recovers.append(mid_latents_history[:, :, -len_1x:, :, :])
|
| 592 |
+
mid_latents_history = torch.cat(recovers, dim=2)
|
| 593 |
+
|
| 594 |
+
# Split and update back to original tensors
|
| 595 |
+
latents_4x_recovered, latents_2x_recovered, latents_history_short_recovered = mid_latents_history.split(
|
| 596 |
+
[len_4x, len_2x, ori_len_1x], dim=2
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
return (
|
| 600 |
+
latents_history_short_recovered,
|
| 601 |
+
latents_2x_recovered,
|
| 602 |
+
latents_4x_recovered,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
# ======================================== prepare stage1 training ========================================
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def prepare_stage1_clean_input_from_latents(
|
| 610 |
+
history_latents, # VAE latents, (B, C_latent, F_latent, H_latent, W_latent)
|
| 611 |
+
target_latents,
|
| 612 |
+
x0_latents=None,
|
| 613 |
+
latent_window_size: int = 9,
|
| 614 |
+
history_sizes: list = [16, 2, 1],
|
| 615 |
+
is_random_drop: bool = False,
|
| 616 |
+
random_drop_i2v_ratio: float = 0,
|
| 617 |
+
random_drop_v2v_ratio: float = 0,
|
| 618 |
+
random_drop_t2v_ratio: float = 0,
|
| 619 |
+
is_keep_x0: bool = True,
|
| 620 |
+
dtype=torch.bfloat16,
|
| 621 |
+
device="cpu",
|
| 622 |
+
):
|
| 623 |
+
if is_keep_x0:
|
| 624 |
+
latents_prefix = x0_latents.to(device, dtype=dtype)
|
| 625 |
+
else:
|
| 626 |
+
assert x0_latents is None
|
| 627 |
+
|
| 628 |
+
history_sizes = sorted(history_sizes, reverse=True) # From big to small
|
| 629 |
+
history_window_size = sum(history_sizes)
|
| 630 |
+
total_window_size = history_window_size + latent_window_size
|
| 631 |
+
assert total_window_size == history_latents.shape[2] + target_latents.shape[2], (
|
| 632 |
+
f"total_window_size mismatch: expected {total_window_size}"
|
| 633 |
+
f"(history={history_latents.shape[2]} + target={target_latents.shape[2]}), "
|
| 634 |
+
f"but got {history_latents.shape[2] + target_latents.shape[2]}"
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
indices = (
|
| 638 |
+
torch.arange(0, sum([1, *history_sizes, latent_window_size])).unsqueeze(0).expand(target_latents.shape[0], -1)
|
| 639 |
+
)
|
| 640 |
+
(
|
| 641 |
+
indices_prefix,
|
| 642 |
+
indices_latents_history_long,
|
| 643 |
+
indices_latents_history_mid,
|
| 644 |
+
indices_latents_history_1x,
|
| 645 |
+
indices_hidden_states,
|
| 646 |
+
) = indices.split([1, *history_sizes, latent_window_size], dim=1)
|
| 647 |
+
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=1)
|
| 648 |
+
|
| 649 |
+
latents_history_long, latents_history_mid, latents_history_1x = history_latents.split(history_sizes, dim=2)
|
| 650 |
+
|
| 651 |
+
if is_random_drop:
|
| 652 |
+
if random_drop_t2v_ratio != 0 and torch.rand(1).item() <= random_drop_t2v_ratio:
|
| 653 |
+
if is_keep_x0:
|
| 654 |
+
latents_prefix = torch.zeros_like(
|
| 655 |
+
latents_prefix, device=latents_history_1x.device, dtype=latents_history_1x.dtype
|
| 656 |
+
)
|
| 657 |
+
latents_history_1x = torch.zeros_like(
|
| 658 |
+
latents_history_1x,
|
| 659 |
+
device=latents_history_1x.device,
|
| 660 |
+
dtype=latents_history_1x.dtype,
|
| 661 |
+
)
|
| 662 |
+
latents_history_mid = torch.zeros_like(
|
| 663 |
+
latents_history_mid,
|
| 664 |
+
device=latents_history_1x.device,
|
| 665 |
+
dtype=latents_history_1x.dtype,
|
| 666 |
+
)
|
| 667 |
+
latents_history_long = torch.zeros_like(
|
| 668 |
+
latents_history_long,
|
| 669 |
+
device=latents_history_1x.device,
|
| 670 |
+
dtype=latents_history_1x.dtype,
|
| 671 |
+
)
|
| 672 |
+
else:
|
| 673 |
+
len_4x = latents_history_long.shape[2]
|
| 674 |
+
len_2x = latents_history_mid.shape[2]
|
| 675 |
+
len_1x = latents_history_1x.shape[2]
|
| 676 |
+
hist_seq_len = len_4x + len_2x + len_1x
|
| 677 |
+
|
| 678 |
+
total_drop = 0
|
| 679 |
+
is_drop_triggered = False
|
| 680 |
+
|
| 681 |
+
if random_drop_i2v_ratio != 0 and torch.rand(1).item() <= random_drop_i2v_ratio:
|
| 682 |
+
total_drop = max(0, hist_seq_len - 1)
|
| 683 |
+
is_drop_triggered = True
|
| 684 |
+
elif random_drop_v2v_ratio != 0 and torch.rand(1).item() <= random_drop_v2v_ratio:
|
| 685 |
+
max_windows = hist_seq_len // latent_window_size
|
| 686 |
+
tail_num = hist_seq_len % latent_window_size
|
| 687 |
+
total_drop = tail_num
|
| 688 |
+
if max_windows > 0:
|
| 689 |
+
drop_windows = random.randint(0, max_windows)
|
| 690 |
+
total_drop += drop_windows * latent_window_size
|
| 691 |
+
is_drop_triggered = True
|
| 692 |
+
|
| 693 |
+
if is_drop_triggered and total_drop > 0:
|
| 694 |
+
remaining_drop = total_drop
|
| 695 |
+
if remaining_drop > 0 and len_4x > 0:
|
| 696 |
+
drop_4x = min(remaining_drop, len_4x)
|
| 697 |
+
latents_history_long[:, :, :drop_4x, :, :] = 0
|
| 698 |
+
remaining_drop -= drop_4x
|
| 699 |
+
if remaining_drop > 0 and len_2x > 0:
|
| 700 |
+
drop_2x = min(remaining_drop, len_2x)
|
| 701 |
+
latents_history_mid[:, :, :drop_2x, :, :] = 0
|
| 702 |
+
remaining_drop -= drop_2x
|
| 703 |
+
if remaining_drop > 0 and len_1x > 0:
|
| 704 |
+
drop_1x = min(remaining_drop, len_1x)
|
| 705 |
+
latents_history_1x[:, :, :drop_1x, :, :] = 0
|
| 706 |
+
|
| 707 |
+
if is_keep_x0:
|
| 708 |
+
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
|
| 709 |
+
else:
|
| 710 |
+
latents_history_short = latents_history_1x
|
| 711 |
+
|
| 712 |
+
return (
|
| 713 |
+
target_latents,
|
| 714 |
+
indices_hidden_states,
|
| 715 |
+
indices_latents_history_short,
|
| 716 |
+
indices_latents_history_mid,
|
| 717 |
+
indices_latents_history_long,
|
| 718 |
+
latents_history_short,
|
| 719 |
+
latents_history_mid,
|
| 720 |
+
latents_history_long,
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def prepare_stage1_noise_input(
|
| 725 |
+
args,
|
| 726 |
+
model_input,
|
| 727 |
+
noise_scheduler,
|
| 728 |
+
recycle_vars=None,
|
| 729 |
+
latents_history_short=None,
|
| 730 |
+
latents_history_mid=None,
|
| 731 |
+
latents_history_long=None,
|
| 732 |
+
latent_window_size=9,
|
| 733 |
+
is_keep_x0=True,
|
| 734 |
+
return_list=True,
|
| 735 |
+
):
|
| 736 |
+
# Sample noise that we'll add to the latents
|
| 737 |
+
noise = torch.randn_like(model_input)
|
| 738 |
+
bsz = model_input.shape[0]
|
| 739 |
+
|
| 740 |
+
use_clean_input = False
|
| 741 |
+
noise_w_error = noise
|
| 742 |
+
model_input_w_error = model_input
|
| 743 |
+
|
| 744 |
+
# Sample a random timestep for each image
|
| 745 |
+
# for weighting schemes where we sample timesteps non-uniformly
|
| 746 |
+
u = compute_density_for_timestep_sampling(
|
| 747 |
+
weighting_scheme=args.training_config.weighting_scheme,
|
| 748 |
+
batch_size=bsz,
|
| 749 |
+
logit_mean=args.training_config.logit_mean,
|
| 750 |
+
logit_std=args.training_config.logit_std,
|
| 751 |
+
mode_scale=args.training_config.mode_scale,
|
| 752 |
+
)
|
| 753 |
+
indices = (u * noise_scheduler.config.num_train_timesteps).long()
|
| 754 |
+
|
| 755 |
+
noise_scheduler.temp_sigmas = noise_scheduler.sigmas
|
| 756 |
+
noise_scheduler.temp_timesteps = noise_scheduler.timesteps
|
| 757 |
+
if args.training_config.use_dynamic_shifting:
|
| 758 |
+
noise_scheduler.temp_sigmas = apply_schedule_shift(
|
| 759 |
+
noise_scheduler.sigmas,
|
| 760 |
+
noise,
|
| 761 |
+
base_seq_len=args.training_config.base_seq_len,
|
| 762 |
+
max_seq_len=args.training_config.max_seq_len,
|
| 763 |
+
base_shift=args.training_config.base_shift,
|
| 764 |
+
max_shift=args.training_config.max_shift,
|
| 765 |
+
) # torch.Size([2, 1, 1, 1, 1])
|
| 766 |
+
|
| 767 |
+
noise_scheduler.temp_timesteps = noise_scheduler.temp_sigmas * 1000.0 # rescale to [0, 1000.0)
|
| 768 |
+
while noise_scheduler.temp_timesteps.ndim > 1:
|
| 769 |
+
noise_scheduler.temp_timesteps = noise_scheduler.temp_timesteps.squeeze(-1)
|
| 770 |
+
|
| 771 |
+
timesteps = noise_scheduler.temp_timesteps[indices].to(
|
| 772 |
+
device=model_input.device, non_blocking=True
|
| 773 |
+
) # torch.Size([2]), torch.float32
|
| 774 |
+
|
| 775 |
+
# Add noise according to flow matching.
|
| 776 |
+
# zt = (1 - texp) * x + texp * z1
|
| 777 |
+
sigmas = noise_scheduler.temp_sigmas[indices].flatten()
|
| 778 |
+
while len(sigmas.shape) < model_input.ndim:
|
| 779 |
+
sigmas = sigmas.unsqueeze(-1)
|
| 780 |
+
|
| 781 |
+
sigmas = sigmas.to(model_input.device, dtype=model_input.dtype)
|
| 782 |
+
|
| 783 |
+
if args.training_config.use_error_recycling:
|
| 784 |
+
(
|
| 785 |
+
model_input_w_error,
|
| 786 |
+
noise_w_error,
|
| 787 |
+
latents_history_long,
|
| 788 |
+
latents_history_mid,
|
| 789 |
+
latents_history_short,
|
| 790 |
+
use_clean_input,
|
| 791 |
+
) = apply_error_injection(
|
| 792 |
+
args,
|
| 793 |
+
recycle_vars,
|
| 794 |
+
model_input,
|
| 795 |
+
noise,
|
| 796 |
+
timesteps,
|
| 797 |
+
latents_history_long,
|
| 798 |
+
latents_history_mid,
|
| 799 |
+
latents_history_short,
|
| 800 |
+
model_input_w_error,
|
| 801 |
+
noise_w_error,
|
| 802 |
+
is_keep_x0,
|
| 803 |
+
latent_window_size,
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
if args.training_config.corrupt_history and latents_history_short is not None:
|
| 807 |
+
latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents(
|
| 808 |
+
latents_history_short,
|
| 809 |
+
latents_history_mid,
|
| 810 |
+
latents_history_long,
|
| 811 |
+
latent_window_size,
|
| 812 |
+
is_keep_x0=True,
|
| 813 |
+
# choose mode
|
| 814 |
+
corrupt_mode=args.training_config.corrupt_mode_history,
|
| 815 |
+
noise_mode_prob=args.training_config.corrupt_mode_prob_history,
|
| 816 |
+
# for noise
|
| 817 |
+
is_frame_independent=args.training_config.is_frame_independent_corrupt_history,
|
| 818 |
+
is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history,
|
| 819 |
+
corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short,
|
| 820 |
+
corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid,
|
| 821 |
+
corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long,
|
| 822 |
+
noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history,
|
| 823 |
+
# for downsample
|
| 824 |
+
downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history,
|
| 825 |
+
downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
if args.training_config.corrupt_model_input:
|
| 829 |
+
model_input_w_error = corrupt_model_input(
|
| 830 |
+
model_input_w_error,
|
| 831 |
+
# choose mode
|
| 832 |
+
corrupt_mode=args.training_config.corrupt_mode_model_input,
|
| 833 |
+
noise_mode_prob=args.training_config.corrupt_mode_prob_model_input,
|
| 834 |
+
# for noise
|
| 835 |
+
is_frame_independent=args.training_config.is_frame_independent_corrupt_model_input,
|
| 836 |
+
is_chunk_independent=args.training_config.is_chunk_independent_corrupt_model_input,
|
| 837 |
+
noise_corrupt_ratio=args.training_config.noise_corrupt_ratio_model_input,
|
| 838 |
+
noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_model_input,
|
| 839 |
+
# for downsample
|
| 840 |
+
downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_model_input,
|
| 841 |
+
downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_model_input,
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
# Get flow-matching target
|
| 845 |
+
noisy_model_input = (1.0 - sigmas) * model_input_w_error + sigmas * noise_w_error
|
| 846 |
+
target = noise_w_error - model_input
|
| 847 |
+
|
| 848 |
+
noisy_model_input_list = [noisy_model_input] if return_list else noisy_model_input
|
| 849 |
+
sigmas_list = [sigmas] if return_list else sigmas
|
| 850 |
+
timesteps_list = [timesteps] if return_list else timesteps
|
| 851 |
+
targets_list = [target] if return_list else target
|
| 852 |
+
|
| 853 |
+
return (
|
| 854 |
+
noisy_model_input_list,
|
| 855 |
+
sigmas_list,
|
| 856 |
+
timesteps_list,
|
| 857 |
+
targets_list,
|
| 858 |
+
latents_history_short,
|
| 859 |
+
latents_history_mid,
|
| 860 |
+
latents_history_long,
|
| 861 |
+
use_clean_input,
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
# ======================================== prepare stage2 training ========================================
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
def prepare_stage2_clean_input(
|
| 869 |
+
args,
|
| 870 |
+
scheduler,
|
| 871 |
+
latents, # [b c t h w]
|
| 872 |
+
pyramid_stage_num=3,
|
| 873 |
+
stage2_sample_ratios=[1, 1, 1],
|
| 874 |
+
):
|
| 875 |
+
assert pyramid_stage_num == len(stage2_sample_ratios)
|
| 876 |
+
|
| 877 |
+
# Get clen pyramid latent list
|
| 878 |
+
pyramid_latent_list = []
|
| 879 |
+
pyramid_latent_list.append(latents)
|
| 880 |
+
num_frames, height, width = latents.shape[-3], latents.shape[-2], latents.shape[-1]
|
| 881 |
+
for _ in range(pyramid_stage_num - 1):
|
| 882 |
+
height //= 2
|
| 883 |
+
width //= 2
|
| 884 |
+
latents = rearrange(latents, "b c t h w -> (b t) c h w")
|
| 885 |
+
latents = torch.nn.functional.interpolate(latents, size=(height, width), mode="bilinear")
|
| 886 |
+
latents = rearrange(latents, "(b t) c h w -> b c t h w", t=num_frames)
|
| 887 |
+
pyramid_latent_list.append(latents)
|
| 888 |
+
pyramid_latent_list = list(reversed(pyramid_latent_list))
|
| 889 |
+
|
| 890 |
+
# Get pyramid noise list
|
| 891 |
+
noise = torch.randn_like(pyramid_latent_list[-1])
|
| 892 |
+
device = noise.device
|
| 893 |
+
dtype = pyramid_latent_list[-1].dtype
|
| 894 |
+
latent_frame_num = noise.shape[2]
|
| 895 |
+
input_video_num = noise.shape[0]
|
| 896 |
+
|
| 897 |
+
height, width = noise.shape[-2], noise.shape[-1]
|
| 898 |
+
noise_list = [noise]
|
| 899 |
+
cur_noise = noise
|
| 900 |
+
for i_s in range(pyramid_stage_num - 1):
|
| 901 |
+
height //= 2
|
| 902 |
+
width //= 2
|
| 903 |
+
cur_noise = rearrange(cur_noise, "b c t h w -> (b t) c h w")
|
| 904 |
+
cur_noise = F.interpolate(cur_noise, size=(height, width), mode="bilinear") * 2
|
| 905 |
+
cur_noise = rearrange(cur_noise, "(b t) c h w -> b c t h w", t=latent_frame_num)
|
| 906 |
+
noise_list.append(cur_noise)
|
| 907 |
+
noise_list = list(reversed(noise_list)) # make sure from low res to high res
|
| 908 |
+
|
| 909 |
+
# Get pyramid target list
|
| 910 |
+
# To calculate the batchsize
|
| 911 |
+
bsz = input_video_num
|
| 912 |
+
|
| 913 |
+
# from low resolution to high resolution
|
| 914 |
+
noisy_latents_list = []
|
| 915 |
+
sigmas_list = []
|
| 916 |
+
targets_list = []
|
| 917 |
+
timesteps_list = []
|
| 918 |
+
training_steps = scheduler.config.num_train_timesteps
|
| 919 |
+
for i_s, cur_sample_ratio in zip(range(pyramid_stage_num), stage2_sample_ratios):
|
| 920 |
+
clean_latent = pyramid_latent_list[i_s] # [bs, c, t, h, w]
|
| 921 |
+
last_clean_latent = None if i_s == 0 else pyramid_latent_list[i_s - 1]
|
| 922 |
+
start_sigma = scheduler.start_sigmas[i_s]
|
| 923 |
+
end_sigma = scheduler.end_sigmas[i_s]
|
| 924 |
+
|
| 925 |
+
if i_s == 0:
|
| 926 |
+
start_point = noise_list[i_s]
|
| 927 |
+
else:
|
| 928 |
+
# Get the upsampled latent
|
| 929 |
+
last_clean_latent = rearrange(last_clean_latent, "b c t h w -> (b t) c h w")
|
| 930 |
+
last_clean_latent = F.interpolate(
|
| 931 |
+
last_clean_latent,
|
| 932 |
+
size=(
|
| 933 |
+
last_clean_latent.shape[-2] * 2,
|
| 934 |
+
last_clean_latent.shape[-1] * 2,
|
| 935 |
+
),
|
| 936 |
+
mode="nearest",
|
| 937 |
+
)
|
| 938 |
+
last_clean_latent = rearrange(last_clean_latent, "(b t) c h w -> b c t h w", t=latent_frame_num)
|
| 939 |
+
start_point = start_sigma * noise_list[i_s] + (1 - start_sigma) * last_clean_latent
|
| 940 |
+
|
| 941 |
+
if i_s == pyramid_stage_num - 1:
|
| 942 |
+
end_point = clean_latent
|
| 943 |
+
else:
|
| 944 |
+
end_point = end_sigma * noise_list[i_s] + (1 - end_sigma) * clean_latent
|
| 945 |
+
|
| 946 |
+
for _ in range(cur_sample_ratio):
|
| 947 |
+
# Sample a random timestep for each image
|
| 948 |
+
# for weighting schemes where we sample timesteps non-uniformly
|
| 949 |
+
u = compute_density_for_timestep_sampling(
|
| 950 |
+
weighting_scheme=get_config_value(args, "weighting_scheme"),
|
| 951 |
+
batch_size=bsz,
|
| 952 |
+
logit_mean=get_config_value(args, "logit_mean"),
|
| 953 |
+
logit_std=get_config_value(args, "logit_std"),
|
| 954 |
+
mode_scale=get_config_value(args, "mode_scale"),
|
| 955 |
+
)
|
| 956 |
+
indices = (u * training_steps).long() # Totally 1000 training steps per stage
|
| 957 |
+
indices = indices.clamp(0, training_steps - 1)
|
| 958 |
+
timesteps = scheduler.timesteps_per_stage[i_s][indices].to(device=device)
|
| 959 |
+
|
| 960 |
+
# Add noise according to flow matching.
|
| 961 |
+
# zt = (1 - texp) * x + texp * z1
|
| 962 |
+
sigmas = scheduler.sigmas_per_stage[i_s][indices].to(device=device)
|
| 963 |
+
while len(sigmas.shape) < start_point.ndim:
|
| 964 |
+
sigmas = sigmas.unsqueeze(-1)
|
| 965 |
+
|
| 966 |
+
if get_config_value(args, "use_dynamic_shifting"):
|
| 967 |
+
temp_sigmas = apply_schedule_shift(
|
| 968 |
+
sigmas,
|
| 969 |
+
start_point,
|
| 970 |
+
base_seq_len=get_config_value(args, "base_seq_len"),
|
| 971 |
+
max_seq_len=get_config_value(args, "max_seq_len"),
|
| 972 |
+
base_shift=get_config_value(args, "base_shift"),
|
| 973 |
+
max_shift=get_config_value(args, "max_shift"),
|
| 974 |
+
) # torch.Size([2, 1, 1, 1, 1])
|
| 975 |
+
temp_timesteps = scheduler.timesteps_per_stage[i_s].min() + temp_sigmas * (
|
| 976 |
+
scheduler.timesteps_per_stage[i_s].max() - scheduler.timesteps_per_stage[i_s].min()
|
| 977 |
+
)
|
| 978 |
+
while temp_timesteps.ndim > 1:
|
| 979 |
+
temp_timesteps = temp_timesteps.squeeze(-1)
|
| 980 |
+
|
| 981 |
+
sigmas = temp_sigmas
|
| 982 |
+
timesteps = temp_timesteps
|
| 983 |
+
|
| 984 |
+
if args.training_config.corrupt_model_input:
|
| 985 |
+
end_point = corrupt_model_input(
|
| 986 |
+
end_point,
|
| 987 |
+
# choose mode
|
| 988 |
+
corrupt_mode=args.training_config.corrupt_mode_model_input,
|
| 989 |
+
noise_mode_prob=args.training_config.corrupt_mode_prob_model_input,
|
| 990 |
+
# for noise
|
| 991 |
+
is_frame_independent=args.training_config.is_frame_independent_corrupt_model_input,
|
| 992 |
+
is_chunk_independent=args.training_config.is_chunk_independent_corrupt_model_input,
|
| 993 |
+
noise_corrupt_ratio=args.training_config.noise_corrupt_ratio_model_input,
|
| 994 |
+
noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_model_input,
|
| 995 |
+
# for downsample
|
| 996 |
+
downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_model_input,
|
| 997 |
+
downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_model_input,
|
| 998 |
+
)
|
| 999 |
+
|
| 1000 |
+
noisy_latents = sigmas * start_point + (1 - sigmas) * end_point
|
| 1001 |
+
|
| 1002 |
+
# [stage1_latent, stage2_latent, ..., stagen_latent]
|
| 1003 |
+
noisy_latents_list.append(noisy_latents.to(dtype))
|
| 1004 |
+
sigmas_list.append(sigmas.to(dtype))
|
| 1005 |
+
timesteps_list.append(timesteps)
|
| 1006 |
+
targets_list.append(start_point - end_point) # The standard rectified flow matching objective
|
| 1007 |
+
|
| 1008 |
+
return noisy_latents_list, sigmas_list, timesteps_list, targets_list
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
def prepare_stage2_noise_input(
|
| 1012 |
+
args,
|
| 1013 |
+
scheduler,
|
| 1014 |
+
latents, # [b c t h w]
|
| 1015 |
+
pyramid_stage_num=3,
|
| 1016 |
+
stage2_sample_ratios=[1, 1, 1],
|
| 1017 |
+
latents_history_short=None,
|
| 1018 |
+
latents_history_mid=None,
|
| 1019 |
+
latents_history_long=None,
|
| 1020 |
+
latent_window_size=9,
|
| 1021 |
+
return_list=True,
|
| 1022 |
+
is_navit_pyramid=False,
|
| 1023 |
+
is_efficient_sample=False,
|
| 1024 |
+
):
|
| 1025 |
+
noisy_model_input_list, sigmas_list, timesteps_list, targets_list = prepare_stage2_clean_input(
|
| 1026 |
+
args=args,
|
| 1027 |
+
scheduler=scheduler,
|
| 1028 |
+
latents=latents,
|
| 1029 |
+
pyramid_stage_num=pyramid_stage_num,
|
| 1030 |
+
stage2_sample_ratios=stage2_sample_ratios,
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
if args.training_config.corrupt_history and latents_history_short is not None:
|
| 1034 |
+
latents_history_short, latents_history_mid, latents_history_long = corrupt_history_latents(
|
| 1035 |
+
latents_history_short,
|
| 1036 |
+
latents_history_mid,
|
| 1037 |
+
latents_history_long,
|
| 1038 |
+
latent_window_size,
|
| 1039 |
+
is_keep_x0=True,
|
| 1040 |
+
# choose mode
|
| 1041 |
+
corrupt_mode=args.training_config.corrupt_mode_history,
|
| 1042 |
+
noise_mode_prob=args.training_config.corrupt_mode_prob_history,
|
| 1043 |
+
# for noise
|
| 1044 |
+
is_frame_independent=args.training_config.is_frame_independent_corrupt_history,
|
| 1045 |
+
is_chunk_independent=args.training_config.is_chunk_independent_corrupt_history,
|
| 1046 |
+
corrupt_ratio_1x=args.training_config.noise_corrupt_ratio_history_short,
|
| 1047 |
+
corrupt_ratio_2x=args.training_config.noise_corrupt_ratio_history_mid,
|
| 1048 |
+
corrupt_ratio_4x=args.training_config.noise_corrupt_ratio_history_long,
|
| 1049 |
+
noise_corrupt_clean_prob=args.training_config.noise_corrupt_clean_prob_history,
|
| 1050 |
+
# for downsample
|
| 1051 |
+
downsample_min_corrupt_ratio=args.training_config.downsample_min_corrupt_ratio_history,
|
| 1052 |
+
downsample_max_corrupt_ratio=args.training_config.downsample_max_corrupt_ratio_history,
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
if is_navit_pyramid:
|
| 1056 |
+
return (
|
| 1057 |
+
[noisy_model_input_list],
|
| 1058 |
+
[sigmas_list],
|
| 1059 |
+
[timesteps_list],
|
| 1060 |
+
[targets_list],
|
| 1061 |
+
latents_history_short,
|
| 1062 |
+
latents_history_mid,
|
| 1063 |
+
latents_history_long,
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
if is_efficient_sample:
|
| 1067 |
+
temp_list = list(range(len(noisy_model_input_list)))
|
| 1068 |
+
random_index = random.choice(temp_list)
|
| 1069 |
+
|
| 1070 |
+
noisy_model_input = noisy_model_input_list[random_index]
|
| 1071 |
+
sigmas = sigmas_list[random_index]
|
| 1072 |
+
timesteps = timesteps_list[random_index]
|
| 1073 |
+
targets = targets_list[random_index]
|
| 1074 |
+
|
| 1075 |
+
base_results = (noisy_model_input, sigmas, timesteps, targets)
|
| 1076 |
+
additional_results = (latents_history_short, latents_history_mid, latents_history_long)
|
| 1077 |
+
|
| 1078 |
+
if return_list:
|
| 1079 |
+
return tuple([item] for item in base_results) + additional_results
|
| 1080 |
+
else:
|
| 1081 |
+
return base_results + additional_results
|
| 1082 |
+
|
| 1083 |
+
return (
|
| 1084 |
+
noisy_model_input_list,
|
| 1085 |
+
sigmas_list,
|
| 1086 |
+
timesteps_list,
|
| 1087 |
+
targets_list,
|
| 1088 |
+
latents_history_short,
|
| 1089 |
+
latents_history_mid,
|
| 1090 |
+
latents_history_long,
|
| 1091 |
+
)
|
Helios/_DEV/helios/utils/utils_helios_post.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/helios/utils/utils_recycle_batch.py
ADDED
|
@@ -0,0 +1,724 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
latents_history_long,
|
| 15 |
+
latents_history_mid,
|
| 16 |
+
latents_history_short,
|
| 17 |
+
model_input_w_error,
|
| 18 |
+
noise_w_error,
|
| 19 |
+
is_keep_x0,
|
| 20 |
+
latent_window_size,
|
| 21 |
+
):
|
| 22 |
+
batch_size, _, _, h, w = noise.shape
|
| 23 |
+
|
| 24 |
+
# Get grid indices for all batch items
|
| 25 |
+
current_grid_indices = get_timestep_grid(args, recycle_vars, timesteps, noise)
|
| 26 |
+
|
| 27 |
+
# Handle single item (backward compatibility)
|
| 28 |
+
if isinstance(current_grid_indices, int):
|
| 29 |
+
current_grid_indices = torch.tensor([current_grid_indices], device=noise.device)
|
| 30 |
+
|
| 31 |
+
# Check buffer availability for each batch item
|
| 32 |
+
has_latent_buffer_data = torch.tensor(
|
| 33 |
+
[len(recycle_vars.latent_error_buffer[(h, w)][grid_idx.item()]) > 0 for grid_idx in current_grid_indices],
|
| 34 |
+
device=noise.device,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
has_y_buffer_data = any(len(buffer) > 0 for buffer in recycle_vars.y_error_buffer[(h, w)].values())
|
| 38 |
+
|
| 39 |
+
# Generate random decisions for each batch item
|
| 40 |
+
latent_random = torch.rand(batch_size, device=noise.device)
|
| 41 |
+
noise_random = torch.rand(batch_size, device=noise.device)
|
| 42 |
+
y_random = torch.rand(batch_size, device=noise.device)
|
| 43 |
+
clean_random = torch.rand(batch_size, device=noise.device)
|
| 44 |
+
|
| 45 |
+
# Determine which operations to apply for each batch item
|
| 46 |
+
add_error_latent = latent_random < args.training_config.latent_prob
|
| 47 |
+
add_error_noise = noise_random < args.training_config.noise_prob
|
| 48 |
+
add_error_y = y_random < args.training_config.y_prob
|
| 49 |
+
use_clean_input = clean_random < args.training_config.clean_prob
|
| 50 |
+
|
| 51 |
+
# Clean input overrides all errors
|
| 52 |
+
add_error_noise = add_error_noise & ~use_clean_input
|
| 53 |
+
add_error_y = add_error_y & ~use_clean_input
|
| 54 |
+
add_error_latent = add_error_latent & ~use_clean_input
|
| 55 |
+
|
| 56 |
+
# Apply noise error
|
| 57 |
+
if add_error_noise.any() and has_latent_buffer_data.any():
|
| 58 |
+
noise_error_sampled = sample_noise_error_from_noise_buffer(
|
| 59 |
+
args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device
|
| 60 |
+
)
|
| 61 |
+
mask = add_error_noise & has_latent_buffer_data
|
| 62 |
+
if mask.any():
|
| 63 |
+
noise_w_error[mask] = noise[mask] + noise_error_sampled[mask].to(model_input.dtype)
|
| 64 |
+
|
| 65 |
+
# Apply y error for selected batch items
|
| 66 |
+
if add_error_y.any() and has_y_buffer_data:
|
| 67 |
+
len_4x = latents_history_long.shape[2]
|
| 68 |
+
len_2x = latents_history_mid.shape[2]
|
| 69 |
+
len_1x = latents_history_short.shape[2]
|
| 70 |
+
|
| 71 |
+
hist_seq_len = len_4x + len_2x + len_1x
|
| 72 |
+
hist_seq_len_copy = hist_seq_len
|
| 73 |
+
|
| 74 |
+
ori_len_1x = len_1x
|
| 75 |
+
if is_keep_x0:
|
| 76 |
+
len_1x -= 1
|
| 77 |
+
hist_seq_len -= 1
|
| 78 |
+
begin_num = 1
|
| 79 |
+
else:
|
| 80 |
+
begin_num = 0
|
| 81 |
+
|
| 82 |
+
max_windows = hist_seq_len // latent_window_size
|
| 83 |
+
tail_num = hist_seq_len % latent_window_size
|
| 84 |
+
|
| 85 |
+
assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num
|
| 86 |
+
|
| 87 |
+
# Process each batch item independently
|
| 88 |
+
for batch_idx in range(batch_size):
|
| 89 |
+
if not add_error_y[batch_idx]:
|
| 90 |
+
continue
|
| 91 |
+
|
| 92 |
+
# Split history for this batch item
|
| 93 |
+
tail_latents_history = None
|
| 94 |
+
begin_latents_history = None
|
| 95 |
+
|
| 96 |
+
latents_4x_item = latents_history_long[batch_idx : batch_idx + 1]
|
| 97 |
+
latents_2x_item = latents_history_mid[batch_idx : batch_idx + 1]
|
| 98 |
+
latents_clean_item = latents_history_short[batch_idx : batch_idx + 1]
|
| 99 |
+
|
| 100 |
+
if tail_num != 0:
|
| 101 |
+
tail_latents_history = latents_4x_item[:, :, :tail_num, :, :]
|
| 102 |
+
latents_4x_item = latents_4x_item[:, :, tail_num:, :, :]
|
| 103 |
+
# Apply tail error
|
| 104 |
+
if tail_latents_history.sum() != 0 and random.random() < args.training_config.y_prob:
|
| 105 |
+
y_error_sampled = sample_y_error_from_latent_buffer(
|
| 106 |
+
args,
|
| 107 |
+
recycle_vars,
|
| 108 |
+
model_input[batch_idx : batch_idx + 1],
|
| 109 |
+
model_input.dtype,
|
| 110 |
+
model_input.device,
|
| 111 |
+
)
|
| 112 |
+
random_error_num = torch.randint(1, tail_num + 1, (1,)).item()
|
| 113 |
+
tail_latents_history[:, :, -random_error_num:, ...] = (
|
| 114 |
+
tail_latents_history[:, :, -random_error_num:, ...]
|
| 115 |
+
+ y_error_sampled[:, :, -random_error_num:, ...]
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if begin_num != 0:
|
| 119 |
+
begin_latents_history = latents_clean_item[:, :, :begin_num, :, :]
|
| 120 |
+
latents_clean_item = latents_clean_item[:, :, begin_num:, :, :]
|
| 121 |
+
# Apply begin error
|
| 122 |
+
if begin_latents_history.sum() != 0 and random.random() < args.training_config.y_prob:
|
| 123 |
+
y_error_sampled = sample_y_error_from_latent_buffer(
|
| 124 |
+
args,
|
| 125 |
+
recycle_vars,
|
| 126 |
+
model_input[batch_idx : batch_idx + 1],
|
| 127 |
+
model_input.dtype,
|
| 128 |
+
model_input.device,
|
| 129 |
+
)
|
| 130 |
+
begin_latents_history = begin_latents_history + y_error_sampled[:, :, :1, ...]
|
| 131 |
+
|
| 132 |
+
# Process mid windows
|
| 133 |
+
mid_latents_history = torch.cat([latents_4x_item, latents_2x_item, latents_clean_item], dim=2)
|
| 134 |
+
window_num = mid_latents_history.shape[2] // latent_window_size
|
| 135 |
+
assert mid_latents_history.shape[2] % latent_window_size == 0, (
|
| 136 |
+
f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
seq_begin = 0
|
| 140 |
+
for _ in range(window_num):
|
| 141 |
+
seq_end = seq_begin + latent_window_size
|
| 142 |
+
if (
|
| 143 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :].sum() != 0
|
| 144 |
+
and random.random() < args.training_config.y_prob
|
| 145 |
+
):
|
| 146 |
+
y_error_sampled = sample_y_error_from_latent_buffer(
|
| 147 |
+
args,
|
| 148 |
+
recycle_vars,
|
| 149 |
+
model_input[batch_idx : batch_idx + 1],
|
| 150 |
+
model_input.dtype,
|
| 151 |
+
model_input.device,
|
| 152 |
+
)
|
| 153 |
+
max_start_idx = max(0, y_error_sampled.shape[2] - args.training_config.y_error_num)
|
| 154 |
+
random_frame_idx = torch.randint(0, max_start_idx + 1, (1,)).item()
|
| 155 |
+
error_to_add = y_error_sampled[
|
| 156 |
+
:, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, ...
|
| 157 |
+
]
|
| 158 |
+
# Modify
|
| 159 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :][
|
| 160 |
+
:, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, :
|
| 161 |
+
] = (
|
| 162 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :][
|
| 163 |
+
:, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, :
|
| 164 |
+
]
|
| 165 |
+
+ error_to_add
|
| 166 |
+
)
|
| 167 |
+
seq_begin = seq_end
|
| 168 |
+
|
| 169 |
+
# Recover structure
|
| 170 |
+
recovers = []
|
| 171 |
+
if tail_latents_history is not None:
|
| 172 |
+
recovers.append(tail_latents_history)
|
| 173 |
+
recovers.append(mid_latents_history[:, :, :-len_1x, :, :])
|
| 174 |
+
if begin_latents_history is not None:
|
| 175 |
+
recovers.append(begin_latents_history)
|
| 176 |
+
recovers.append(mid_latents_history[:, :, -len_1x:, :, :])
|
| 177 |
+
mid_latents_history = torch.cat(recovers, dim=2)
|
| 178 |
+
|
| 179 |
+
# Split and update back to original tensors
|
| 180 |
+
latents_4x_recovered, latents_2x_recovered, latents_clean_recovered = mid_latents_history.split(
|
| 181 |
+
[len_4x, len_2x, ori_len_1x], dim=2
|
| 182 |
+
)
|
| 183 |
+
latents_history_long[batch_idx : batch_idx + 1] = latents_4x_recovered
|
| 184 |
+
latents_history_mid[batch_idx : batch_idx + 1] = latents_2x_recovered
|
| 185 |
+
latents_history_short[batch_idx : batch_idx + 1] = latents_clean_recovered
|
| 186 |
+
|
| 187 |
+
# Apply latent error
|
| 188 |
+
if add_error_latent.any() and has_latent_buffer_data.any():
|
| 189 |
+
latent_error_sampled = sample_latent_error_from_latent_buffer(
|
| 190 |
+
args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device
|
| 191 |
+
)
|
| 192 |
+
mask = add_error_latent & has_latent_buffer_data
|
| 193 |
+
if mask.any():
|
| 194 |
+
model_input_w_error[mask] = model_input[mask] + latent_error_sampled[mask].to(model_input.dtype)
|
| 195 |
+
|
| 196 |
+
return (
|
| 197 |
+
model_input_w_error,
|
| 198 |
+
noise_w_error,
|
| 199 |
+
latents_history_long,
|
| 200 |
+
latents_history_mid,
|
| 201 |
+
latents_history_short,
|
| 202 |
+
use_clean_input,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def step_recycle(scheduler, model_output, timestep, sample, to_final=False, self_corr=False):
|
| 207 |
+
"""
|
| 208 |
+
Args:
|
| 209 |
+
timestep: scalar, 1D tensor with shape [batch_size], or tensor that can be flattened
|
| 210 |
+
"""
|
| 211 |
+
# Normalize timestep to 1D tensor
|
| 212 |
+
if isinstance(timestep, torch.Tensor):
|
| 213 |
+
timestep_vals = timestep.flatten().cpu()
|
| 214 |
+
else:
|
| 215 |
+
# Scalar value, convert to tensor
|
| 216 |
+
timestep_vals = torch.tensor([timestep])
|
| 217 |
+
|
| 218 |
+
batch_size = timestep_vals.shape[0]
|
| 219 |
+
|
| 220 |
+
# Find timestep indices for all batch items
|
| 221 |
+
# timestep_vals: [batch_size], scheduler.temp_timesteps: [num_timesteps]
|
| 222 |
+
diffs = torch.abs(
|
| 223 |
+
scheduler.temp_timesteps.unsqueeze(0) - timestep_vals.unsqueeze(-1)
|
| 224 |
+
) # [batch_size, num_timesteps]
|
| 225 |
+
timestep_ids = torch.argmin(diffs, dim=-1) # [batch_size]
|
| 226 |
+
|
| 227 |
+
# Get sigmas for all batch items
|
| 228 |
+
sigmas = scheduler.temp_sigmas[timestep_ids] # [batch_size]
|
| 229 |
+
|
| 230 |
+
# Calculate next sigmas
|
| 231 |
+
if to_final:
|
| 232 |
+
# All items go to final
|
| 233 |
+
sigmas_next = torch.ones(batch_size) if self_corr else torch.zeros(batch_size)
|
| 234 |
+
else:
|
| 235 |
+
# Check which items are at the end
|
| 236 |
+
at_end = timestep_ids + 1 >= len(scheduler.temp_timesteps)
|
| 237 |
+
|
| 238 |
+
# Get next sigmas (clamped to valid range)
|
| 239 |
+
next_ids = torch.clamp(timestep_ids + 1, 0, len(scheduler.temp_timesteps) - 1)
|
| 240 |
+
sigmas_next = scheduler.temp_sigmas[next_ids] # [batch_size]
|
| 241 |
+
|
| 242 |
+
# Override with 1 or 0 for items at the end
|
| 243 |
+
if self_corr:
|
| 244 |
+
sigmas_next[at_end] = 1.0
|
| 245 |
+
else:
|
| 246 |
+
sigmas_next[at_end] = 0.0
|
| 247 |
+
|
| 248 |
+
# Move sigmas to same device as sample
|
| 249 |
+
sigmas = sigmas.to(sample.device, dtype=sample.dtype)
|
| 250 |
+
sigmas_next = sigmas_next.to(sample.device, dtype=sample.dtype)
|
| 251 |
+
|
| 252 |
+
# Compute prev_sample for all batch items
|
| 253 |
+
# Reshape sigmas to broadcast correctly: [batch_size, 1, 1, 1, 1] for 5D tensors
|
| 254 |
+
shape = [batch_size] + [1] * (sample.ndim - 1)
|
| 255 |
+
sigma_diff = (sigmas_next - sigmas).view(*shape)
|
| 256 |
+
|
| 257 |
+
prev_sample = sample + model_output * sigma_diff
|
| 258 |
+
|
| 259 |
+
return prev_sample
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def get_timesteps(
|
| 263 |
+
num_inference_steps=50,
|
| 264 |
+
denoising_strength=1,
|
| 265 |
+
shift=1.0,
|
| 266 |
+
num_train_timesteps=1000,
|
| 267 |
+
sigma_max=1.0,
|
| 268 |
+
sigma_min=0.0,
|
| 269 |
+
inverse_timesteps=False,
|
| 270 |
+
extra_one_step=True,
|
| 271 |
+
reverse_sigmas=False,
|
| 272 |
+
):
|
| 273 |
+
sigma_start = sigma_min + (sigma_max - sigma_min) * denoising_strength
|
| 274 |
+
if extra_one_step:
|
| 275 |
+
sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps + 1)[:-1]
|
| 276 |
+
else:
|
| 277 |
+
sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps)
|
| 278 |
+
if inverse_timesteps:
|
| 279 |
+
sigmas = torch.flip(sigmas, dims=[0])
|
| 280 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
|
| 281 |
+
if reverse_sigmas:
|
| 282 |
+
sigmas = 1 - sigmas
|
| 283 |
+
timesteps = sigmas * num_train_timesteps
|
| 284 |
+
return timesteps, sigmas
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def get_timestep_grid(args, recycle_vars, timesteps, noise):
|
| 288 |
+
"""Get the grid index for a given timesteps."""
|
| 289 |
+
_, _, _, h, w = noise.shape
|
| 290 |
+
|
| 291 |
+
# Handle different timesteps formats (scalar tensor, tensor with batch dim, etc.)
|
| 292 |
+
if isinstance(timesteps, torch.Tensor):
|
| 293 |
+
timestep_vals = timesteps.flatten()
|
| 294 |
+
else:
|
| 295 |
+
# Already a scalar value
|
| 296 |
+
timestep_vals = torch.tensor([timesteps], device=noise.device if hasattr(noise, "device") else "cpu")
|
| 297 |
+
|
| 298 |
+
if args.training_config.use_dynamic_shifting:
|
| 299 |
+
temp_sigmas = apply_schedule_shift(
|
| 300 |
+
recycle_vars.recycle_sigmas,
|
| 301 |
+
noise,
|
| 302 |
+
base_seq_len=args.training_config.base_seq_len,
|
| 303 |
+
max_seq_len=args.training_config.max_seq_len,
|
| 304 |
+
base_shift=args.training_config.base_shift,
|
| 305 |
+
max_shift=args.training_config.max_shift,
|
| 306 |
+
) # torch.Size([2, 1, 1, 1, 1])
|
| 307 |
+
|
| 308 |
+
temp_inferece_timesteps = temp_sigmas * 1000.0 # rescale to [0, 1000.0)
|
| 309 |
+
while temp_inferece_timesteps.ndim > 1:
|
| 310 |
+
temp_inferece_timesteps = temp_inferece_timesteps.squeeze(-1)
|
| 311 |
+
else:
|
| 312 |
+
temp_inferece_timesteps = recycle_vars.recycle_inferece_timesteps
|
| 313 |
+
|
| 314 |
+
# Ensure timesteps is within valid range and calculate grid index
|
| 315 |
+
timestep_vals = torch.clamp(timestep_vals, 0, 999)
|
| 316 |
+
grid_timesteps = temp_inferece_timesteps.to(timestep_vals.device)
|
| 317 |
+
|
| 318 |
+
diffs = torch.abs(grid_timesteps.unsqueeze(0) - timestep_vals.unsqueeze(-1))
|
| 319 |
+
grid_indices = torch.argmin(diffs, dim=-1)
|
| 320 |
+
|
| 321 |
+
# Ensure grid index is within valid range
|
| 322 |
+
max_grid_idx = len(recycle_vars.latent_error_buffer[(h, w)]) - 1
|
| 323 |
+
grid_indices = torch.clamp(grid_indices, 0, max_grid_idx)
|
| 324 |
+
|
| 325 |
+
return grid_indices
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def sample_noise_error_from_noise_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"):
|
| 329 |
+
"""Randomly sample an error from the buffer based on timestep grid."""
|
| 330 |
+
batch_size, _, _, h, w = latents.shape
|
| 331 |
+
grid_indices = get_timestep_grid(args, recycle_vars, timestep, latents)
|
| 332 |
+
|
| 333 |
+
# Handle single item (backward compatibility)
|
| 334 |
+
if isinstance(grid_indices, int):
|
| 335 |
+
grid_indices = torch.tensor([grid_indices], device=device)
|
| 336 |
+
|
| 337 |
+
# Initialize output tensor
|
| 338 |
+
error_samples = torch.zeros_like(latents)
|
| 339 |
+
|
| 340 |
+
# Sample error for each item in batch
|
| 341 |
+
for i, grid_idx in enumerate(grid_indices):
|
| 342 |
+
grid_idx = grid_idx.item()
|
| 343 |
+
|
| 344 |
+
if not recycle_vars.latent_error_buffer[(h, w)][grid_idx]:
|
| 345 |
+
continue # Keep zeros for this batch item
|
| 346 |
+
|
| 347 |
+
# Randomly select one sample from the corresponding grid
|
| 348 |
+
selected_sample = random.choice(recycle_vars.latent_error_buffer[(h, w)][grid_idx])
|
| 349 |
+
|
| 350 |
+
# Apply random intensity modulation
|
| 351 |
+
min_mod = 1.0 - args.training_config.error_modulate_factor
|
| 352 |
+
max_mod = 1.0 + args.training_config.error_modulate_factor
|
| 353 |
+
intensity_mod = random.uniform(min_mod, max_mod)
|
| 354 |
+
|
| 355 |
+
error_sample = selected_sample * intensity_mod
|
| 356 |
+
error_sample = error_sample
|
| 357 |
+
|
| 358 |
+
# Assign to the i-th batch item
|
| 359 |
+
error_samples[i] = error_sample
|
| 360 |
+
|
| 361 |
+
error_samples = error_samples.to(device, dtype=dtype)
|
| 362 |
+
|
| 363 |
+
return error_samples
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def sample_latent_error_from_latent_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"):
|
| 367 |
+
"""Randomly sample an error from the buffer based on timestep grid."""
|
| 368 |
+
batch_size, _, _, h, w = latents.shape
|
| 369 |
+
grid_indices = get_timestep_grid(args, recycle_vars, timestep, latents)
|
| 370 |
+
|
| 371 |
+
# Handle single item (backward compatibility)
|
| 372 |
+
if isinstance(grid_indices, int):
|
| 373 |
+
grid_indices = torch.tensor([grid_indices], device=device)
|
| 374 |
+
|
| 375 |
+
# Initialize output tensor
|
| 376 |
+
error_samples = torch.zeros_like(latents)
|
| 377 |
+
|
| 378 |
+
# Sample error for each item in batch
|
| 379 |
+
for i, grid_idx in enumerate(grid_indices):
|
| 380 |
+
grid_idx = grid_idx.item()
|
| 381 |
+
|
| 382 |
+
if not recycle_vars.y_error_buffer[(h, w)][grid_idx]:
|
| 383 |
+
continue # Keep zeros for this batch item
|
| 384 |
+
|
| 385 |
+
# Randomly select one sample from the corresponding grid
|
| 386 |
+
selected_sample = random.choice(recycle_vars.y_error_buffer[(h, w)][grid_idx])
|
| 387 |
+
|
| 388 |
+
# Apply random intensity modulation
|
| 389 |
+
min_mod = 1.0 - args.training_config.error_modulate_factor
|
| 390 |
+
max_mod = 1.0 + args.training_config.error_modulate_factor
|
| 391 |
+
intensity_mod = random.uniform(min_mod, max_mod)
|
| 392 |
+
|
| 393 |
+
error_sample = selected_sample * intensity_mod
|
| 394 |
+
error_sample = error_sample
|
| 395 |
+
|
| 396 |
+
# Assign to the i-th batch item
|
| 397 |
+
error_samples[i] = error_sample
|
| 398 |
+
|
| 399 |
+
error_samples = error_samples.to(device, dtype=dtype)
|
| 400 |
+
|
| 401 |
+
return error_samples
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def sample_y_error_from_latent_buffer(args, recycle_vars, latents, dtype=torch.bfloat16, device="cpu"):
|
| 405 |
+
"""Specially sample y_error from buffer - can be configured to sample from all grids or custom range."""
|
| 406 |
+
batch_size, _, _, h, w = latents.shape
|
| 407 |
+
|
| 408 |
+
# Sample from all grids that have data
|
| 409 |
+
all_samples = []
|
| 410 |
+
for grid_idx, buffer in recycle_vars.y_error_buffer[(h, w)].items():
|
| 411 |
+
if buffer: # Only add non-empty buffers
|
| 412 |
+
all_samples.extend(buffer)
|
| 413 |
+
|
| 414 |
+
if not all_samples:
|
| 415 |
+
return torch.zeros_like(latents)
|
| 416 |
+
|
| 417 |
+
# Initialize output tensor
|
| 418 |
+
error_samples = torch.zeros_like(latents)
|
| 419 |
+
|
| 420 |
+
# Sample independently for each batch item
|
| 421 |
+
for i in range(batch_size):
|
| 422 |
+
# Randomly select one sample from all available samples
|
| 423 |
+
selected_sample = random.choice(all_samples)
|
| 424 |
+
|
| 425 |
+
# Apply random intensity modulation
|
| 426 |
+
min_mod = 1.0 - args.training_config.error_modulate_factor
|
| 427 |
+
max_mod = 1.0 + args.training_config.error_modulate_factor
|
| 428 |
+
intensity_mod = random.uniform(min_mod, max_mod)
|
| 429 |
+
|
| 430 |
+
error_sample = selected_sample * intensity_mod
|
| 431 |
+
error_sample = error_sample
|
| 432 |
+
|
| 433 |
+
# Assign to the i-th batch item
|
| 434 |
+
error_samples[i] = error_sample
|
| 435 |
+
|
| 436 |
+
error_samples = error_samples.to(device, dtype=dtype)
|
| 437 |
+
|
| 438 |
+
return error_samples
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def compute_l2_distance_batch(new_tensor, stored_tensors):
|
| 442 |
+
"""Compute L2 distances between new tensor and all stored tensors efficiently."""
|
| 443 |
+
if not stored_tensors:
|
| 444 |
+
return torch.tensor([])
|
| 445 |
+
|
| 446 |
+
# Stack all stored tensors for batch computation
|
| 447 |
+
stored_stack = torch.stack(stored_tensors) # [num_stored, ...]
|
| 448 |
+
new_flat = new_tensor.flatten()
|
| 449 |
+
stored_flat = stored_stack.flatten(start_dim=1) # [num_stored, flattened_size]
|
| 450 |
+
|
| 451 |
+
# Compute L2 distances in batch
|
| 452 |
+
distances = torch.norm(stored_flat - new_flat.unsqueeze(0), p=2, dim=1)
|
| 453 |
+
return distances
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def compute_l2_distance(tensor1, tensor2):
|
| 457 |
+
"""Compute L2 distance between two tensors"""
|
| 458 |
+
# Flatten tensors
|
| 459 |
+
flat1 = tensor1.flatten()
|
| 460 |
+
flat2 = tensor2.flatten()
|
| 461 |
+
|
| 462 |
+
# Compute L2 distance (Euclidean distance)
|
| 463 |
+
l2_distance = torch.norm(flat1 - flat2, p=2)
|
| 464 |
+
return l2_distance.item()
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def add_error_to_latent_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input):
|
| 468 |
+
"""Add error sample to buffer using specified replacement strategy based on timestep grid."""
|
| 469 |
+
batch_size, _, _, h, w = noisy_model_input.shape
|
| 470 |
+
grid_indices = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input)
|
| 471 |
+
error_cpu = error_sample.detach().cpu()
|
| 472 |
+
|
| 473 |
+
# Process each batch item
|
| 474 |
+
for i, grid_idx in enumerate(grid_indices):
|
| 475 |
+
grid_idx = grid_idx.item()
|
| 476 |
+
error_cpu = error_sample[i].detach().cpu()
|
| 477 |
+
|
| 478 |
+
if len(recycle_vars.latent_error_buffer[(h, w)][grid_idx]) < args.training_config.error_buffer_size:
|
| 479 |
+
# Buffer not full, simply add
|
| 480 |
+
recycle_vars.latent_error_buffer[(h, w)][grid_idx].append(error_cpu)
|
| 481 |
+
else:
|
| 482 |
+
# Buffer full, use specified replacement strategy
|
| 483 |
+
if args.training_config.buffer_replacement_strategy == "random":
|
| 484 |
+
# Random replacement - O(1), fastest
|
| 485 |
+
replace_idx = random.randint(0, len(recycle_vars.latent_error_buffer[(h, w)][grid_idx]) - 1)
|
| 486 |
+
recycle_vars.latent_error_buffer[(h, w)][grid_idx][replace_idx] = error_cpu
|
| 487 |
+
|
| 488 |
+
elif args.training_config.buffer_replacement_strategy == "fifo":
|
| 489 |
+
# First-in-first-out - O(1), simple queue behavior
|
| 490 |
+
recycle_vars.latent_error_buffer[(h, w)][grid_idx].pop(0)
|
| 491 |
+
recycle_vars.latent_error_buffer[(h, w)][grid_idx].append(error_cpu)
|
| 492 |
+
|
| 493 |
+
elif args.training_config.buffer_replacement_strategy == "l2_batch":
|
| 494 |
+
# Batch L2 computation - O(n) but vectorized, much faster than original
|
| 495 |
+
distances = compute_l2_distance_batch(error_cpu, recycle_vars.latent_error_buffer[(h, w)][grid_idx])
|
| 496 |
+
most_similar_idx = torch.argmin(distances).item()
|
| 497 |
+
recycle_vars.latent_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu
|
| 498 |
+
|
| 499 |
+
elif args.training_config.buffer_replacement_strategy == "l2_similarity":
|
| 500 |
+
# Original L2 similarity method - O(n), slowest but most precise
|
| 501 |
+
min_distance = float("inf")
|
| 502 |
+
most_similar_idx = -1
|
| 503 |
+
|
| 504 |
+
for j, stored_error in enumerate(recycle_vars.latent_error_buffer[(h, w)][grid_idx]):
|
| 505 |
+
distance = compute_l2_distance(error_cpu, stored_error)
|
| 506 |
+
if distance < min_distance:
|
| 507 |
+
min_distance = distance
|
| 508 |
+
most_similar_idx = j
|
| 509 |
+
|
| 510 |
+
if most_similar_idx != -1:
|
| 511 |
+
recycle_vars.latent_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def add_error_to_y_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input):
|
| 515 |
+
"""Add error sample to buffer using specified replacement strategy based on timestep grid."""
|
| 516 |
+
batch_size, _, _, h, w = noisy_model_input.shape
|
| 517 |
+
grid_indices = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input)
|
| 518 |
+
error_cpu = error_sample.detach().cpu()
|
| 519 |
+
|
| 520 |
+
# Process each batch item
|
| 521 |
+
for i, grid_idx in enumerate(grid_indices):
|
| 522 |
+
grid_idx = grid_idx.item()
|
| 523 |
+
error_cpu = error_sample[i].detach().cpu()
|
| 524 |
+
|
| 525 |
+
if len(recycle_vars.y_error_buffer[(h, w)][grid_idx]) < args.training_config.error_buffer_size:
|
| 526 |
+
# Buffer not full, simply add
|
| 527 |
+
recycle_vars.y_error_buffer[(h, w)][grid_idx].append(error_cpu)
|
| 528 |
+
else:
|
| 529 |
+
# Buffer full, use specified replacement strategy
|
| 530 |
+
if args.training_config.buffer_replacement_strategy == "random":
|
| 531 |
+
# Random replacement - O(1), fastest
|
| 532 |
+
replace_idx = random.randint(0, len(recycle_vars.y_error_buffer[(h, w)][grid_idx]) - 1)
|
| 533 |
+
recycle_vars.y_error_buffer[(h, w)][grid_idx][replace_idx] = error_cpu
|
| 534 |
+
|
| 535 |
+
elif args.training_config.buffer_replacement_strategy == "fifo":
|
| 536 |
+
# First-in-first-out - O(1), simple queue behavior
|
| 537 |
+
recycle_vars.y_error_buffer[(h, w)][grid_idx].pop(0)
|
| 538 |
+
recycle_vars.y_error_buffer[(h, w)][grid_idx].append(error_cpu)
|
| 539 |
+
|
| 540 |
+
elif args.training_config.buffer_replacement_strategy == "l2_batch":
|
| 541 |
+
# Batch L2 computation - O(n) but vectorized, much faster than original
|
| 542 |
+
distances = compute_l2_distance_batch(error_cpu, recycle_vars.y_error_buffer[(h, w)][grid_idx])
|
| 543 |
+
most_similar_idx = torch.argmin(distances).item()
|
| 544 |
+
recycle_vars.y_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu
|
| 545 |
+
|
| 546 |
+
elif args.training_config.buffer_replacement_strategy == "l2_similarity":
|
| 547 |
+
# Original L2 similarity method - O(n), slowest but most precise
|
| 548 |
+
min_distance = float("inf")
|
| 549 |
+
most_similar_idx = -1
|
| 550 |
+
|
| 551 |
+
for j, stored_error in enumerate(recycle_vars.y_error_buffer[(h, w)][grid_idx]):
|
| 552 |
+
distance = compute_l2_distance(error_cpu, stored_error)
|
| 553 |
+
if distance < min_distance:
|
| 554 |
+
min_distance = distance
|
| 555 |
+
most_similar_idx = j
|
| 556 |
+
|
| 557 |
+
if most_similar_idx != -1:
|
| 558 |
+
recycle_vars.y_error_buffer[(h, w)][grid_idx][most_similar_idx] = error_cpu
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def update_error_buffers_distributed(
|
| 562 |
+
args, recycle_vars, gathered_noise_errors, gathered_y_errors, gathered_timesteps, noisy_model_input
|
| 563 |
+
):
|
| 564 |
+
"""Update error buffers with samples gathered from all processes.
|
| 565 |
+
Args:
|
| 566 |
+
gathered_noise_errors: shape [num_gpus, batch_size, ...]
|
| 567 |
+
gathered_y_errors: shape [num_gpus, batch_size, ...]
|
| 568 |
+
gathered_timesteps: shape [num_gpus, batch_size]
|
| 569 |
+
"""
|
| 570 |
+
num_gpus = gathered_noise_errors.shape[0]
|
| 571 |
+
|
| 572 |
+
# Process each GPU's batch
|
| 573 |
+
for gpu_idx in range(num_gpus):
|
| 574 |
+
noise_error_batch = gathered_noise_errors[gpu_idx] # [batch_size, ...]
|
| 575 |
+
y_error_batch = gathered_y_errors[gpu_idx] # [batch_size, ...]
|
| 576 |
+
timestep_batch = gathered_timesteps[gpu_idx] # [batch_size]
|
| 577 |
+
|
| 578 |
+
# Add the entire batch to buffers
|
| 579 |
+
add_error_to_latent_buffer(args, recycle_vars, noise_error_batch, timestep_batch, noisy_model_input)
|
| 580 |
+
add_error_to_y_buffer(args, recycle_vars, y_error_batch, timestep_batch, noisy_model_input)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def update_error_buffers_local(args, recycle_vars, noise_error, y_error, timestep, noisy_model_input):
|
| 584 |
+
"""Update error buffers with samples from local GPU only (post-warmup).
|
| 585 |
+
Args:
|
| 586 |
+
noise_error: shape [batch_size, ...]
|
| 587 |
+
y_error: shape [batch_size, ...]
|
| 588 |
+
timestep: shape [batch_size] or scalar
|
| 589 |
+
"""
|
| 590 |
+
add_error_to_latent_buffer(args, recycle_vars, noise_error, timestep, noisy_model_input)
|
| 591 |
+
add_error_to_y_buffer(args, recycle_vars, y_error, timestep, noisy_model_input)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def process_and_update_error_buffers(
|
| 595 |
+
args,
|
| 596 |
+
recycle_vars,
|
| 597 |
+
accelerator,
|
| 598 |
+
global_step,
|
| 599 |
+
noise_scheduler_copy,
|
| 600 |
+
model_pred,
|
| 601 |
+
target,
|
| 602 |
+
timesteps,
|
| 603 |
+
noisy_model_input,
|
| 604 |
+
use_clean_input,
|
| 605 |
+
):
|
| 606 |
+
x_0_pred = step_recycle(
|
| 607 |
+
noise_scheduler_copy,
|
| 608 |
+
model_pred,
|
| 609 |
+
timesteps,
|
| 610 |
+
noisy_model_input,
|
| 611 |
+
to_final=True,
|
| 612 |
+
self_corr=True,
|
| 613 |
+
)
|
| 614 |
+
noise_corr_gt = step_recycle(
|
| 615 |
+
noise_scheduler_copy,
|
| 616 |
+
target,
|
| 617 |
+
timesteps,
|
| 618 |
+
noisy_model_input,
|
| 619 |
+
to_final=True,
|
| 620 |
+
self_corr=True,
|
| 621 |
+
)
|
| 622 |
+
noise_error = x_0_pred - noise_corr_gt
|
| 623 |
+
|
| 624 |
+
x_1_pred = step_recycle(
|
| 625 |
+
noise_scheduler_copy,
|
| 626 |
+
model_pred,
|
| 627 |
+
timesteps,
|
| 628 |
+
noisy_model_input,
|
| 629 |
+
to_final=True,
|
| 630 |
+
self_corr=False,
|
| 631 |
+
)
|
| 632 |
+
latent_corr_gt = step_recycle(
|
| 633 |
+
noise_scheduler_copy,
|
| 634 |
+
target,
|
| 635 |
+
timesteps,
|
| 636 |
+
noisy_model_input,
|
| 637 |
+
to_final=True,
|
| 638 |
+
self_corr=False,
|
| 639 |
+
)
|
| 640 |
+
y_error = x_1_pred - latent_corr_gt
|
| 641 |
+
|
| 642 |
+
# Check if we're in warmup phase
|
| 643 |
+
if global_step <= args.training_config.buffer_warmup_iter:
|
| 644 |
+
|
| 645 |
+
def gather_with_optional_gpu_dim(tensor, keep_gpu_dim=False):
|
| 646 |
+
gathered = accelerator.gather(tensor)
|
| 647 |
+
|
| 648 |
+
if keep_gpu_dim:
|
| 649 |
+
num_processes = accelerator.num_processes
|
| 650 |
+
batch_size = tensor.shape[0]
|
| 651 |
+
gathered = gathered.view(num_processes, batch_size, *gathered.shape[1:])
|
| 652 |
+
|
| 653 |
+
return gathered
|
| 654 |
+
|
| 655 |
+
# During warmup: gather errors and timesteps from all GPUs and update buffers
|
| 656 |
+
gathered_noise_errors = gather_with_optional_gpu_dim(noise_error, keep_gpu_dim=True)
|
| 657 |
+
gathered_y_errors = gather_with_optional_gpu_dim(y_error, keep_gpu_dim=True)
|
| 658 |
+
gathered_timesteps = gather_with_optional_gpu_dim(timesteps, keep_gpu_dim=True)
|
| 659 |
+
gathered_use_clean = gather_with_optional_gpu_dim(use_clean_input, keep_gpu_dim=True)
|
| 660 |
+
# Shape: [num_gpus, batch_size]
|
| 661 |
+
|
| 662 |
+
clean_mask = gathered_use_clean # [num_gpus, batch_size]
|
| 663 |
+
non_clean_mask = ~clean_mask # [num_gpus, batch_size]
|
| 664 |
+
num_gpus = gathered_noise_errors.shape[0]
|
| 665 |
+
|
| 666 |
+
# Process clean samples: update with probability for each one
|
| 667 |
+
if clean_mask.any():
|
| 668 |
+
for gpu_idx in range(num_gpus):
|
| 669 |
+
gpu_clean_mask = clean_mask[gpu_idx]
|
| 670 |
+
if gpu_clean_mask.any():
|
| 671 |
+
p = random.random()
|
| 672 |
+
if p < args.training_config.clean_buffer_update_prob:
|
| 673 |
+
update_error_buffers_distributed(
|
| 674 |
+
args,
|
| 675 |
+
recycle_vars,
|
| 676 |
+
gathered_noise_errors[gpu_idx : gpu_idx + 1, gpu_clean_mask],
|
| 677 |
+
gathered_y_errors[gpu_idx : gpu_idx + 1, gpu_clean_mask],
|
| 678 |
+
gathered_timesteps[gpu_idx : gpu_idx + 1, gpu_clean_mask],
|
| 679 |
+
noisy_model_input,
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
# Process non-clean samples: always update
|
| 683 |
+
if non_clean_mask.any():
|
| 684 |
+
for gpu_idx in range(num_gpus):
|
| 685 |
+
gpu_non_clean_mask = non_clean_mask[gpu_idx]
|
| 686 |
+
if gpu_non_clean_mask.any():
|
| 687 |
+
update_error_buffers_distributed(
|
| 688 |
+
args,
|
| 689 |
+
recycle_vars,
|
| 690 |
+
gathered_noise_errors[gpu_idx : gpu_idx + 1, gpu_non_clean_mask],
|
| 691 |
+
gathered_y_errors[gpu_idx : gpu_idx + 1, gpu_non_clean_mask],
|
| 692 |
+
gathered_timesteps[gpu_idx : gpu_idx + 1, gpu_non_clean_mask],
|
| 693 |
+
noisy_model_input,
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
else:
|
| 697 |
+
# After warmup: only use local GPU errors
|
| 698 |
+
# Separate clean and non-clean samples
|
| 699 |
+
clean_mask = use_clean_input # Boolean tensor
|
| 700 |
+
non_clean_mask = ~use_clean_input
|
| 701 |
+
|
| 702 |
+
# Process clean samples: update with probability
|
| 703 |
+
if clean_mask.any():
|
| 704 |
+
p = random.random()
|
| 705 |
+
if p < args.training_config.clean_buffer_update_prob:
|
| 706 |
+
update_error_buffers_local(
|
| 707 |
+
args,
|
| 708 |
+
recycle_vars,
|
| 709 |
+
noise_error[clean_mask],
|
| 710 |
+
y_error[clean_mask],
|
| 711 |
+
timesteps[clean_mask],
|
| 712 |
+
noisy_model_input,
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
# Process non-clean samples: always update
|
| 716 |
+
if non_clean_mask.any():
|
| 717 |
+
update_error_buffers_local(
|
| 718 |
+
args,
|
| 719 |
+
recycle_vars,
|
| 720 |
+
noise_error[non_clean_mask],
|
| 721 |
+
y_error[non_clean_mask],
|
| 722 |
+
timesteps[non_clean_mask],
|
| 723 |
+
noisy_model_input,
|
| 724 |
+
)
|
Helios/_DEV/helios/utils/utils_recycle_single.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from .utils_base import apply_schedule_shift
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def apply_error_injection(
|
| 9 |
+
args,
|
| 10 |
+
recycle_vars,
|
| 11 |
+
model_input,
|
| 12 |
+
noise,
|
| 13 |
+
timesteps,
|
| 14 |
+
latents_history_long,
|
| 15 |
+
latents_history_mid,
|
| 16 |
+
latents_history_short,
|
| 17 |
+
model_input_w_error,
|
| 18 |
+
noise_w_error,
|
| 19 |
+
is_keep_x0,
|
| 20 |
+
latent_window_size,
|
| 21 |
+
):
|
| 22 |
+
# Check if buffer has data for the current timestep grid
|
| 23 |
+
current_grid_idx = get_timestep_grid(args, recycle_vars, timesteps, noise)
|
| 24 |
+
has_latent_buffer_data = len(recycle_vars.latent_error_buffer[current_grid_idx]) > 0
|
| 25 |
+
has_y_buffer_data = any(len(buffer) > 0 for buffer in recycle_vars.y_error_buffer.values())
|
| 26 |
+
|
| 27 |
+
add_error_latent = False
|
| 28 |
+
add_error_noise = False
|
| 29 |
+
add_error_y = False
|
| 30 |
+
use_clean_input = False
|
| 31 |
+
|
| 32 |
+
latent_random = random.random()
|
| 33 |
+
noise_random = random.random()
|
| 34 |
+
y_random = random.random()
|
| 35 |
+
clean_random = random.random()
|
| 36 |
+
|
| 37 |
+
if latent_random < args.training_config.latent_prob:
|
| 38 |
+
add_error_latent = True
|
| 39 |
+
if noise_random < args.training_config.noise_prob:
|
| 40 |
+
add_error_noise = True
|
| 41 |
+
if y_random < args.training_config.y_prob:
|
| 42 |
+
add_error_y = True
|
| 43 |
+
if clean_random < args.training_config.clean_prob:
|
| 44 |
+
add_error_noise = False
|
| 45 |
+
add_error_y = False
|
| 46 |
+
add_error_latent = False
|
| 47 |
+
use_clean_input = True
|
| 48 |
+
|
| 49 |
+
if add_error_noise and has_latent_buffer_data:
|
| 50 |
+
noise_error_sampled = sample_noise_error_from_noise_buffer(
|
| 51 |
+
args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device
|
| 52 |
+
)
|
| 53 |
+
noise_w_error = noise + noise_error_sampled.to(model_input.dtype)
|
| 54 |
+
|
| 55 |
+
if add_error_y and has_y_buffer_data:
|
| 56 |
+
len_4x = latents_history_long.shape[2]
|
| 57 |
+
len_2x = latents_history_mid.shape[2]
|
| 58 |
+
len_1x = latents_history_short.shape[2]
|
| 59 |
+
|
| 60 |
+
hist_seq_len = len_4x + len_2x + len_1x
|
| 61 |
+
hist_seq_len_copy = hist_seq_len
|
| 62 |
+
|
| 63 |
+
ori_len_1x = len_1x
|
| 64 |
+
if is_keep_x0:
|
| 65 |
+
len_1x -= 1
|
| 66 |
+
hist_seq_len -= 1
|
| 67 |
+
begin_num = 1
|
| 68 |
+
else:
|
| 69 |
+
begin_num = 0
|
| 70 |
+
|
| 71 |
+
max_windows = hist_seq_len // latent_window_size
|
| 72 |
+
tail_num = hist_seq_len % latent_window_size
|
| 73 |
+
|
| 74 |
+
assert hist_seq_len_copy == tail_num + max_windows * latent_window_size + begin_num
|
| 75 |
+
|
| 76 |
+
tail_latents_history = None
|
| 77 |
+
begin_latents_history = None
|
| 78 |
+
if tail_num != 0:
|
| 79 |
+
tail_latents_history, latents_history_long = (
|
| 80 |
+
latents_history_long[:, :, :tail_num, :, :],
|
| 81 |
+
latents_history_long[:, :, tail_num:, :, :],
|
| 82 |
+
)
|
| 83 |
+
# for tail
|
| 84 |
+
if random.random() < args.training_config.y_prob:
|
| 85 |
+
y_error_sampled = sample_y_error_from_latent_buffer(
|
| 86 |
+
args, recycle_vars, model_input, model_input.dtype, model_input.device
|
| 87 |
+
)
|
| 88 |
+
random_error_num = torch.randint(1, tail_num + 1, (1,)).item()
|
| 89 |
+
tail_latents_history[:, :, -random_error_num:, ...] = (
|
| 90 |
+
tail_latents_history[:, :, -random_error_num:, ...]
|
| 91 |
+
+ y_error_sampled[:, :, -random_error_num:, ...]
|
| 92 |
+
)
|
| 93 |
+
if begin_num != 0:
|
| 94 |
+
begin_latents_history, latents_history_short = (
|
| 95 |
+
latents_history_short[:, :, :begin_num, :, :],
|
| 96 |
+
latents_history_short[:, :, begin_num:, :, :],
|
| 97 |
+
)
|
| 98 |
+
# for begin
|
| 99 |
+
if random.random() < args.training_config.y_prob:
|
| 100 |
+
y_error_sampled = sample_y_error_from_latent_buffer(
|
| 101 |
+
args, recycle_vars, model_input, model_input.dtype, model_input.device
|
| 102 |
+
)
|
| 103 |
+
begin_latents_history = begin_latents_history + y_error_sampled[:, :, :1, ...]
|
| 104 |
+
|
| 105 |
+
# for mid
|
| 106 |
+
mid_latents_history = torch.cat([latents_history_long, latents_history_mid, latents_history_short], dim=2)
|
| 107 |
+
window_num = mid_latents_history.shape[2] // latent_window_size
|
| 108 |
+
assert mid_latents_history.shape[2] % latent_window_size == 0, (
|
| 109 |
+
f"mid length {mid_latents_history.shape[2]} not divisible by window size {latent_window_size}"
|
| 110 |
+
)
|
| 111 |
+
seq_begin = 0
|
| 112 |
+
for _ in range(window_num):
|
| 113 |
+
seq_end = seq_begin + latent_window_size
|
| 114 |
+
if random.random() < args.training_config.y_prob:
|
| 115 |
+
y_error_sampled = sample_y_error_from_latent_buffer(
|
| 116 |
+
args, recycle_vars, model_input, model_input.dtype, model_input.device
|
| 117 |
+
)
|
| 118 |
+
max_start_idx = max(0, y_error_sampled.shape[2] - args.training_config.y_error_num)
|
| 119 |
+
random_frame_idx = torch.randint(0, max_start_idx + 1, (1,)).item()
|
| 120 |
+
error_to_add = y_error_sampled[
|
| 121 |
+
:, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, ...
|
| 122 |
+
]
|
| 123 |
+
# Modify
|
| 124 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :][
|
| 125 |
+
:, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, :
|
| 126 |
+
] = (
|
| 127 |
+
mid_latents_history[:, :, seq_begin:seq_end, :, :][
|
| 128 |
+
:, :, random_frame_idx : random_frame_idx + args.training_config.y_error_num, :, :
|
| 129 |
+
]
|
| 130 |
+
+ error_to_add
|
| 131 |
+
)
|
| 132 |
+
seq_begin = seq_end
|
| 133 |
+
|
| 134 |
+
# recover
|
| 135 |
+
recovers = []
|
| 136 |
+
if tail_latents_history is not None:
|
| 137 |
+
recovers.append(tail_latents_history)
|
| 138 |
+
recovers.append(mid_latents_history[:, :, :-len_1x, :, :])
|
| 139 |
+
if begin_latents_history is not None:
|
| 140 |
+
recovers.append(begin_latents_history)
|
| 141 |
+
recovers.append(mid_latents_history[:, :, -len_1x:, :, :])
|
| 142 |
+
mid_latents_history = torch.cat(recovers, dim=2)
|
| 143 |
+
latents_history_long, latents_history_mid, latents_history_short = mid_latents_history.split(
|
| 144 |
+
[len_4x, len_2x, ori_len_1x], dim=2
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
if add_error_latent and has_latent_buffer_data:
|
| 148 |
+
latent_error_sampled = sample_latent_error_from_latent_buffer(
|
| 149 |
+
args, recycle_vars, model_input, timesteps, model_input.dtype, model_input.device
|
| 150 |
+
)
|
| 151 |
+
model_input_w_error = model_input + latent_error_sampled.to(model_input.dtype)
|
| 152 |
+
|
| 153 |
+
return (
|
| 154 |
+
model_input_w_error,
|
| 155 |
+
noise_w_error,
|
| 156 |
+
latents_history_long,
|
| 157 |
+
latents_history_mid,
|
| 158 |
+
latents_history_short,
|
| 159 |
+
use_clean_input,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def step_recycle(scheduler, model_output, timestep, sample, to_final=False, self_corr=False):
|
| 164 |
+
if isinstance(timestep, torch.Tensor):
|
| 165 |
+
timestep = timestep.cpu()
|
| 166 |
+
timestep_id = torch.argmin((scheduler.temp_timesteps - timestep).abs())
|
| 167 |
+
sigma = scheduler.temp_sigmas[timestep_id]
|
| 168 |
+
if to_final or timestep_id + 1 >= len(scheduler.temp_timesteps):
|
| 169 |
+
sigma_ = 1 if self_corr else 0
|
| 170 |
+
else:
|
| 171 |
+
sigma_ = scheduler.temp_sigmas[timestep_id + 1]
|
| 172 |
+
prev_sample = sample + model_output * (sigma_ - sigma)
|
| 173 |
+
return prev_sample
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def get_timesteps(
|
| 177 |
+
num_inference_steps=50,
|
| 178 |
+
denoising_strength=1,
|
| 179 |
+
shift=1.0,
|
| 180 |
+
num_train_timesteps=1000,
|
| 181 |
+
sigma_max=1.0,
|
| 182 |
+
sigma_min=0.0,
|
| 183 |
+
inverse_timesteps=False,
|
| 184 |
+
extra_one_step=True,
|
| 185 |
+
reverse_sigmas=False,
|
| 186 |
+
):
|
| 187 |
+
sigma_start = sigma_min + (sigma_max - sigma_min) * denoising_strength
|
| 188 |
+
if extra_one_step:
|
| 189 |
+
sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps + 1)[:-1]
|
| 190 |
+
else:
|
| 191 |
+
sigmas = torch.linspace(sigma_start, sigma_min, num_inference_steps)
|
| 192 |
+
if inverse_timesteps:
|
| 193 |
+
sigmas = torch.flip(sigmas, dims=[0])
|
| 194 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
|
| 195 |
+
if reverse_sigmas:
|
| 196 |
+
sigmas = 1 - sigmas
|
| 197 |
+
timesteps = sigmas * num_train_timesteps
|
| 198 |
+
return timesteps, sigmas
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def get_timestep_grid(args, recycle_vars, timesteps, noise):
|
| 202 |
+
"""Get the grid index for a given timesteps."""
|
| 203 |
+
# Handle different timesteps formats (scalar tensor, tensor with batch dim, etc.)
|
| 204 |
+
if isinstance(timesteps, torch.Tensor):
|
| 205 |
+
if timesteps.numel() == 1:
|
| 206 |
+
# Single timesteps value
|
| 207 |
+
timestep_val = timesteps.item()
|
| 208 |
+
else:
|
| 209 |
+
# Tensor with batch dimension, take the first element
|
| 210 |
+
timestep_val = timesteps.flatten()[0].item()
|
| 211 |
+
else:
|
| 212 |
+
# Already a scalar value
|
| 213 |
+
timestep_val = timesteps
|
| 214 |
+
|
| 215 |
+
if args.training_config.use_dynamic_shifting:
|
| 216 |
+
temp_sigmas = apply_schedule_shift(
|
| 217 |
+
recycle_vars.recycle_sigmas,
|
| 218 |
+
noise,
|
| 219 |
+
base_seq_len=args.training_config.base_seq_len,
|
| 220 |
+
max_seq_len=args.training_config.max_seq_len,
|
| 221 |
+
base_shift=args.training_config.base_shift,
|
| 222 |
+
max_shift=args.training_config.max_shift,
|
| 223 |
+
) # torch.Size([2, 1, 1, 1, 1])
|
| 224 |
+
|
| 225 |
+
temp_inferece_timesteps = temp_sigmas * 1000.0 # rescale to [0, 1000.0)
|
| 226 |
+
while temp_inferece_timesteps.ndim > 1:
|
| 227 |
+
temp_inferece_timesteps = temp_inferece_timesteps.squeeze(-1)
|
| 228 |
+
else:
|
| 229 |
+
temp_inferece_timesteps = recycle_vars.recycle_inferece_timesteps
|
| 230 |
+
|
| 231 |
+
# Ensure timesteps is within valid range and calculate grid index
|
| 232 |
+
timestep_val = max(0, min(timestep_val, 999)) # Clamp to [0, 999]
|
| 233 |
+
grid_idx = torch.argmin((temp_inferece_timesteps - timestep_val).abs()).item()
|
| 234 |
+
|
| 235 |
+
# Ensure grid index is within valid range
|
| 236 |
+
max_grid_idx = len(recycle_vars.latent_error_buffer) - 1
|
| 237 |
+
grid_idx = min(grid_idx, max_grid_idx)
|
| 238 |
+
|
| 239 |
+
return grid_idx
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def sample_noise_error_from_noise_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"):
|
| 243 |
+
"""Randomly sample an error from the buffer based on timestep grid."""
|
| 244 |
+
grid_idx = get_timestep_grid(args, recycle_vars, timestep, latents)
|
| 245 |
+
|
| 246 |
+
if not recycle_vars.latent_error_buffer[grid_idx]:
|
| 247 |
+
return torch.zeros_like(latents)
|
| 248 |
+
|
| 249 |
+
# Randomly select one sample from the corresponding grid
|
| 250 |
+
selected_sample = random.choice(recycle_vars.latent_error_buffer[grid_idx])
|
| 251 |
+
error_sample = selected_sample
|
| 252 |
+
|
| 253 |
+
min_mod = 1.0 - args.training_config.error_modulate_factor
|
| 254 |
+
max_mod = 1.0 + args.training_config.error_modulate_factor
|
| 255 |
+
intensity_mod = random.uniform(min_mod, max_mod)
|
| 256 |
+
error_sample = error_sample * intensity_mod
|
| 257 |
+
|
| 258 |
+
error_sample = error_sample.to(device, dtype=dtype)
|
| 259 |
+
|
| 260 |
+
return error_sample
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def sample_latent_error_from_latent_buffer(args, recycle_vars, latents, timestep, dtype=torch.bfloat16, device="cpu"):
|
| 264 |
+
"""Randomly sample an error from the buffer based on timestep grid."""
|
| 265 |
+
grid_idx = get_timestep_grid(args, recycle_vars, timestep, latents)
|
| 266 |
+
|
| 267 |
+
if not recycle_vars.y_error_buffer[grid_idx]:
|
| 268 |
+
return torch.zeros_like(latents)
|
| 269 |
+
|
| 270 |
+
# Randomly select one sample from the corresponding grid
|
| 271 |
+
selected_sample = random.choice(recycle_vars.y_error_buffer[grid_idx])
|
| 272 |
+
error_sample = selected_sample
|
| 273 |
+
|
| 274 |
+
min_mod = 1.0 - args.training_config.error_modulate_factor
|
| 275 |
+
max_mod = 1.0 + args.training_config.error_modulate_factor
|
| 276 |
+
intensity_mod = random.uniform(min_mod, max_mod)
|
| 277 |
+
error_sample = error_sample * intensity_mod
|
| 278 |
+
|
| 279 |
+
error_sample = error_sample.to(device, dtype=dtype)
|
| 280 |
+
|
| 281 |
+
return error_sample
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def sample_y_error_from_latent_buffer(args, recycle_vars, latents, dtype=torch.bfloat16, device="cpu"):
|
| 285 |
+
"""Specially sample y_error from buffer - can be configured to sample from all grids or custom range."""
|
| 286 |
+
# Sample from all grids that have data
|
| 287 |
+
all_samples = []
|
| 288 |
+
for grid_idx, buffer in recycle_vars.y_error_buffer.items():
|
| 289 |
+
if buffer: # Only add non-empty buffers
|
| 290 |
+
all_samples.extend(buffer)
|
| 291 |
+
|
| 292 |
+
if not all_samples:
|
| 293 |
+
return torch.zeros_like(latents)
|
| 294 |
+
|
| 295 |
+
# Randomly select one sample from all available samples
|
| 296 |
+
selected_sample = random.choice(all_samples)
|
| 297 |
+
error_sample = selected_sample
|
| 298 |
+
|
| 299 |
+
min_mod = 1.0 - args.training_config.error_modulate_factor
|
| 300 |
+
max_mod = 1.0 + args.training_config.error_modulate_factor
|
| 301 |
+
intensity_mod = random.uniform(min_mod, max_mod)
|
| 302 |
+
error_sample = error_sample * intensity_mod
|
| 303 |
+
|
| 304 |
+
error_sample = error_sample.to(device, dtype=dtype)
|
| 305 |
+
|
| 306 |
+
return error_sample
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def compute_l2_distance_batch(new_tensor, stored_tensors):
|
| 310 |
+
"""Compute L2 distances between new tensor and all stored tensors efficiently."""
|
| 311 |
+
if not stored_tensors:
|
| 312 |
+
return torch.tensor([])
|
| 313 |
+
|
| 314 |
+
# Stack all stored tensors for batch computation
|
| 315 |
+
stored_stack = torch.stack(stored_tensors) # [num_stored, ...]
|
| 316 |
+
new_flat = new_tensor.flatten()
|
| 317 |
+
stored_flat = stored_stack.flatten(start_dim=1) # [num_stored, flattened_size]
|
| 318 |
+
|
| 319 |
+
# Compute L2 distances in batch
|
| 320 |
+
distances = torch.norm(stored_flat - new_flat.unsqueeze(0), p=2, dim=1)
|
| 321 |
+
return distances
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def compute_l2_distance(tensor1, tensor2):
|
| 325 |
+
"""Compute L2 distance between two tensors"""
|
| 326 |
+
# Flatten tensors
|
| 327 |
+
flat1 = tensor1.flatten()
|
| 328 |
+
flat2 = tensor2.flatten()
|
| 329 |
+
|
| 330 |
+
# Compute L2 distance (Euclidean distance)
|
| 331 |
+
l2_distance = torch.norm(flat1 - flat2, p=2)
|
| 332 |
+
return l2_distance.item()
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def add_error_to_latent_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input):
|
| 336 |
+
"""Add error sample to buffer using specified replacement strategy based on timestep grid."""
|
| 337 |
+
grid_idx = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input)
|
| 338 |
+
error_cpu = error_sample.detach().cpu()
|
| 339 |
+
|
| 340 |
+
if len(recycle_vars.latent_error_buffer[grid_idx]) < args.training_config.error_buffer_size:
|
| 341 |
+
# Buffer not full, simply add
|
| 342 |
+
recycle_vars.latent_error_buffer[grid_idx].append(error_cpu)
|
| 343 |
+
else:
|
| 344 |
+
# Buffer full, use specified replacement strategy
|
| 345 |
+
if args.training_config.buffer_replacement_strategy == "random":
|
| 346 |
+
# Random replacement - O(1), fastest
|
| 347 |
+
replace_idx = random.randint(0, len(recycle_vars.latent_error_buffer[grid_idx]) - 1)
|
| 348 |
+
recycle_vars.latent_error_buffer[grid_idx][replace_idx] = error_cpu
|
| 349 |
+
|
| 350 |
+
elif args.training_config.buffer_replacement_strategy == "fifo":
|
| 351 |
+
# First-in-first-out - O(1), simple queue behavior
|
| 352 |
+
recycle_vars.latent_error_buffer[grid_idx].pop(0)
|
| 353 |
+
recycle_vars.latent_error_buffer[grid_idx].append(error_cpu)
|
| 354 |
+
|
| 355 |
+
elif args.training_config.buffer_replacement_strategy == "l2_batch":
|
| 356 |
+
# Batch L2 computation - O(n) but vectorized, much faster than original
|
| 357 |
+
distances = compute_l2_distance_batch(error_cpu, recycle_vars.latent_error_buffer[grid_idx])
|
| 358 |
+
most_similar_idx = torch.argmin(distances).item()
|
| 359 |
+
recycle_vars.latent_error_buffer[grid_idx][most_similar_idx] = error_cpu
|
| 360 |
+
|
| 361 |
+
elif args.training_config.buffer_replacement_strategy == "l2_similarity":
|
| 362 |
+
# Original L2 similarity method - O(n), slowest but most precise
|
| 363 |
+
min_distance = float("inf")
|
| 364 |
+
most_similar_idx = -1
|
| 365 |
+
|
| 366 |
+
for i, stored_error in enumerate(recycle_vars.latent_error_buffer[grid_idx]):
|
| 367 |
+
distance = compute_l2_distance(error_cpu, stored_error)
|
| 368 |
+
if distance < min_distance:
|
| 369 |
+
min_distance = distance
|
| 370 |
+
most_similar_idx = i
|
| 371 |
+
|
| 372 |
+
if most_similar_idx != -1:
|
| 373 |
+
recycle_vars.latent_error_buffer[grid_idx][most_similar_idx] = error_cpu
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def add_error_to_y_buffer(args, recycle_vars, error_sample, timestep, noisy_model_input):
|
| 377 |
+
"""Add error sample to buffer using specified replacement strategy based on timestep grid."""
|
| 378 |
+
grid_idx = get_timestep_grid(args, recycle_vars, timestep, noisy_model_input)
|
| 379 |
+
error_cpu = error_sample.detach().cpu()
|
| 380 |
+
|
| 381 |
+
if len(recycle_vars.y_error_buffer[grid_idx]) < args.training_config.error_buffer_size:
|
| 382 |
+
# Buffer not full, simply add
|
| 383 |
+
recycle_vars.y_error_buffer[grid_idx].append(error_cpu)
|
| 384 |
+
else:
|
| 385 |
+
# Buffer full, use specified replacement strategy
|
| 386 |
+
if args.training_config.buffer_replacement_strategy == "random":
|
| 387 |
+
# Random replacement - O(1), fastest
|
| 388 |
+
replace_idx = random.randint(0, len(recycle_vars.y_error_buffer[grid_idx]) - 1)
|
| 389 |
+
recycle_vars.y_error_buffer[grid_idx][replace_idx] = error_cpu
|
| 390 |
+
|
| 391 |
+
elif args.training_config.buffer_replacement_strategy == "fifo":
|
| 392 |
+
# First-in-first-out - O(1), simple queue behavior
|
| 393 |
+
recycle_vars.y_error_buffer[grid_idx].pop(0)
|
| 394 |
+
recycle_vars.y_error_buffer[grid_idx].append(error_cpu)
|
| 395 |
+
|
| 396 |
+
elif args.training_config.buffer_replacement_strategy == "l2_batch":
|
| 397 |
+
# Batch L2 computation - O(n) but vectorized, much faster than original
|
| 398 |
+
distances = compute_l2_distance_batch(error_cpu, recycle_vars.y_error_buffer[grid_idx])
|
| 399 |
+
most_similar_idx = torch.argmin(distances).item()
|
| 400 |
+
recycle_vars.y_error_buffer[grid_idx][most_similar_idx] = error_cpu
|
| 401 |
+
|
| 402 |
+
elif args.training_config.buffer_replacement_strategy == "l2_similarity":
|
| 403 |
+
# Original L2 similarity method - O(n), slowest but most precise
|
| 404 |
+
min_distance = float("inf")
|
| 405 |
+
most_similar_idx = -1
|
| 406 |
+
|
| 407 |
+
for i, stored_error in enumerate(recycle_vars.y_error_buffer[grid_idx]):
|
| 408 |
+
distance = compute_l2_distance(error_cpu, stored_error)
|
| 409 |
+
if distance < min_distance:
|
| 410 |
+
min_distance = distance
|
| 411 |
+
most_similar_idx = i
|
| 412 |
+
|
| 413 |
+
if most_similar_idx != -1:
|
| 414 |
+
recycle_vars.y_error_buffer[grid_idx][most_similar_idx] = error_cpu
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def update_error_buffers_distributed(
|
| 418 |
+
args, recycle_vars, gathered_noise_errors, gathered_y_errors, gathered_timesteps, noisy_model_input
|
| 419 |
+
):
|
| 420 |
+
"""Update error buffers with samples gathered from all processes."""
|
| 421 |
+
# gathered_tensors have shape [num_gpus, batch_size, ...] for errors
|
| 422 |
+
# gathered_timesteps have shape [num_gpus, batch_size] for timesteps
|
| 423 |
+
# In this case, batch_size is 1, so shapes are [num_gpus, 1, ...] and [num_gpus, 1]
|
| 424 |
+
num_gpus = gathered_noise_errors.shape[0]
|
| 425 |
+
for i in range(num_gpus):
|
| 426 |
+
noise_error_sample = gathered_noise_errors[i]
|
| 427 |
+
y_error_sample = gathered_y_errors[i]
|
| 428 |
+
timestep_sample = gathered_timesteps[i] # Get the corresponding timestep for this GPU
|
| 429 |
+
|
| 430 |
+
add_error_to_latent_buffer(args, recycle_vars, noise_error_sample, timestep_sample, noisy_model_input)
|
| 431 |
+
add_error_to_y_buffer(args, recycle_vars, y_error_sample, timestep_sample, noisy_model_input)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def update_error_buffers_local(args, recycle_vars, noise_error, y_error, timestep, noisy_model_input):
|
| 435 |
+
"""Update error buffers with samples from local GPU only (post-warmup)."""
|
| 436 |
+
add_error_to_latent_buffer(args, recycle_vars, noise_error, timestep, noisy_model_input)
|
| 437 |
+
add_error_to_y_buffer(args, recycle_vars, y_error, timestep, noisy_model_input)
|
Helios/_DEV/helios/videoalign/__init__.py
ADDED
|
File without changes
|
Helios/_DEV/helios/videoalign/data.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from .prompt_template import build_prompt
|
| 7 |
+
from .vision_process import process_vision_info
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class DataConfig:
|
| 12 |
+
meta_data: str = "/path/to/dataset/meta_data.csv"
|
| 13 |
+
data_dir: str = "/path/to/dataset"
|
| 14 |
+
meta_data_test: str = None
|
| 15 |
+
max_frame_pixels: int = 240 * 320
|
| 16 |
+
num_frames: float = None
|
| 17 |
+
fps: float = 2.0
|
| 18 |
+
p_shuffle_frames: float = 0.0
|
| 19 |
+
p_color_jitter: float = 0.0
|
| 20 |
+
eval_dim: Union[str, List[str]] = "VQ"
|
| 21 |
+
prompt_template_type: str = "none"
|
| 22 |
+
add_noise: bool = False
|
| 23 |
+
sample_type: str = "uniform"
|
| 24 |
+
use_tied_data: bool = True
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def convert_GSB_csv_to_reward_data(
|
| 28 |
+
example,
|
| 29 |
+
data_dir,
|
| 30 |
+
eval_dims=["VQ"],
|
| 31 |
+
max_pixels=448 * 448,
|
| 32 |
+
fps=2.0,
|
| 33 |
+
num_frames=None,
|
| 34 |
+
prompt_template_type="none",
|
| 35 |
+
sample_type="uniform",
|
| 36 |
+
):
|
| 37 |
+
"""
|
| 38 |
+
Convert Good/Same/Bad csv data to reward data.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
example (dict): A dataframe containing the GSB csv data.
|
| 42 |
+
data_dir (str): The directory path to the video files.
|
| 43 |
+
eval_dim (str): The dimension to evaluate ("VQ"/"MQ"/"TA").
|
| 44 |
+
max_pixels (int): The maximum number of pixels allowed for videos.
|
| 45 |
+
num_frames (float): Number of frames.
|
| 46 |
+
prompt_template_type (str): The type of prompt template to use ("none"/"simple"/"video_score").
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
dict: A dictionary containing the reward data.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
A_data = [
|
| 53 |
+
{
|
| 54 |
+
"role": "user",
|
| 55 |
+
"content": [
|
| 56 |
+
{
|
| 57 |
+
"type": "video",
|
| 58 |
+
"video": f"file://{data_dir}/{example['path_A']}",
|
| 59 |
+
"max_pixels": max_pixels,
|
| 60 |
+
"fps": fps if num_frames is None else None,
|
| 61 |
+
"nframes": min(num_frames, example["num_frames_A"]) if num_frames is not None else None,
|
| 62 |
+
"sample_type": sample_type,
|
| 63 |
+
},
|
| 64 |
+
{"type": "text", "text": build_prompt(example["prompt"], eval_dims, prompt_template_type)},
|
| 65 |
+
],
|
| 66 |
+
}
|
| 67 |
+
]
|
| 68 |
+
B_data = [
|
| 69 |
+
{
|
| 70 |
+
"role": "user",
|
| 71 |
+
"content": [
|
| 72 |
+
{
|
| 73 |
+
"type": "video",
|
| 74 |
+
"video": f"file://{data_dir}/{example['path_B']}",
|
| 75 |
+
"max_pixels": max_pixels,
|
| 76 |
+
"fps": fps if num_frames is None else None,
|
| 77 |
+
"nframes": min(num_frames, example["num_frames_B"]) if num_frames is not None else None,
|
| 78 |
+
"sample_type": sample_type,
|
| 79 |
+
},
|
| 80 |
+
{"type": "text", "text": build_prompt(example["prompt"], eval_dims, prompt_template_type)},
|
| 81 |
+
],
|
| 82 |
+
}
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
chosen_labels = []
|
| 86 |
+
A_scores = []
|
| 87 |
+
B_scores = []
|
| 88 |
+
|
| 89 |
+
for eval_dim in eval_dims:
|
| 90 |
+
### chosen_label: 1 if A is chosen, -1 if B is chosen, 0 if tied.
|
| 91 |
+
### 22 if invalid. ooaaeeaa o.O
|
| 92 |
+
try:
|
| 93 |
+
if example[f"{eval_dim}"] is not None:
|
| 94 |
+
if example[f"{eval_dim}"] == "A":
|
| 95 |
+
chosen_label = 1
|
| 96 |
+
elif example[f"{eval_dim}"] == "B":
|
| 97 |
+
chosen_label = -1
|
| 98 |
+
elif example[f"{eval_dim}"] == "same":
|
| 99 |
+
chosen_label = 0
|
| 100 |
+
elif example[f"{eval_dim}"] == "invalid":
|
| 101 |
+
chosen_label = 22
|
| 102 |
+
else:
|
| 103 |
+
chosen_label = 22
|
| 104 |
+
else:
|
| 105 |
+
chosen_label = 22
|
| 106 |
+
except Exception:
|
| 107 |
+
chosen_label = 22
|
| 108 |
+
|
| 109 |
+
chosen_labels.append(chosen_label)
|
| 110 |
+
if f"MOS_A_{eval_dim}" in example and f"MOS_B_{eval_dim}" in example:
|
| 111 |
+
try:
|
| 112 |
+
A_score = example[f"MOS_A_{eval_dim}"] if example[f"MOS_A_{eval_dim}"] is not None else 0.0
|
| 113 |
+
B_score = example[f"MOS_B_{eval_dim}"] if example[f"MOS_B_{eval_dim}"] is not None else 0.0
|
| 114 |
+
except Exception:
|
| 115 |
+
A_score = 0.0
|
| 116 |
+
B_score = 0.0
|
| 117 |
+
A_scores.append(A_score)
|
| 118 |
+
B_scores.append(B_score)
|
| 119 |
+
else:
|
| 120 |
+
A_scores.append(0.0)
|
| 121 |
+
B_scores.append(0.0)
|
| 122 |
+
|
| 123 |
+
chosen_labels = torch.tensor(chosen_labels, dtype=torch.long)
|
| 124 |
+
A_scores = torch.tensor(A_scores, dtype=torch.float)
|
| 125 |
+
B_scores = torch.tensor(B_scores, dtype=torch.float)
|
| 126 |
+
metainfo_idx = None
|
| 127 |
+
if "metainfo_idx" in example:
|
| 128 |
+
metainfo_idx = example["metainfo_idx"]
|
| 129 |
+
|
| 130 |
+
return {
|
| 131 |
+
"A_data": A_data,
|
| 132 |
+
"B_data": B_data,
|
| 133 |
+
"A_scores": A_scores,
|
| 134 |
+
"B_scores": B_scores,
|
| 135 |
+
"chosen_label": chosen_labels,
|
| 136 |
+
"metainfo_idx": metainfo_idx,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class QWen2VLDataCollator:
|
| 141 |
+
def __init__(self, processor, add_noise=False, p_shuffle_frames=0.0, p_color_jitter=0.0):
|
| 142 |
+
self.processor = processor
|
| 143 |
+
self.add_noise = add_noise
|
| 144 |
+
self.set_noise_step = None
|
| 145 |
+
|
| 146 |
+
self.p_shuffle_frames = p_shuffle_frames
|
| 147 |
+
self.p_color_jitter = p_color_jitter
|
| 148 |
+
|
| 149 |
+
self.noise_adder = None
|
| 150 |
+
|
| 151 |
+
def _clean_message(self, message):
|
| 152 |
+
"""
|
| 153 |
+
remove unnecessary keys from message(very very necessary)
|
| 154 |
+
"""
|
| 155 |
+
out_message = [
|
| 156 |
+
{
|
| 157 |
+
"role": "user",
|
| 158 |
+
"content": [
|
| 159 |
+
{
|
| 160 |
+
"type": "video",
|
| 161 |
+
"video": message[0]["content"][0]["video"],
|
| 162 |
+
"max_pixels": message[0]["content"][0]["max_pixels"],
|
| 163 |
+
"fps": message[0]["content"][0]["fps"] if "fps" in message[0]["content"][0] else None,
|
| 164 |
+
"nframes": message[0]["content"][0]["nframes"]
|
| 165 |
+
if "nframes" in message[0]["content"][0]
|
| 166 |
+
else None,
|
| 167 |
+
"sample_type": message[0]["content"][0]["sample_type"]
|
| 168 |
+
if "sample_type" in message[0]["content"][0]
|
| 169 |
+
else "uniform",
|
| 170 |
+
},
|
| 171 |
+
{"type": "text", "text": message[0]["content"][1]["text"]},
|
| 172 |
+
],
|
| 173 |
+
}
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
if out_message[0]["content"][0]["fps"] is None:
|
| 177 |
+
out_message[0]["content"][0].pop("fps")
|
| 178 |
+
if out_message[0]["content"][0]["nframes"] is None:
|
| 179 |
+
out_message[0]["content"][0].pop("nframes")
|
| 180 |
+
|
| 181 |
+
return out_message
|
| 182 |
+
|
| 183 |
+
def _pad_sequence(self, sequences, attention_mask, max_len, padding_side="right"):
|
| 184 |
+
"""
|
| 185 |
+
Pad the sequences to the maximum length.
|
| 186 |
+
"""
|
| 187 |
+
assert padding_side in ["right", "left"]
|
| 188 |
+
if sequences.shape[1] >= max_len:
|
| 189 |
+
return sequences, attention_mask
|
| 190 |
+
|
| 191 |
+
pad_len = max_len - sequences.shape[1]
|
| 192 |
+
padding = (0, pad_len) if padding_side == "right" else (pad_len, 0)
|
| 193 |
+
|
| 194 |
+
sequences_padded = torch.nn.functional.pad(
|
| 195 |
+
sequences, padding, "constant", self.processor.tokenizer.pad_token_id
|
| 196 |
+
)
|
| 197 |
+
attention_mask_padded = torch.nn.functional.pad(attention_mask, padding, "constant", 0)
|
| 198 |
+
|
| 199 |
+
return sequences_padded, attention_mask_padded
|
| 200 |
+
|
| 201 |
+
def __call__(self, features, enable_noise=True):
|
| 202 |
+
"""
|
| 203 |
+
Preprocess inputs to token sequences and return a batch
|
| 204 |
+
"""
|
| 205 |
+
# try:
|
| 206 |
+
features_A = []
|
| 207 |
+
features_B = []
|
| 208 |
+
# check if we have a margin. If we do, we need to batch it as well
|
| 209 |
+
# has_margin = "margin" in features[0]
|
| 210 |
+
has_idx = "metainfo_idx" in features[0] and features[0]["metainfo_idx"] is not None
|
| 211 |
+
|
| 212 |
+
for idx, feature in enumerate(features):
|
| 213 |
+
features_A.append(self._clean_message(feature["A_data"]))
|
| 214 |
+
features_B.append(self._clean_message(feature["B_data"]))
|
| 215 |
+
|
| 216 |
+
# import pdb; pdb.set_trace()
|
| 217 |
+
image_inputs_A, video_inputs_A = process_vision_info(features_A)
|
| 218 |
+
image_inputs_B, video_inputs_B = process_vision_info(features_B)
|
| 219 |
+
|
| 220 |
+
video_inputs_A = [video_inputs_A[i].float() / 255.0 for i in range(len(video_inputs_A))]
|
| 221 |
+
video_inputs_B = [video_inputs_B[i].float() / 255.0 for i in range(len(video_inputs_B))]
|
| 222 |
+
do_rescale = False
|
| 223 |
+
# print(f"{video_inputs_A[0].shape}, {video_inputs_B[0].shape}")
|
| 224 |
+
|
| 225 |
+
# if not enable_noise:
|
| 226 |
+
# print("Not training, no noise added.")
|
| 227 |
+
batch_A = self.processor(
|
| 228 |
+
text=self.processor.apply_chat_template(features_A, tokenize=False, add_generation_prompt=True),
|
| 229 |
+
images=image_inputs_A,
|
| 230 |
+
videos=video_inputs_A,
|
| 231 |
+
padding=True,
|
| 232 |
+
return_tensors="pt",
|
| 233 |
+
videos_kwargs={"do_rescale": do_rescale},
|
| 234 |
+
)
|
| 235 |
+
batch_B = self.processor(
|
| 236 |
+
text=self.processor.apply_chat_template(features_B, tokenize=False, add_generation_prompt=True),
|
| 237 |
+
images=image_inputs_B,
|
| 238 |
+
videos=video_inputs_B,
|
| 239 |
+
padding=True,
|
| 240 |
+
return_tensors="pt",
|
| 241 |
+
videos_kwargs={"do_rescale": do_rescale},
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# pdb.set_trace()
|
| 245 |
+
max_len = max(batch_A["input_ids"].shape[1], batch_B["input_ids"].shape[1])
|
| 246 |
+
batch_A["input_ids"], batch_A["attention_mask"] = self._pad_sequence(
|
| 247 |
+
batch_A["input_ids"], batch_A["attention_mask"], max_len, "right"
|
| 248 |
+
)
|
| 249 |
+
batch_B["input_ids"], batch_B["attention_mask"] = self._pad_sequence(
|
| 250 |
+
batch_B["input_ids"], batch_B["attention_mask"], max_len, "right"
|
| 251 |
+
)
|
| 252 |
+
# print(f"Batch A: {batch_A['input_ids'].shape}, Batch B: {batch_B['input_ids'].shape}")
|
| 253 |
+
|
| 254 |
+
chosen_label = torch.stack([torch.tensor(feature["chosen_label"]) for feature in features])
|
| 255 |
+
|
| 256 |
+
A_scores = torch.stack([torch.tensor(feature["A_scores"]) for feature in features])
|
| 257 |
+
B_scores = torch.stack([torch.tensor(feature["B_scores"]) for feature in features])
|
| 258 |
+
|
| 259 |
+
batch = {
|
| 260 |
+
"A": batch_A,
|
| 261 |
+
"B": batch_B,
|
| 262 |
+
"return_loss": True,
|
| 263 |
+
"chosen_label": chosen_label,
|
| 264 |
+
"A_scores": A_scores,
|
| 265 |
+
"B_scores": B_scores,
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
if has_idx:
|
| 269 |
+
metainfo_idx = torch.stack([torch.tensor(feature["metainfo_idx"]) for feature in features])
|
| 270 |
+
batch["metainfo_idx"] = metainfo_idx
|
| 271 |
+
|
| 272 |
+
# pdb.set_trace()
|
| 273 |
+
return batch
|
| 274 |
+
|
| 275 |
+
# except Exception as e:
|
| 276 |
+
# print(f"Error processing batch: {e} in reading.")
|
| 277 |
+
# # get next batch
|
| 278 |
+
# return None
|
Helios/_DEV/helios/videoalign/inference.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 6 |
+
from collections.abc import Mapping
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from .data import DataConfig
|
| 11 |
+
from .prompt_template import build_prompt
|
| 12 |
+
from .train_reward import create_model_and_processor
|
| 13 |
+
from .utils import ModelConfig, PEFTLoraConfig, TrainingConfig, load_model_from_checkpoint
|
| 14 |
+
from .vision_process import process_video_tensor, process_vision_info
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_configs_from_json(config_path):
|
| 18 |
+
with open(config_path, "r") as f:
|
| 19 |
+
config_dict = json.load(f)
|
| 20 |
+
|
| 21 |
+
# del config_dict["training_args"]["_n_gpu"]
|
| 22 |
+
del config_dict["data_config"]["meta_data"]
|
| 23 |
+
del config_dict["data_config"]["data_dir"]
|
| 24 |
+
|
| 25 |
+
return (
|
| 26 |
+
config_dict["data_config"],
|
| 27 |
+
None,
|
| 28 |
+
config_dict["model_config"],
|
| 29 |
+
config_dict["peft_lora_config"],
|
| 30 |
+
config_dict["inference_config"] if "inference_config" in config_dict else None,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class VideoVLMRewardInference:
|
| 35 |
+
def __init__(self, load_from_pretrained, load_from_pretrained_step=-1, device="cuda", dtype=torch.bfloat16):
|
| 36 |
+
config_path = os.path.join(load_from_pretrained, "model_config.json")
|
| 37 |
+
data_config, _, model_config, peft_lora_config, inference_config = load_configs_from_json(config_path)
|
| 38 |
+
data_config = DataConfig(**data_config)
|
| 39 |
+
model_config = ModelConfig(**model_config)
|
| 40 |
+
peft_lora_config = PEFTLoraConfig(**peft_lora_config)
|
| 41 |
+
|
| 42 |
+
training_args = TrainingConfig(
|
| 43 |
+
load_from_pretrained=load_from_pretrained,
|
| 44 |
+
load_from_pretrained_step=load_from_pretrained_step,
|
| 45 |
+
gradient_checkpointing=False,
|
| 46 |
+
disable_flash_attn2=False,
|
| 47 |
+
bf16=True if dtype == torch.bfloat16 else False,
|
| 48 |
+
fp16=True if dtype == torch.float16 else False,
|
| 49 |
+
output_dir="",
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
model, processor, peft_config = create_model_and_processor(
|
| 53 |
+
model_config=model_config,
|
| 54 |
+
peft_lora_config=peft_lora_config,
|
| 55 |
+
training_args=training_args,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
self.device = device
|
| 59 |
+
|
| 60 |
+
model, checkpoint_step = load_model_from_checkpoint(model, load_from_pretrained, load_from_pretrained_step)
|
| 61 |
+
model.eval()
|
| 62 |
+
|
| 63 |
+
self.model = model
|
| 64 |
+
self.processor = processor
|
| 65 |
+
|
| 66 |
+
self.model.to(self.device)
|
| 67 |
+
|
| 68 |
+
self.data_config = data_config
|
| 69 |
+
|
| 70 |
+
self.inference_config = inference_config
|
| 71 |
+
|
| 72 |
+
def _norm(self, reward):
|
| 73 |
+
if self.inference_config is None:
|
| 74 |
+
return reward
|
| 75 |
+
else:
|
| 76 |
+
reward["VQ"] = (reward["VQ"] - self.inference_config["VQ_mean"]) / self.inference_config["VQ_std"]
|
| 77 |
+
reward["MQ"] = (reward["MQ"] - self.inference_config["MQ_mean"]) / self.inference_config["MQ_std"]
|
| 78 |
+
reward["TA"] = (reward["TA"] - self.inference_config["TA_mean"]) / self.inference_config["TA_std"]
|
| 79 |
+
return reward
|
| 80 |
+
|
| 81 |
+
def _pad_sequence(self, sequences, attention_mask, max_len, padding_side="right"):
|
| 82 |
+
"""
|
| 83 |
+
Pad the sequences to the maximum length.
|
| 84 |
+
"""
|
| 85 |
+
assert padding_side in ["right", "left"]
|
| 86 |
+
if sequences.shape[1] >= max_len:
|
| 87 |
+
return sequences, attention_mask
|
| 88 |
+
|
| 89 |
+
pad_len = max_len - sequences.shape[1]
|
| 90 |
+
padding = (0, pad_len) if padding_side == "right" else (pad_len, 0)
|
| 91 |
+
|
| 92 |
+
sequences_padded = torch.nn.functional.pad(
|
| 93 |
+
sequences, padding, "constant", self.processor.tokenizer.pad_token_id
|
| 94 |
+
)
|
| 95 |
+
attention_mask_padded = torch.nn.functional.pad(attention_mask, padding, "constant", 0)
|
| 96 |
+
|
| 97 |
+
return sequences_padded, attention_mask_padded
|
| 98 |
+
|
| 99 |
+
def _prepare_input(self, data):
|
| 100 |
+
"""
|
| 101 |
+
Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and
|
| 102 |
+
handling potential state.
|
| 103 |
+
"""
|
| 104 |
+
if isinstance(data, Mapping):
|
| 105 |
+
return type(data)({k: self._prepare_input(v) for k, v in data.items()})
|
| 106 |
+
elif isinstance(data, (tuple, list)):
|
| 107 |
+
return type(data)(self._prepare_input(v) for v in data)
|
| 108 |
+
elif isinstance(data, torch.Tensor):
|
| 109 |
+
kwargs = {"device": self.device}
|
| 110 |
+
## TODO: Maybe need to add dtype
|
| 111 |
+
# if self.is_deepspeed_enabled and (torch.is_floating_point(data) or torch.is_complex(data)):
|
| 112 |
+
# # NLP models inputs are int/uint and those get adjusted to the right dtype of the
|
| 113 |
+
# # embedding. Other models such as wav2vec2's inputs are already float and thus
|
| 114 |
+
# # may need special handling to match the dtypes of the model
|
| 115 |
+
# kwargs.update({"dtype": self.accelerator.state.deepspeed_plugin.hf_ds_config.dtype()})
|
| 116 |
+
return data.to(**kwargs)
|
| 117 |
+
return data
|
| 118 |
+
|
| 119 |
+
def _prepare_inputs(self, inputs):
|
| 120 |
+
"""
|
| 121 |
+
Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and
|
| 122 |
+
handling potential state.
|
| 123 |
+
"""
|
| 124 |
+
inputs = self._prepare_input(inputs)
|
| 125 |
+
if len(inputs) == 0:
|
| 126 |
+
raise ValueError
|
| 127 |
+
return inputs
|
| 128 |
+
|
| 129 |
+
def prepare_batch(self, videos, prompts, fps=None, num_frames=None, max_pixels=None):
|
| 130 |
+
"""
|
| 131 |
+
Modified to accept either file paths (str) or Tensors (torch.Tensor) in 'videos'.
|
| 132 |
+
"""
|
| 133 |
+
fps = self.data_config.fps if fps is None else fps
|
| 134 |
+
num_frames = self.data_config.num_frames if num_frames is None else num_frames
|
| 135 |
+
max_pixels = self.data_config.max_frame_pixels if max_pixels is None else max_pixels
|
| 136 |
+
|
| 137 |
+
if isinstance(videos, list) and all(isinstance(v, torch.Tensor) for v in videos):
|
| 138 |
+
chat_data = [
|
| 139 |
+
[
|
| 140 |
+
{
|
| 141 |
+
"role": "user",
|
| 142 |
+
"content": [
|
| 143 |
+
{"type": "video", "video": "file://dummy_path"},
|
| 144 |
+
{
|
| 145 |
+
"type": "text",
|
| 146 |
+
"text": build_prompt(
|
| 147 |
+
prompt, self.data_config.eval_dim, self.data_config.prompt_template_type
|
| 148 |
+
),
|
| 149 |
+
},
|
| 150 |
+
],
|
| 151 |
+
}
|
| 152 |
+
]
|
| 153 |
+
for prompt in prompts
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
image_inputs = None
|
| 157 |
+
video_inputs = [process_video_tensor(tensor) for tensor in videos]
|
| 158 |
+
else:
|
| 159 |
+
if num_frames is None:
|
| 160 |
+
chat_data = [
|
| 161 |
+
[
|
| 162 |
+
{
|
| 163 |
+
"role": "user",
|
| 164 |
+
"content": [
|
| 165 |
+
{
|
| 166 |
+
"type": "video",
|
| 167 |
+
"video": f"file://{video_path}",
|
| 168 |
+
"max_pixels": max_pixels,
|
| 169 |
+
"fps": fps,
|
| 170 |
+
"sample_type": self.data_config.sample_type,
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"type": "text",
|
| 174 |
+
"text": build_prompt(
|
| 175 |
+
prompt, self.data_config.eval_dim, self.data_config.prompt_template_type
|
| 176 |
+
),
|
| 177 |
+
},
|
| 178 |
+
],
|
| 179 |
+
},
|
| 180 |
+
]
|
| 181 |
+
for video_path, prompt in zip(videos, prompts)
|
| 182 |
+
]
|
| 183 |
+
else:
|
| 184 |
+
chat_data = [
|
| 185 |
+
[
|
| 186 |
+
{
|
| 187 |
+
"role": "user",
|
| 188 |
+
"content": [
|
| 189 |
+
{
|
| 190 |
+
"type": "video",
|
| 191 |
+
"video": f"file://{video_path}",
|
| 192 |
+
"max_pixels": max_pixels,
|
| 193 |
+
"nframes": num_frames,
|
| 194 |
+
"sample_type": self.data_config.sample_type,
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"type": "text",
|
| 198 |
+
"text": build_prompt(
|
| 199 |
+
prompt, self.data_config.eval_dim, self.data_config.prompt_template_type
|
| 200 |
+
),
|
| 201 |
+
},
|
| 202 |
+
],
|
| 203 |
+
},
|
| 204 |
+
]
|
| 205 |
+
for video_path, prompt in zip(videos, prompts)
|
| 206 |
+
]
|
| 207 |
+
image_inputs, video_inputs = process_vision_info(chat_data)
|
| 208 |
+
|
| 209 |
+
batch = self.processor(
|
| 210 |
+
text=self.processor.apply_chat_template(chat_data, tokenize=False, add_generation_prompt=True),
|
| 211 |
+
images=image_inputs,
|
| 212 |
+
videos=video_inputs,
|
| 213 |
+
padding=True,
|
| 214 |
+
return_tensors="pt",
|
| 215 |
+
videos_kwargs={"do_rescale": True},
|
| 216 |
+
)
|
| 217 |
+
batch = self._prepare_inputs(batch)
|
| 218 |
+
return batch
|
| 219 |
+
|
| 220 |
+
def reward(
|
| 221 |
+
self,
|
| 222 |
+
videos,
|
| 223 |
+
prompts,
|
| 224 |
+
fps=None,
|
| 225 |
+
num_frames=None,
|
| 226 |
+
max_pixels=None,
|
| 227 |
+
use_norm=True,
|
| 228 |
+
return_batch_score=False,
|
| 229 |
+
device="cpu",
|
| 230 |
+
dtype=torch.float32,
|
| 231 |
+
):
|
| 232 |
+
"""
|
| 233 |
+
videos: List[str] (paths) OR List[torch.Tensor]
|
| 234 |
+
"""
|
| 235 |
+
assert fps is None or num_frames is None, "fps and num_frames cannot be set at the same time."
|
| 236 |
+
|
| 237 |
+
batch = self.prepare_batch(videos, prompts, fps, num_frames, max_pixels)
|
| 238 |
+
rewards = self.model(return_dict=True, **batch)["logits"]
|
| 239 |
+
|
| 240 |
+
rewards = [{"VQ": reward[0].item(), "MQ": reward[1].item(), "TA": reward[2].item()} for reward in rewards]
|
| 241 |
+
for i in range(len(rewards)):
|
| 242 |
+
if use_norm:
|
| 243 |
+
rewards[i] = self._norm(rewards[i])
|
| 244 |
+
rewards[i]["Overall"] = rewards[i]["VQ"] + rewards[i]["MQ"] + rewards[i]["TA"]
|
| 245 |
+
if return_batch_score:
|
| 246 |
+
batch_score = {
|
| 247 |
+
"VQ": torch.tensor(sum(r["VQ"] for r in rewards) / len(rewards), device=device, dtype=dtype),
|
| 248 |
+
"MQ": torch.tensor(sum(r["MQ"] for r in rewards) / len(rewards), device=device, dtype=dtype),
|
| 249 |
+
"TA": torch.tensor(sum(r["TA"] for r in rewards) / len(rewards), device=device, dtype=dtype),
|
| 250 |
+
"Overall": torch.tensor(sum(r["Overall"] for r in rewards) / len(rewards), device=device, dtype=dtype),
|
| 251 |
+
}
|
| 252 |
+
return batch_score
|
| 253 |
+
|
| 254 |
+
return rewards
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def main():
|
| 258 |
+
load_from_pretrained = "/mnt/bn/yufan-dev-my/ysh_new/Ckpts/Videoreward"
|
| 259 |
+
device = "cuda:0"
|
| 260 |
+
dtype = torch.bfloat16
|
| 261 |
+
|
| 262 |
+
inferencer = VideoVLMRewardInference(load_from_pretrained, device=device, dtype=dtype)
|
| 263 |
+
|
| 264 |
+
video_paths = [
|
| 265 |
+
"/mnt/bn/yufan-dev-my/ysh_new/Codes/0_exps/0_results/t2v/short/sana-video/2_240_ori81.mp4",
|
| 266 |
+
"/mnt/bn/yufan-dev-my/ysh_new/Codes/0_exps/0_results/t2v/short/sana-video/4_240_ori81.mp4",
|
| 267 |
+
"/mnt/bn/yufan-dev-my/ysh_new/Codes/0_exps/0_results/t2v/short/sana-video/5_240_ori81.mp4",
|
| 268 |
+
]
|
| 269 |
+
|
| 270 |
+
prompts = [
|
| 271 |
+
"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.",
|
| 272 |
+
"A drone view of waves crashing against the rugged cliffs along Big Sur’s Garay Point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore, casting long shadows. In the distance, a small island with a lighthouse stands tall, its beam piercing the twilight. Green shrubbery covers the cliff’s edge, and the steep drop from the road down to the beach is a dramatic feat, with the cliff’s edges jutting out over the sea. The camera angle provides a bird's-eye view, capturing the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway. The scene is bathed in a warm, golden hue, highlighting the textures and details of the rocky terrain.",
|
| 273 |
+
"A close-up 3D animated scene of a short, fluffy monster kneeling beside a melting red candle. The monster has large, wide eyes and an open mouth, gazing at the flame with a look of wonder and curiosity. Its soft, fluffy fur contrasts with the warm, dramatic lighting that highlights every detail of its gentle, innocent expression. The pose conveys a sense of playfulness and exploration, as if the creature is discovering the world for the first time. The background features a cozy, warmly lit room with subtle hints of a fireplace and soft furnishings, enhancing the overall atmosphere. The use of warm colors and dramatic lighting creates a captivating and inviting scene.",
|
| 274 |
+
]
|
| 275 |
+
|
| 276 |
+
# # Way 1
|
| 277 |
+
print(f"\n{'=' * 20} Way 1: File Path Input {'=' * 20}")
|
| 278 |
+
with torch.no_grad():
|
| 279 |
+
rewards_path = inferencer.reward(video_paths, prompts, use_norm=True)
|
| 280 |
+
print(rewards_path)
|
| 281 |
+
|
| 282 |
+
# Way 2
|
| 283 |
+
print(f"\n{'=' * 20} Way 2: Tensor Input {'=' * 20}")
|
| 284 |
+
from video_reader import PyVideoReader
|
| 285 |
+
|
| 286 |
+
video_tensors = []
|
| 287 |
+
print("Loading videos into Tensors manually...")
|
| 288 |
+
for i, path in enumerate(video_paths):
|
| 289 |
+
vr = PyVideoReader(path, threads=0)
|
| 290 |
+
frames = vr.get_batch(range(len(vr)))
|
| 291 |
+
tensor_input = torch.tensor(frames).permute(0, 3, 1, 2)
|
| 292 |
+
video_tensors.append(tensor_input)
|
| 293 |
+
del video_paths
|
| 294 |
+
|
| 295 |
+
print(f"Loaded {len(video_tensors)} tensors.")
|
| 296 |
+
|
| 297 |
+
with torch.no_grad():
|
| 298 |
+
rewards_tensor = inferencer.reward(
|
| 299 |
+
video_tensors, # [torch.Size([249, 3, 480, 832]), torch.Size([249, 3, 480, 832]), torch.Size([249, 3, 480, 832])]
|
| 300 |
+
prompts,
|
| 301 |
+
use_norm=True,
|
| 302 |
+
return_batch_score=False,
|
| 303 |
+
)
|
| 304 |
+
print(rewards_tensor)
|
| 305 |
+
|
| 306 |
+
# --- 验证环节 ---
|
| 307 |
+
print(f"\n{'=' * 20} Verification {'=' * 20}")
|
| 308 |
+
for i, (r_path, r_tensor) in enumerate(zip(rewards_path, rewards_tensor)):
|
| 309 |
+
score_path = r_path["Overall"]
|
| 310 |
+
score_tensor = r_tensor["Overall"]
|
| 311 |
+
diff = abs(score_path - score_tensor)
|
| 312 |
+
|
| 313 |
+
status = "✅ CONSISTENT" if diff < 1e-3 else "❌ MISMATCH"
|
| 314 |
+
print(f"Video {i + 1}:")
|
| 315 |
+
print(f" Path Input Score: {score_path:.4f}")
|
| 316 |
+
print(f" Tensor Input Score: {score_tensor:.4f}")
|
| 317 |
+
print(f" Difference: {diff:.6f} -> {status}")
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
main()
|
Helios/_DEV/helios/videoalign/prompt_template.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
VIDEOSCORE_QUERY_PROMPT = """
|
| 2 |
+
Suppose you are an expert in judging and evaluating the quality of AI-generated videos,
|
| 3 |
+
please watch the frames of a given video and see the text prompt for generating the video,
|
| 4 |
+
then give scores based on its {dimension_name}, i.e., {dimension_description}.
|
| 5 |
+
Output a float number from 1.0 to 5.0 for this dimension,
|
| 6 |
+
the higher the number is, the better the video performs in that sub-score,
|
| 7 |
+
the lowest 1.0 means Bad, the highest 5.0 means Perfect/Real (the video is like a real video).
|
| 8 |
+
The text prompt used for generation is "{text_prompt}".
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
DIMENSION_DESCRIPTIONS = {
|
| 12 |
+
"VQ": ["visual quality", "the quality of the video in terms of clearness, resolution, brightness, and color"],
|
| 13 |
+
"TA": ["text-to-video alignment", "the alignment between the text prompt and the video content and motion"],
|
| 14 |
+
"MQ": ["motion quality", "the quality of the motion in terms of consistency, smoothness, and completeness"],
|
| 15 |
+
"Overall": [
|
| 16 |
+
"Overall Performance",
|
| 17 |
+
"the overall performance of the video in terms of visual quality, text-to-video alignment, and motion quality",
|
| 18 |
+
],
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
SIMPLE_PROMPT = """
|
| 22 |
+
Please evaluate the {dimension_name} of a generated video. Consider {dimension_description}.
|
| 23 |
+
The text prompt used for generation is "{text_prompt}".
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
DETAILED_PROMPT_WITH_SPECIAL_TOKEN = """
|
| 27 |
+
You are tasked with evaluating a generated video based on three distinct criteria: Visual Quality, Motion Quality, and Text Alignment. Please provide a rating from 0 to 10 for each of the three categories, with 0 being the worst and 10 being the best. Each evaluation should be independent of the others.
|
| 28 |
+
|
| 29 |
+
**Visual Quality:**
|
| 30 |
+
Evaluate the overall visual quality of the video, with a focus on static factors. The following sub-dimensions should be considered:
|
| 31 |
+
- **Reasonableness:** The video should not contain any significant biological or logical errors, such as abnormal body structures or nonsensical environmental setups.
|
| 32 |
+
- **Clarity:** Evaluate the sharpness and visibility of the video. The image should be clear and easy to interpret, with no blurring or indistinct areas.
|
| 33 |
+
- **Detail Richness:** Consider the level of detail in textures, materials, lighting, and other visual elements (e.g., hair, clothing, shadows).
|
| 34 |
+
- **Aesthetic and Creativity:** Assess the artistic aspects of the video, including the color scheme, composition, atmosphere, depth of field, and the overall creative appeal. The scene should convey a sense of harmony and balance.
|
| 35 |
+
- **Safety:** The video should not contain harmful or inappropriate content, such as political, violent, or adult material. If such content is present, the image quality and satisfaction score should be the lowest possible.
|
| 36 |
+
|
| 37 |
+
Please provide the ratings of Visual Quality: <|VQ_reward|>
|
| 38 |
+
END
|
| 39 |
+
|
| 40 |
+
**Motion Quality:**
|
| 41 |
+
Assess the dynamic aspects of the video, with a focus on dynamic factors. Consider the following sub-dimensions:
|
| 42 |
+
- **Stability:** Evaluate the continuity and stability between frames. There should be no sudden, unnatural jumps, and the video should maintain stable attributes (e.g., no fluctuating colors, textures, or missing body parts).
|
| 43 |
+
- **Naturalness:** The movement should align with physical laws and be realistic. For example, clothing should flow naturally with motion, and facial expressions should change appropriately (e.g., blinking, mouth movements).
|
| 44 |
+
- **Aesthetic Quality:** The movement should be smooth and fluid. The transitions between different motions or camera angles should be seamless, and the overall dynamic feel should be visually pleasing.
|
| 45 |
+
- **Fusion:** Ensure that elements in motion (e.g., edges of the subject, hair, clothing) blend naturally with the background, without obvious artifacts or the feeling of cut-and-paste effects.
|
| 46 |
+
- **Clarity of Motion:** The video should be clear and smooth in motion. Pay attention to any areas where the video might have blurry or unsteady sections that hinder visual continuity.
|
| 47 |
+
- **Amplitude:** If the video is largely static or has little movement, assign a low score for motion quality.
|
| 48 |
+
|
| 49 |
+
Please provide the ratings of Motion Quality: <|MQ_reward|>
|
| 50 |
+
END
|
| 51 |
+
|
| 52 |
+
**Text Alignment:**
|
| 53 |
+
Assess how well the video matches the textual prompt across the following sub-dimensions:
|
| 54 |
+
- **Subject Relevance** Evaluate how accurately the subject(s) in the video (e.g., person, animal, object) align with the textual description. The subject should match the description in terms of number, appearance, and behavior.
|
| 55 |
+
- **Motion Relevance:** Evaluate if the dynamic actions (e.g., gestures, posture, facial expressions like talking or blinking) align with the described prompt. The motion should match the prompt in terms of type, scale, and direction.
|
| 56 |
+
- **Environment Relevance:** Assess whether the background and scene fit the prompt. This includes checking if real-world locations or scenes are accurately represented, though some stylistic adaptation is acceptable.
|
| 57 |
+
- **Style Relevance:** If the prompt specifies a particular artistic or stylistic style, evaluate how well the video adheres to this style.
|
| 58 |
+
- **Camera Movement Relevance:** Check if the camera movements (e.g., following the subject, focus shifts) are consistent with the expected behavior from the prompt.
|
| 59 |
+
|
| 60 |
+
Textual prompt - {text_prompt}
|
| 61 |
+
Please provide the ratings of Text Alignment: <|TA_reward|>
|
| 62 |
+
END
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
DETAILED_PROMPT = """
|
| 66 |
+
You are tasked with evaluating a generated video based on three distinct criteria: Visual Quality, Motion Quality, and Text Alignment. Please provide a rating from 0 to 10 for each of the three categories, with 0 being the worst and 10 being the best. Each evaluation should be independent of the others.
|
| 67 |
+
|
| 68 |
+
**Visual Quality:**
|
| 69 |
+
Evaluate the overall visual quality of the video, with a focus on static factors. The following sub-dimensions should be considered:
|
| 70 |
+
- **Reasonableness:** The video should not contain any significant biological or logical errors, such as abnormal body structures or nonsensical environmental setups.
|
| 71 |
+
- **Clarity:** Evaluate the sharpness and visibility of the video. The image should be clear and easy to interpret, with no blurring or indistinct areas.
|
| 72 |
+
- **Detail Richness:** Consider the level of detail in textures, materials, lighting, and other visual elements (e.g., hair, clothing, shadows).
|
| 73 |
+
- **Aesthetic and Creativity:** Assess the artistic aspects of the video, including the color scheme, composition, atmosphere, depth of field, and the overall creative appeal. The scene should convey a sense of harmony and balance.
|
| 74 |
+
- **Safety:** The video should not contain harmful or inappropriate content, such as political, violent, or adult material. If such content is present, the image quality and satisfaction score should be the lowest possible.
|
| 75 |
+
|
| 76 |
+
**Motion Quality:**
|
| 77 |
+
Assess the dynamic aspects of the video, with a focus on dynamic factors. Consider the following sub-dimensions:
|
| 78 |
+
- **Stability:** Evaluate the continuity and stability between frames. There should be no sudden, unnatural jumps, and the video should maintain stable attributes (e.g., no fluctuating colors, textures, or missing body parts).
|
| 79 |
+
- **Naturalness:** The movement should align with physical laws and be realistic. For example, clothing should flow naturally with motion, and facial expressions should change appropriately (e.g., blinking, mouth movements).
|
| 80 |
+
- **Aesthetic Quality:** The movement should be smooth and fluid. The transitions between different motions or camera angles should be seamless, and the overall dynamic feel should be visually pleasing.
|
| 81 |
+
- **Fusion:** Ensure that elements in motion (e.g., edges of the subject, hair, clothing) blend naturally with the background, without obvious artifacts or the feeling of cut-and-paste effects.
|
| 82 |
+
- **Clarity of Motion:** The video should be clear and smooth in motion. Pay attention to any areas where the video might have blurry or unsteady sections that hinder visual continuity.
|
| 83 |
+
- **Amplitude:** If the video is largely static or has little movement, assign a low score for motion quality.
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
**Text Alignment:**
|
| 87 |
+
Assess how well the video matches the textual prompt across the following sub-dimensions:
|
| 88 |
+
- **Subject Relevance** Evaluate how accurately the subject(s) in the video (e.g., person, animal, object) align with the textual description. The subject should match the description in terms of number, appearance, and behavior.
|
| 89 |
+
- **Motion Relevance:** Evaluate if the dynamic actions (e.g., gestures, posture, facial expressions like talking or blinking) align with the described prompt. The motion should match the prompt in terms of type, scale, and direction.
|
| 90 |
+
- **Environment Relevance:** Assess whether the background and scene fit the prompt. This includes checking if real-world locations or scenes are accurately represented, though some stylistic adaptation is acceptable.
|
| 91 |
+
- **Style Relevance:** If the prompt specifies a particular artistic or stylistic style, evaluate how well the video adheres to this style.
|
| 92 |
+
- **Camera Movement Relevance:** Check if the camera movements (e.g., following the subject, focus shifts) are consistent with the expected behavior from the prompt.
|
| 93 |
+
|
| 94 |
+
Textual prompt - {text_prompt}
|
| 95 |
+
Please provide the ratings of Visual Quality, Motion Quality, and Text Alignment.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
SIMPLE_PROMPT_NO_PROMPT = """
|
| 99 |
+
Please evaluate the {dimension_name} of a generated video. Consider {dimension_description}.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def build_prompt(prompt, dimension, template_type):
|
| 104 |
+
if isinstance(dimension, list) and len(dimension) > 1:
|
| 105 |
+
dimension_name = ", ".join([DIMENSION_DESCRIPTIONS[d][0] for d in dimension])
|
| 106 |
+
dimension_name = f"overall performance({dimension_name})"
|
| 107 |
+
dimension_description = "the overall performance of the video"
|
| 108 |
+
else:
|
| 109 |
+
if isinstance(dimension, list):
|
| 110 |
+
dimension = dimension[0]
|
| 111 |
+
dimension_name = DIMENSION_DESCRIPTIONS[dimension][0]
|
| 112 |
+
dimension_description = DIMENSION_DESCRIPTIONS[dimension][1]
|
| 113 |
+
|
| 114 |
+
if template_type == "none":
|
| 115 |
+
return prompt
|
| 116 |
+
elif template_type == "simple":
|
| 117 |
+
return SIMPLE_PROMPT.format(
|
| 118 |
+
dimension_name=dimension_name, dimension_description=dimension_description, text_prompt=prompt
|
| 119 |
+
)
|
| 120 |
+
elif template_type == "video_score":
|
| 121 |
+
return VIDEOSCORE_QUERY_PROMPT.format(
|
| 122 |
+
dimension_name=dimension_name, dimension_description=dimension_description, text_prompt=prompt
|
| 123 |
+
)
|
| 124 |
+
elif template_type == "detailed_special":
|
| 125 |
+
return DETAILED_PROMPT_WITH_SPECIAL_TOKEN.format(text_prompt=prompt)
|
| 126 |
+
elif template_type == "detailed":
|
| 127 |
+
return DETAILED_PROMPT.format(text_prompt=prompt)
|
| 128 |
+
else:
|
| 129 |
+
raise ValueError("Invalid template type")
|
Helios/_DEV/helios/videoalign/train_reward.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from peft import LoraConfig, get_peft_model
|
| 3 |
+
from transformers import AutoProcessor
|
| 4 |
+
|
| 5 |
+
from diffusers.utils import is_flash_attn_3_available, is_flash_attn_available
|
| 6 |
+
|
| 7 |
+
from .trainer import Qwen2VLRewardModelBT
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def find_target_linear_names(model, num_lora_modules=-1, lora_namespan_exclude=[], verbose=False):
|
| 11 |
+
"""
|
| 12 |
+
Find the target linear modules for LoRA.
|
| 13 |
+
"""
|
| 14 |
+
linear_cls = torch.nn.Linear
|
| 15 |
+
embedding_cls = torch.nn.Embedding
|
| 16 |
+
lora_module_names = []
|
| 17 |
+
|
| 18 |
+
for name, module in model.named_modules():
|
| 19 |
+
if any(ex_keyword in name for ex_keyword in lora_namespan_exclude):
|
| 20 |
+
# print(f"Excluding module: {name}")
|
| 21 |
+
continue
|
| 22 |
+
|
| 23 |
+
if isinstance(module, (linear_cls, embedding_cls)):
|
| 24 |
+
lora_module_names.append(name)
|
| 25 |
+
|
| 26 |
+
if num_lora_modules > 0:
|
| 27 |
+
lora_module_names = lora_module_names[-num_lora_modules:]
|
| 28 |
+
if verbose:
|
| 29 |
+
print(f"Found {len(lora_module_names)} lora modules: {lora_module_names}")
|
| 30 |
+
return lora_module_names
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def set_requires_grad(parameters, requires_grad):
|
| 34 |
+
for p in parameters:
|
| 35 |
+
p.requires_grad = requires_grad
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def create_model_and_processor(
|
| 39 |
+
model_config,
|
| 40 |
+
peft_lora_config,
|
| 41 |
+
training_args,
|
| 42 |
+
cache_dir=None,
|
| 43 |
+
):
|
| 44 |
+
# create model
|
| 45 |
+
torch_dtype = (
|
| 46 |
+
model_config.torch_dtype
|
| 47 |
+
if model_config.torch_dtype in ["auto", None]
|
| 48 |
+
else getattr(torch, model_config.torch_dtype)
|
| 49 |
+
)
|
| 50 |
+
model_kwargs = {
|
| 51 |
+
"revision": model_config.model_revision,
|
| 52 |
+
"use_cache": True if training_args.gradient_checkpointing else False,
|
| 53 |
+
}
|
| 54 |
+
# pdb.set_trace()
|
| 55 |
+
|
| 56 |
+
# create processor and set padding
|
| 57 |
+
processor = AutoProcessor.from_pretrained(
|
| 58 |
+
model_config.model_name_or_path, padding_side="right", cache_dir=cache_dir
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
special_token_ids = None
|
| 62 |
+
if model_config.use_special_tokens:
|
| 63 |
+
special_tokens = ["<|VQ_reward|>", "<|MQ_reward|>", "<|TA_reward|>"]
|
| 64 |
+
processor.tokenizer.add_special_tokens({"additional_special_tokens": special_tokens})
|
| 65 |
+
special_token_ids = processor.tokenizer.convert_tokens_to_ids(special_tokens)
|
| 66 |
+
|
| 67 |
+
if is_flash_attn_3_available():
|
| 68 |
+
attn_implementation = "flash_attention_3"
|
| 69 |
+
elif is_flash_attn_available():
|
| 70 |
+
attn_implementation = "flash_attention_2"
|
| 71 |
+
else:
|
| 72 |
+
attn_implementation = "sdpa"
|
| 73 |
+
|
| 74 |
+
print(f"Using {attn_implementation} for Reward!")
|
| 75 |
+
|
| 76 |
+
model = Qwen2VLRewardModelBT.from_pretrained(
|
| 77 |
+
model_config.model_name_or_path,
|
| 78 |
+
output_dim=model_config.output_dim,
|
| 79 |
+
reward_token=model_config.reward_token,
|
| 80 |
+
special_token_ids=special_token_ids,
|
| 81 |
+
dtype=torch_dtype,
|
| 82 |
+
attn_implementation=attn_implementation,
|
| 83 |
+
cache_dir=cache_dir,
|
| 84 |
+
**model_kwargs,
|
| 85 |
+
)
|
| 86 |
+
if model_config.use_special_tokens:
|
| 87 |
+
model.resize_token_embeddings(len(processor.tokenizer))
|
| 88 |
+
|
| 89 |
+
if training_args.bf16:
|
| 90 |
+
model.to(torch.bfloat16)
|
| 91 |
+
if training_args.fp16:
|
| 92 |
+
model.to(torch.float16)
|
| 93 |
+
|
| 94 |
+
# create lora and peft model
|
| 95 |
+
if peft_lora_config.lora_enable:
|
| 96 |
+
target_modules = find_target_linear_names(
|
| 97 |
+
model,
|
| 98 |
+
num_lora_modules=peft_lora_config.num_lora_modules,
|
| 99 |
+
lora_namespan_exclude=peft_lora_config.lora_namespan_exclude,
|
| 100 |
+
)
|
| 101 |
+
peft_config = LoraConfig(
|
| 102 |
+
target_modules=target_modules,
|
| 103 |
+
r=peft_lora_config.lora_r,
|
| 104 |
+
lora_alpha=peft_lora_config.lora_alpha,
|
| 105 |
+
lora_dropout=peft_lora_config.lora_dropout,
|
| 106 |
+
task_type=peft_lora_config.lora_task_type,
|
| 107 |
+
use_rslora=peft_lora_config.use_rslora,
|
| 108 |
+
bias="none",
|
| 109 |
+
modules_to_save=peft_lora_config.lora_modules_to_save,
|
| 110 |
+
)
|
| 111 |
+
model = get_peft_model(model, peft_config)
|
| 112 |
+
else:
|
| 113 |
+
peft_config = None
|
| 114 |
+
|
| 115 |
+
model.config.tokenizer_padding_side = processor.tokenizer.padding_side
|
| 116 |
+
model.config.pad_token_id = processor.tokenizer.pad_token_id
|
| 117 |
+
|
| 118 |
+
return model, processor, peft_config
|
Helios/_DEV/helios/videoalign/trainer.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# from training.train_utils import get_peft_state_maybe_zero_3, get_peft_state_non_lora_maybe_zero_3
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from transformers import Qwen2VLForConditionalGeneration
|
| 7 |
+
from transformers.trainer import (
|
| 8 |
+
is_torch_xla_available,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if is_torch_xla_available():
|
| 13 |
+
pass
|
| 14 |
+
else:
|
| 15 |
+
IS_XLA_FSDPV2_POST_2_2 = False
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Qwen2VLRewardModelBT(Qwen2VLForConditionalGeneration):
|
| 19 |
+
def __init__(self, config, output_dim=4, reward_token="last", special_token_ids=None):
|
| 20 |
+
super().__init__(config)
|
| 21 |
+
# pdb.set_trace()
|
| 22 |
+
self.output_dim = output_dim
|
| 23 |
+
self.rm_head = nn.Linear(config.hidden_size, output_dim, bias=False)
|
| 24 |
+
self.reward_token = reward_token
|
| 25 |
+
|
| 26 |
+
self.special_token_ids = special_token_ids
|
| 27 |
+
if self.special_token_ids is not None:
|
| 28 |
+
self.reward_token = "special"
|
| 29 |
+
|
| 30 |
+
def forward(
|
| 31 |
+
self,
|
| 32 |
+
input_ids: torch.LongTensor = None,
|
| 33 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 34 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 35 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 36 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 37 |
+
labels: Optional[torch.LongTensor] = None,
|
| 38 |
+
use_cache: Optional[bool] = None,
|
| 39 |
+
output_attentions: Optional[bool] = None,
|
| 40 |
+
output_hidden_states: Optional[bool] = None,
|
| 41 |
+
return_dict: Optional[bool] = None,
|
| 42 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 43 |
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
| 44 |
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
| 45 |
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
| 46 |
+
rope_deltas: Optional[torch.LongTensor] = None,
|
| 47 |
+
):
|
| 48 |
+
## modified from the origin class Qwen2VLForConditionalGeneration
|
| 49 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 50 |
+
output_hidden_states = (
|
| 51 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 52 |
+
)
|
| 53 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 54 |
+
# pdb.set_trace()
|
| 55 |
+
if inputs_embeds is None:
|
| 56 |
+
# inputs_embeds = self.model.embed_tokens(input_ids)
|
| 57 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 58 |
+
if pixel_values is not None:
|
| 59 |
+
pixel_values = pixel_values.type(self.visual.get_dtype())
|
| 60 |
+
image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
|
| 61 |
+
image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1).expand_as(inputs_embeds)
|
| 62 |
+
image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 63 |
+
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
|
| 64 |
+
|
| 65 |
+
if pixel_values_videos is not None:
|
| 66 |
+
pixel_values_videos = pixel_values_videos.type(self.visual.get_dtype())
|
| 67 |
+
video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
|
| 68 |
+
video_mask = (input_ids == self.config.video_token_id).unsqueeze(-1).expand_as(inputs_embeds)
|
| 69 |
+
video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 70 |
+
inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
|
| 71 |
+
|
| 72 |
+
if attention_mask is not None:
|
| 73 |
+
attention_mask = attention_mask.to(inputs_embeds.device)
|
| 74 |
+
|
| 75 |
+
outputs = self.model(
|
| 76 |
+
input_ids=None,
|
| 77 |
+
position_ids=position_ids,
|
| 78 |
+
attention_mask=attention_mask,
|
| 79 |
+
past_key_values=past_key_values,
|
| 80 |
+
inputs_embeds=inputs_embeds,
|
| 81 |
+
use_cache=use_cache,
|
| 82 |
+
output_attentions=output_attentions,
|
| 83 |
+
output_hidden_states=output_hidden_states,
|
| 84 |
+
return_dict=return_dict,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
hidden_states = outputs[0] # [B, L, D]
|
| 88 |
+
|
| 89 |
+
logits = self.rm_head(hidden_states) # [B, L, N]
|
| 90 |
+
|
| 91 |
+
if input_ids is not None:
|
| 92 |
+
batch_size = input_ids.shape[0]
|
| 93 |
+
else:
|
| 94 |
+
batch_size = inputs_embeds.shape[0]
|
| 95 |
+
|
| 96 |
+
## get sequence length
|
| 97 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 98 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 99 |
+
if self.config.pad_token_id is None:
|
| 100 |
+
sequence_lengths = -1
|
| 101 |
+
else:
|
| 102 |
+
if input_ids is not None:
|
| 103 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 104 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 105 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 106 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 107 |
+
else:
|
| 108 |
+
sequence_lengths = -1
|
| 109 |
+
|
| 110 |
+
## get the last token's logits
|
| 111 |
+
if self.reward_token == "last":
|
| 112 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 113 |
+
elif self.reward_token == "mean":
|
| 114 |
+
## get the mean of all valid tokens' logits
|
| 115 |
+
valid_lengths = torch.clamp(sequence_lengths, min=0, max=logits.size(1) - 1)
|
| 116 |
+
pooled_logits = torch.stack([logits[i, : valid_lengths[i]].mean(dim=0) for i in range(batch_size)])
|
| 117 |
+
elif self.reward_token == "special":
|
| 118 |
+
# special_token_ids = self.tokenizer.convert_tokens_to_ids(self.special_tokens)
|
| 119 |
+
# create a mask for special tokens
|
| 120 |
+
special_token_mask = torch.zeros_like(input_ids, dtype=torch.bool)
|
| 121 |
+
for special_token_id in self.special_token_ids:
|
| 122 |
+
special_token_mask = special_token_mask | (input_ids == special_token_id)
|
| 123 |
+
pooled_logits = logits[special_token_mask, ...]
|
| 124 |
+
pooled_logits = pooled_logits.view(batch_size, 3, -1) # [B, 3, N] assert 3 attributes
|
| 125 |
+
if self.output_dim == 3:
|
| 126 |
+
pooled_logits = pooled_logits.diagonal(dim1=1, dim2=2)
|
| 127 |
+
pooled_logits = pooled_logits.view(batch_size, -1)
|
| 128 |
+
|
| 129 |
+
# pdb.set_trace()
|
| 130 |
+
else:
|
| 131 |
+
raise ValueError("Invalid reward_token")
|
| 132 |
+
|
| 133 |
+
return {"logits": pooled_logits}
|
Helios/_DEV/helios/videoalign/utils.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import os
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from typing import List, Literal, Optional
|
| 5 |
+
|
| 6 |
+
import safetensors
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import TrainingArguments
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
########## DataClass For Configure ##########
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class TrainingConfig(TrainingArguments):
|
| 16 |
+
max_length: Optional[int] = None
|
| 17 |
+
dataset_num_proc: Optional[int] = None
|
| 18 |
+
center_rewards_coefficient: Optional[float] = None
|
| 19 |
+
disable_flash_attn2: bool = field(default=False)
|
| 20 |
+
|
| 21 |
+
vision_lr: Optional[float] = None
|
| 22 |
+
merger_lr: Optional[float] = None
|
| 23 |
+
special_token_lr: Optional[float] = None
|
| 24 |
+
|
| 25 |
+
conduct_eval: Optional[bool] = True
|
| 26 |
+
load_from_pretrained: str = None
|
| 27 |
+
load_from_pretrained_step: int = None
|
| 28 |
+
logging_epochs: Optional[float] = None
|
| 29 |
+
eval_epochs: Optional[float] = None
|
| 30 |
+
save_epochs: Optional[float] = None
|
| 31 |
+
remove_unused_columns: Optional[bool] = False
|
| 32 |
+
|
| 33 |
+
save_full_model: Optional[bool] = False
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class PEFTLoraConfig:
|
| 38 |
+
lora_enable: bool = False
|
| 39 |
+
vision_lora: bool = False
|
| 40 |
+
lora_r: int = 16
|
| 41 |
+
lora_alpha: int = 32
|
| 42 |
+
lora_dropout: float = 0.05
|
| 43 |
+
lora_target_modules: Optional[List[str]] = None
|
| 44 |
+
lora_namespan_exclude: Optional[List[str]] = None
|
| 45 |
+
lora_modules_to_save: Optional[List[str]] = None
|
| 46 |
+
lora_task_type: str = "CAUSAL_LM"
|
| 47 |
+
use_rslora: bool = False
|
| 48 |
+
num_lora_modules: int = -1
|
| 49 |
+
|
| 50 |
+
def __post_init__(self):
|
| 51 |
+
if isinstance(self.lora_target_modules, list) and len(self.lora_target_modules) == 1:
|
| 52 |
+
self.lora_target_modules = self.lora_target_modules[0]
|
| 53 |
+
|
| 54 |
+
if isinstance(self.lora_namespan_exclude, list) and len(self.lora_namespan_exclude) == 1:
|
| 55 |
+
self.lora_namespan_exclude = self.lora_namespan_exclude[0]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class ModelConfig:
|
| 60 |
+
model_name_or_path: Optional[str] = None
|
| 61 |
+
model_revision: str = "main"
|
| 62 |
+
|
| 63 |
+
output_dim: int = 1
|
| 64 |
+
|
| 65 |
+
use_special_tokens: bool = False
|
| 66 |
+
|
| 67 |
+
freeze_vision_tower: bool = field(default=False)
|
| 68 |
+
freeze_llm: bool = field(default=False)
|
| 69 |
+
tune_merger: bool = field(default=False)
|
| 70 |
+
|
| 71 |
+
torch_dtype: Optional[Literal["auto", "bfloat16", "float16", "float32"]] = None
|
| 72 |
+
trust_remote_code: bool = False
|
| 73 |
+
attn_implementation: Optional[str] = None
|
| 74 |
+
load_in_8bit: bool = False
|
| 75 |
+
load_in_4bit: bool = False
|
| 76 |
+
bnb_4bit_quant_type: Literal["fp4", "nf4"] = "nf4"
|
| 77 |
+
use_bnb_nested_quant: bool = False
|
| 78 |
+
reward_token: Literal["last", "mean", "special"] = "last"
|
| 79 |
+
loss_type: Literal["bt", "reg", "btt", "margin", "constant_margin", "scaled"] = "regular"
|
| 80 |
+
|
| 81 |
+
def __post_init__(self):
|
| 82 |
+
if self.load_in_8bit and self.load_in_4bit:
|
| 83 |
+
raise ValueError("You can't use 8 bit and 4 bit precision at the same time")
|
| 84 |
+
|
| 85 |
+
# if isinstance(self.lora_target_modules, list) and len(self.lora_target_modules) == 1:
|
| 86 |
+
# self.lora_target_modules = self.lora_target_modules[0]
|
| 87 |
+
|
| 88 |
+
# if isinstance(self.lora_namespan_exclude, list) and len(self.lora_namespan_exclude) == 1:
|
| 89 |
+
# self.lora_namespan_exclude = self.lora_namespan_exclude[0]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
########## Functions for get trainable modules' parameters ##########
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
| 96 |
+
from deepspeed import zero
|
| 97 |
+
|
| 98 |
+
if hasattr(param, "ds_id"):
|
| 99 |
+
# if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
| 100 |
+
# if not ignore_status:
|
| 101 |
+
# logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
|
| 102 |
+
with zero.GatheredParameters([param]):
|
| 103 |
+
param = param.data.detach().cpu().clone()
|
| 104 |
+
else:
|
| 105 |
+
param = param.detach().cpu().clone()
|
| 106 |
+
return param
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# Borrowed from peft.utils.get_peft_model_state_dict
|
| 110 |
+
def get_peft_state_maybe_zero_3(named_params, bias):
|
| 111 |
+
if bias == "none":
|
| 112 |
+
to_return = {k: t for k, t in named_params if "lora_" in k}
|
| 113 |
+
elif bias == "all":
|
| 114 |
+
to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
|
| 115 |
+
elif bias == "lora_only":
|
| 116 |
+
to_return = {}
|
| 117 |
+
maybe_lora_bias = {}
|
| 118 |
+
lora_bias_names = set()
|
| 119 |
+
for k, t in named_params:
|
| 120 |
+
if "lora_" in k:
|
| 121 |
+
to_return[k] = t
|
| 122 |
+
bias_name = k.split("lora_")[0] + "bias"
|
| 123 |
+
lora_bias_names.add(bias_name)
|
| 124 |
+
elif "bias" in k:
|
| 125 |
+
maybe_lora_bias[k] = t
|
| 126 |
+
for k, t in maybe_lora_bias:
|
| 127 |
+
if bias_name in lora_bias_names:
|
| 128 |
+
to_return[bias_name] = t
|
| 129 |
+
else:
|
| 130 |
+
raise NotImplementedError
|
| 131 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True) for k, v in to_return.items()}
|
| 132 |
+
return to_return
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
|
| 136 |
+
to_return = {k: t for k, t in named_params if "lora_" not in k}
|
| 137 |
+
if require_grad_only:
|
| 138 |
+
to_return = {k: t for k, t in to_return.items() if t.requires_grad}
|
| 139 |
+
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
|
| 140 |
+
return to_return
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
########## Load Models From Folder ##########
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _insert_adapter_name_into_state_dict(
|
| 147 |
+
state_dict: dict[str, torch.Tensor], adapter_name: str, parameter_prefix: str
|
| 148 |
+
) -> dict[str, torch.Tensor]:
|
| 149 |
+
"""Utility function to remap the state_dict keys to fit the PEFT model by inserting the adapter name."""
|
| 150 |
+
peft_model_state_dict = {}
|
| 151 |
+
for key, val in state_dict.items():
|
| 152 |
+
if parameter_prefix in key:
|
| 153 |
+
suffix = key.split(parameter_prefix)[1]
|
| 154 |
+
if "." in suffix:
|
| 155 |
+
suffix_to_replace = ".".join(suffix.split(".")[1:])
|
| 156 |
+
key = key.replace(suffix_to_replace, f"{adapter_name}.{suffix_to_replace}")
|
| 157 |
+
else:
|
| 158 |
+
key = f"{key}.{adapter_name}"
|
| 159 |
+
peft_model_state_dict[key] = val
|
| 160 |
+
else:
|
| 161 |
+
peft_model_state_dict[key] = val
|
| 162 |
+
return peft_model_state_dict
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def save_video(tensor, path):
|
| 166 |
+
from torchvision.io import write_video
|
| 167 |
+
|
| 168 |
+
tensor = tensor * 255.0
|
| 169 |
+
tensor = tensor.permute(0, 2, 3, 1)
|
| 170 |
+
tensor = tensor.clamp(0, 255).byte()
|
| 171 |
+
write_video(path, tensor, 4, video_codec="h264")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def load_model_from_checkpoint(model, checkpoint_dir, checkpoint_step):
|
| 175 |
+
checkpoint_paths = glob.glob(os.path.join(checkpoint_dir, "checkpoint-*"))
|
| 176 |
+
checkpoint_paths.sort(key=lambda x: int(x.split("-")[-1]), reverse=True)
|
| 177 |
+
|
| 178 |
+
if checkpoint_step is None or checkpoint_step == -1:
|
| 179 |
+
# get the latest checkpoint
|
| 180 |
+
checkpoint_path = checkpoint_paths[0]
|
| 181 |
+
print(f"===> Checkpoint step is not provided, using the latest checkpoint: {checkpoint_path}")
|
| 182 |
+
else:
|
| 183 |
+
checkpoint_path = os.path.join(checkpoint_dir, f"checkpoint-{checkpoint_step}")
|
| 184 |
+
if checkpoint_path not in checkpoint_paths:
|
| 185 |
+
checkpoint_path = checkpoint_paths[0]
|
| 186 |
+
print(f"===> Checkpoint step {checkpoint_step} not found, using the latest checkpoint: {checkpoint_path}")
|
| 187 |
+
else:
|
| 188 |
+
print(f"===> Checkpoint step {checkpoint_step} found, using the specified checkpoint: {checkpoint_path}")
|
| 189 |
+
|
| 190 |
+
checkpoint_step = checkpoint_path.split("checkpoint-")[-1].split("/")[0]
|
| 191 |
+
|
| 192 |
+
full_ckpt = os.path.join(checkpoint_path, "model.pth")
|
| 193 |
+
lora_ckpt = os.path.join(checkpoint_path, "adapter_model.safetensors")
|
| 194 |
+
non_lora_ckpt = os.path.join(checkpoint_path, "non_lora_state_dict.pth")
|
| 195 |
+
if os.path.exists(full_ckpt):
|
| 196 |
+
model_state_dict = torch.load(full_ckpt, map_location="cpu", weights_only=True)
|
| 197 |
+
# Create a new state_dict to store the modified key-value pairs
|
| 198 |
+
new_state_dict = {}
|
| 199 |
+
|
| 200 |
+
# for key, value in model_state_dict.items():
|
| 201 |
+
# if key.startswith("base_model.model.model"):
|
| 202 |
+
# new_key = "base_model.model.model.language_model" + key[len("base_model.model.model"):]
|
| 203 |
+
# new_state_dict[new_key] = value
|
| 204 |
+
# elif key.startswith("base_model.model.visual"):
|
| 205 |
+
# new_key = "base_model.model.model.visual" + key[len("base_model.model.visual"):]
|
| 206 |
+
# new_state_dict[new_key] = value
|
| 207 |
+
# else:
|
| 208 |
+
# new_state_dict[key] = value
|
| 209 |
+
for key, value in model_state_dict.items():
|
| 210 |
+
if key.startswith("base_model.model.model"):
|
| 211 |
+
new_key = "base_model.model.model.language_model" + key[len("base_model.model.model") :]
|
| 212 |
+
new_state_dict[new_key] = value
|
| 213 |
+
elif key.startswith("base_model.model.visual"):
|
| 214 |
+
new_key = "base_model.model.model.visual" + key[len("base_model.model.visual") :]
|
| 215 |
+
new_state_dict[new_key] = value
|
| 216 |
+
else:
|
| 217 |
+
new_state_dict[key] = value
|
| 218 |
+
|
| 219 |
+
# Load the modified state_dict into the model
|
| 220 |
+
model.load_state_dict(new_state_dict)
|
| 221 |
+
# model_state_dict = torch.load(full_ckpt, map_location="cpu")
|
| 222 |
+
# model.load_state_dict(model_state_dict)
|
| 223 |
+
else:
|
| 224 |
+
lora_state_dict = safetensors.torch.load_file(lora_ckpt)
|
| 225 |
+
non_lora_state_dict = torch.load(non_lora_ckpt, map_location="cpu")
|
| 226 |
+
|
| 227 |
+
lora_state_dict = _insert_adapter_name_into_state_dict(
|
| 228 |
+
lora_state_dict, adapter_name="default", parameter_prefix="lora_"
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
model_state_dict = model.state_dict()
|
| 232 |
+
model_state_dict.update(non_lora_state_dict)
|
| 233 |
+
model_state_dict.update(lora_state_dict)
|
| 234 |
+
model.load_state_dict(model_state_dict)
|
| 235 |
+
|
| 236 |
+
return model, checkpoint_step
|
Helios/_DEV/helios/videoalign/vision_process.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
import sys
|
| 6 |
+
import warnings
|
| 7 |
+
from functools import lru_cache
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
import torch
|
| 12 |
+
import torchvision
|
| 13 |
+
from packaging import version
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from torchvision import io, transforms
|
| 16 |
+
from torchvision.transforms import InterpolationMode
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
IMAGE_FACTOR = 28
|
| 22 |
+
MIN_PIXELS = 4 * 28 * 28
|
| 23 |
+
MAX_PIXELS = 16384 * 28 * 28
|
| 24 |
+
MAX_RATIO = 200
|
| 25 |
+
|
| 26 |
+
VIDEO_MIN_PIXELS = 128 * 28 * 28
|
| 27 |
+
VIDEO_MAX_PIXELS = 768 * 28 * 28
|
| 28 |
+
VIDEO_TOTAL_PIXELS = 24576 * 28 * 28
|
| 29 |
+
FRAME_FACTOR = 2
|
| 30 |
+
FPS = 2.0
|
| 31 |
+
FPS_MIN_FRAMES = 4
|
| 32 |
+
FPS_MAX_FRAMES = 768
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def round_by_factor(number: int, factor: int) -> int:
|
| 36 |
+
"""Returns the closest integer to 'number' that is divisible by 'factor'."""
|
| 37 |
+
return round(number / factor) * factor
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def ceil_by_factor(number: int, factor: int) -> int:
|
| 41 |
+
"""Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""
|
| 42 |
+
return math.ceil(number / factor) * factor
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def floor_by_factor(number: int, factor: int) -> int:
|
| 46 |
+
"""Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""
|
| 47 |
+
return math.floor(number / factor) * factor
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def smart_resize(
|
| 51 |
+
height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS
|
| 52 |
+
) -> tuple[int, int]:
|
| 53 |
+
"""
|
| 54 |
+
Rescales the image so that the following conditions are met:
|
| 55 |
+
|
| 56 |
+
1. Both dimensions (height and width) are divisible by 'factor'.
|
| 57 |
+
|
| 58 |
+
2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
|
| 59 |
+
|
| 60 |
+
3. The aspect ratio of the image is maintained as closely as possible.
|
| 61 |
+
"""
|
| 62 |
+
if max(height, width) / min(height, width) > MAX_RATIO:
|
| 63 |
+
raise ValueError(
|
| 64 |
+
f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}"
|
| 65 |
+
)
|
| 66 |
+
h_bar = max(factor, round_by_factor(height, factor))
|
| 67 |
+
w_bar = max(factor, round_by_factor(width, factor))
|
| 68 |
+
if h_bar * w_bar > max_pixels:
|
| 69 |
+
beta = math.sqrt((height * width) / max_pixels)
|
| 70 |
+
h_bar = floor_by_factor(height / beta, factor)
|
| 71 |
+
w_bar = floor_by_factor(width / beta, factor)
|
| 72 |
+
elif h_bar * w_bar < min_pixels:
|
| 73 |
+
beta = math.sqrt(min_pixels / (height * width))
|
| 74 |
+
h_bar = ceil_by_factor(height * beta, factor)
|
| 75 |
+
w_bar = ceil_by_factor(width * beta, factor)
|
| 76 |
+
return h_bar, w_bar
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def fetch_image(ele: dict[str, str | Image.Image], size_factor: int = IMAGE_FACTOR) -> Image.Image:
|
| 80 |
+
if "image" in ele:
|
| 81 |
+
image = ele["image"]
|
| 82 |
+
else:
|
| 83 |
+
image = ele["image_url"]
|
| 84 |
+
image_obj = None
|
| 85 |
+
if isinstance(image, Image.Image):
|
| 86 |
+
image_obj = image
|
| 87 |
+
elif image.startswith("http://") or image.startswith("https://"):
|
| 88 |
+
image_obj = Image.open(requests.get(image, stream=True).raw)
|
| 89 |
+
elif image.startswith("file://"):
|
| 90 |
+
image_obj = Image.open(image[7:])
|
| 91 |
+
elif image.startswith("data:image"):
|
| 92 |
+
if "base64," in image:
|
| 93 |
+
_, base64_data = image.split("base64,", 1)
|
| 94 |
+
data = base64.b64decode(base64_data)
|
| 95 |
+
image_obj = Image.open(BytesIO(data))
|
| 96 |
+
else:
|
| 97 |
+
image_obj = Image.open(image)
|
| 98 |
+
if image_obj is None:
|
| 99 |
+
raise ValueError(f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}")
|
| 100 |
+
image = image_obj.convert("RGB")
|
| 101 |
+
## resize
|
| 102 |
+
if "resized_height" in ele and "resized_width" in ele:
|
| 103 |
+
resized_height, resized_width = smart_resize(
|
| 104 |
+
ele["resized_height"],
|
| 105 |
+
ele["resized_width"],
|
| 106 |
+
factor=size_factor,
|
| 107 |
+
)
|
| 108 |
+
else:
|
| 109 |
+
width, height = image.size
|
| 110 |
+
min_pixels = ele.get("min_pixels", MIN_PIXELS)
|
| 111 |
+
max_pixels = ele.get("max_pixels", MAX_PIXELS)
|
| 112 |
+
resized_height, resized_width = smart_resize(
|
| 113 |
+
height,
|
| 114 |
+
width,
|
| 115 |
+
factor=size_factor,
|
| 116 |
+
min_pixels=min_pixels,
|
| 117 |
+
max_pixels=max_pixels,
|
| 118 |
+
)
|
| 119 |
+
image = image.resize((resized_width, resized_height))
|
| 120 |
+
|
| 121 |
+
return image
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def smart_nframes(
|
| 125 |
+
ele: dict,
|
| 126 |
+
total_frames: int,
|
| 127 |
+
video_fps: int | float,
|
| 128 |
+
) -> int:
|
| 129 |
+
"""calculate the number of frames for video used for model inputs.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
ele (dict): a dict contains the configuration of video.
|
| 133 |
+
support either `fps` or `nframes`:
|
| 134 |
+
- nframes: the number of frames to extract for model inputs.
|
| 135 |
+
- fps: the fps to extract frames for model inputs.
|
| 136 |
+
- min_frames: the minimum number of frames of the video, only used when fps is provided.
|
| 137 |
+
- max_frames: the maximum number of frames of the video, only used when fps is provided.
|
| 138 |
+
total_frames (int): the original total number of frames of the video.
|
| 139 |
+
video_fps (int | float): the original fps of the video.
|
| 140 |
+
|
| 141 |
+
Raises:
|
| 142 |
+
ValueError: nframes should in interval [FRAME_FACTOR, total_frames].
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
int: the number of frames for video used for model inputs.
|
| 146 |
+
"""
|
| 147 |
+
assert not ("fps" in ele and "nframes" in ele), "Only accept either `fps` or `nframes`"
|
| 148 |
+
if "nframes" in ele:
|
| 149 |
+
nframes = round_by_factor(ele["nframes"], FRAME_FACTOR)
|
| 150 |
+
else:
|
| 151 |
+
fps = ele.get("fps", FPS)
|
| 152 |
+
min_frames = ceil_by_factor(ele.get("min_frames", FPS_MIN_FRAMES), FRAME_FACTOR)
|
| 153 |
+
max_frames = floor_by_factor(ele.get("max_frames", min(FPS_MAX_FRAMES, total_frames)), FRAME_FACTOR)
|
| 154 |
+
nframes = total_frames / video_fps * fps
|
| 155 |
+
nframes = min(max(nframes, min_frames), max_frames)
|
| 156 |
+
nframes = round_by_factor(nframes, FRAME_FACTOR)
|
| 157 |
+
if nframes > total_frames:
|
| 158 |
+
nframes = total_frames
|
| 159 |
+
if not (FRAME_FACTOR <= nframes and nframes <= total_frames):
|
| 160 |
+
raise ValueError(f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}.")
|
| 161 |
+
return nframes
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _read_video_torchvision(
|
| 165 |
+
ele: dict,
|
| 166 |
+
) -> torch.Tensor:
|
| 167 |
+
"""read video using torchvision.io.read_video
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
ele (dict): a dict contains the configuration of video.
|
| 171 |
+
support keys:
|
| 172 |
+
- video: the path of video. support "file://", "http://", "https://" and local path.
|
| 173 |
+
- video_start: the start time of video.
|
| 174 |
+
- video_end: the end time of video.
|
| 175 |
+
Returns:
|
| 176 |
+
torch.Tensor: the video tensor with shape (T, C, H, W).
|
| 177 |
+
"""
|
| 178 |
+
video_path = ele["video"]
|
| 179 |
+
if version.parse(torchvision.__version__) < version.parse("0.19.0"):
|
| 180 |
+
if "http://" in video_path or "https://" in video_path:
|
| 181 |
+
warnings.warn("torchvision < 0.19.0 does not support http/https video path, please upgrade to 0.19.0.")
|
| 182 |
+
if "file://" in video_path:
|
| 183 |
+
video_path = video_path[7:]
|
| 184 |
+
# st = time.time()
|
| 185 |
+
video, audio, info = io.read_video(
|
| 186 |
+
video_path,
|
| 187 |
+
start_pts=ele.get("video_start", 0.0),
|
| 188 |
+
end_pts=ele.get("video_end", None),
|
| 189 |
+
pts_unit="sec",
|
| 190 |
+
output_format="TCHW",
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
total_frames, video_fps = video.size(0), info["video_fps"]
|
| 194 |
+
# logger.info(f"torchvision: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
|
| 195 |
+
if ele["sample_type"] == "uniform":
|
| 196 |
+
nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
|
| 197 |
+
idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
|
| 198 |
+
elif ele["sample_type"] == "multi_pts":
|
| 199 |
+
frames_each_pts = 6
|
| 200 |
+
num_pts = 4
|
| 201 |
+
fps = 8
|
| 202 |
+
nframes = int(total_frames * fps // video_fps)
|
| 203 |
+
frames_idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
|
| 204 |
+
|
| 205 |
+
start_pt = int(frames_each_pts // 2)
|
| 206 |
+
end_pt = int(nframes - frames_each_pts // 2 - 1)
|
| 207 |
+
pts = torch.linspace(start_pt, end_pt, num_pts).round().long().tolist()
|
| 208 |
+
idx = []
|
| 209 |
+
for pt in pts:
|
| 210 |
+
idx.extend(frames_idx[pt - frames_each_pts // 2 : pt + frames_each_pts // 2])
|
| 211 |
+
|
| 212 |
+
video = video[idx]
|
| 213 |
+
return video
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def is_video_reader_available() -> bool:
|
| 217 |
+
import importlib.util
|
| 218 |
+
|
| 219 |
+
return importlib.util.find_spec("video_reader") is not None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _read_video_video_reader(
|
| 223 |
+
ele: dict,
|
| 224 |
+
) -> torch.Tensor:
|
| 225 |
+
"""read video using video_reader.VideoReader
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
ele (dict): a dict contains the configuration of video.
|
| 229 |
+
support keys:
|
| 230 |
+
- video: the path of video. support "file://", "http://", "https://" and local path.
|
| 231 |
+
- video_start: the start time of video.
|
| 232 |
+
- video_end: the end time of video.
|
| 233 |
+
Returns:
|
| 234 |
+
torch.Tensor: the video tensor with shape (T, C, H, W).
|
| 235 |
+
"""
|
| 236 |
+
from video_reader import PyVideoReader
|
| 237 |
+
|
| 238 |
+
video_path = ele["video"]
|
| 239 |
+
# st = time.time()
|
| 240 |
+
vr = PyVideoReader(video_path, threads=0)
|
| 241 |
+
# TODO: support start_pts and end_pts
|
| 242 |
+
if "video_start" in ele or "video_end" in ele:
|
| 243 |
+
raise NotImplementedError("not support start_pts and end_pts in video_reader for now.")
|
| 244 |
+
total_frames, video_fps = int(len(vr)), float(vr.get_info()["fps"])
|
| 245 |
+
if total_frames <= 93:
|
| 246 |
+
video_fps = 16
|
| 247 |
+
elif total_frames <= 49:
|
| 248 |
+
video_fps = 8
|
| 249 |
+
# logger.info(f"video_reader: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
|
| 250 |
+
if ele["sample_type"] == "uniform":
|
| 251 |
+
nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
|
| 252 |
+
# nframes = max(nframes, 8)
|
| 253 |
+
# import pdb; pdb.set_trace()
|
| 254 |
+
idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
|
| 255 |
+
elif ele["sample_type"] == "multi_pts":
|
| 256 |
+
frames_each_pts = 6
|
| 257 |
+
num_pts = 4
|
| 258 |
+
fps = 8
|
| 259 |
+
nframes = int(total_frames * fps // video_fps)
|
| 260 |
+
frames_idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
|
| 261 |
+
|
| 262 |
+
start_pt = int(frames_each_pts // 2)
|
| 263 |
+
end_pt = int(nframes - frames_each_pts // 2 - 1)
|
| 264 |
+
pts = torch.linspace(start_pt, end_pt, num_pts).round().long().tolist()
|
| 265 |
+
idx = []
|
| 266 |
+
for pt in pts:
|
| 267 |
+
idx.extend(frames_idx[pt - frames_each_pts // 2 : pt + frames_each_pts // 2])
|
| 268 |
+
video = vr.get_batch(idx)
|
| 269 |
+
video = torch.tensor(video).permute(0, 3, 1, 2) # Convert to TCHW format
|
| 270 |
+
return video
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
VIDEO_READER_BACKENDS = {
|
| 274 |
+
"video_reader": _read_video_video_reader,
|
| 275 |
+
"torchvision": _read_video_torchvision,
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
FORCE_QWENVL_VIDEO_READER = os.getenv("FORCE_QWENVL_VIDEO_READER", None)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@lru_cache(maxsize=1)
|
| 282 |
+
def get_video_reader_backend() -> str:
|
| 283 |
+
if FORCE_QWENVL_VIDEO_READER is not None:
|
| 284 |
+
video_reader_backend = FORCE_QWENVL_VIDEO_READER
|
| 285 |
+
elif is_video_reader_available():
|
| 286 |
+
video_reader_backend = "video_reader"
|
| 287 |
+
else:
|
| 288 |
+
video_reader_backend = "torchvision"
|
| 289 |
+
print(f"qwen-vl-utils using {video_reader_backend} to read video.", file=sys.stderr)
|
| 290 |
+
return video_reader_backend
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def fetch_video(ele: dict, image_factor: int = IMAGE_FACTOR) -> torch.Tensor | list[Image.Image]:
|
| 294 |
+
if isinstance(ele["video"], str):
|
| 295 |
+
video_reader_backend = get_video_reader_backend()
|
| 296 |
+
video = VIDEO_READER_BACKENDS[video_reader_backend](ele)
|
| 297 |
+
# import pdb; pdb.set_trace()
|
| 298 |
+
nframes, _, height, width = video.shape
|
| 299 |
+
|
| 300 |
+
min_pixels = ele.get("min_pixels", VIDEO_MIN_PIXELS)
|
| 301 |
+
total_pixels = ele.get("total_pixels", VIDEO_TOTAL_PIXELS)
|
| 302 |
+
max_pixels = max(min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05))
|
| 303 |
+
max_pixels = ele.get("max_pixels", max_pixels)
|
| 304 |
+
if "resized_height" in ele and "resized_width" in ele:
|
| 305 |
+
resized_height, resized_width = smart_resize(
|
| 306 |
+
ele["resized_height"],
|
| 307 |
+
ele["resized_width"],
|
| 308 |
+
factor=image_factor,
|
| 309 |
+
)
|
| 310 |
+
else:
|
| 311 |
+
resized_height, resized_width = smart_resize(
|
| 312 |
+
height,
|
| 313 |
+
width,
|
| 314 |
+
factor=image_factor,
|
| 315 |
+
min_pixels=min_pixels,
|
| 316 |
+
max_pixels=max_pixels,
|
| 317 |
+
)
|
| 318 |
+
video = transforms.functional.resize(
|
| 319 |
+
video,
|
| 320 |
+
[resized_height, resized_width],
|
| 321 |
+
interpolation=InterpolationMode.BICUBIC,
|
| 322 |
+
antialias=True,
|
| 323 |
+
).float()
|
| 324 |
+
return video
|
| 325 |
+
else:
|
| 326 |
+
assert isinstance(ele["video"], (list, tuple))
|
| 327 |
+
process_info = ele.copy()
|
| 328 |
+
process_info.pop("type", None)
|
| 329 |
+
process_info.pop("video", None)
|
| 330 |
+
images = [
|
| 331 |
+
fetch_image({"image": video_element, **process_info}, size_factor=image_factor)
|
| 332 |
+
for video_element in ele["video"]
|
| 333 |
+
]
|
| 334 |
+
nframes = ceil_by_factor(len(images), FRAME_FACTOR)
|
| 335 |
+
if len(images) < nframes:
|
| 336 |
+
images.extend([images[-1]] * (nframes - len(images)))
|
| 337 |
+
return images
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def extract_vision_info(conversations: list[dict] | list[list[dict]]) -> list[dict]:
|
| 341 |
+
vision_infos = []
|
| 342 |
+
if isinstance(conversations[0], dict):
|
| 343 |
+
conversations = [conversations]
|
| 344 |
+
for conversation in conversations:
|
| 345 |
+
for message in conversation:
|
| 346 |
+
if isinstance(message["content"], list):
|
| 347 |
+
for ele in message["content"]:
|
| 348 |
+
if (
|
| 349 |
+
"image" in ele
|
| 350 |
+
or "image_url" in ele
|
| 351 |
+
or "video" in ele
|
| 352 |
+
or ele["type"] in ("image", "image_url", "video")
|
| 353 |
+
):
|
| 354 |
+
vision_infos.append(ele)
|
| 355 |
+
return vision_infos
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def process_vision_info(
|
| 359 |
+
conversations: list[dict] | list[list[dict]],
|
| 360 |
+
) -> tuple[list[Image.Image] | None, list[torch.Tensor | list[Image.Image]] | None]:
|
| 361 |
+
vision_infos = extract_vision_info(conversations)
|
| 362 |
+
## Read images or videos
|
| 363 |
+
image_inputs = []
|
| 364 |
+
video_inputs = []
|
| 365 |
+
for vision_info in vision_infos:
|
| 366 |
+
if "image" in vision_info or "image_url" in vision_info:
|
| 367 |
+
image_inputs.append(fetch_image(vision_info))
|
| 368 |
+
elif "video" in vision_info:
|
| 369 |
+
video_inputs.append(fetch_video(vision_info))
|
| 370 |
+
else:
|
| 371 |
+
raise ValueError("image, image_url or video should in content.")
|
| 372 |
+
if len(image_inputs) == 0:
|
| 373 |
+
image_inputs = None
|
| 374 |
+
if len(video_inputs) == 0:
|
| 375 |
+
video_inputs = None
|
| 376 |
+
return image_inputs, video_inputs
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def process_video_tensor(
|
| 380 |
+
video: torch.Tensor,
|
| 381 |
+
nframes: int = 20,
|
| 382 |
+
resized_height: int = 336,
|
| 383 |
+
resized_width: int = 588,
|
| 384 |
+
) -> torch.Tensor:
|
| 385 |
+
T, C, H, W = video.shape
|
| 386 |
+
|
| 387 |
+
idx = torch.linspace(0, T - 1, nframes).round().long()
|
| 388 |
+
video = video[idx]
|
| 389 |
+
|
| 390 |
+
video = transforms.functional.resize(
|
| 391 |
+
video,
|
| 392 |
+
[resized_height, resized_width],
|
| 393 |
+
interpolation=InterpolationMode.BICUBIC,
|
| 394 |
+
antialias=True,
|
| 395 |
+
).float()
|
| 396 |
+
return video
|
Helios/_DEV/output_helios/helios-base/A_beautifully_crafted_green_ceramic_vase_adorned_with_intricate_patterns_and_det_1779441980/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/output_helios/helios-base/A_close_up_of_a_sleek_black_bicycle_parked_on_a_clean_paved_street_The_bicycle_h_1779439971/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/output_helios/helios-base/A_close_up_view_of_a_vibrant_pink_ceramic_bowl_with_intricate_floral_patterns_pa_1779441890/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/output_helios/helios-base/A_detailed_close_up_of_a_sleek_glossy_purple_suitcase_with_silver_hardware_The_s_1779445728/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/output_helios/helios-base/A_front_view_of_a_colorful_kite_lying_flat_on_the_bottom_of_a_skateboard_The_ska_1779440072/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/output_helios/helios-base/A_front_view_of_a_creative_culinary_fusion_dish_featuring_a_hot_dog_placed_atop__1779438168/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/output_helios/helios-base/A_vibrant_underwater_coral_reef_teeming_with_life_The_corals_are_in_various_shap_1779445801/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Helios/_DEV/output_helios/helios-base/A_woman_dancing_1779378268/relative_l1.csv
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 5 |
+
0,-1,3,990.56787109375,0.08483197540044785
|
| 6 |
+
0,-1,4,987.2460327148438,0.08009830117225647
|
| 7 |
+
0,-1,5,983.80029296875,0.07057536393404007
|
| 8 |
+
0,-1,6,980.2235717773438,0.04802758991718292
|
| 9 |
+
0,-1,7,976.5081787109375,0.07817491888999939
|
| 10 |
+
0,-1,8,972.64599609375,0.0625346451997757
|
| 11 |
+
0,-1,9,968.6281127929688,0.06670602411031723
|
| 12 |
+
0,-1,10,964.4448852539062,0.13630107045173645
|
| 13 |
+
0,-1,11,960.0859375,0.06584817171096802
|
| 14 |
+
0,-1,12,955.5398559570312,0.08350265026092529
|
| 15 |
+
0,-1,13,950.7944946289062,0.08591210842132568
|
| 16 |
+
0,-1,14,945.8363647460938,0.13262689113616943
|
| 17 |
+
0,-1,15,940.6508178710938,0.07238229364156723
|
| 18 |
+
0,-1,16,935.2218627929688,0.09051541239023209
|
| 19 |
+
0,-1,17,929.5319213867188,0.12088219821453094
|
| 20 |
+
0,-1,18,923.5617065429688,0.14103534817695618
|
| 21 |
+
0,-1,19,917.2901000976562,0.08698604255914688
|
| 22 |
+
0,-1,20,910.6935424804688,0.11635714769363403
|
| 23 |
+
0,-1,21,903.7461547851562,0.11028948426246643
|
| 24 |
+
0,-1,22,896.419189453125,0.15013201534748077
|
| 25 |
+
0,-1,23,888.6807250976562,0.1311371624469757
|
| 26 |
+
0,-1,24,880.4949951171875,0.19751965999603271
|
| 27 |
+
0,-1,25,871.8221435546875,0.2383548617362976
|
| 28 |
+
0,-1,26,862.6173095703125,0.17049884796142578
|
| 29 |
+
0,-1,27,852.8300170898438,0.21639640629291534
|
| 30 |
+
0,-1,28,842.4031982421875,0.19410116970539093
|
| 31 |
+
0,-1,29,831.27197265625,0.22741833329200745
|
| 32 |
+
0,-1,30,819.362548828125,0.23831278085708618
|
| 33 |
+
0,-1,31,806.59033203125,0.22017505764961243
|
| 34 |
+
0,-1,32,792.8580322265625,0.4130346179008484
|
| 35 |
+
0,-1,33,778.0531616210938,0.2744807004928589
|
| 36 |
+
0,-1,34,762.0449829101562,0.37864968180656433
|
| 37 |
+
0,-1,35,744.6805419921875,0.3492948114871979
|
| 38 |
+
0,-1,36,725.7799072265625,0.46409839391708374
|
| 39 |
+
0,-1,37,705.1297607421875,0.40662717819213867
|
| 40 |
+
0,-1,38,682.475341796875,0.5081633925437927
|
| 41 |
+
0,-1,39,657.5100708007812,0.45880454778671265
|
| 42 |
+
0,-1,40,629.861328125,0.5602932572364807
|
| 43 |
+
0,-1,41,599.0718383789062,0.5158243775367737
|
| 44 |
+
0,-1,42,564.5742797851562,0.7128055691719055
|
| 45 |
+
0,-1,43,525.6558227539062,0.7992662191390991
|
| 46 |
+
0,-1,44,481.4084777832031,0.6328389644622803
|
| 47 |
+
0,-1,45,430.6573791503906,0.8070102334022522
|
| 48 |
+
0,-1,46,371.8548278808594,0.8515591025352478
|
| 49 |
+
0,-1,47,302.919677734375,0.9368497729301453
|
| 50 |
+
0,-1,48,220.98605346679688,0.8796585202217102
|
| 51 |
+
0,-1,49,121.9947509765625,1.2312424182891846
|
| 52 |
+
1,-1,0,999.8531494140625,0.03624670207500458
|
| 53 |
+
1,-1,1,996.8655395507812,0.07165471464395523
|
| 54 |
+
1,-1,2,993.7723388671875,0.03155628964304924
|
| 55 |
+
1,-1,3,990.56787109375,0.056210942566394806
|
| 56 |
+
1,-1,4,987.2460327148438,0.053518958389759064
|
| 57 |
+
1,-1,5,983.80029296875,0.0530499629676342
|
| 58 |
+
1,-1,6,980.2235717773438,0.04741671308875084
|
| 59 |
+
1,-1,7,976.5081787109375,0.04803739860653877
|
| 60 |
+
1,-1,8,972.64599609375,0.05842754617333412
|
| 61 |
+
1,-1,9,968.6281127929688,0.4486943781375885
|
| 62 |
+
1,-1,10,964.4448852539062,0.06682908535003662
|
| 63 |
+
1,-1,11,960.0859375,0.10405473411083221
|
| 64 |
+
1,-1,12,955.5398559570312,0.09412363916635513
|
| 65 |
+
1,-1,13,950.7944946289062,0.0726625993847847
|
| 66 |
+
1,-1,14,945.8363647460938,0.0669218972325325
|
| 67 |
+
1,-1,15,940.6508178710938,0.07415453344583511
|
| 68 |
+
1,-1,16,935.2218627929688,0.1126844510436058
|
| 69 |
+
1,-1,17,929.5319213867188,0.09317794442176819
|
| 70 |
+
1,-1,18,923.5617065429688,0.10127455741167068
|
| 71 |
+
1,-1,19,917.2901000976562,0.13545776903629303
|
| 72 |
+
1,-1,20,910.6935424804688,0.10525280237197876
|
| 73 |
+
1,-1,21,903.7461547851562,0.10674560815095901
|
| 74 |
+
1,-1,22,896.419189453125,0.12109290063381195
|
| 75 |
+
1,-1,23,888.6807250976562,0.15840622782707214
|
| 76 |
+
1,-1,24,880.4949951171875,0.13410934805870056
|
| 77 |
+
1,-1,25,871.8221435546875,0.34412819147109985
|
| 78 |
+
1,-1,26,862.6173095703125,0.15101169049739838
|
| 79 |
+
1,-1,27,852.8300170898438,0.1736321896314621
|
| 80 |
+
1,-1,28,842.4031982421875,0.38356631994247437
|
| 81 |
+
1,-1,29,831.27197265625,0.39209622144699097
|
| 82 |
+
1,-1,30,819.362548828125,0.21551835536956787
|
| 83 |
+
1,-1,31,806.59033203125,0.30495142936706543
|
| 84 |
+
1,-1,32,792.8580322265625,0.25277721881866455
|
| 85 |
+
1,-1,33,778.0531616210938,0.31062841415405273
|
| 86 |
+
1,-1,34,762.0449829101562,0.33962252736091614
|
| 87 |
+
1,-1,35,744.6805419921875,0.37112024426460266
|
| 88 |
+
1,-1,36,725.7799072265625,0.4327954649925232
|
| 89 |
+
1,-1,37,705.1297607421875,0.6683275103569031
|
| 90 |
+
1,-1,38,682.475341796875,0.553996205329895
|
| 91 |
+
1,-1,39,657.5100708007812,5.26118278503418
|
| 92 |
+
1,-1,40,629.861328125,0.5473806858062744
|
| 93 |
+
1,-1,41,599.0718383789062,0.597531259059906
|
| 94 |
+
1,-1,42,564.5742797851562,0.6634519100189209
|
| 95 |
+
1,-1,43,525.6558227539062,0.7166421413421631
|
| 96 |
+
1,-1,44,481.4084777832031,0.9395881295204163
|
| 97 |
+
1,-1,45,430.6573791503906,0.9884947538375854
|
| 98 |
+
1,-1,46,371.8548278808594,0.7545281648635864
|
| 99 |
+
1,-1,47,302.919677734375,0.9624993205070496
|
| 100 |
+
1,-1,48,220.98605346679688,1.159847378730774
|
| 101 |
+
1,-1,49,121.9947509765625,0.7360488176345825
|
| 102 |
+
2,-1,0,999.8531494140625,0.0288735032081604
|
| 103 |
+
2,-1,1,996.8655395507812,0.07416917383670807
|
| 104 |
+
2,-1,2,993.7723388671875,0.051815830171108246
|
| 105 |
+
2,-1,3,990.56787109375,0.04775497317314148
|
| 106 |
+
2,-1,4,987.2460327148438,0.06091343238949776
|
| 107 |
+
2,-1,5,983.80029296875,0.10853061079978943
|
| 108 |
+
2,-1,6,980.2235717773438,0.06723586469888687
|
| 109 |
+
2,-1,7,976.5081787109375,0.049189068377017975
|
| 110 |
+
2,-1,8,972.64599609375,0.07407137751579285
|
| 111 |
+
2,-1,9,968.6281127929688,0.13893790543079376
|
| 112 |
+
2,-1,10,964.4448852539062,0.14785702526569366
|
| 113 |
+
2,-1,11,960.0859375,0.08305556327104568
|
| 114 |
+
2,-1,12,955.5398559570312,0.12652549147605896
|
| 115 |
+
2,-1,13,950.7944946289062,0.07935374230146408
|
| 116 |
+
2,-1,14,945.8363647460938,0.220855712890625
|
| 117 |
+
2,-1,15,940.6508178710938,0.1035865917801857
|
| 118 |
+
2,-1,16,935.2218627929688,0.13510257005691528
|
| 119 |
+
2,-1,17,929.5319213867188,0.10435187816619873
|
| 120 |
+
2,-1,18,923.5617065429688,0.09614348411560059
|
| 121 |
+
2,-1,19,917.2901000976562,0.1463916301727295
|
| 122 |
+
2,-1,20,910.6935424804688,0.12360315769910812
|
| 123 |
+
2,-1,21,903.7461547851562,0.12062233686447144
|
| 124 |
+
2,-1,22,896.419189453125,0.12362800538539886
|
| 125 |
+
2,-1,23,888.6807250976562,0.13205184042453766
|
| 126 |
+
2,-1,24,880.4949951171875,0.15743429958820343
|
| 127 |
+
2,-1,25,871.8221435546875,0.1535092443227768
|
| 128 |
+
2,-1,26,862.6173095703125,0.18612059950828552
|
| 129 |
+
2,-1,27,852.8300170898438,0.21592804789543152
|
| 130 |
+
2,-1,28,842.4031982421875,0.2141854465007782
|
| 131 |
+
2,-1,29,831.27197265625,0.24770326912403107
|
| 132 |
+
2,-1,30,819.362548828125,0.2301183044910431
|
| 133 |
+
2,-1,31,806.59033203125,0.28837916254997253
|
| 134 |
+
2,-1,32,792.8580322265625,0.28074881434440613
|
| 135 |
+
2,-1,33,778.0531616210938,0.27006325125694275
|
| 136 |
+
2,-1,34,762.0449829101562,0.33337464928627014
|
| 137 |
+
2,-1,35,744.6805419921875,0.28511446714401245
|
| 138 |
+
2,-1,36,725.7799072265625,0.3836577236652374
|
| 139 |
+
2,-1,37,705.1297607421875,0.78025883436203
|
| 140 |
+
2,-1,38,682.475341796875,0.40665745735168457
|
| 141 |
+
2,-1,39,657.5100708007812,0.49699899554252625
|
| 142 |
+
2,-1,40,629.861328125,0.8030208349227905
|
| 143 |
+
2,-1,41,599.0718383789062,0.6307190656661987
|
| 144 |
+
2,-1,42,564.5742797851562,0.8205258846282959
|
| 145 |
+
2,-1,43,525.6558227539062,0.6443222761154175
|
| 146 |
+
2,-1,44,481.4084777832031,0.7825407385826111
|
| 147 |
+
2,-1,45,430.6573791503906,0.8667947053909302
|
| 148 |
+
2,-1,46,371.8548278808594,1.5348774194717407
|
| 149 |
+
2,-1,47,302.919677734375,0.9636214375495911
|
| 150 |
+
2,-1,48,220.98605346679688,6.670920372009277
|
| 151 |
+
2,-1,49,121.9947509765625,1.6488206386566162
|
Helios/_DEV/output_helios/helios-base/A_woman_dancing_1779378754/relative_l1.csv
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
chunk_index,stage_index,step_index,timestep,relative_l1
|
| 2 |
+
0,-1,0,999.8531494140625,0.03883999586105347
|
| 3 |
+
0,-1,1,996.8655395507812,0.07517043501138687
|
| 4 |
+
0,-1,2,993.7723388671875,0.03654193505644798
|
| 5 |
+
0,-1,3,990.56787109375,0.08483197540044785
|
| 6 |
+
0,-1,4,987.2460327148438,0.08009830117225647
|
| 7 |
+
0,-1,5,983.80029296875,0.07057536393404007
|
| 8 |
+
0,-1,6,980.2235717773438,0.04802758991718292
|
| 9 |
+
0,-1,7,976.5081787109375,0.07817491888999939
|
| 10 |
+
0,-1,8,972.64599609375,0.0625346451997757
|
| 11 |
+
0,-1,9,968.6281127929688,0.06670602411031723
|
| 12 |
+
0,-1,10,964.4448852539062,0.13630107045173645
|
| 13 |
+
0,-1,11,960.0859375,0.06584817171096802
|
| 14 |
+
0,-1,12,955.5398559570312,0.08350265026092529
|
| 15 |
+
0,-1,13,950.7944946289062,0.08591210842132568
|
| 16 |
+
0,-1,14,945.8363647460938,0.13262689113616943
|
| 17 |
+
0,-1,15,940.6508178710938,0.07238229364156723
|
| 18 |
+
0,-1,16,935.2218627929688,0.09051541239023209
|
| 19 |
+
0,-1,17,929.5319213867188,0.12088219821453094
|
| 20 |
+
0,-1,18,923.5617065429688,0.14103534817695618
|
| 21 |
+
0,-1,19,917.2901000976562,0.08698604255914688
|
| 22 |
+
0,-1,20,910.6935424804688,0.11635714769363403
|
| 23 |
+
0,-1,21,903.7461547851562,0.11028948426246643
|
| 24 |
+
0,-1,22,896.419189453125,0.15013201534748077
|
| 25 |
+
0,-1,23,888.6807250976562,0.1311371624469757
|
| 26 |
+
0,-1,24,880.4949951171875,0.19751965999603271
|
| 27 |
+
0,-1,25,871.8221435546875,0.2383548617362976
|
| 28 |
+
0,-1,26,862.6173095703125,0.17049884796142578
|
| 29 |
+
0,-1,27,852.8300170898438,0.21639640629291534
|
| 30 |
+
0,-1,28,842.4031982421875,0.19410116970539093
|
| 31 |
+
0,-1,29,831.27197265625,0.22741833329200745
|
| 32 |
+
0,-1,30,819.362548828125,0.23831278085708618
|
| 33 |
+
0,-1,31,806.59033203125,0.22017505764961243
|
| 34 |
+
0,-1,32,792.8580322265625,0.4130346179008484
|
| 35 |
+
0,-1,33,778.0531616210938,0.2744807004928589
|
| 36 |
+
0,-1,34,762.0449829101562,0.37864968180656433
|
| 37 |
+
0,-1,35,744.6805419921875,0.3492948114871979
|
| 38 |
+
0,-1,36,725.7799072265625,0.46409839391708374
|
| 39 |
+
0,-1,37,705.1297607421875,0.40662717819213867
|
| 40 |
+
0,-1,38,682.475341796875,0.5081633925437927
|
| 41 |
+
0,-1,39,657.5100708007812,0.45880454778671265
|
| 42 |
+
0,-1,40,629.861328125,0.5602932572364807
|
| 43 |
+
0,-1,41,599.0718383789062,0.5158243775367737
|
| 44 |
+
0,-1,42,564.5742797851562,0.7128055691719055
|
| 45 |
+
0,-1,43,525.6558227539062,0.7992662191390991
|
| 46 |
+
0,-1,44,481.4084777832031,0.6328389644622803
|
| 47 |
+
0,-1,45,430.6573791503906,0.8070102334022522
|
| 48 |
+
0,-1,46,371.8548278808594,0.8515591025352478
|
| 49 |
+
0,-1,47,302.919677734375,0.9368497729301453
|
| 50 |
+
0,-1,48,220.98605346679688,0.8796585202217102
|
| 51 |
+
0,-1,49,121.9947509765625,1.2312424182891846
|
| 52 |
+
1,-1,0,999.8531494140625,0.03624670207500458
|
| 53 |
+
1,-1,1,996.8655395507812,0.07165471464395523
|
| 54 |
+
1,-1,2,993.7723388671875,0.03155628964304924
|
| 55 |
+
1,-1,3,990.56787109375,0.056210942566394806
|
| 56 |
+
1,-1,4,987.2460327148438,0.053518958389759064
|
| 57 |
+
1,-1,5,983.80029296875,0.0530499629676342
|
| 58 |
+
1,-1,6,980.2235717773438,0.04741671308875084
|
| 59 |
+
1,-1,7,976.5081787109375,0.04803739860653877
|
| 60 |
+
1,-1,8,972.64599609375,0.05842754617333412
|
| 61 |
+
1,-1,9,968.6281127929688,0.4486943781375885
|
| 62 |
+
1,-1,10,964.4448852539062,0.06682908535003662
|
| 63 |
+
1,-1,11,960.0859375,0.10405473411083221
|
| 64 |
+
1,-1,12,955.5398559570312,0.09412363916635513
|
| 65 |
+
1,-1,13,950.7944946289062,0.0726625993847847
|
| 66 |
+
1,-1,14,945.8363647460938,0.0669218972325325
|
| 67 |
+
1,-1,15,940.6508178710938,0.07415453344583511
|
| 68 |
+
1,-1,16,935.2218627929688,0.1126844510436058
|
| 69 |
+
1,-1,17,929.5319213867188,0.09317794442176819
|
| 70 |
+
1,-1,18,923.5617065429688,0.10127455741167068
|
| 71 |
+
1,-1,19,917.2901000976562,0.13545776903629303
|
| 72 |
+
1,-1,20,910.6935424804688,0.10525280237197876
|
| 73 |
+
1,-1,21,903.7461547851562,0.10674560815095901
|
| 74 |
+
1,-1,22,896.419189453125,0.12109290063381195
|
| 75 |
+
1,-1,23,888.6807250976562,0.15840622782707214
|
| 76 |
+
1,-1,24,880.4949951171875,0.13410934805870056
|
| 77 |
+
1,-1,25,871.8221435546875,0.34412819147109985
|
| 78 |
+
1,-1,26,862.6173095703125,0.15101169049739838
|
| 79 |
+
1,-1,27,852.8300170898438,0.1736321896314621
|
| 80 |
+
1,-1,28,842.4031982421875,0.38356631994247437
|
| 81 |
+
1,-1,29,831.27197265625,0.39209622144699097
|
| 82 |
+
1,-1,30,819.362548828125,0.21551835536956787
|
| 83 |
+
1,-1,31,806.59033203125,0.30495142936706543
|
| 84 |
+
1,-1,32,792.8580322265625,0.25277721881866455
|
| 85 |
+
1,-1,33,778.0531616210938,0.31062841415405273
|
| 86 |
+
1,-1,34,762.0449829101562,0.33962252736091614
|
| 87 |
+
1,-1,35,744.6805419921875,0.37112024426460266
|
| 88 |
+
1,-1,36,725.7799072265625,0.4327954649925232
|
| 89 |
+
1,-1,37,705.1297607421875,0.6683275103569031
|
| 90 |
+
1,-1,38,682.475341796875,0.553996205329895
|
| 91 |
+
1,-1,39,657.5100708007812,5.26118278503418
|
| 92 |
+
1,-1,40,629.861328125,0.5473806858062744
|
| 93 |
+
1,-1,41,599.0718383789062,0.597531259059906
|
| 94 |
+
1,-1,42,564.5742797851562,0.6634519100189209
|
| 95 |
+
1,-1,43,525.6558227539062,0.7166421413421631
|
| 96 |
+
1,-1,44,481.4084777832031,0.9395881295204163
|
| 97 |
+
1,-1,45,430.6573791503906,0.9884947538375854
|
| 98 |
+
1,-1,46,371.8548278808594,0.7545281648635864
|
| 99 |
+
1,-1,47,302.919677734375,0.9624993205070496
|
| 100 |
+
1,-1,48,220.98605346679688,1.159847378730774
|
| 101 |
+
1,-1,49,121.9947509765625,0.7360488176345825
|
| 102 |
+
2,-1,0,999.8531494140625,0.0288735032081604
|
| 103 |
+
2,-1,1,996.8655395507812,0.07416917383670807
|
| 104 |
+
2,-1,2,993.7723388671875,0.051815830171108246
|
| 105 |
+
2,-1,3,990.56787109375,0.04775497317314148
|
| 106 |
+
2,-1,4,987.2460327148438,0.06091343238949776
|
| 107 |
+
2,-1,5,983.80029296875,0.10853061079978943
|
| 108 |
+
2,-1,6,980.2235717773438,0.06723586469888687
|
| 109 |
+
2,-1,7,976.5081787109375,0.049189068377017975
|
| 110 |
+
2,-1,8,972.64599609375,0.07407137751579285
|
| 111 |
+
2,-1,9,968.6281127929688,0.13893790543079376
|
| 112 |
+
2,-1,10,964.4448852539062,0.14785702526569366
|
| 113 |
+
2,-1,11,960.0859375,0.08305556327104568
|
| 114 |
+
2,-1,12,955.5398559570312,0.12652549147605896
|
| 115 |
+
2,-1,13,950.7944946289062,0.07935374230146408
|
| 116 |
+
2,-1,14,945.8363647460938,0.220855712890625
|
| 117 |
+
2,-1,15,940.6508178710938,0.1035865917801857
|
| 118 |
+
2,-1,16,935.2218627929688,0.13510257005691528
|
| 119 |
+
2,-1,17,929.5319213867188,0.10435187816619873
|
| 120 |
+
2,-1,18,923.5617065429688,0.09614348411560059
|
| 121 |
+
2,-1,19,917.2901000976562,0.1463916301727295
|
| 122 |
+
2,-1,20,910.6935424804688,0.12360315769910812
|
| 123 |
+
2,-1,21,903.7461547851562,0.12062233686447144
|
| 124 |
+
2,-1,22,896.419189453125,0.12362800538539886
|
| 125 |
+
2,-1,23,888.6807250976562,0.13205184042453766
|
| 126 |
+
2,-1,24,880.4949951171875,0.15743429958820343
|
| 127 |
+
2,-1,25,871.8221435546875,0.1535092443227768
|
| 128 |
+
2,-1,26,862.6173095703125,0.18612059950828552
|
| 129 |
+
2,-1,27,852.8300170898438,0.21592804789543152
|
| 130 |
+
2,-1,28,842.4031982421875,0.2141854465007782
|
| 131 |
+
2,-1,29,831.27197265625,0.24770326912403107
|
| 132 |
+
2,-1,30,819.362548828125,0.2301183044910431
|
| 133 |
+
2,-1,31,806.59033203125,0.28837916254997253
|
| 134 |
+
2,-1,32,792.8580322265625,0.28074881434440613
|
| 135 |
+
2,-1,33,778.0531616210938,0.27006325125694275
|
| 136 |
+
2,-1,34,762.0449829101562,0.33337464928627014
|
| 137 |
+
2,-1,35,744.6805419921875,0.28511446714401245
|
| 138 |
+
2,-1,36,725.7799072265625,0.3836577236652374
|
| 139 |
+
2,-1,37,705.1297607421875,0.78025883436203
|
| 140 |
+
2,-1,38,682.475341796875,0.40665745735168457
|
| 141 |
+
2,-1,39,657.5100708007812,0.49699899554252625
|
| 142 |
+
2,-1,40,629.861328125,0.8030208349227905
|
| 143 |
+
2,-1,41,599.0718383789062,0.6307190656661987
|
| 144 |
+
2,-1,42,564.5742797851562,0.8205258846282959
|
| 145 |
+
2,-1,43,525.6558227539062,0.6443222761154175
|
| 146 |
+
2,-1,44,481.4084777832031,0.7825407385826111
|
| 147 |
+
2,-1,45,430.6573791503906,0.8667947053909302
|
| 148 |
+
2,-1,46,371.8548278808594,1.5348774194717407
|
| 149 |
+
2,-1,47,302.919677734375,0.9636214375495911
|
| 150 |
+
2,-1,48,220.98605346679688,6.670920372009277
|
| 151 |
+
2,-1,49,121.9947509765625,1.6488206386566162
|
Helios/_DEV/output_helios/helios-base/Animated_style_a_well_dressed_couple_in_formal_evening_wear_is_walking_down_a_bu_1779443890/relative_l1.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|