#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python import gc 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) # 關閉最吃顯存的原生 Math 計算 """ [R2V STAGE 1] Video VAE 編碼參考檔 → ref_blocks + anchors ================================================================ R2V 模式: Reference-to-Video - 使用影片/圖片作為參考來源,支援混合影像+影片 不修改框架源碼的解決方案:直接呼叫 _build_block 然後手動合併 anchors 每個任務一次跑完: 1. 用 config.load_task_references(idx) 載入參考檔 2. 手動呼叫 _build_block() 為每個 reference 編碼 3. 手動合併 visual_anchor 和 audio_anchor 4. 落盤 result1_ref_{idx}.pt 說明:和 ref2va_step1.py 一樣,但 for R2V 單權重策略: Video VAE (NF4 量化, ~1.6GB VRAM) 下一階段: r2v_step2.py (Text Encoder) → r2v_step3.py (DiT) → r2v_step4.py (VAE Decoder) """ import os import sys import gc import importlib.util import torch from PIL import Image # ============================================================================== # 動態加載專案配置 # ============================================================================== config_path = os.path.abspath("config.py") if not os.path.exists(config_path): potential_path = "/home/mikehu/data/AI/minimax-h3/outputs/cat/config.py" if os.path.exists(potential_path): config_path = potential_path os.chdir("/home/mikehu/data/AI/minimax-h3/outputs/cat") else: print(f">> [Error] Cannot find config.py in {os.getcwd()}") print(">> 請透過 run_r2v_h3.sh 執行 (會 cd 到專案目錄。)") 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 TASK_REGISTRY = config.TASK_REGISTRY RUN_CONFIG = config.RUN_CONFIG def get_enabled_tasks(): return sorted(TASK_REGISTRY.keys()) def load_task_references(task): return config.load_task_references(task) from diffsynth.pipelines.minimax_h3_audio_video import ( MiniMaxH3Pipeline, ModelConfig, MiniMaxH3Unit_ReferenceEncoder, ) from diffsynth.models.minimax_h3_dit import patchify_video, unpack_audio os.environ["DIFFSYNTH_SKIP_DOWNLOAD"] = "True" os.environ["HIP_VISIBLE_DEVICES"] = "0" os.environ["CUDA_VISIBLE_DEVICES"] = "0" os.environ["HSA_OVERRIDE_GFX_VERSION"] = "11.0.0" MAX_IMAGE_REFS = 9 def manual_build_reference_blocks(pipe, ref_unit, references, num_frames, seed): """ Step1 的手動版處理:改用 reference 的 frames 或 image 的好的 shape 直接用 _encode_video_ref 或 _encode_image_ref 而不需要 video_latents """ device = pipe.device ref_image_short_edge = 768 ref_video_short_edge = 768 ref_video_max_pixels = 768*1344 # 逐個處理每個 reference,直接呼叫 _encode_*_ref ref_blocks_out = [] for ref in references: kind = ref["type"] if kind == "image": img = ref["image"] # 直接呼叫 _encode_image_ref rows, lh, lw, prepared = ref_unit._encode_image_ref( pipe, img, ref_image_short_edge ) block = { "kind": kind, "visual_clean": rows, "latent_t": 1, "latent_h": lh, "latent_w": lw, "prepared_image": prepared, "ref_audio_t": 0 } ref_blocks_out.append(block) elif kind in ("video", "video_audio"): frames = ref["video"] # 直接呼叫 _encode_video_ref rows, lt, lh, lw, prepared = ref_unit._encode_video_ref( pipe, frames, num_frames, ref_video_short_edge, ref_video_max_pixels ) block = { "kind": kind, "visual_clean": rows, "latent_t": lt, "latent_h": lh, "latent_w": lw, "prepared_frames": prepared, "ref_audio_t": 0 } if kind == "video_audio": # 如果有 audio,這裡需要補上,但我們 config 沒提供 audio,所以省略 pass ref_blocks_out.append(block) # 手動合併 visual_anchor # 參考: process() 中的邏輯,但 Step1 不需要 video_latents # 我們直接用 block 的 latent 信息生成 noise visual_blocks = [b for b in ref_blocks_out if "visual_clean" in b] visual_parts = [] for i, block in enumerate(visual_blocks): clean = block.pop("visual_clean").to(device=device, dtype=pipe.torch_dtype) if pipe.imgvid_cond_noise_aug == 1.0: anchor = clean else: # Step1 的特殊處理:沒有 video_latents,用 num_frames + i (index) # 簡化版:用 block 自身的 latent_t latent_t = int(block["latent_t"]) latent_h = int(block["latent_h"]) latent_w = int(block["latent_w"]) # 生成 noise noise_shape = (1, 24, latent_t, latent_h, latent_w) noise = pipe.generate_noise( noise_shape, seed=seed + i, rand_device="cpu", rand_torch_dtype=pipe.torch_dtype, device="cpu", torch_dtype=pipe.torch_dtype ) noise_rows = patchify_video(noise).to(device=device, dtype=pipe.torch_dtype) ts = torch.tensor(pipe.imgvid_cond_noise_aug, dtype=pipe.torch_dtype, device=device) anchor = ts * clean + (1.0 - ts) * noise_rows visual_parts.append(anchor) # 手動合併 audio_anchor (我們沒有 audio,所以可以忽略) audio_parts = [] for block in ref_blocks_out: # 新增 audio support if exists if "audio_clean" not in block or int(block.get("ref_audio_t", 0)) <= 0: continue clean = block.pop("audio_clean").to(device=device, dtype=pipe.torch_dtype) if pipe.audio_cond_noise_aug == 1.0: anchor = clean else: noise = pipe.generate_noise( clean.shape, seed=seed + len(visual_blocks), rand_device="cpu", rand_torch_dtype=pipe.torch_dtype, device=device, torch_dtype=pipe.torch_dtype ) ts = torch.tensor(pipe.audio_cond_noise_aug, dtype=pipe.torch_dtype, device=device) anchor = ts * clean + (1.0 - ts) * noise audio_parts.append(anchor) return { "ref_blocks": ref_blocks_out, "ref_visual_anchor": torch.cat(visual_parts, dim=0) if visual_parts else None, "ref_audio_anchor": torch.cat(audio_parts, dim=0) if audio_parts else None, } def main(): enabled_ids = get_enabled_tasks() if not enabled_ids: print(">> [Error] 沒有啟用的任務") sys.exit(1) print("\n========== [R2V STAGE 1] Video VAE 編碼參考檔 (混合影像+影片) ==========") print(f">> [Config] 專案配置: {config_path}") #--- 前置檢查 --- for idx in enabled_ids: task = TASK_REGISTRY[idx] n = len(task.references or []) if n == 0: print(f">> [Error] Task {idx} 沒有 references。R2V 至少需要 1 個參考檔。") sys.exit(1) if n > MAX_IMAGE_REFS: print(f">> [Error] Task {idx} 有 {n} 個參考檔, 超過官方上限 {MAX_IMAGE_REFS} 個。") sys.exit(1) # Clean GPU cache torch.cuda.empty_cache() gc.collect() # 單一權重: video VAE 全駐 GPU vae_cp = os.path.join(MODELS_DIR, "DiffSynth-Studio/vae/video_vae_nf4.safetensors") if not os.path.exists(vae_cp): vae_cp = os.path.join(MODELS_DIR, "vae/video_vae_nf4.safetensors") print(f">> [VAE] 使用模型: {vae_cp}") if not os.path.exists(vae_cp): print(f">> [Error] VAE 模型不存在: {vae_cp}") sys.exit(1) pipe = MiniMaxH3Pipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ModelConfig( path=vae_cp, offload_dtype=torch.bfloat16, offload_device="cuda", onload_dtype=torch.bfloat16, onload_device="cuda", preparing_dtype=torch.bfloat16, preparing_device="cuda", computation_dtype=torch.bfloat16, computation_device="cuda", ), ], processor_config=None, vram_limit=18.0, ) # 使用 pipeline 內建的 ReferenceEncoder ref_unit = MiniMaxH3Unit_ReferenceEncoder() seed = RUN_CONFIG.default_seed if hasattr(RUN_CONFIG, "default_seed") else 42 # 斷點續傳 last_completed_idx = -1 output_dir = os.path.dirname(config_path) if config_path != "config.py" else os.getcwd() if os.path.exists(".restart"): try: with open(".restart") as f: last_completed_idx = int(f.read().strip()) print(f"\n[RESUME] 偵測到續傳, 從任務 ID > {last_completed_idx} 開始。") except Exception: pass done = 0 for idx in enabled_ids: if idx <= last_completed_idx: print(f">> [SKIP] Task {idx} 已完成 (續傳)。") continue if os.path.exists(".stop"): with open(".restart", "w") as f: f.write(str(last_completed_idx)) os.remove(".stop") print(f"\n[STOP] 偵測到 .stop。進度已存至 .restart。") return task = TASK_REGISTRY[idx] nf = task.frame_end - task.frame_start + 1 # 載入參考檔 refs = load_task_references(task) num_refs = len(refs) if num_refs == 0: print(f">> [Error] Task {idx} 沒有參考檔") continue # 顯示參考類型 detected_types = [] for ref in refs: if "image" in ref: detected_types.append("image") elif "video" in ref: detected_types.append("video") print(f"\n>> [Task {idx}] 編碼 {num_refs} 個參考檔 (目標 {task.width}x{task.height}, {nf}f)...") print(f" 參考類型: {detected_types}") try: # 🎯 使用手動版,直接呼叫 _encode_*_ref ref_output = manual_build_reference_blocks( pipe=pipe, ref_unit=ref_unit, references=refs, num_frames=nf, seed=seed + idx, # 每個 task 不同 seed ) save_name = f"result1_ref_{idx}.pt" save_path = os.path.join(output_dir, save_name) # 移除不需要落盤的大型 tensors if "ref_visual_anchor" in ref_output and ref_output["ref_visual_anchor"] is not None: ref_output["ref_visual_anchor"] = move_to_cpu(ref_output["ref_visual_anchor"]) if "ref_audio_anchor" in ref_output and ref_output["ref_audio_anchor"] is not None: ref_output["ref_audio_anchor"] = move_to_cpu(ref_output["ref_audio_anchor"]) # 保存 torch.save({ "ref_blocks": ref_output["ref_blocks"], "ref_visual_anchor": ref_output.get("ref_visual_anchor"), "ref_audio_anchor": ref_output.get("ref_audio_anchor"), "task_config": { "width": task.width, "height": task.height, "fps": task.fps, "num_frames": nf, "frame_start": task.frame_start, "frame_end": task.frame_end, }, "seed": seed + idx, }, save_path) # 顯示結果 block_types = [b['kind'] for b in ref_output['ref_blocks']] print(f">> [成功] Task {idx} ({task.name}) 已儲存至 {save_path}") print(f" ref_blocks types: {block_types}") if ref_output.get("ref_visual_anchor") is not None: print(f" ref_visual_anchor shape: {ref_output['ref_visual_anchor'].shape}") last_completed_idx = idx done += 1 except Exception as e: print(f">> [ERROR] Task {idx} 失敗: {e}") import traceback traceback.print_exc() # 嘗試清理 GPU try: torch.cuda.empty_cache() gc.collect() except: pass continue # Clean GPU cache between tasks torch.cuda.empty_cache() gc.collect() print("\n" + "="*60) print("[R2V STAGE 1] 完成!可以執行 Step2 (text encoder)") print("="*60) def move_to_cpu(obj): """递歸地將 tensor 移到 CPU""" if isinstance(obj, torch.Tensor): return obj.detach().cpu() if isinstance(obj, dict): return {k: move_to_cpu(v) for k, v in obj.items()} if isinstance(obj, (list, tuple)): return type(obj)(move_to_cpu(x) for x in obj) return obj if __name__ == "__main__": main()