308 lines
12 KiB
Python
308 lines
12 KiB
Python
#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
|
||
import gc
|
||
import os
|
||
import sys
|
||
import time
|
||
import importlib.util
|
||
import torch
|
||
|
||
# 強制啟用 PyTorch ROCm 的記憶體高效與 Flash 注意力後端
|
||
torch.backends.cuda.enable_flash_sdp(True)
|
||
torch.backends.cuda.enable_mem_efficient_sdp(True)
|
||
torch.backends.cuda.enable_math_sdp(False)
|
||
|
||
"""
|
||
[REF2VA STAGE 4] VAE 像素還原 (video + audio VAE)
|
||
- 權重常駐 GPU,不反覆搬移回 CPU
|
||
- 進入迴圈前以 Task 0 規格執行 Dummy 預熱與極限測試
|
||
- 修正 Audio 維度相容性 (嚴格保證 [2, S] 格式)
|
||
- 保持原本的任務略過邏輯
|
||
"""
|
||
|
||
# ==============================================================================
|
||
# 動態加載專案配置
|
||
# ==============================================================================
|
||
config_path = os.path.join(os.getcwd(), "config.py")
|
||
if not os.path.exists(config_path):
|
||
print(f">> [Error] Cannot find config.py in {os.getcwd()}")
|
||
sys.exit(1)
|
||
|
||
spec = importlib.util.spec_from_file_location("config", config_path)
|
||
config = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(config)
|
||
|
||
MODELS_DIR = config.MODELS_DIR
|
||
VRAM_CONFIG = config.VRAM_CONFIG
|
||
TASK_REGISTRY = config.TASK_REGISTRY
|
||
VIDEO_SETTINGS = config.VIDEO_SETTINGS
|
||
OUTPUT_DIR = config.OUTPUT_DIR
|
||
RUN_CONFIG = config.RUN_CONFIG
|
||
|
||
|
||
def get_enabled_tasks():
|
||
return config.get_enabled_tasks()
|
||
|
||
|
||
from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig
|
||
from diffsynth.utils.data.audio_video import write_video_audio
|
||
|
||
os.environ["HIP_VISIBLE_DEVICES"] = "0"
|
||
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
|
||
os.environ["HSA_OVERRIDE_GFX_VERSION"] = "11.0.0"
|
||
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
||
os.environ["DIFFSYNTH_SKIP_DOWNLOAD"] = "True"
|
||
|
||
|
||
def move_to_cuda(obj, dtype=None):
|
||
"""Recursively move objects to CUDA device and optionally cast dtype."""
|
||
if isinstance(obj, torch.Tensor):
|
||
obj = obj.to("cuda")
|
||
if dtype is not None:
|
||
obj = obj.to(dtype)
|
||
return obj
|
||
if isinstance(obj, dict):
|
||
return {k: move_to_cuda(v, dtype) for k, v in obj.items()}
|
||
if isinstance(obj, (list, tuple)):
|
||
return type(obj)(move_to_cuda(x, dtype) for x in obj)
|
||
return obj
|
||
|
||
|
||
def format_audio_for_output(audio_raw, is_dummy=False):
|
||
"""
|
||
音訊標準化處理:
|
||
嚴格保證回傳張量形狀為 [2, Samples] (DiffSynth 規定的雙聲道格式),
|
||
並處理 NaN/Inf 與音量正規化。
|
||
"""
|
||
if not isinstance(audio_raw, torch.Tensor):
|
||
return audio_raw
|
||
|
||
audio = audio_raw.detach().cpu().float()
|
||
|
||
# 1. 清理 NaN / Inf
|
||
if torch.isnan(audio).any() or torch.isinf(audio).any():
|
||
if not is_dummy:
|
||
print(">> [Warning] 檢測到 Audio 解碼輸出包含 NaN/Inf!進行數值清理...")
|
||
audio = torch.nan_to_num(audio, nan=0.0, posinf=1.0, neginf=-1.0)
|
||
|
||
# 2. 徹底消除前綴的 Batch 維度 (例如 [1, 2, S] -> [2, S])
|
||
while audio.ndim > 2 and audio.shape[0] == 1:
|
||
audio = audio.squeeze(0)
|
||
|
||
# 3. 確保維度為 [2, Samples]
|
||
if audio.ndim == 1:
|
||
# 單聲道 [S] -> 複製為雙聲道 [2, S]
|
||
audio = audio.unsqueeze(0).repeat(2, 1)
|
||
elif audio.ndim == 2:
|
||
# 若形狀為 [S, 2],轉置為 [2, S]
|
||
if audio.shape[0] not in (1, 2) and audio.shape[1] in (1, 2):
|
||
audio = audio.transpose(0, 1)
|
||
# 若形狀為 [1, S],複製為雙聲道 [2, S]
|
||
if audio.shape[0] == 1:
|
||
audio = audio.repeat(2, 1)
|
||
|
||
# 4. 音量正規化
|
||
max_val = audio.abs().max()
|
||
if max_val > 1.0:
|
||
audio = audio / max_val
|
||
elif max_val == 0.0 and not is_dummy:
|
||
print(">> [Warning] Audio 輸出全為 0 (靜音)!請檢查 Step 3 生成的 audio latent。")
|
||
|
||
return audio
|
||
|
||
|
||
def run_pre_dummy_test(pipe, video_vae, audio_vae, fps):
|
||
# 獲取 registry 中的第一個可用 task 作為參考規格 (不假設編號從 0 開始)
|
||
first_task_id = next(iter(TASK_REGISTRY))
|
||
task0 = TASK_REGISTRY[first_task_id]
|
||
target_w = task0.width
|
||
target_h = task0.height
|
||
target_frames = task0.num_frames
|
||
|
||
print("\n" + "=" * 68)
|
||
print(f">> [PRE-LOOP TEST] 執行 VAE 空畫面預熱與解碼測試...")
|
||
print(f">> 參考 Task 0 規格: {target_w}x{target_h}, {target_frames} 幀 (FPS: {fps})")
|
||
print("=" * 68)
|
||
|
||
dummy_out_path = os.path.join(OUTPUT_DIR, f"dummy_test_{target_w}x{target_h}_{target_frames}f.mp4")
|
||
|
||
video_pt_0 = "result3_video_00.pt"
|
||
audio_pt_0 = "result3_audio_00.pt"
|
||
|
||
if os.path.exists(video_pt_0) and os.path.exists(audio_pt_0):
|
||
print(f">> [Dummy] 發現 {video_pt_0},沿用其結構克隆全 0 特徵張量...")
|
||
raw_v = torch.load(video_pt_0, weights_only=False)
|
||
video_data = move_to_cuda({
|
||
"args": [torch.zeros_like(a) if isinstance(a, torch.Tensor) else a for a in raw_v.get("args", [])],
|
||
"kwargs": {k: (torch.zeros_like(v) if isinstance(v, torch.Tensor) else v) for k, v in raw_v.get("kwargs", {}).items()}
|
||
})
|
||
raw_a = torch.load(audio_pt_0, weights_only=False)
|
||
audio_data = move_to_cuda({
|
||
"args": [torch.zeros_like(a) if isinstance(a, torch.Tensor) else a for a in raw_a.get("args", [])],
|
||
"kwargs": {k: (torch.zeros_like(v) if isinstance(v, torch.Tensor) else v) for k, v in raw_a.get("kwargs", {}).items()}
|
||
}, dtype=torch.float32)
|
||
else:
|
||
print(f">> [Dummy] 未發現 Task 0 的 pt 檔,直接以數學公式推算全 0 張量...")
|
||
w_lat = target_w // 16
|
||
h_lat = target_h // 16
|
||
t_lat = ((target_frames - 5) // 17 * 5 + 2) if target_frames > 5 else 1
|
||
dummy_v_latent = torch.zeros((1, 24, t_lat, h_lat, w_lat), device="cuda", dtype=torch.bfloat16)
|
||
video_data = {"args": [dummy_v_latent], "kwargs": {}}
|
||
|
||
ta_lat = int((target_frames / fps) * 40)
|
||
dummy_a_latent = torch.zeros((2, 32, ta_lat), device="cuda", dtype=torch.float32)
|
||
audio_data = {"args": [dummy_a_latent], "kwargs": {}}
|
||
|
||
torch.cuda.reset_peak_memory_stats()
|
||
t0 = time.time()
|
||
|
||
# 直接解碼,不搬移權重
|
||
print(">> [Dummy] 解碼 Video VAE...")
|
||
with torch.no_grad():
|
||
video_raw = video_vae.decode_video(*video_data["args"], **video_data["kwargs"])
|
||
video = pipe.vae_output_to_video(video_raw, min_value=0, max_value=1)
|
||
video_time = time.time() - t0
|
||
|
||
print(">> [Dummy] 解碼 Audio VAE...")
|
||
with torch.no_grad():
|
||
kwargs = audio_data.get("kwargs", {}).copy()
|
||
if "dtype" in kwargs:
|
||
kwargs["dtype"] = torch.float32
|
||
audio_raw = audio_vae.decode_audio(*audio_data["args"], **kwargs)
|
||
|
||
# 關鍵修正:透過共用函式統一正規化為 [2, Samples]
|
||
audio = format_audio_for_output(audio_raw, is_dummy=True)
|
||
sample_rate = getattr(audio_vae, "sample_rate", 32000)
|
||
|
||
write_video_audio(
|
||
video=video,
|
||
audio=audio,
|
||
output_path=dummy_out_path,
|
||
fps=fps,
|
||
audio_sample_rate=sample_rate,
|
||
)
|
||
|
||
peak_vram = torch.cuda.max_memory_allocated() / (1024**3)
|
||
print(f">> [Dummy 完成] 測試檔案已存至: {dummy_out_path}")
|
||
print(f">> [Dummy 報告] 解碼耗時: {video_time:.2f} 秒 | 顯存峰值: {peak_vram:.2f} GB")
|
||
print("=" * 68 + "\n")
|
||
|
||
# 僅刪除產出資料的變數參照,模型權重留在 GPU 內
|
||
del video_data, audio_data, video_raw, audio_raw, video, audio
|
||
|
||
|
||
def main():
|
||
print("\n========== [REF2VA STAGE 4] VAE 像素還原 ==========")
|
||
print(f">> [Config] 專案配置: {config_path}")
|
||
print(f">> [Config] 輸出路徑: {OUTPUT_DIR}")
|
||
|
||
enabled_ids = get_enabled_tasks()
|
||
print(f">> [Config] 啟用任務: {enabled_ids}")
|
||
|
||
fps = VIDEO_SETTINGS.get("default_fps", 24)
|
||
|
||
# 載入 Pipeline
|
||
print(">> [INFO] 開始初始化 VAE...")
|
||
pipe = MiniMaxH3Pipeline.from_pretrained(
|
||
torch_dtype=torch.bfloat16,
|
||
device="cuda",
|
||
model_configs=[
|
||
ModelConfig(
|
||
model_id="DiffSynth-Studio/MiniMax-H3-NF4",
|
||
origin_file_pattern="video_vae_nf4.safetensors",
|
||
path=os.path.join(MODELS_DIR, "vae/video_vae_nf4.safetensors"),
|
||
**VRAM_CONFIG
|
||
),
|
||
ModelConfig(
|
||
model_id="DiffSynth-Studio/MiniMax-H3-NF4",
|
||
origin_file_pattern="audio_vae_nf4.safetensors",
|
||
path=os.path.join(MODELS_DIR, "vae/audio_vae_nf4.safetensors"),
|
||
**VRAM_CONFIG
|
||
),
|
||
],
|
||
processor_config=None,
|
||
vram_limit=18.0,
|
||
)
|
||
|
||
# 關鍵優化:權重一次性常駐 GPU
|
||
video_vae = pipe.video_vae.to("cuda")
|
||
audio_vae = pipe.audio_vae.to("cuda", dtype=torch.float32)
|
||
|
||
print(f">> [OK] VAE 已常駐 GPU 顯存 (video_vae: {type(video_vae).__name__}, audio_vae: {type(audio_vae).__name__})")
|
||
|
||
# =========================================================================
|
||
# 【前置步驟】在進入原本的 for-loop 之前,先執行一次 Dummy 測試
|
||
# =========================================================================
|
||
ENABLE_DUMMY_TEST = True # 不需要時改為 False 即可完全關閉
|
||
if ENABLE_DUMMY_TEST:
|
||
run_pre_dummy_test(pipe, video_vae, audio_vae, fps)
|
||
|
||
# =========================================================================
|
||
# 正式任務迴圈 (原本的檢查與跳過邏輯)
|
||
# =========================================================================
|
||
done = 0
|
||
for task_idx in enabled_ids:
|
||
task = TASK_REGISTRY[task_idx]
|
||
out_path = os.path.join(OUTPUT_DIR, f"ref2va_output_{task_idx:02d}_l0.mp4")
|
||
|
||
if os.path.exists(out_path):
|
||
print(f"\n>> [SKIP] Task {task_idx}: 輸出已存在: {out_path}")
|
||
done += 1
|
||
continue
|
||
|
||
video_pt = f"result3_video_{task_idx:02d}.pt"
|
||
audio_pt = f"result3_audio_{task_idx:02d}.pt"
|
||
|
||
if not os.path.exists(video_pt) or not os.path.exists(audio_pt):
|
||
print(f">> [Skip] 缺少 {video_pt} 或 {audio_pt}")
|
||
continue
|
||
|
||
print(f"\n>> [Task {task_idx}] 開始處理: {task.name}")
|
||
print(f">> [Task {task_idx}] 載入 latent: {video_pt}, {audio_pt}")
|
||
|
||
video_data = move_to_cuda(torch.load(video_pt, weights_only=False))
|
||
audio_data = move_to_cuda(torch.load(audio_pt, weights_only=False), dtype=torch.float32)
|
||
|
||
# ----------------- Video Decode -----------------
|
||
print(">> [Task] 解碼 Video VAE...")
|
||
with torch.no_grad():
|
||
video_raw = video_vae.decode_video(*video_data["args"], **video_data["kwargs"])
|
||
video = pipe.vae_output_to_video(video_raw, min_value=0, max_value=1)
|
||
|
||
# ----------------- Audio Decode -----------------
|
||
print(">> [Task] 解碼 Audio VAE...")
|
||
with torch.no_grad():
|
||
kwargs = audio_data.get("kwargs", {}).copy()
|
||
if "dtype" in kwargs:
|
||
kwargs["dtype"] = torch.float32
|
||
audio_raw = audio_vae.decode_audio(*audio_data["args"], **kwargs)
|
||
|
||
# ----------------- 音訊後處理與健全檢查 -----------------
|
||
audio = format_audio_for_output(audio_raw, is_dummy=False)
|
||
|
||
sample_rate = getattr(audio_vae, "sample_rate", 32000)
|
||
if sample_rate is None:
|
||
sample_rate = VIDEO_SETTINGS.get("default_audio_sample_rate", 32000)
|
||
|
||
print(f">> [Task] 儲存影片: {out_path}")
|
||
print(f">> - 影片幀數: {len(video)} 幀 (FPS: {fps})")
|
||
print(f">> - 音訊規格: Shape={tuple(audio.shape) if isinstance(audio, torch.Tensor) else None}, SampleRate={sample_rate}")
|
||
|
||
write_video_audio(
|
||
video=video,
|
||
audio=audio,
|
||
output_path=out_path,
|
||
fps=fps,
|
||
audio_sample_rate=sample_rate,
|
||
)
|
||
print(f">> [SUCCESS] Task {task_idx} 完成!")
|
||
|
||
# 僅清理本次生成的資料張量,權重繼續留在 GPU
|
||
del video_data, audio_data, video_raw, audio_raw, video, audio
|
||
done += 1
|
||
|
||
print(f"\n========== [REF2VA STAGE 4] 完成 {done}/{len(enabled_ids)} 個任務 ==========")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|