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5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from diffusers import (CogVideoXDDIMScheduler, DDIMScheduler,
|
| 10 |
+
DPMSolverMultistepScheduler,
|
| 11 |
+
EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,
|
| 12 |
+
PNDMScheduler)
|
| 13 |
+
from PIL import Image
|
| 14 |
+
|
| 15 |
+
current_file_path = os.path.abspath(__file__)
|
| 16 |
+
project_roots = [os.path.dirname(current_file_path), os.path.dirname(os.path.dirname(current_file_path)), os.path.dirname(os.path.dirname(os.path.dirname(current_file_path)))]
|
| 17 |
+
for project_root in project_roots:
|
| 18 |
+
sys.path.insert(0, project_root) if project_root not in sys.path else None
|
| 19 |
+
|
| 20 |
+
from videox_fun.dist import set_multi_gpus_devices, shard_model
|
| 21 |
+
from videox_fun.models import (AutoencoderKLCogVideoX,
|
| 22 |
+
CogVideoXTransformer3DModel, T5EncoderModel,
|
| 23 |
+
T5Tokenizer)
|
| 24 |
+
from videox_fun.pipeline import (CogVideoXFunInpaintPipeline,
|
| 25 |
+
CogVideoXFunPipeline)
|
| 26 |
+
from videox_fun.data.dataset_image_video import (
|
| 27 |
+
CAMERA_POSES_CSV_NAME,
|
| 28 |
+
EMG_CONTEXT_SEC,
|
| 29 |
+
compute_normalization_stats_from_participant,
|
| 30 |
+
extract_emg_bbox_rows,
|
| 31 |
+
frame_name_to_idx,
|
| 32 |
+
list_frame_files,
|
| 33 |
+
load_bimanual_signal_df,
|
| 34 |
+
load_camera_pose_feature_df,
|
| 35 |
+
load_camera_pose_time_dict,
|
| 36 |
+
load_participant_bbox_df,
|
| 37 |
+
relative_pose_to_features,
|
| 38 |
+
resample_feature_window,
|
| 39 |
+
zero_emg_bbox_rows,
|
| 40 |
+
zero_head_pose_rows,
|
| 41 |
+
)
|
| 42 |
+
from videox_fun.utils.fp8_optimization import (convert_model_weight_to_float8, replace_parameters_by_name,
|
| 43 |
+
convert_weight_dtype_wrapper)
|
| 44 |
+
from videox_fun.utils.lora_utils import create_network
|
| 45 |
+
from videox_fun.utils.utils import get_image_to_video_latent, save_videos_grid
|
| 46 |
+
from videox_fun.utils.hypernet import VideoHyperDream
|
| 47 |
+
import json
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def load_module_from_path(module_name: str, module_path: str):
|
| 51 |
+
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
| 52 |
+
module = importlib.util.module_from_spec(spec)
|
| 53 |
+
assert spec.loader is not None
|
| 54 |
+
spec.loader.exec_module(module)
|
| 55 |
+
return module
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class MultimodalReferenceEncoder(torch.nn.Module):
|
| 59 |
+
def __init__(self, encoder_model: torch.nn.Module):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.encoder_model = encoder_model
|
| 62 |
+
|
| 63 |
+
def forward(self, ref_values):
|
| 64 |
+
emg_x = ref_values["emg_values"].float()
|
| 65 |
+
hand_bbox_x = ref_values["hand_bbox_values"].float()
|
| 66 |
+
head_pose_x = ref_values["head_pose_values"].float()
|
| 67 |
+
|
| 68 |
+
hand_camera_x = torch.cat([hand_bbox_x, head_pose_x], dim=-1)
|
| 69 |
+
emg_features = self.encoder_model.emg_encoder(emg_x)
|
| 70 |
+
hand_camera_features = self.encoder_model.hand_camera_encoder(hand_camera_x)
|
| 71 |
+
emg_features = torch.nn.functional.adaptive_avg_pool1d(
|
| 72 |
+
emg_features.transpose(1, 2),
|
| 73 |
+
hand_camera_features.shape[1],
|
| 74 |
+
).transpose(1, 2)
|
| 75 |
+
fused = torch.cat([emg_features, hand_camera_features], dim=-2)
|
| 76 |
+
return fused
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def parse_args():
|
| 80 |
+
parser = argparse.ArgumentParser(description="CogVideoX-Fun I2V Inference with LiLoRA and HyperNetwork")
|
| 81 |
+
|
| 82 |
+
# GPU memory mode
|
| 83 |
+
parser.add_argument("--gpu_memory_mode", type=str, default="model_full_load",
|
| 84 |
+
choices=["model_full_load", "model_full_load_and_qfloat8", "model_cpu_offload",
|
| 85 |
+
"model_cpu_offload_and_qfloat8", "sequential_cpu_offload"],
|
| 86 |
+
help="GPU memory mode")
|
| 87 |
+
|
| 88 |
+
# Multi GPUs config
|
| 89 |
+
parser.add_argument("--ulysses_degree", type=int, default=1, help="Ulysses degree for multi-GPU inference")
|
| 90 |
+
parser.add_argument("--ring_degree", type=int, default=1, help="Ring degree for multi-GPU inference")
|
| 91 |
+
parser.add_argument("--fsdp_dit", action="store_true", help="Use FSDP for transformer")
|
| 92 |
+
parser.add_argument("--fsdp_text_encoder", action="store_true", default=True, help="Use FSDP for text encoder")
|
| 93 |
+
parser.add_argument("--compile_dit", action="store_true", help="Compile transformer for speedup")
|
| 94 |
+
|
| 95 |
+
# Model paths
|
| 96 |
+
parser.add_argument("--model_name", type=str, default="models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP",
|
| 97 |
+
help="Path to pretrained model")
|
| 98 |
+
parser.add_argument("--sampler_name", type=str, default="DDIM_Origin",
|
| 99 |
+
choices=["Euler", "Euler A", "DPM++", "PNDM", "DDIM_Cog", "DDIM_Origin"],
|
| 100 |
+
help="Sampler name")
|
| 101 |
+
parser.add_argument("--transformer_path", type=str, default=None, help="Path to transformer checkpoint")
|
| 102 |
+
parser.add_argument("--vae_path", type=str, default=None, help="Path to VAE checkpoint")
|
| 103 |
+
|
| 104 |
+
# LiLoRA and HyperNetwork paths
|
| 105 |
+
parser.add_argument("--lilora_path", type=str, default=None, help="Path to LiLoRA weights (.safetensors)")
|
| 106 |
+
parser.add_argument("--hypernetwork_path", type=str, default=None, help="Path to HyperNetwork weights (.safetensors)")
|
| 107 |
+
parser.add_argument("--hypernetwork_input_dim", type=int, default=None,
|
| 108 |
+
help="Override HyperNetwork input feature dimension. If unset, infer from checkpoint or multimodal encoder.")
|
| 109 |
+
parser.add_argument("--multimodal_ref_encoder_ckpt_path", type=str, default=None,
|
| 110 |
+
help="Checkpoint for the EMG multimodal reference encoder used during training.")
|
| 111 |
+
parser.add_argument("--multimodal_ref_encoder_script", type=str, default=None,
|
| 112 |
+
help="Python script that defines MultimodalEMGMaskedAutoencoder and load_emg2pose_backbone.")
|
| 113 |
+
parser.add_argument("--emg2pose_ckpt_path", type=str, default=None,
|
| 114 |
+
help="Path to the EMG2Pose backbone checkpoint required by the multimodal reference encoder.")
|
| 115 |
+
parser.add_argument("--emg2pose_repo", type=str, default=None,
|
| 116 |
+
help="Path to the EMG2Pose repository required by the multimodal reference encoder.")
|
| 117 |
+
parser.add_argument("--emg_normalization_participant", type=str, default=None,
|
| 118 |
+
help="Participant directory used to compute EMG normalization stats when building ref_values from raw CSVs.")
|
| 119 |
+
parser.add_argument("--emg_camera_pose_csv_name", type=str, default=CAMERA_POSES_CSV_NAME,
|
| 120 |
+
help="Camera pose CSV filename under each participant directory.")
|
| 121 |
+
parser.add_argument("--emg_bbox_csv_name", type=str, default="hand_bboxes.csv",
|
| 122 |
+
help="Hand bbox CSV filename under each participant directory.")
|
| 123 |
+
parser.add_argument("--emg_context_sec", type=float, default=EMG_CONTEXT_SEC,
|
| 124 |
+
help="Extra sensor context before/after the selected video clip.")
|
| 125 |
+
|
| 126 |
+
# LiLoRA params (should match training config)
|
| 127 |
+
parser.add_argument("--lora_rank", type=int, default=1, help="LiLoRA rank")
|
| 128 |
+
parser.add_argument("--lora_down_dim", type=int, default=200, help="LiLoRA down dimension")
|
| 129 |
+
parser.add_argument("--lora_up_dim", type=int, default=100, help="LiLoRA up dimension")
|
| 130 |
+
parser.add_argument("--lora_weight", type=float, default=0.55, help="LiLoRA weight multiplier")
|
| 131 |
+
|
| 132 |
+
# Input data paths
|
| 133 |
+
parser.add_argument("--first_frame_path", type=str, default=None, help="Path to first frame image")
|
| 134 |
+
parser.add_argument("--ref_video_path", type=str, default=None, help="Path to reference video for HyperNetwork")
|
| 135 |
+
|
| 136 |
+
# Video generation params
|
| 137 |
+
parser.add_argument("--video_length", type=int, default=49, help="Number of frames to generate")
|
| 138 |
+
parser.add_argument("--fps", type=int, default=8, help="FPS for output video")
|
| 139 |
+
parser.add_argument("--partial_video_length", type=int, default=None,
|
| 140 |
+
help="Length of each sub video segment for ultra long video generation")
|
| 141 |
+
parser.add_argument("--overlap_video_length", type=int, default=4,
|
| 142 |
+
help="Overlap length between segments for ultra long video generation")
|
| 143 |
+
|
| 144 |
+
# Weight dtype
|
| 145 |
+
parser.add_argument("--weight_dtype", type=str, default="bfloat16", choices=["bfloat16", "float16", "float32"],
|
| 146 |
+
help="Weight dtype")
|
| 147 |
+
|
| 148 |
+
# Prompts
|
| 149 |
+
parser.add_argument("--prompt", type=str, default=None, help="Prompt for video generation")
|
| 150 |
+
parser.add_argument("--negative_prompt", type=str,
|
| 151 |
+
default="The video is not of a high quality, it has a low resolution. "
|
| 152 |
+
"Watermark present in each frame. The background is solid. "
|
| 153 |
+
"Strange body and strange trajectory. Distortion.",
|
| 154 |
+
help="Negative prompt")
|
| 155 |
+
|
| 156 |
+
# Inference params
|
| 157 |
+
parser.add_argument("--guidance_scale", type=float, default=6.0, help="Guidance scale")
|
| 158 |
+
parser.add_argument("--seed", type=int, default=43, help="Random seed")
|
| 159 |
+
parser.add_argument("--num_inference_steps", type=int, default=50, help="Number of inference steps")
|
| 160 |
+
|
| 161 |
+
# Output
|
| 162 |
+
parser.add_argument("--save_path", type=str, default="samples/cogvideox-fun-videos_i2v",
|
| 163 |
+
help="Path to save generated videos")
|
| 164 |
+
|
| 165 |
+
# Test set (JSON)
|
| 166 |
+
parser.add_argument("--test_json_path", type=str, default=None,
|
| 167 |
+
help="Path to JSON file containing test samples")
|
| 168 |
+
|
| 169 |
+
return parser.parse_args()
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _resolve_path(path_value, base_dir=None):
|
| 173 |
+
if path_value is None:
|
| 174 |
+
return None
|
| 175 |
+
if os.path.isabs(path_value):
|
| 176 |
+
return path_value
|
| 177 |
+
if base_dir is not None:
|
| 178 |
+
candidate = os.path.join(base_dir, path_value)
|
| 179 |
+
if os.path.exists(candidate):
|
| 180 |
+
return candidate
|
| 181 |
+
return os.path.abspath(path_value)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _as_numpy_float32(value):
|
| 185 |
+
if value is None:
|
| 186 |
+
return None
|
| 187 |
+
if torch.is_tensor(value):
|
| 188 |
+
value = value.detach().cpu().numpy()
|
| 189 |
+
return np.asarray(value, dtype=np.float32)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _coerce_ref_values_dict(ref_values):
|
| 193 |
+
if ref_values is None:
|
| 194 |
+
return None
|
| 195 |
+
|
| 196 |
+
required = ("emg_values", "hand_bbox_values", "head_pose_values")
|
| 197 |
+
if not all(key in ref_values for key in required):
|
| 198 |
+
missing = [key for key in required if key not in ref_values]
|
| 199 |
+
raise ValueError(f"ref_values is missing required keys: {missing}")
|
| 200 |
+
|
| 201 |
+
out = {}
|
| 202 |
+
for key in required:
|
| 203 |
+
out[key] = _as_numpy_float32(ref_values[key])
|
| 204 |
+
return out
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _infer_participant_path(sample_info, first_frame_path):
|
| 208 |
+
participant_path = sample_info.get("participant_path")
|
| 209 |
+
if participant_path is not None:
|
| 210 |
+
return participant_path
|
| 211 |
+
|
| 212 |
+
if first_frame_path is None:
|
| 213 |
+
return None
|
| 214 |
+
|
| 215 |
+
frame_dir = os.path.dirname(first_frame_path)
|
| 216 |
+
if os.path.basename(frame_dir) == "frames":
|
| 217 |
+
return os.path.dirname(frame_dir)
|
| 218 |
+
return os.path.dirname(first_frame_path)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _infer_frame_indices(sample_info, first_frame_path, video_length):
|
| 222 |
+
frame_indices = sample_info.get("frame_indices")
|
| 223 |
+
if frame_indices is not None:
|
| 224 |
+
return [int(x) for x in frame_indices]
|
| 225 |
+
|
| 226 |
+
frame_dir = sample_info.get("frames_dir")
|
| 227 |
+
if frame_dir is None and first_frame_path is not None:
|
| 228 |
+
frame_dir = os.path.dirname(first_frame_path)
|
| 229 |
+
|
| 230 |
+
if first_frame_path is None:
|
| 231 |
+
return None
|
| 232 |
+
|
| 233 |
+
try:
|
| 234 |
+
start_idx = frame_name_to_idx(first_frame_path)
|
| 235 |
+
except Exception:
|
| 236 |
+
start_idx = None
|
| 237 |
+
|
| 238 |
+
if frame_dir is not None and os.path.isdir(frame_dir):
|
| 239 |
+
try:
|
| 240 |
+
frame_paths = list_frame_files(frame_dir)
|
| 241 |
+
filename_to_pos = {os.path.basename(path): idx for idx, path in enumerate(frame_paths)}
|
| 242 |
+
start_pos = filename_to_pos.get(os.path.basename(first_frame_path))
|
| 243 |
+
if start_pos is not None:
|
| 244 |
+
selected = frame_paths[start_pos:start_pos + video_length]
|
| 245 |
+
if len(selected) == video_length:
|
| 246 |
+
return [frame_name_to_idx(path) for path in selected]
|
| 247 |
+
except Exception:
|
| 248 |
+
pass
|
| 249 |
+
|
| 250 |
+
if start_idx is not None:
|
| 251 |
+
return [start_idx + i for i in range(video_length)]
|
| 252 |
+
return None
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def build_emg_ref_values(sample_info, first_frame_path, video_length, args):
|
| 256 |
+
direct_ref_values = sample_info.get("ref_values")
|
| 257 |
+
if direct_ref_values is not None:
|
| 258 |
+
return _coerce_ref_values_dict(direct_ref_values)
|
| 259 |
+
|
| 260 |
+
if all(key in sample_info for key in ("emg_values", "hand_bbox_values", "head_pose_values")):
|
| 261 |
+
return _coerce_ref_values_dict(sample_info)
|
| 262 |
+
|
| 263 |
+
participant_path = _infer_participant_path(sample_info, first_frame_path)
|
| 264 |
+
frame_indices = _infer_frame_indices(sample_info, first_frame_path, video_length)
|
| 265 |
+
if participant_path is None or frame_indices is None:
|
| 266 |
+
return None
|
| 267 |
+
|
| 268 |
+
participant_path = os.path.abspath(participant_path)
|
| 269 |
+
pose_time_dict = load_camera_pose_time_dict(participant_path, args.emg_camera_pose_csv_name)
|
| 270 |
+
hand_data, signal_cols = load_bimanual_signal_df(participant_path)
|
| 271 |
+
|
| 272 |
+
clip_times = []
|
| 273 |
+
for frame_idx in frame_indices:
|
| 274 |
+
if frame_idx not in pose_time_dict:
|
| 275 |
+
raise ValueError(f"Missing pose timestamp for frame_idx={frame_idx} in {participant_path}")
|
| 276 |
+
clip_times.append(float(pose_time_dict[frame_idx]))
|
| 277 |
+
|
| 278 |
+
sensor_start_t = min(clip_times) - args.emg_context_sec
|
| 279 |
+
sensor_end_t = max(clip_times) + args.emg_context_sec
|
| 280 |
+
|
| 281 |
+
emg_signal_length = int(sample_info.get("emg_fixed_signal_length") or sample_info.get("signal_length") or 1883)
|
| 282 |
+
left_emg = resample_feature_window(
|
| 283 |
+
hand_data["left_time"],
|
| 284 |
+
hand_data["left_data"],
|
| 285 |
+
sensor_start_t,
|
| 286 |
+
sensor_end_t,
|
| 287 |
+
emg_signal_length,
|
| 288 |
+
)
|
| 289 |
+
right_emg = resample_feature_window(
|
| 290 |
+
hand_data["right_time"],
|
| 291 |
+
hand_data["right_data"],
|
| 292 |
+
sensor_start_t,
|
| 293 |
+
sensor_end_t,
|
| 294 |
+
emg_signal_length,
|
| 295 |
+
)
|
| 296 |
+
emg_values = np.concatenate([left_emg, right_emg], axis=1).astype(np.float32)
|
| 297 |
+
|
| 298 |
+
norm_participant = args.emg_normalization_participant
|
| 299 |
+
if norm_participant is not None:
|
| 300 |
+
norm_participant = os.path.abspath(norm_participant)
|
| 301 |
+
norm_mean, norm_std, _ = compute_normalization_stats_from_participant(norm_participant)
|
| 302 |
+
emg_values = ((emg_values - norm_mean) / norm_std).astype(np.float32)
|
| 303 |
+
|
| 304 |
+
try:
|
| 305 |
+
bbox_df = load_participant_bbox_df(participant_path, args.emg_bbox_csv_name).set_index("frame_idx")
|
| 306 |
+
bbox_values, _ = extract_emg_bbox_rows(bbox_df, frame_indices)
|
| 307 |
+
except Exception:
|
| 308 |
+
bbox_values, _ = zero_emg_bbox_rows(frame_indices)
|
| 309 |
+
|
| 310 |
+
try:
|
| 311 |
+
pose_df = load_camera_pose_feature_df(participant_path, args.emg_camera_pose_csv_name).set_index("frame_idx")
|
| 312 |
+
if frame_indices[0] not in pose_df.index:
|
| 313 |
+
raise ValueError(f"Reference frame {frame_indices[0]} missing from pose CSV")
|
| 314 |
+
ref_row = pose_df.loc[frame_indices[0]]
|
| 315 |
+
from videox_fun.data.dataset_image_video import pose_row_to_T
|
| 316 |
+
|
| 317 |
+
T_ref = pose_row_to_T(ref_row["tx"], ref_row["ty"], ref_row["tz"], ref_row["qx"], ref_row["qy"], ref_row["qz"], ref_row["qw"])
|
| 318 |
+
pose_rows = []
|
| 319 |
+
for frame_idx in frame_indices:
|
| 320 |
+
if frame_idx not in pose_df.index:
|
| 321 |
+
raise ValueError(f"Frame {frame_idx} missing from pose CSV")
|
| 322 |
+
row = pose_df.loc[frame_idx]
|
| 323 |
+
T_curr = pose_row_to_T(row["tx"], row["ty"], row["tz"], row["qx"], row["qy"], row["qz"], row["qw"])
|
| 324 |
+
pose_rows.append(relative_pose_to_features(T_ref, T_curr))
|
| 325 |
+
head_pose_values = np.asarray(pose_rows, dtype=np.float32)
|
| 326 |
+
except Exception:
|
| 327 |
+
head_pose_values, _ = zero_head_pose_rows(frame_indices)
|
| 328 |
+
|
| 329 |
+
return {
|
| 330 |
+
"emg_values": emg_values.astype(np.float32),
|
| 331 |
+
"hand_bbox_values": bbox_values.astype(np.float32),
|
| 332 |
+
"head_pose_values": head_pose_values.astype(np.float32),
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def build_multimodal_ref_encoder(args, sample_ref_values, weight_dtype):
|
| 337 |
+
missing = []
|
| 338 |
+
if args.multimodal_ref_encoder_ckpt_path is None:
|
| 339 |
+
missing.append("--multimodal_ref_encoder_ckpt_path")
|
| 340 |
+
if args.multimodal_ref_encoder_script is None:
|
| 341 |
+
missing.append("--multimodal_ref_encoder_script")
|
| 342 |
+
if args.emg2pose_ckpt_path is None:
|
| 343 |
+
missing.append("--emg2pose_ckpt_path")
|
| 344 |
+
if args.emg2pose_repo is None:
|
| 345 |
+
missing.append("--emg2pose_repo")
|
| 346 |
+
if missing:
|
| 347 |
+
raise ValueError(f"EMG-conditioned inference requires: {', '.join(missing)}")
|
| 348 |
+
|
| 349 |
+
videox_module = load_module_from_path(
|
| 350 |
+
"videox_emg_multimodal_infer",
|
| 351 |
+
args.multimodal_ref_encoder_script,
|
| 352 |
+
)
|
| 353 |
+
checkpoint = torch.load(args.multimodal_ref_encoder_ckpt_path, map_location="cpu")
|
| 354 |
+
checkpoint_config = checkpoint.get("config", {})
|
| 355 |
+
|
| 356 |
+
emg_channels = int(sample_ref_values["emg_values"].shape[-1])
|
| 357 |
+
bbox_channels = int(sample_ref_values["hand_bbox_values"].shape[-1])
|
| 358 |
+
pose_channels = int(sample_ref_values["head_pose_values"].shape[-1])
|
| 359 |
+
hand_camera_channels = bbox_channels + pose_channels
|
| 360 |
+
seq_len = int(sample_ref_values["emg_values"].shape[0])
|
| 361 |
+
|
| 362 |
+
emg_backbone = videox_module.load_emg2pose_backbone(
|
| 363 |
+
str(args.emg2pose_ckpt_path),
|
| 364 |
+
str(args.emg2pose_repo),
|
| 365 |
+
)
|
| 366 |
+
encoder_model = videox_module.MultimodalEMGMaskedAutoencoder(
|
| 367 |
+
emg_channels=emg_channels,
|
| 368 |
+
hand_camera_channels=hand_camera_channels,
|
| 369 |
+
bbox_channels=bbox_channels,
|
| 370 |
+
pose_channels=pose_channels,
|
| 371 |
+
emg_backbone=emg_backbone,
|
| 372 |
+
seq_len=seq_len,
|
| 373 |
+
hidden_dim=checkpoint_config.get("hidden_dim", 256),
|
| 374 |
+
latent_dim=checkpoint_config.get("latent_dim", 256),
|
| 375 |
+
kernel_size=checkpoint_config.get("kernel_size", 3),
|
| 376 |
+
dilation_rates=checkpoint_config.get("dilation_rates", [1, 2, 4, 8, 16, 32]),
|
| 377 |
+
encoder_stacks=checkpoint_config.get("encoder_stacks", 3),
|
| 378 |
+
decoder_stacks=checkpoint_config.get("decoder_stacks", 2),
|
| 379 |
+
dropout=checkpoint_config.get("dropout", 0.1),
|
| 380 |
+
derivative_loss_weight=checkpoint_config.get("derivative_loss_weight", 0.1),
|
| 381 |
+
frequency_loss_weight=checkpoint_config.get("frequency_loss_weight", 0.05),
|
| 382 |
+
high_freq_weight=checkpoint_config.get("high_freq_weight", 2.0),
|
| 383 |
+
)
|
| 384 |
+
encoder_model.load_state_dict(checkpoint["model"], strict=True)
|
| 385 |
+
encoder_model.eval()
|
| 386 |
+
encoder_model.requires_grad_(False)
|
| 387 |
+
encoder_model = encoder_model.to(dtype=weight_dtype)
|
| 388 |
+
return MultimodalReferenceEncoder(encoder_model), int(checkpoint_config.get("latent_dim", 256))
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def get_hypernetwork_input_dim(args, hyper_state_dict, multimodal_input_dim=None):
|
| 392 |
+
if args.hypernetwork_input_dim is not None:
|
| 393 |
+
return int(args.hypernetwork_input_dim)
|
| 394 |
+
if multimodal_input_dim is not None:
|
| 395 |
+
return int(multimodal_input_dim)
|
| 396 |
+
feature_proj_weight = hyper_state_dict.get("img_weight_generator.feature_proj.weight")
|
| 397 |
+
if feature_proj_weight is None:
|
| 398 |
+
raise ValueError("Could not infer HyperNetwork input dim from checkpoint. Please pass --hypernetwork_input_dim.")
|
| 399 |
+
return int(feature_proj_weight.shape[1])
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features):
|
| 403 |
+
_, weight_list = hypernetwork(ref_features)
|
| 404 |
+
for weight, lora_layer in zip(weight_list, lilora_network.unet_loras):
|
| 405 |
+
if weight.dim() == 3:
|
| 406 |
+
weight = weight.view(weight.size(0), -1)
|
| 407 |
+
elif weight.dim() == 2:
|
| 408 |
+
if weight.size(0) == 1:
|
| 409 |
+
weight = weight.view(-1)
|
| 410 |
+
else:
|
| 411 |
+
weight = weight.view(weight.size(0), -1)
|
| 412 |
+
elif weight.dim() == 1:
|
| 413 |
+
weight = weight.view(-1)
|
| 414 |
+
lora_layer.update_weight(weight)
|
| 415 |
+
lora_layer.down_aux.data = lora_layer.down_aux.data.to(dtype=weight.dtype)
|
| 416 |
+
lora_layer.up_aux.data = lora_layer.up_aux.data.to(dtype=weight.dtype)
|
| 417 |
+
return len(weight_list)
|
| 418 |
+
|
| 419 |
+
def load_ref_video_frames(ref_video_path, target_size, num_frames=None):
|
| 420 |
+
"""
|
| 421 |
+
Load reference video frames from video file or image directory
|
| 422 |
+
|
| 423 |
+
Args:
|
| 424 |
+
ref_video_path: Path to video file or directory containing image frames
|
| 425 |
+
target_size: Target size [height, width] for resizing
|
| 426 |
+
num_frames: Number of frames to load (if None, load all available)
|
| 427 |
+
|
| 428 |
+
Returns:
|
| 429 |
+
ref_pixel_values: Tensor of shape [B, F, C, H, W] in 0~1 range
|
| 430 |
+
"""
|
| 431 |
+
import cv2
|
| 432 |
+
|
| 433 |
+
target_h, target_w = target_size
|
| 434 |
+
|
| 435 |
+
ref_frames = []
|
| 436 |
+
|
| 437 |
+
if os.path.isfile(ref_video_path):
|
| 438 |
+
cap = cv2.VideoCapture(ref_video_path)
|
| 439 |
+
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 440 |
+
|
| 441 |
+
if num_frames is None:
|
| 442 |
+
num_frames = frame_count
|
| 443 |
+
|
| 444 |
+
for i in range(num_frames):
|
| 445 |
+
ret, frame = cap.read()
|
| 446 |
+
if not ret:
|
| 447 |
+
break
|
| 448 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 449 |
+
frame = Image.fromarray(frame)
|
| 450 |
+
frame = frame.resize((target_w, target_h))
|
| 451 |
+
ref_frames.append(np.array(frame))
|
| 452 |
+
|
| 453 |
+
cap.release()
|
| 454 |
+
elif os.path.isdir(ref_video_path):
|
| 455 |
+
image_files = sorted([f for f in os.listdir(ref_video_path) if f.endswith(('.png', '.jpg', '.jpeg'))])
|
| 456 |
+
|
| 457 |
+
if num_frames is None:
|
| 458 |
+
num_frames = len(image_files)
|
| 459 |
+
|
| 460 |
+
for i in range(num_frames):
|
| 461 |
+
if i >= len(image_files):
|
| 462 |
+
break
|
| 463 |
+
frame = Image.open(os.path.join(ref_video_path, image_files[i])).convert('RGB')
|
| 464 |
+
frame = frame.resize((target_w, target_h))
|
| 465 |
+
ref_frames.append(np.array(frame))
|
| 466 |
+
|
| 467 |
+
if len(ref_frames) == 0:
|
| 468 |
+
raise ValueError(f"No frames loaded from {ref_video_path}")
|
| 469 |
+
|
| 470 |
+
ref_frames_np = np.array(ref_frames)
|
| 471 |
+
ref_frames_tensor = torch.from_numpy(ref_frames_np).float()
|
| 472 |
+
ref_frames_tensor = ref_frames_tensor / 255.0
|
| 473 |
+
|
| 474 |
+
ref_frames_tensor = ref_frames_tensor.unsqueeze(0)
|
| 475 |
+
|
| 476 |
+
print(f"DEBUG: ref_frames_tensor shape after unsqueeze(0): {ref_frames_tensor.shape}")
|
| 477 |
+
|
| 478 |
+
return ref_frames_tensor
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def get_model_device(model):
|
| 482 |
+
"""安全获取模型实际设备,处理 CPU offload 模式"""
|
| 483 |
+
try:
|
| 484 |
+
params = list(model.parameters())
|
| 485 |
+
if len(params) > 0:
|
| 486 |
+
return params[0].device
|
| 487 |
+
buffers = list(model.buffers())
|
| 488 |
+
if len(buffers) > 0:
|
| 489 |
+
return buffers[0].device
|
| 490 |
+
except Exception:
|
| 491 |
+
pass
|
| 492 |
+
return torch.device("cpu")
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def process_sample(
|
| 496 |
+
pipeline,
|
| 497 |
+
vae,
|
| 498 |
+
device,
|
| 499 |
+
weight_dtype,
|
| 500 |
+
hypernetwork,
|
| 501 |
+
lilora_network,
|
| 502 |
+
multimodal_ref_encoder,
|
| 503 |
+
sample_info,
|
| 504 |
+
sample_size,
|
| 505 |
+
args,
|
| 506 |
+
):
|
| 507 |
+
"""
|
| 508 |
+
Process a single test sample
|
| 509 |
+
|
| 510 |
+
Args:
|
| 511 |
+
pipeline: CogVideoX pipeline
|
| 512 |
+
vae: VAE model
|
| 513 |
+
device: device
|
| 514 |
+
weight_dtype: weight dtype
|
| 515 |
+
hypernetwork: VideoHyperDream model (or None)
|
| 516 |
+
lilora_network: LoRANetwork model (or None)
|
| 517 |
+
sample_info: dict with first_frame_path, ref_video_path, text, video_name
|
| 518 |
+
sample_size: [height, width]
|
| 519 |
+
args: other arguments
|
| 520 |
+
|
| 521 |
+
Returns:
|
| 522 |
+
sample: generated video tensor
|
| 523 |
+
"""
|
| 524 |
+
first_frame_path = sample_info.get('first_frame_path')
|
| 525 |
+
ref_video_path = sample_info.get('ref_video_path')
|
| 526 |
+
prompt = sample_info.get('text', '')
|
| 527 |
+
video_name = sample_info.get('video_name', 'sample')
|
| 528 |
+
|
| 529 |
+
# 如果 JSON 中没有提供 prompt,使用命令行参数中的默认值
|
| 530 |
+
if not prompt or not prompt.strip():
|
| 531 |
+
prompt = args.get('prompt', '')
|
| 532 |
+
if prompt:
|
| 533 |
+
print(f"Using prompt from command line: {prompt[:50]}...")
|
| 534 |
+
else:
|
| 535 |
+
print(f"Warning: No prompt provided for sample {video_name}")
|
| 536 |
+
return None
|
| 537 |
+
|
| 538 |
+
if first_frame_path is None or not os.path.exists(first_frame_path):
|
| 539 |
+
print(f"Warning: first_frame_path not found: {first_frame_path}")
|
| 540 |
+
return None
|
| 541 |
+
|
| 542 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(
|
| 543 |
+
first_frame_path, None, video_length=args['video_length'], sample_size=sample_size
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
original_image = Image.open(first_frame_path).convert('RGB')
|
| 547 |
+
original_width, original_height = original_image.size
|
| 548 |
+
print(f"\n[Debug Input Video Processing]")
|
| 549 |
+
print(f"[Debug Input] first_frame_path: {first_frame_path}")
|
| 550 |
+
print(f"[Debug Input] Original image size: ({original_width}, {original_height})")
|
| 551 |
+
print(f"[Debug Input] sample_size (after resize): {sample_size}")
|
| 552 |
+
print(f"[Debug Input] input_video type: {type(input_video)}")
|
| 553 |
+
if isinstance(input_video, torch.Tensor):
|
| 554 |
+
print(f"[Debug Input] input_video shape: {input_video.shape}")
|
| 555 |
+
if input_video.dim() == 5:
|
| 556 |
+
B, C, F, H, W = input_video.shape
|
| 557 |
+
print(f"[Debug Input] Input tensor: B={B}, C={C}, F={F}, H={H}, W={W}")
|
| 558 |
+
print(f"[Debug Input] Height matches sample_size[0]: {H == sample_size[0]}, Width matches sample_size[1]: {W == sample_size[1]}")
|
| 559 |
+
if input_video_mask is not None and isinstance(input_video_mask, torch.Tensor):
|
| 560 |
+
print(f"[Debug Input] input_video_mask shape: {input_video_mask.shape}")
|
| 561 |
+
print("-" * 40)
|
| 562 |
+
|
| 563 |
+
if hypernetwork is not None and lilora_network is not None:
|
| 564 |
+
emg_ref_values = build_emg_ref_values(sample_info, first_frame_path, args['video_length'], args['cli_args'])
|
| 565 |
+
|
| 566 |
+
if emg_ref_values is not None:
|
| 567 |
+
if multimodal_ref_encoder is None:
|
| 568 |
+
multimodal_ref_encoder, _ = build_multimodal_ref_encoder(
|
| 569 |
+
args["cli_args"],
|
| 570 |
+
emg_ref_values,
|
| 571 |
+
weight_dtype,
|
| 572 |
+
)
|
| 573 |
+
multimodal_ref_encoder = multimodal_ref_encoder.to(device=device, dtype=weight_dtype)
|
| 574 |
+
multimodal_ref_encoder.eval()
|
| 575 |
+
|
| 576 |
+
ref_inputs = {
|
| 577 |
+
key: torch.from_numpy(value).unsqueeze(0).to(device=device, dtype=weight_dtype)
|
| 578 |
+
for key, value in emg_ref_values.items()
|
| 579 |
+
}
|
| 580 |
+
with torch.no_grad():
|
| 581 |
+
ref_features = multimodal_ref_encoder(ref_inputs)
|
| 582 |
+
updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
|
| 583 |
+
print(
|
| 584 |
+
f"Updated {updated_layers} LiLoRA layers with multimodal EMG reference features "
|
| 585 |
+
f"from sample {video_name}."
|
| 586 |
+
)
|
| 587 |
+
elif ref_video_path is not None and os.path.exists(ref_video_path):
|
| 588 |
+
print(f"Generating weights from reference video: {ref_video_path}")
|
| 589 |
+
ref_frames_tensor = load_ref_video_frames(ref_video_path, sample_size)
|
| 590 |
+
_, F, _, _, _ = ref_frames_tensor.shape
|
| 591 |
+
ref_pixel_values = ref_frames_tensor.permute(0, 4, 1, 2, 3).contiguous()
|
| 592 |
+
ref_pixel_values = ref_pixel_values.to(dtype=weight_dtype)
|
| 593 |
+
|
| 594 |
+
with torch.no_grad():
|
| 595 |
+
vae_device = get_model_device(vae)
|
| 596 |
+
ref_pixel_values = ref_pixel_values.to(device=vae_device, dtype=weight_dtype)
|
| 597 |
+
ref_features = vae.encode(ref_pixel_values).latent_dist.sample()
|
| 598 |
+
ref_features = ref_features * vae.config.scaling_factor
|
| 599 |
+
|
| 600 |
+
updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
|
| 601 |
+
print(f"Updated {updated_layers} LiLoRA layers with hypernetwork weights from {F} reference frames.")
|
| 602 |
+
|
| 603 |
+
generator = torch.Generator(device=device).manual_seed(args.get('seed', 43))
|
| 604 |
+
|
| 605 |
+
with torch.no_grad():
|
| 606 |
+
sample = pipeline(
|
| 607 |
+
prompt,
|
| 608 |
+
num_frames=args['video_length'],
|
| 609 |
+
negative_prompt=args.get('negative_prompt', ''),
|
| 610 |
+
height=sample_size[0],
|
| 611 |
+
width=sample_size[1],
|
| 612 |
+
generator=generator,
|
| 613 |
+
guidance_scale=args.get('guidance_scale', 6.0),
|
| 614 |
+
num_inference_steps=args.get('num_inference_steps', 50),
|
| 615 |
+
video=input_video,
|
| 616 |
+
mask_video=input_video_mask
|
| 617 |
+
).videos
|
| 618 |
+
|
| 619 |
+
print(f"\n[Debug Pipeline Output @ Inference]")
|
| 620 |
+
print(f"[Debug Pipeline] Original image size: ({original_width}, {original_height})")
|
| 621 |
+
print(f"[Debug Pipeline] Sample size requested: ({sample_size[0]}, {sample_size[1]})")
|
| 622 |
+
print(f"[Debug Pipeline] Pipeline output shape: {sample.shape}")
|
| 623 |
+
|
| 624 |
+
if isinstance(sample, torch.Tensor):
|
| 625 |
+
if sample.dim() == 5:
|
| 626 |
+
B, C, F, H, W = sample.shape
|
| 627 |
+
print(f"[Debug Pipeline] Output tensor shape: B={B}, C={C}, F={F}, H={H}, W={W}")
|
| 628 |
+
|
| 629 |
+
expected_H = original_height
|
| 630 |
+
expected_W = original_width
|
| 631 |
+
print(f"\n[Debug Size Verification]")
|
| 632 |
+
print(f"[Debug] Comparing: Original image ({original_height}, {original_width}) vs Output video ({H}, {W})")
|
| 633 |
+
|
| 634 |
+
if H == expected_H and W == expected_W:
|
| 635 |
+
print(f"[Debug] ✓ Size MATCH! Output matches original image size")
|
| 636 |
+
else:
|
| 637 |
+
print(f"[Debug] ✗ Size MISMATCH!")
|
| 638 |
+
print(f"[Debug] Expected: ({expected_H}, {expected_W})")
|
| 639 |
+
print(f"[Debug] Got: ({H}, {W})")
|
| 640 |
+
print(f"[Debug] Difference: H={H-expected_H} ({((H-expected_H)/expected_H*100):.1f}%), W={W-expected_W} ({((W-expected_W)/expected_W*100):.1f}%)")
|
| 641 |
+
|
| 642 |
+
if H != expected_H or W != expected_W:
|
| 643 |
+
print(f"\n[Debug Analysis]")
|
| 644 |
+
print(f"[Debug] VAE config - scaling_factor: {vae.config.scaling_factor}")
|
| 645 |
+
print(f"[Debug] VAE config - latent_channels: {vae.config.latent_channels}")
|
| 646 |
+
if hasattr(vae, 'config') and hasattr(vae.config, 'decoder'):
|
| 647 |
+
print(f"[Debug] VAE decoder will upsample by factor of 4x or 8x")
|
| 648 |
+
else:
|
| 649 |
+
print(f"[Debug Pipeline] Unexpected tensor dimensions: {sample.dim()}")
|
| 650 |
+
|
| 651 |
+
print("-" * 80)
|
| 652 |
+
|
| 653 |
+
return sample
|
| 654 |
+
|
| 655 |
+
def main():
|
| 656 |
+
args = parse_args()
|
| 657 |
+
|
| 658 |
+
# Convert weight dtype string to torch dtype
|
| 659 |
+
weight_dtype_map = {
|
| 660 |
+
"bfloat16": torch.bfloat16,
|
| 661 |
+
"float16": torch.float16,
|
| 662 |
+
"float32": torch.float32
|
| 663 |
+
}
|
| 664 |
+
weight_dtype = weight_dtype_map.get(args.weight_dtype, torch.bfloat16)
|
| 665 |
+
|
| 666 |
+
# GPU memory mode, which can be chosen in [model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload].
|
| 667 |
+
# model_full_load means that the entire model will be moved to the GPU.
|
| 668 |
+
#
|
| 669 |
+
# model_full_load_and_qfloat8 means that the entire model will be moved to the GPU,
|
| 670 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 671 |
+
#
|
| 672 |
+
# model_cpu_offload means that the entire model will be moved to the CPU after use, which can save some GPU memory.
|
| 673 |
+
#
|
| 674 |
+
# model_cpu_offload_and_qfloat8 indicates that the entire model will be moved to the CPU after use,
|
| 675 |
+
# and the transformer model has been quantized to float8, which can save more GPU memory.
|
| 676 |
+
#
|
| 677 |
+
# sequential_cpu_offload means that each layer of the model will be moved to the CPU after use,
|
| 678 |
+
# resulting in slower speeds but saving a large amount of GPU memory.
|
| 679 |
+
GPU_memory_mode = args.gpu_memory_mode
|
| 680 |
+
# Multi GPUs config
|
| 681 |
+
# Please ensure that the product of ulysses_degree and ring_degree equals the number of GPUs used.
|
| 682 |
+
# For example, if you are using 8 GPUs, you can set ulysses_degree = 2 and ring_degree = 4.
|
| 683 |
+
# If you are using 1 GPU, you can set ulysses_degree = 1 and ring_degree = 1.
|
| 684 |
+
ulysses_degree = args.ulysses_degree
|
| 685 |
+
ring_degree = args.ring_degree
|
| 686 |
+
# Use FSDP to save more GPU memory in multi gpus.
|
| 687 |
+
fsdp_dit = args.fsdp_dit
|
| 688 |
+
fsdp_text_encoder = args.fsdp_text_encoder
|
| 689 |
+
# Compile will give a speedup in fixed resolution and need a little GPU memory.
|
| 690 |
+
# The compile_dit is not compatible with the fsdp_dit and sequential_cpu_offload.
|
| 691 |
+
compile_dit = args.compile_dit
|
| 692 |
+
|
| 693 |
+
# Config and model path
|
| 694 |
+
model_name = args.model_name
|
| 695 |
+
|
| 696 |
+
# Choose the sampler in "Euler" "Euler A" "DPM++" "PNDM" "DDIM_Cog" and "DDIM_Origin"
|
| 697 |
+
sampler_name = args.sampler_name
|
| 698 |
+
|
| 699 |
+
# Load pretrained model if need
|
| 700 |
+
transformer_path = args.transformer_path
|
| 701 |
+
vae_path = args.vae_path
|
| 702 |
+
|
| 703 |
+
# LiLoRA and HyperNetwork paths
|
| 704 |
+
lilora_path = args.lilora_path
|
| 705 |
+
hypernetwork_path = args.hypernetwork_path
|
| 706 |
+
|
| 707 |
+
# Input data paths
|
| 708 |
+
first_frame_path = args.first_frame_path
|
| 709 |
+
ref_video_path = args.ref_video_path
|
| 710 |
+
|
| 711 |
+
# LiLoRA params (should match training config)
|
| 712 |
+
lora_rank = args.lora_rank
|
| 713 |
+
lora_down_dim = args.lora_down_dim
|
| 714 |
+
lora_up_dim = args.lora_up_dim
|
| 715 |
+
lora_weight = args.lora_weight
|
| 716 |
+
|
| 717 |
+
# Other params
|
| 718 |
+
sample_size = [384, 672]
|
| 719 |
+
# V1.0 and V1.1 support up to 49 frames of video generation,
|
| 720 |
+
# while V1.5 supports up to 85 frames.
|
| 721 |
+
video_length = args.video_length
|
| 722 |
+
fps = args.fps
|
| 723 |
+
|
| 724 |
+
# If you want to generate ultra long videos, please set partial_video_length as the length of each sub video segment
|
| 725 |
+
partial_video_length = args.partial_video_length
|
| 726 |
+
overlap_video_length = args.overlap_video_length
|
| 727 |
+
|
| 728 |
+
# If you want to generate from text, please set the validation_image_start = None and validation_image_end = None
|
| 729 |
+
validation_image_start = None # Will be set from first_frame_path below
|
| 730 |
+
validation_image_end = None
|
| 731 |
+
|
| 732 |
+
# Use first_frame_path for image-to-video generation
|
| 733 |
+
# If first_frame_path is provided, it will be used as the starting frame
|
| 734 |
+
# and sample_size will be set to match the first frame dimensions
|
| 735 |
+
# Note: If test_json_path is provided, first_frame_path will be read from JSON
|
| 736 |
+
if args.test_json_path is None: # Only check when NOT using test JSON
|
| 737 |
+
if first_frame_path is not None and os.path.exists(first_frame_path):
|
| 738 |
+
first_frame = Image.open(first_frame_path).convert('RGB')
|
| 739 |
+
W, H = first_frame.size
|
| 740 |
+
sample_size = [H, W] # PIL image.size is (W, H), sample_size should be [H, W]
|
| 741 |
+
validation_image_start = first_frame_path
|
| 742 |
+
validation_image_end = None
|
| 743 |
+
print(f"Using first frame from: {first_frame_path}, sample_size: {sample_size}")
|
| 744 |
+
else:
|
| 745 |
+
raise ValueError("first_frame_path must be provided and exist for direct I2V inference")
|
| 746 |
+
|
| 747 |
+
# HyperNetwork reference video path (required when using hypernetwork)
|
| 748 |
+
# Reference video should be a video file path or a list of image frames
|
| 749 |
+
# The reference video will be encoded by VAE and used by HyperNetwork to generate LiLoRA weights
|
| 750 |
+
ref_video_path = args.ref_video_path
|
| 751 |
+
|
| 752 |
+
# prompts
|
| 753 |
+
prompt = args.prompt
|
| 754 |
+
negative_prompt = args.negative_prompt
|
| 755 |
+
guidance_scale = args.guidance_scale
|
| 756 |
+
seed = args.seed
|
| 757 |
+
num_inference_steps = args.num_inference_steps
|
| 758 |
+
lora_weight = args.lora_weight
|
| 759 |
+
save_path = args.save_path
|
| 760 |
+
|
| 761 |
+
# 初始化多 GPU 设备
|
| 762 |
+
device = set_multi_gpus_devices(ulysses_degree, ring_degree)
|
| 763 |
+
|
| 764 |
+
transformer = CogVideoXTransformer3DModel.from_pretrained(
|
| 765 |
+
model_name,
|
| 766 |
+
subfolder="transformer",
|
| 767 |
+
low_cpu_mem_usage=True,
|
| 768 |
+
torch_dtype=weight_dtype,
|
| 769 |
+
).to(weight_dtype)
|
| 770 |
+
|
| 771 |
+
if transformer_path is not None:
|
| 772 |
+
print(f"From checkpoint: {transformer_path}")
|
| 773 |
+
if transformer_path.endswith("safetensors"):
|
| 774 |
+
from safetensors.torch import load_file, safe_open
|
| 775 |
+
state_dict = load_file(transformer_path)
|
| 776 |
+
else:
|
| 777 |
+
state_dict = torch.load(transformer_path, map_location="cpu")
|
| 778 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 779 |
+
|
| 780 |
+
m, u = transformer.load_state_dict(state_dict, strict=False)
|
| 781 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 782 |
+
|
| 783 |
+
# Get Vae
|
| 784 |
+
vae = AutoencoderKLCogVideoX.from_pretrained(
|
| 785 |
+
model_name,
|
| 786 |
+
subfolder="vae"
|
| 787 |
+
).to(weight_dtype)
|
| 788 |
+
|
| 789 |
+
vae.enable_tiling()
|
| 790 |
+
|
| 791 |
+
if vae_path is not None:
|
| 792 |
+
print(f"From checkpoint: {vae_path}")
|
| 793 |
+
if vae_path.endswith("safetensors"):
|
| 794 |
+
from safetensors.torch import load_file, safe_open
|
| 795 |
+
state_dict = load_file(vae_path)
|
| 796 |
+
else:
|
| 797 |
+
state_dict = torch.load(vae_path, map_location="cpu")
|
| 798 |
+
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
|
| 799 |
+
|
| 800 |
+
m, u = vae.load_state_dict(state_dict, strict=False)
|
| 801 |
+
print(f"missing keys: {len(m)}, unexpected keys: {len(u)}")
|
| 802 |
+
|
| 803 |
+
# Get tokenizer and text_encoder
|
| 804 |
+
tokenizer = T5Tokenizer.from_pretrained(
|
| 805 |
+
model_name, subfolder="tokenizer"
|
| 806 |
+
)
|
| 807 |
+
text_encoder = T5EncoderModel.from_pretrained(
|
| 808 |
+
model_name, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
# Get Scheduler
|
| 812 |
+
Chosen_Scheduler = scheduler_dict = {
|
| 813 |
+
"Euler": EulerDiscreteScheduler,
|
| 814 |
+
"Euler A": EulerAncestralDiscreteScheduler,
|
| 815 |
+
"DPM++": DPMSolverMultistepScheduler,
|
| 816 |
+
"PNDM": PNDMScheduler,
|
| 817 |
+
"DDIM_Cog": CogVideoXDDIMScheduler,
|
| 818 |
+
"DDIM_Origin": DDIMScheduler,
|
| 819 |
+
}[sampler_name]
|
| 820 |
+
scheduler = Chosen_Scheduler.from_pretrained(
|
| 821 |
+
model_name,
|
| 822 |
+
subfolder="scheduler"
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
if transformer.config.in_channels != vae.config.latent_channels:
|
| 826 |
+
pipeline = CogVideoXFunInpaintPipeline(
|
| 827 |
+
vae=vae,
|
| 828 |
+
tokenizer=tokenizer,
|
| 829 |
+
text_encoder=text_encoder,
|
| 830 |
+
transformer=transformer,
|
| 831 |
+
scheduler=scheduler,
|
| 832 |
+
)
|
| 833 |
+
else:
|
| 834 |
+
pipeline = CogVideoXFunPipeline(
|
| 835 |
+
vae=vae,
|
| 836 |
+
tokenizer=tokenizer,
|
| 837 |
+
text_encoder=text_encoder,
|
| 838 |
+
transformer=transformer,
|
| 839 |
+
scheduler=scheduler,
|
| 840 |
+
)
|
| 841 |
+
if ulysses_degree > 1 or ring_degree > 1:
|
| 842 |
+
from functools import partial
|
| 843 |
+
transformer.enable_multi_gpus_inference()
|
| 844 |
+
if fsdp_dit:
|
| 845 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 846 |
+
pipeline.transformer = shard_fn(pipeline.transformer)
|
| 847 |
+
print("Add FSDP DIT")
|
| 848 |
+
if fsdp_text_encoder:
|
| 849 |
+
shard_fn = partial(shard_model, device_id=device, param_dtype=weight_dtype)
|
| 850 |
+
pipeline.text_encoder = shard_fn(pipeline.text_encoder)
|
| 851 |
+
print("Add FSDP TEXT ENCODER")
|
| 852 |
+
|
| 853 |
+
if compile_dit:
|
| 854 |
+
for i in range(len(pipeline.transformer.transformer_blocks)):
|
| 855 |
+
pipeline.transformer.transformer_blocks[i] = torch.compile(pipeline.transformer.transformer_blocks[i])
|
| 856 |
+
print("Add Compile")
|
| 857 |
+
|
| 858 |
+
if GPU_memory_mode == "sequential_cpu_offload":
|
| 859 |
+
pipeline.enable_sequential_cpu_offload(device=device)
|
| 860 |
+
elif GPU_memory_mode == "model_cpu_offload_and_qfloat8":
|
| 861 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 862 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 863 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 864 |
+
elif GPU_memory_mode == "model_cpu_offload":
|
| 865 |
+
pipeline.enable_model_cpu_offload(device=device)
|
| 866 |
+
elif GPU_memory_mode == "model_full_load_and_qfloat8":
|
| 867 |
+
convert_model_weight_to_float8(transformer, exclude_module_name=[], device=device)
|
| 868 |
+
convert_weight_dtype_wrapper(transformer, weight_dtype)
|
| 869 |
+
pipeline.to(device=device)
|
| 870 |
+
else:
|
| 871 |
+
pipeline.to(device=device)
|
| 872 |
+
|
| 873 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 874 |
+
|
| 875 |
+
lilora_network = None
|
| 876 |
+
if lilora_path is not None:
|
| 877 |
+
lora_weight_dim = (lora_down_dim + lora_up_dim) * lora_rank
|
| 878 |
+
|
| 879 |
+
lilora_network = create_network(
|
| 880 |
+
multiplier=lora_weight,
|
| 881 |
+
network_dim=lora_rank,
|
| 882 |
+
network_alpha=lora_weight,
|
| 883 |
+
text_encoder=pipeline.text_encoder,
|
| 884 |
+
transformer=pipeline.transformer,
|
| 885 |
+
down_dim=lora_down_dim,
|
| 886 |
+
up_dim=lora_up_dim,
|
| 887 |
+
is_train=False,
|
| 888 |
+
)
|
| 889 |
+
lilora_network.apply_to(pipeline.text_encoder, pipeline.transformer, apply_text_encoder=False, apply_unet=True)
|
| 890 |
+
|
| 891 |
+
from safetensors.torch import load_file
|
| 892 |
+
lora_state_dict = load_file(lilora_path)
|
| 893 |
+
info = lilora_network.load_weights(lilora_path)
|
| 894 |
+
print(f"LiLoRA weights loaded from {lilora_path} (missing: {len(info.missing_keys)}, unexpected: {len(info.unexpected_keys)})")
|
| 895 |
+
|
| 896 |
+
print(f"Total LoRA modules in UNet: {len(lilora_network.unet_loras)}")
|
| 897 |
+
|
| 898 |
+
hypernetwork = None
|
| 899 |
+
multimodal_ref_encoder = None
|
| 900 |
+
if hypernetwork_path is not None and lilora_network is not None:
|
| 901 |
+
from safetensors.torch import load_file
|
| 902 |
+
|
| 903 |
+
lora_weight_dim = (lora_down_dim + lora_up_dim) * lora_rank
|
| 904 |
+
weight_num = len(lilora_network.unet_loras)
|
| 905 |
+
hyper_state_dict = load_file(hypernetwork_path)
|
| 906 |
+
hypernetwork_input_dim = get_hypernetwork_input_dim(args, hyper_state_dict, None)
|
| 907 |
+
|
| 908 |
+
print(
|
| 909 |
+
f"Creating VideoHyperDream with weight_num={weight_num}, "
|
| 910 |
+
f"weight_dim={lora_weight_dim}, video_feat_dim={hypernetwork_input_dim}"
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
hypernetwork = VideoHyperDream(
|
| 914 |
+
video_feat_dim=hypernetwork_input_dim,
|
| 915 |
+
weight_num=weight_num,
|
| 916 |
+
weight_dim=lora_weight_dim,
|
| 917 |
+
).to(device=device, dtype=weight_dtype)
|
| 918 |
+
|
| 919 |
+
hypernetwork.load_state_dict(hyper_state_dict, strict=False)
|
| 920 |
+
hypernetwork.eval()
|
| 921 |
+
|
| 922 |
+
if lilora_network is not None and len(lilora_network.unet_loras) > 0:
|
| 923 |
+
hypernetwork.set_lilora(lilora_network.unet_loras)
|
| 924 |
+
hypernetwork.set_device(device)
|
| 925 |
+
print(f"HyperNetwork loaded. Connected to {len(lilora_network.unet_loras)} LiLoRA layers from create_network.")
|
| 926 |
+
else:
|
| 927 |
+
print("Warning: No LiLoRA layers found from create_network!")
|
| 928 |
+
hypernetwork = None
|
| 929 |
+
|
| 930 |
+
def save_results(sample, video_length, video_name=None):
|
| 931 |
+
if not os.path.exists(save_path):
|
| 932 |
+
os.makedirs(save_path, exist_ok=True)
|
| 933 |
+
|
| 934 |
+
if video_name is None:
|
| 935 |
+
index = len([path for path in os.listdir(save_path)]) + 1
|
| 936 |
+
prefix = str(index).zfill(8)
|
| 937 |
+
video_name = prefix
|
| 938 |
+
|
| 939 |
+
if video_length == 1:
|
| 940 |
+
video_path = os.path.join(save_path, video_name + ".png")
|
| 941 |
+
|
| 942 |
+
image = sample[0, :, 0]
|
| 943 |
+
image = image.transpose(0, 1).transpose(1, 2)
|
| 944 |
+
image = (image * 255).numpy().astype(np.uint8)
|
| 945 |
+
image = Image.fromarray(image)
|
| 946 |
+
image.save(video_path)
|
| 947 |
+
else:
|
| 948 |
+
video_path = os.path.join(save_path, video_name + ".mp4")
|
| 949 |
+
save_videos_grid(sample, video_path, fps=fps)
|
| 950 |
+
|
| 951 |
+
print(f"Results saved to: {video_path}")
|
| 952 |
+
return video_path
|
| 953 |
+
|
| 954 |
+
def process_test_set():
|
| 955 |
+
if args.test_json_path is None or not os.path.exists(args.test_json_path):
|
| 956 |
+
print("No test JSON path provided or file not found.")
|
| 957 |
+
return
|
| 958 |
+
|
| 959 |
+
json_dir = os.path.dirname(os.path.abspath(args.test_json_path))
|
| 960 |
+
|
| 961 |
+
with open(args.test_json_path, 'r') as f:
|
| 962 |
+
test_data = json.load(f)
|
| 963 |
+
|
| 964 |
+
if isinstance(test_data, list):
|
| 965 |
+
samples = test_data
|
| 966 |
+
elif isinstance(test_data, dict):
|
| 967 |
+
samples = test_data.get('samples', [])
|
| 968 |
+
else:
|
| 969 |
+
print(f"Unknown test data format in {args.test_json_path}")
|
| 970 |
+
return
|
| 971 |
+
|
| 972 |
+
print(f"Processing {len(samples)} test samples...")
|
| 973 |
+
|
| 974 |
+
for idx, sample_info in enumerate(samples):
|
| 975 |
+
print(f"\n{'='*60}")
|
| 976 |
+
print(f"Processing sample {idx + 1}/{len(samples)}: {sample_info.get('video_name', f'sample_{idx}')}")
|
| 977 |
+
print(f"{'='*60}")
|
| 978 |
+
|
| 979 |
+
try:
|
| 980 |
+
sample_info_copy = sample_info.copy()
|
| 981 |
+
sample_first_frame = _resolve_path(sample_info.get('first_frame_path'), json_dir)
|
| 982 |
+
sample_ref_video_path = _resolve_path(sample_info.get('ref_video_path'), json_dir)
|
| 983 |
+
sample_participant_path = _resolve_path(sample_info.get('participant_path'), json_dir)
|
| 984 |
+
|
| 985 |
+
if sample_first_frame:
|
| 986 |
+
if os.path.exists(sample_first_frame):
|
| 987 |
+
first_frame = Image.open(sample_first_frame).convert('RGB')
|
| 988 |
+
W, H = first_frame.size
|
| 989 |
+
current_sample_size = [H, W] # PIL image.size is (W, H), sample_size should be [H, W]
|
| 990 |
+
print(f"Dynamic sample_size: {current_sample_size}")
|
| 991 |
+
|
| 992 |
+
sample_info_copy['first_frame_path'] = sample_first_frame
|
| 993 |
+
else:
|
| 994 |
+
raise FileNotFoundError(f"first_frame_path not found: {sample_first_frame}")
|
| 995 |
+
else:
|
| 996 |
+
raise ValueError("first_frame_path must be provided for I2V inference")
|
| 997 |
+
|
| 998 |
+
if sample_ref_video_path is not None:
|
| 999 |
+
sample_info_copy['ref_video_path'] = sample_ref_video_path
|
| 1000 |
+
if sample_participant_path is not None:
|
| 1001 |
+
sample_info_copy['participant_path'] = sample_participant_path
|
| 1002 |
+
|
| 1003 |
+
sample_args = {
|
| 1004 |
+
'video_length': args.video_length,
|
| 1005 |
+
'seed': args.seed + idx,
|
| 1006 |
+
'negative_prompt': args.negative_prompt,
|
| 1007 |
+
'guidance_scale': args.guidance_scale,
|
| 1008 |
+
'num_inference_steps': args.num_inference_steps,
|
| 1009 |
+
'prompt': args.prompt,
|
| 1010 |
+
'cli_args': args,
|
| 1011 |
+
}
|
| 1012 |
+
|
| 1013 |
+
sample = process_sample(
|
| 1014 |
+
pipeline=pipeline,
|
| 1015 |
+
vae=vae,
|
| 1016 |
+
device=device,
|
| 1017 |
+
weight_dtype=weight_dtype,
|
| 1018 |
+
hypernetwork=hypernetwork,
|
| 1019 |
+
lilora_network=lilora_network,
|
| 1020 |
+
multimodal_ref_encoder=multimodal_ref_encoder,
|
| 1021 |
+
sample_info=sample_info_copy,
|
| 1022 |
+
sample_size=current_sample_size,
|
| 1023 |
+
args=sample_args
|
| 1024 |
+
)
|
| 1025 |
+
|
| 1026 |
+
if sample is not None:
|
| 1027 |
+
video_name = sample_info.get('video_name', f'sample_{idx}')
|
| 1028 |
+
save_results(sample, sample_args['video_length'], video_name)
|
| 1029 |
+
else:
|
| 1030 |
+
print(f"Skipping sample {idx + 1} due to missing first frame.")
|
| 1031 |
+
|
| 1032 |
+
except Exception as e:
|
| 1033 |
+
print(f"Error processing sample {idx + 1}: {str(e)}")
|
| 1034 |
+
import traceback
|
| 1035 |
+
traceback.print_exc()
|
| 1036 |
+
|
| 1037 |
+
print(f"\nAll {len(samples)} samples processed.")
|
| 1038 |
+
|
| 1039 |
+
if args.test_json_path is not None:
|
| 1040 |
+
process_test_set()
|
| 1041 |
+
else:
|
| 1042 |
+
if partial_video_length is not None:
|
| 1043 |
+
partial_video_length = int((partial_video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 1044 |
+
latent_frames = (partial_video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 1045 |
+
if partial_video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 1046 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 1047 |
+
partial_video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 1048 |
+
|
| 1049 |
+
init_frames = 0
|
| 1050 |
+
last_frames = init_frames + partial_video_length
|
| 1051 |
+
while init_frames < video_length:
|
| 1052 |
+
if last_frames >= video_length:
|
| 1053 |
+
_partial_video_length = video_length - init_frames
|
| 1054 |
+
_partial_video_length = int((_partial_video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1
|
| 1055 |
+
latent_frames = (_partial_video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 1056 |
+
if _partial_video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 1057 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 1058 |
+
_partial_video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 1059 |
+
|
| 1060 |
+
if _partial_video_length <= 0:
|
| 1061 |
+
break
|
| 1062 |
+
else:
|
| 1063 |
+
_partial_video_length = partial_video_length
|
| 1064 |
+
|
| 1065 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image, None, video_length=_partial_video_length, sample_size=sample_size)
|
| 1066 |
+
|
| 1067 |
+
if hypernetwork is not None and ref_video_path is not None and init_frames == 0:
|
| 1068 |
+
print(f"Loading reference video from {ref_video_path}...")
|
| 1069 |
+
ref_frames_tensor = load_ref_video_frames(ref_video_path, sample_size)
|
| 1070 |
+
_, F, _, _, _ = ref_frames_tensor.shape
|
| 1071 |
+
ref_pixel_values = ref_frames_tensor.permute(0, 4, 1, 2, 3).contiguous()
|
| 1072 |
+
|
| 1073 |
+
with torch.no_grad():
|
| 1074 |
+
vae_device = get_model_device(vae)
|
| 1075 |
+
ref_pixel_values = ref_pixel_values.to(device=vae_device, dtype=weight_dtype)
|
| 1076 |
+
ref_features = vae.encode(ref_pixel_values).latent_dist.sample()
|
| 1077 |
+
ref_features = ref_features * vae.config.scaling_factor
|
| 1078 |
+
|
| 1079 |
+
updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
|
| 1080 |
+
print(f"Updated {updated_layers} LiLoRA layers with hypernetwork weights from {F} reference frames.")
|
| 1081 |
+
|
| 1082 |
+
with torch.no_grad():
|
| 1083 |
+
sample = pipeline(
|
| 1084 |
+
args.prompt,
|
| 1085 |
+
num_frames = _partial_video_length,
|
| 1086 |
+
negative_prompt = negative_prompt,
|
| 1087 |
+
height = sample_size[0],
|
| 1088 |
+
width = sample_size[1],
|
| 1089 |
+
generator = generator,
|
| 1090 |
+
guidance_scale = guidance_scale,
|
| 1091 |
+
num_inference_steps = num_inference_steps,
|
| 1092 |
+
|
| 1093 |
+
video = input_video,
|
| 1094 |
+
mask_video = input_video_mask
|
| 1095 |
+
).videos
|
| 1096 |
+
|
| 1097 |
+
if init_frames != 0:
|
| 1098 |
+
mix_ratio = torch.from_numpy(
|
| 1099 |
+
np.array([float(_index) / float(overlap_video_length) for _index in range(overlap_video_length)], np.float32)
|
| 1100 |
+
).unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
|
| 1101 |
+
|
| 1102 |
+
new_sample[:, :, -overlap_video_length:] = new_sample[:, :, -overlap_video_length:] * (1 - mix_ratio) + \
|
| 1103 |
+
sample[:, :, :overlap_video_length] * mix_ratio
|
| 1104 |
+
new_sample = torch.cat([new_sample, sample[:, :, overlap_video_length:]], dim = 2)
|
| 1105 |
+
|
| 1106 |
+
sample = new_sample
|
| 1107 |
+
else:
|
| 1108 |
+
new_sample = sample
|
| 1109 |
+
|
| 1110 |
+
if last_frames >= video_length:
|
| 1111 |
+
break
|
| 1112 |
+
|
| 1113 |
+
validation_image = [
|
| 1114 |
+
Image.fromarray(
|
| 1115 |
+
(sample[0, :, _index].transpose(0, 1).transpose(1, 2) * 255).numpy().astype(np.uint8)
|
| 1116 |
+
) for _index in range(-overlap_video_length, 0)
|
| 1117 |
+
]
|
| 1118 |
+
|
| 1119 |
+
init_frames = init_frames + _partial_video_length - overlap_video_length
|
| 1120 |
+
last_frames = init_frames + _partial_video_length
|
| 1121 |
+
else:
|
| 1122 |
+
video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
|
| 1123 |
+
latent_frames = (video_length - 1) // vae.config.temporal_compression_ratio + 1
|
| 1124 |
+
if video_length != 1 and transformer.config.patch_size_t is not None and latent_frames % transformer.config.patch_size_t != 0:
|
| 1125 |
+
additional_frames = transformer.config.patch_size_t - latent_frames % transformer.config.patch_size_t
|
| 1126 |
+
video_length += additional_frames * vae.config.temporal_compression_ratio
|
| 1127 |
+
input_video, input_video_mask, clip_image = get_image_to_video_latent(validation_image_start, validation_image_end, video_length=video_length, sample_size=sample_size)
|
| 1128 |
+
|
| 1129 |
+
if hypernetwork is not None and ref_video_path is not None:
|
| 1130 |
+
print(f"Loading reference video from {ref_video_path}...")
|
| 1131 |
+
ref_frames_tensor = load_ref_video_frames(ref_video_path, sample_size)
|
| 1132 |
+
_, F, _, _, _ = ref_frames_tensor.shape
|
| 1133 |
+
ref_pixel_values = ref_frames_tensor.permute(0, 4, 1, 2, 3).contiguous()
|
| 1134 |
+
|
| 1135 |
+
with torch.no_grad():
|
| 1136 |
+
vae_device = get_model_device(vae)
|
| 1137 |
+
ref_pixel_values = ref_pixel_values.to(device=vae_device, dtype=weight_dtype)
|
| 1138 |
+
ref_features = vae.encode(ref_pixel_values).latent_dist.sample()
|
| 1139 |
+
ref_features = ref_features * vae.config.scaling_factor
|
| 1140 |
+
|
| 1141 |
+
updated_layers = apply_hypernetwork_weights(hypernetwork, lilora_network, ref_features)
|
| 1142 |
+
print(f"Updated {updated_layers} LiLoRA layers with hypernetwork weights from {F} reference frames.")
|
| 1143 |
+
|
| 1144 |
+
with torch.no_grad():
|
| 1145 |
+
sample = pipeline(
|
| 1146 |
+
args.prompt,
|
| 1147 |
+
num_frames = video_length,
|
| 1148 |
+
negative_prompt = negative_prompt,
|
| 1149 |
+
height = sample_size[0],
|
| 1150 |
+
width = sample_size[1],
|
| 1151 |
+
generator = generator,
|
| 1152 |
+
guidance_scale = guidance_scale,
|
| 1153 |
+
num_inference_steps = num_inference_steps,
|
| 1154 |
+
|
| 1155 |
+
video = input_video,
|
| 1156 |
+
mask_video = input_video_mask
|
| 1157 |
+
).videos
|
| 1158 |
+
|
| 1159 |
+
if args.test_json_path is not None:
|
| 1160 |
+
process_test_set()
|
| 1161 |
+
else:
|
| 1162 |
+
if ulysses_degree * ring_degree > 1:
|
| 1163 |
+
import torch.distributed as dist
|
| 1164 |
+
if dist.get_rank() == 0:
|
| 1165 |
+
save_results(sample, video_length)
|
| 1166 |
+
else:
|
| 1167 |
+
save_results(sample, video_length)
|
| 1168 |
+
|
| 1169 |
+
if __name__ == "__main__":
|
| 1170 |
+
main()
|
run_predict_i2v.sh
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# CogVideoX-Fun I2V Inference Script
|
| 4 |
+
# Usage: bash run_predict_i2v.sh [OPTIONS]
|
| 5 |
+
|
| 6 |
+
# =============================================================================
|
| 7 |
+
# 基础设置 (Basic Settings)
|
| 8 |
+
# =============================================================================
|
| 9 |
+
export CUDA_VISIBLE_DEVICES=6
|
| 10 |
+
export PYTHONPATH="/home/xhm001/Desktop/Code/VideoX-Fun-main:${PYTHONPATH}"
|
| 11 |
+
|
| 12 |
+
# 模型路径 (Model Path)
|
| 13 |
+
MODEL_NAME="/home/xhm001/Desktop/Code/VideoX-Fun-main/models/cogvideoxfun/models--alibaba-pai--CogVideoX-Fun-V1.1-5b-InP"
|
| 14 |
+
|
| 15 |
+
# =============================================================================
|
| 16 |
+
# LiLoRA 和 HyperNetwork 路径 (LiLoRA & HyperNetwork Paths)
|
| 17 |
+
# =============================================================================
|
| 18 |
+
# LiLoRA 权重路径
|
| 19 |
+
LILORA_PATH="/home/xhm001/Desktop/Code/VideoX-Fun-main/Hyper_150/checkpoint-14800/checkpoint-checkpoint-14800.safetensors"
|
| 20 |
+
|
| 21 |
+
# HyperNetwork 权重路径
|
| 22 |
+
HYPERNETWORK_PATH="/home/xhm001/Desktop/Code/VideoX-Fun-main/Hyper_150/checkpoint-14800/hypernetwork.safetensors"
|
| 23 |
+
|
| 24 |
+
# EMG 多模态参考编码器路径
|
| 25 |
+
MULTIMODAL_REF_ENCODER_CKPT_PATH=None
|
| 26 |
+
MULTIMODAL_REF_ENCODER_SCRIPT=None
|
| 27 |
+
EMG2POSE_CKPT_PATH=None
|
| 28 |
+
EMG2POSE_REPO=None
|
| 29 |
+
HYPERNETWORK_INPUT_DIM=None
|
| 30 |
+
EMG_NORMALIZATION_PARTICIPANT=None
|
| 31 |
+
|
| 32 |
+
# LiLoRA 训练参数 (应与训练配置匹配)
|
| 33 |
+
LORA_RANK=1
|
| 34 |
+
LORA_DOWN_DIM=100
|
| 35 |
+
LORA_UP_DIM=50
|
| 36 |
+
LORA_WEIGHT=1
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# =============================================================================
|
| 40 |
+
# 输入数据路径 (Input Data Paths)
|
| 41 |
+
# =============================================================================
|
| 42 |
+
# 注意:当使用 --test_json_path 时,以下参数会从 JSON 中读取
|
| 43 |
+
# 单样本推理时,可以手动指定以下参数
|
| 44 |
+
|
| 45 |
+
# 首帧图像路径 (用于图像到视频生成)
|
| 46 |
+
FIRST_FRAME_PATH=None
|
| 47 |
+
|
| 48 |
+
# 参考视频路径 (用于 HyperNetwork 生成权重)
|
| 49 |
+
REF_VIDEO_PATH=None
|
| 50 |
+
|
| 51 |
+
# 测试集 JSON 路径 (可选,批量处理时使用)
|
| 52 |
+
TEST_JSON_PATH=/home/xhm001/Desktop/Code/VideoX-Fun-main/Open_VFX_for_evl/cake.json
|
| 53 |
+
|
| 54 |
+
# =============================================================================
|
| 55 |
+
# 视频生成参数 (Video Generation Parameters)
|
| 56 |
+
# =============================================================================
|
| 57 |
+
VIDEO_LENGTH=49
|
| 58 |
+
FPS=8
|
| 59 |
+
PARTIAL_VIDEO_LENGTH=None
|
| 60 |
+
OVERLAP_VIDEO_LENGTH=4
|
| 61 |
+
|
| 62 |
+
# =============================================================================
|
| 63 |
+
# 推理参数 (Inference Parameters)
|
| 64 |
+
# =============================================================================
|
| 65 |
+
# 注意:当使用 --test_json_path 时,以下参数会从 JSON 中读取
|
| 66 |
+
PROMPT=None
|
| 67 |
+
NEGATIVE_PROMPT="The video is not of a high quality, it has a low resolution. Watermark present in each frame. The background is solid. Strange body and strange trajectory. Distortion."
|
| 68 |
+
GUIDANCE_SCALE=6.0
|
| 69 |
+
SEED=43
|
| 70 |
+
NUM_INFERENCE_STEPS=50
|
| 71 |
+
|
| 72 |
+
# =============================================================================
|
| 73 |
+
# GPU 设置 (GPU Settings)
|
| 74 |
+
# =============================================================================
|
| 75 |
+
# GPU 内存模式: model_full_load, model_full_load_and_qfloat8, model_cpu_offload, model_cpu_offload_and_qfloat8, sequential_cpu_offload
|
| 76 |
+
GPU_MEMORY_MODE="model_full_load"
|
| 77 |
+
|
| 78 |
+
# 多 GPU 设置
|
| 79 |
+
ULYSSES_DEGREE=1
|
| 80 |
+
RING_DEGREE=1
|
| 81 |
+
FSPD_DIT=False
|
| 82 |
+
FSPD_TEXT_ENCODER=False
|
| 83 |
+
COMPILE_DIT=False
|
| 84 |
+
|
| 85 |
+
# 权重数据类型: bfloat16, float16, float32
|
| 86 |
+
WEIGHT_DTYPE="bfloat16"
|
| 87 |
+
|
| 88 |
+
# =============================================================================
|
| 89 |
+
# 采样器选择 (Sampler Selection)
|
| 90 |
+
# =============================================================================
|
| 91 |
+
# 可选: Euler, Euler A, DPM++, PNDM, DDIM_Cog, DDIM_Origin
|
| 92 |
+
SAMPLER_NAME="DDIM_Origin"
|
| 93 |
+
|
| 94 |
+
# =============================================================================
|
| 95 |
+
# 输出路径 (Output Path)
|
| 96 |
+
# =============================================================================
|
| 97 |
+
SAVE_PATH="samples/ALL"
|
| 98 |
+
|
| 99 |
+
# =============================================================================
|
| 100 |
+
# 解析命令行参数 (Parse Command Line Arguments)
|
| 101 |
+
# =============================================================================
|
| 102 |
+
while [[ $# -gt 0 ]]; do
|
| 103 |
+
case $1 in
|
| 104 |
+
--model_name)
|
| 105 |
+
MODEL_NAME="$2"
|
| 106 |
+
shift 2
|
| 107 |
+
;;
|
| 108 |
+
--lilora_path)
|
| 109 |
+
LILORA_PATH="$2"
|
| 110 |
+
shift 2
|
| 111 |
+
;;
|
| 112 |
+
--hypernetwork_path)
|
| 113 |
+
HYPERNETWORK_PATH="$2"
|
| 114 |
+
shift 2
|
| 115 |
+
;;
|
| 116 |
+
--multimodal_ref_encoder_ckpt_path)
|
| 117 |
+
MULTIMODAL_REF_ENCODER_CKPT_PATH="$2"
|
| 118 |
+
shift 2
|
| 119 |
+
;;
|
| 120 |
+
--multimodal_ref_encoder_script)
|
| 121 |
+
MULTIMODAL_REF_ENCODER_SCRIPT="$2"
|
| 122 |
+
shift 2
|
| 123 |
+
;;
|
| 124 |
+
--emg2pose_ckpt_path)
|
| 125 |
+
EMG2POSE_CKPT_PATH="$2"
|
| 126 |
+
shift 2
|
| 127 |
+
;;
|
| 128 |
+
--emg2pose_repo)
|
| 129 |
+
EMG2POSE_REPO="$2"
|
| 130 |
+
shift 2
|
| 131 |
+
;;
|
| 132 |
+
--hypernetwork_input_dim)
|
| 133 |
+
HYPERNETWORK_INPUT_DIM="$2"
|
| 134 |
+
shift 2
|
| 135 |
+
;;
|
| 136 |
+
--emg_normalization_participant)
|
| 137 |
+
EMG_NORMALIZATION_PARTICIPANT="$2"
|
| 138 |
+
shift 2
|
| 139 |
+
;;
|
| 140 |
+
--first_frame_path)
|
| 141 |
+
FIRST_FRAME_PATH="$2"
|
| 142 |
+
shift 2
|
| 143 |
+
;;
|
| 144 |
+
--ref_video_path)
|
| 145 |
+
REF_VIDEO_PATH="$2"
|
| 146 |
+
shift 2
|
| 147 |
+
;;
|
| 148 |
+
--test_json_path)
|
| 149 |
+
TEST_JSON_PATH="$2"
|
| 150 |
+
shift 2
|
| 151 |
+
;;
|
| 152 |
+
--video_length)
|
| 153 |
+
VIDEO_LENGTH="$2"
|
| 154 |
+
shift 2
|
| 155 |
+
;;
|
| 156 |
+
--fps)
|
| 157 |
+
FPS="$2"
|
| 158 |
+
shift 2
|
| 159 |
+
;;
|
| 160 |
+
--prompt)
|
| 161 |
+
PROMPT="$2"
|
| 162 |
+
shift 2
|
| 163 |
+
;;
|
| 164 |
+
--negative_prompt)
|
| 165 |
+
NEGATIVE_PROMPT="$2"
|
| 166 |
+
shift 2
|
| 167 |
+
;;
|
| 168 |
+
--guidance_scale)
|
| 169 |
+
GUIDANCE_SCALE="$2"
|
| 170 |
+
shift 2
|
| 171 |
+
;;
|
| 172 |
+
--seed)
|
| 173 |
+
SEED="$2"
|
| 174 |
+
shift 2
|
| 175 |
+
;;
|
| 176 |
+
--num_inference_steps)
|
| 177 |
+
NUM_INFERENCE_STEPS="$2"
|
| 178 |
+
shift 2
|
| 179 |
+
;;
|
| 180 |
+
--lora_rank)
|
| 181 |
+
LORA_RANK="$2"
|
| 182 |
+
shift 2
|
| 183 |
+
;;
|
| 184 |
+
--lora_down_dim)
|
| 185 |
+
LORA_DOWN_DIM="$2"
|
| 186 |
+
shift 2
|
| 187 |
+
;;
|
| 188 |
+
--lora_up_dim)
|
| 189 |
+
LORA_UP_DIM="$2"
|
| 190 |
+
shift 2
|
| 191 |
+
;;
|
| 192 |
+
--lora_weight)
|
| 193 |
+
LORA_WEIGHT="$2"
|
| 194 |
+
shift 2
|
| 195 |
+
;;
|
| 196 |
+
--save_path)
|
| 197 |
+
SAVE_PATH="$2"
|
| 198 |
+
shift 2
|
| 199 |
+
;;
|
| 200 |
+
--gpu_memory_mode)
|
| 201 |
+
GPU_MEMORY_MODE="$2"
|
| 202 |
+
shift 2
|
| 203 |
+
;;
|
| 204 |
+
--weight_dtype)
|
| 205 |
+
WEIGHT_DTYPE="$2"
|
| 206 |
+
shift 2
|
| 207 |
+
;;
|
| 208 |
+
--sampler_name)
|
| 209 |
+
SAMPLER_NAME="$2"
|
| 210 |
+
shift 2
|
| 211 |
+
;;
|
| 212 |
+
--ulysses_degree)
|
| 213 |
+
ULYSSES_DEGREE="$2"
|
| 214 |
+
shift 2
|
| 215 |
+
;;
|
| 216 |
+
--ring_degree)
|
| 217 |
+
RING_DEGREE="$2"
|
| 218 |
+
shift 2
|
| 219 |
+
;;
|
| 220 |
+
--partial_video_length)
|
| 221 |
+
PARTIAL_VIDEO_LENGTH="$2"
|
| 222 |
+
shift 2
|
| 223 |
+
;;
|
| 224 |
+
--overlap_video_length)
|
| 225 |
+
OVERLAP_VIDEO_LENGTH="$2"
|
| 226 |
+
shift 2
|
| 227 |
+
;;
|
| 228 |
+
--help|-h)
|
| 229 |
+
echo "Usage: bash run_predict_i2v.sh [OPTIONS]"
|
| 230 |
+
echo ""
|
| 231 |
+
echo "Options:"
|
| 232 |
+
echo " --model_name 模型路径 (默认: models/Diffusion_Transformer/CogVideoX-Fun-V1.1-2b-InP)"
|
| 233 |
+
echo " --lilora_path LiLoRA 权重路径"
|
| 234 |
+
echo " --hypernetwork_path HyperNetwork 权重路径"
|
| 235 |
+
echo " --multimodal_ref_encoder_ckpt_path EMG 多模态参考编码器 checkpoint"
|
| 236 |
+
echo " --multimodal_ref_encoder_script EMG 多模态参考编码器脚本"
|
| 237 |
+
echo " --emg2pose_ckpt_path EMG2Pose checkpoint"
|
| 238 |
+
echo " --emg2pose_repo EMG2Pose repo 路径"
|
| 239 |
+
echo " --hypernetwork_input_dim HyperNetwork 输入维度"
|
| 240 |
+
echo " --emg_normalization_participant EMG 归一化参与者目录"
|
| 241 |
+
echo " --first_frame_path 首帧图像路径"
|
| 242 |
+
echo " --ref_video_path 参考视频路径 (用于 HyperNetwork)"
|
| 243 |
+
echo " --test_json_path 测试集 JSON 路径"
|
| 244 |
+
echo " --video_length 生成视频帧数 (默认: 49)"
|
| 245 |
+
echo " --fps 输出视频 FPS (默认: 8)"
|
| 246 |
+
echo " --prompt 生成提示词"
|
| 247 |
+
echo " --negative_prompt 负向提示词"
|
| 248 |
+
echo " --guidance_scale 引导 scale (默认: 6.0)"
|
| 249 |
+
echo " --seed 随机种子 (默认: 43)"
|
| 250 |
+
echo " --num_inference_steps 推理步数 (默认: 50)"
|
| 251 |
+
echo " --lora_rank LoRA rank (默认: 1)"
|
| 252 |
+
echo " --lora_down_dim LoRA down dimension (默认: 200)"
|
| 253 |
+
echo " --lora_up_dim LoRA up dimension (默认: 100)"
|
| 254 |
+
echo " --lora_weight LoRA 权重 (默认: 0.55)"
|
| 255 |
+
echo " --save_path 输出路径 (默认: samples/cogvideox-fun-videos_i2v)"
|
| 256 |
+
echo " --gpu_memory_mode GPU 内存模式"
|
| 257 |
+
echo " --weight_dtype 权重数据类型"
|
| 258 |
+
echo " --sampler_name 采样器名称"
|
| 259 |
+
echo " --help 显示帮助信息"
|
| 260 |
+
exit 0
|
| 261 |
+
;;
|
| 262 |
+
*)
|
| 263 |
+
echo "Unknown option: $1"
|
| 264 |
+
exit 1
|
| 265 |
+
;;
|
| 266 |
+
esac
|
| 267 |
+
done
|
| 268 |
+
|
| 269 |
+
# =============================================================================
|
| 270 |
+
# 构建命令行参数 (Build Command Line Arguments)
|
| 271 |
+
# =============================================================================
|
| 272 |
+
PYTHON_ARGS=()
|
| 273 |
+
|
| 274 |
+
# GPU 设置
|
| 275 |
+
PYTHON_ARGS+=("--gpu_memory_mode" "${GPU_MEMORY_MODE}")
|
| 276 |
+
PYTHON_ARGS+=("--ulysses_degree" "${ULYSSES_DEGREE}")
|
| 277 |
+
PYTHON_ARGS+=("--ring_degree" "${RING_DEGREE}")
|
| 278 |
+
|
| 279 |
+
[[ "${FSPD_DIT}" == "True" ]] && PYTHON_ARGS+=("--fsdp_dit")
|
| 280 |
+
[[ "${FSPD_TEXT_ENCODER}" == "True" ]] && PYTHON_ARGS+=("--fsdp_text_encoder")
|
| 281 |
+
[[ "${COMPILE_DIT}" == "True" ]] && PYTHON_ARGS+=("--compile_dit")
|
| 282 |
+
|
| 283 |
+
# 模型设置
|
| 284 |
+
PYTHON_ARGS+=("--model_name" "${MODEL_NAME}")
|
| 285 |
+
PYTHON_ARGS+=("--sampler_name" "${SAMPLER_NAME}")
|
| 286 |
+
|
| 287 |
+
# LiLoRA 和 HyperNetwork
|
| 288 |
+
[[ -n "${LILORA_PATH}" && "${LILORA_PATH}" != "None" ]] && PYTHON_ARGS+=("--lilora_path" "${LILORA_PATH}")
|
| 289 |
+
[[ -n "${HYPERNETWORK_PATH}" && "${HYPERNETWORK_PATH}" != "None" ]] && PYTHON_ARGS+=("--hypernetwork_path" "${HYPERNETWORK_PATH}")
|
| 290 |
+
[[ -n "${MULTIMODAL_REF_ENCODER_CKPT_PATH}" && "${MULTIMODAL_REF_ENCODER_CKPT_PATH}" != "None" ]] && PYTHON_ARGS+=("--multimodal_ref_encoder_ckpt_path" "${MULTIMODAL_REF_ENCODER_CKPT_PATH}")
|
| 291 |
+
[[ -n "${MULTIMODAL_REF_ENCODER_SCRIPT}" && "${MULTIMODAL_REF_ENCODER_SCRIPT}" != "None" ]] && PYTHON_ARGS+=("--multimodal_ref_encoder_script" "${MULTIMODAL_REF_ENCODER_SCRIPT}")
|
| 292 |
+
[[ -n "${EMG2POSE_CKPT_PATH}" && "${EMG2POSE_CKPT_PATH}" != "None" ]] && PYTHON_ARGS+=("--emg2pose_ckpt_path" "${EMG2POSE_CKPT_PATH}")
|
| 293 |
+
[[ -n "${EMG2POSE_REPO}" && "${EMG2POSE_REPO}" != "None" ]] && PYTHON_ARGS+=("--emg2pose_repo" "${EMG2POSE_REPO}")
|
| 294 |
+
[[ -n "${HYPERNETWORK_INPUT_DIM}" && "${HYPERNETWORK_INPUT_DIM}" != "None" ]] && PYTHON_ARGS+=("--hypernetwork_input_dim" "${HYPERNETWORK_INPUT_DIM}")
|
| 295 |
+
[[ -n "${EMG_NORMALIZATION_PARTICIPANT}" && "${EMG_NORMALIZATION_PARTICIPANT}" != "None" ]] && PYTHON_ARGS+=("--emg_normalization_participant" "${EMG_NORMALIZATION_PARTICIPANT}")
|
| 296 |
+
|
| 297 |
+
# LiLoRA 参数
|
| 298 |
+
PYTHON_ARGS+=("--lora_rank" "${LORA_RANK}")
|
| 299 |
+
PYTHON_ARGS+=("--lora_down_dim" "${LORA_DOWN_DIM}")
|
| 300 |
+
PYTHON_ARGS+=("--lora_up_dim" "${LORA_UP_DIM}")
|
| 301 |
+
[[ -n "${LORA_WEIGHT}" && "${LORA_WEIGHT}" != "None" ]] && PYTHON_ARGS+=("--lora_weight" "${LORA_WEIGHT}")
|
| 302 |
+
|
| 303 |
+
# 视频参数
|
| 304 |
+
PYTHON_ARGS+=("--video_length" "${VIDEO_LENGTH}")
|
| 305 |
+
PYTHON_ARGS+=("--fps" "${FPS}")
|
| 306 |
+
[[ -n "${PARTIAL_VIDEO_LENGTH}" && "${PARTIAL_VIDEO_LENGTH}" != "None" ]] && PYTHON_ARGS+=("--partial_video_length" "${PARTIAL_VIDEO_LENGTH}")
|
| 307 |
+
PYTHON_ARGS+=("--overlap_video_length" "${OVERLAP_VIDEO_LENGTH}")
|
| 308 |
+
|
| 309 |
+
# 权重类型
|
| 310 |
+
PYTHON_ARGS+=("--weight_dtype" "${WEIGHT_DTYPE}")
|
| 311 |
+
|
| 312 |
+
# 推理参数 (单样本时使用,批量时从 JSON 读取)
|
| 313 |
+
if [[ -z "${TEST_JSON_PATH}" || "${TEST_JSON_PATH}" == "None" ]]; then
|
| 314 |
+
[[ -n "${FIRST_FRAME_PATH}" && "${FIRST_FRAME_PATH}" != "None" ]] && PYTHON_ARGS+=("--first_frame_path" "${FIRST_FRAME_PATH}")
|
| 315 |
+
[[ -n "${REF_VIDEO_PATH}" && "${REF_VIDEO_PATH}" != "None" ]] && PYTHON_ARGS+=("--ref_video_path" "${REF_VIDEO_PATH}")
|
| 316 |
+
[[ -n "${PROMPT}" && "${PROMPT}" != "None" ]] && PYTHON_ARGS+=("--prompt" "${PROMPT}")
|
| 317 |
+
PYTHON_ARGS+=("--negative_prompt" "${NEGATIVE_PROMPT}")
|
| 318 |
+
PYTHON_ARGS+=("--guidance_scale" "${GUIDANCE_SCALE}")
|
| 319 |
+
PYTHON_ARGS+=("--seed" "${SEED}")
|
| 320 |
+
PYTHON_ARGS+=("--num_inference_steps" "${NUM_INFERENCE_STEPS}")
|
| 321 |
+
else
|
| 322 |
+
PYTHON_ARGS+=("--test_json_path" "${TEST_JSON_PATH}")
|
| 323 |
+
fi
|
| 324 |
+
|
| 325 |
+
# 输出路径
|
| 326 |
+
PYTHON_ARGS+=("--save_path" "${SAVE_PATH}")
|
| 327 |
+
|
| 328 |
+
# =============================================================================
|
| 329 |
+
# 运行推理脚本 (Run Inference Script)
|
| 330 |
+
# =============================================================================
|
| 331 |
+
echo "========================================"
|
| 332 |
+
echo "CogVideoX-Fun I2V Inference"
|
| 333 |
+
echo "========================================"
|
| 334 |
+
echo "Model: ${MODEL_NAME}"
|
| 335 |
+
echo "LiLoRA: ${LILORA_PATH}"
|
| 336 |
+
echo "HyperNetwork: ${HYPERNETWORK_PATH}"
|
| 337 |
+
echo "Multimodal Ref Encoder: ${MULTIMODAL_REF_ENCODER_CKPT_PATH}"
|
| 338 |
+
echo "Video Length: ${VIDEO_LENGTH}"
|
| 339 |
+
if [[ -n "${TEST_JSON_PATH}" && "${TEST_JSON_PATH}" != "None" ]]; then
|
| 340 |
+
echo "Test Set: ${TEST_JSON_PATH}"
|
| 341 |
+
else
|
| 342 |
+
echo "First Frame: ${FIRST_FRAME_PATH}"
|
| 343 |
+
echo "Prompt: ${PROMPT}"
|
| 344 |
+
fi
|
| 345 |
+
echo "========================================"
|
| 346 |
+
|
| 347 |
+
torchrun --nproc-per-node=1 --master_port=29501\
|
| 348 |
+
/home/xhm001/Desktop/Code/VideoX-Fun-main/examples/cogvideox_fun/predict_i2v.py \
|
| 349 |
+
"${PYTHON_ARGS[@]}"
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
echo ""
|
| 353 |
+
echo "Inference completed!"
|