#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python import os import sys import gc import psutil import importlib.util # ============================================================================== # 【新增】將 C++ 底層的 ROCm 警告攔截並寫入 logfile,保留 tqdm 進度條在螢幕上 # ============================================================================== # 1. 讓 Python 的進度條 (tqdm) 走 stdout,確保終端機依然看得到進度 sys.stderr = sys.stdout # 2. 將 C/C++ 系統層的 stderr (fd 2) 重新導向到 log 檔案 _log_file = open("allocator_warnings.log", "a", buffering=1) os.dup2(_log_file.fileno(), 2) # ============================================================================== # 環境變數設定 # ============================================================================== os.environ["HIP_VISIBLE_DEVICES"] = "0" os.environ["CUDA_VISIBLE_DEVICES"] = "0" os.environ["HSA_OVERRIDE_GFX_VERSION"] = "11.0.0" os.environ["PYTHONNOUSERSITE"] = "1" os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "garbage_collection_threshold:0.8" os.environ["DIFFSYNTH_SKIP_DOWNLOAD"] = "True" os.environ["DIFFSYNTH_ATTENTION_IMPLEMENTATION"] = "xformers" 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 計算 """ [REF2VA STAGE 3] DiT 去噪生成 (ref2va 權重 + Turbo LoRA, 單權重版) ================================================================ 唯一大權重: minimax-h3-ref2va-nf4.safetensors (~16GB NF4). 不載入 video VAE / text encoder / audio VAE (皆為 proxy 或 stub). 每個任務 (全部 N 個視頻在這次載入中一次跑完, DiT 只載入一次): 1. SavedReferenceEncoder: 取代原 ReferenceEncoder 單元 (in-place 替換, 保持單位順序), 回放 step1 落盤的 ref_blocks + anchors, 不編碼。 2. PromptEmbedder 走「主路徑」重跑 presentation_ref2va (輕量 tokenizer/processor), 產生【正確的】0/1 混合 text_token_tags (DiT ADALN 靠它區分 text/vision token — 不能用 text_embedding 快速路徑, 那會回全 1 的 tags)。 3. ref2va DiT 去噪 N steps (cfg_scale=1.0 -> negative 重用 positive, PromptEmbedder 只跑一次)。 4. 然後加入 Turbo LoRA 到 DiT 模型 5. 最終 decode 被 SaveLatent VAE stubs 攔截 -> 落盤 result3_video/audio_{idx}.pt (step4 負責真實 VAE 解碼)。 單權重策略: 任一時刻 DRAM/VRAM 只有 DiT 一個大權重 (proxy/stub 是輕量 nn.Module, 不佔 VRAM/DRAM 模型空間)。 """ # ============================================================================== # 動態加載專案配置 (與 fl2va 一致: cd 到專案目錄後讀 ./config.py) # ============================================================================== 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()}") print(">> 請透過 run_refh3.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 config.get_enabled_tasks() from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig from diffsynth.diffusion.base_pipeline import PipelineUnit def move_to_cpu(obj): 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 # ============================================================================== # SavedReferenceEncoder: 取代原 ReferenceEncoder 單元 # 回傳 step1 預先算好的 ref_blocks (metadata + prepared_image) 與 anchors。 # ============================================================================== class SavedReferenceEncoder(PipelineUnit): def __init__(self): super().__init__( input_params=("references", "seed", "video_latents", "num_frames", "ref_image_short_edge", "ref_video_short_edge", "ref_video_max_pixels"), output_params=("ref_blocks", "ref_visual_anchor", "ref_audio_anchor"), onload_model_names=("video_vae", "audio_vae"), ) self.data = None # 每個 task 前綁定 step1 落盤的內容 def process(self, pipe, references, seed, video_latents, num_frames, ref_image_short_edge, ref_video_short_edge, ref_video_max_pixels): assert self.data is not None, "SavedReferenceEncoder.data 未綁定 (step1 輸出?)" va = self.data["ref_visual_anchor"] aa = self.data["ref_audio_anchor"] return { "ref_blocks": self.data["ref_blocks"], "ref_visual_anchor": va.to(device=pipe.device, dtype=pipe.torch_dtype) if va is not None else None, "ref_audio_anchor": aa.to(device=pipe.device, dtype=pipe.torch_dtype) if aa is not None else None, } # ============================================================================== # ReplayTextEncoder: 回放 step2 落盤的 hidden (不載入 15GB 權重) # PromptEmbedder 主路徑重跑 presentation_ref2va -> 呼叫 pipe.text_encoder(**kwargs) # -> 這裡直接回 step2 的 hidden。長度不一致 = step1/step3 的參考圖縮放參數 # 或 processor 不一致 -> 丟明確錯誤 (而非靜默錯位)。 # ============================================================================== class ReplayTextEncoder(torch.nn.Module): def __init__(self, path): super().__init__() data = torch.load(path, weights_only=False) self.hidden = data["hidden"] self.tags = data["text_token_tags"] def __call__(self, *args, **kwargs): ids = kwargs.get("input_ids") if ids is not None and int(ids.shape[-1]) != int(self.hidden.shape[0]): raise ValueError( f"text encoder 序列長度不符: 回放 hidden={self.hidden.shape[0]}, " f"step3 即時 presentation={ids.shape[-1]}。" f"step1/step3 的參考圖縮放參數 (ref_image_short_edge) 與 processor 必須一致。" ) return self.hidden.to("cuda") # ============================================================================== # SaveLatent VAE stubs: 攔截 __call__ 尾部的最終 decode, 落盤 latent, # ============================================================================== class SaveLatentVideoVAE(torch.nn.Module): def __init__(self, idx): super().__init__() self.idx = idx def decode_video(self, *args, **kwargs): torch.save({"args": move_to_cpu(args), "kwargs": move_to_cpu(kwargs)}, f"result3_video_{self.idx:02d}.pt") latents = args[0] # latent [1,24,T,H',W'] -> pixel [1,3,T_dec,H,W] T, H2, W2 = int(latents.shape[2]), int(latents.shape[3]), int(latents.shape[4]) T_dec = (T - 2) // 5 * 17 + 5 print(f">> [SaveLatentVideoVAE] 已攔截最終 decode -> result3_video_{self.idx:02d}.pt") return torch.zeros((1, 3, T_dec, H2 * 16, W2 * 16)) def decode(self, *args, **kwargs): return self.decode_video(*args, **kwargs) class SaveLatentAudioVAE(torch.nn.Module): def __init__(self, idx): super().__init__() self.idx = idx def decode_audio(self, *args, **kwargs): torch.save({"args": move_to_cpu(args), "kwargs": move_to_cpu(kwargs)}, f"result3_audio_{self.idx:02d}.pt") latents = args[0] # latent [2,32,Ta] (40Hz) -> waveform [2, Ta*800] (32kHz) Ta = int(latents.shape[-1]) print(f">> [SaveLatentAudioVAE] 已攔截最終 decode -> result3_audio_{self.idx:02d}.pt") return torch.zeros((2, Ta * 800)) def decode(self, *args, **kwargs): return self.decode_audio(*args, **kwargs) def drop_file_cache(filepath): """ 告知內核不需要快取該檔案的內容,釋放 Page Cache。 """ try: with open(filepath, 'rb') as f: fd = f.fileno() os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED) print(f">> [Cache] Dropped page cache for {filepath}") except Exception as e: print(f">> [Cache] Failed to drop cache for {filepath}: {e}") def main(): print("\n========== [REF2VA STAGE 3] DiT 去噪生成 (ref2va 權重, 單權重版) ==========") # 步驟一致性檢查 # config.validate_steps_consistency() enabled_ids = get_enabled_tasks() for idx in enabled_ids: if not os.path.exists(f"result1_ref_{idx:02d}.pt") or not os.path.exists(f"result2_text_{idx:02d}.pt"): print(f">> [Error] Task {idx} 缺少前置 pt 檔案。") sys.exit(1) # 檢查所有 result3_video/audio_*.pt 是否已存在,若全部存在則跳過整個 Step 3 all_latents_exist = all( os.path.exists(f"result3_video_{idx:02d}.pt") and os.path.exists(f"result3_audio_{idx:02d}.pt") for idx in enabled_ids ) if all_latents_exist: print(">> [SKIP] 所有 result3_video/audio_*.pt 已存在,跳過 Step 3。") print(f"\n========== [REF2VA STAGE 3] 完成 {len(enabled_ids)}/{len(enabled_ids)} 個任務 (全部跳過) ==========") return torch.cuda.empty_cache() gc.collect() vram_config = { "offload_dtype": torch.bfloat16, "offload_device": "cpu", "onload_dtype": torch.bfloat16, "onload_device": "cpu", "preparing_dtype": torch.bfloat16, "preparing_device": "cuda", "computation_dtype": torch.bfloat16, "computation_device": "cuda", } # 1. 權重只在啟動時從 HDD 載入一次到系統記憶體 (DRAM) pipe = MiniMaxH3Pipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ModelConfig( model_id="DiffSynth-Studio/MiniMax-H3-NF4", origin_file_pattern="minimax-h3-ref2va-nf4.safetensors", path=os.path.join(MODELS_DIR, "diffusion_models/minimax-h3-ref2va-nf4.safetensors"), **vram_config, ), ], processor_config=ModelConfig( model_id="MiniMax/MiniMax-H3", origin_file_pattern="FL2VA/processor/", path=os.path.join(MODELS_DIR, "text_encoders/config"), ), vram_limit=14.0, ) # 釋放權重檔的 Page Cache,避免 DRAM 雙倍佔用 dit_path = os.path.join(MODELS_DIR, "diffusion_models/minimax-h3-ref2va-nf4.safetensors") drop_file_cache(dit_path) seed = RUN_CONFIG.get("default_seed", 42) # 根據每個任務的 steps 決定是否載入 Turbo LoRA # 注意:由於 validate_steps_consistency 已保證所有任務都在同一側 (<=23 或 >23), # 我們只需檢查第一個可用任務或 RUN_CONFIG 即可決定單次運行是否載入 LoRA。 first_idx = enabled_ids[0] if enabled_ids else None first_task = TASK_REGISTRY[first_idx] if first_idx is not None else None effective_steps = first_task.num_inference_steps if first_task and first_task.num_inference_steps is not None else RUN_CONFIG.get("default_num_inference_steps", 8) use_turbo_guidance = False if effective_steps <= 23: lora_path = os.path.join(MODELS_DIR, "loras/minimax_h3_turbo_v4_step600_ema.safetensors") if os.path.exists(lora_path): print(f">> [LoRA] 檢測到步驟 {effective_steps} <= 23, 載入 Turbo LoRA: {os.path.basename(lora_path)}") pipe.load_lora(pipe.dit, lora_config=lora_path, alpha=1.0, verbose=1) use_turbo_guidance = True else: print(f">> [Warning] LoRA 檔案不存在: {lora_path}") else: print(f">> [LoRA] 檢測到步驟 {effective_steps} > 23, 跳過 Turbo LoRA 載入") # --- 額外 LoRA (由專案 config.py 的 EXTRA_LORAS 指定; 格式: (檔案名, strength)) --- for lora_name, lora_strength in getattr(config, "EXTRA_LORAS", []): extra_path = os.path.join(MODELS_DIR, "loras", lora_name) if os.path.exists(extra_path): print(f">> [LoRA] 載入額外 LoRA: {lora_name} (strength={lora_strength})") pipe.load_lora(pipe.dit, lora_config=extra_path, alpha=lora_strength, verbose=1) else: print(f">> [Warning] 額外 LoRA 檔案不存在: {extra_path}") ref_unit = None for i, u in enumerate(pipe.units): if type(u).__name__ == "MiniMaxH3Unit_ReferenceEncoder": ref_unit = SavedReferenceEncoder() pipe.units[i] = ref_unit break last_completed_idx = -1 if os.path.exists(".restart"): try: with open(".restart") as f: last_completed_idx = int(f.read().strip()) except Exception: pass done = 0 for idx in enabled_ids: # 檔案存在即跳過 (與 step1/step2 一致): 已產出 result3 latent 的 task # 不再重跑。這樣「只重跑單一 task」(刪掉該 task 的 result3 檔) 時, # 其餘 task 會自動跳過, 不需要靠 .restart 計數器或改 config。 if os.path.exists(f"result3_video_{idx:02d}.pt") and os.path.exists(f"result3_audio_{idx:02d}.pt"): print(f">> [SKIP] Task {idx} 已有 result3_video/audio latent。") last_completed_idx = idx continue 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。進度 {last_completed_idx} 已存至 .restart。") return task = TASK_REGISTRY[idx] prompt = task.prompts[0] if task.prompts else "" # 優先讀取 task 的 steps,否則使用 RUN_CONFIG steps = task.num_inference_steps if task.num_inference_steps is not None else RUN_CONFIG.get("default_num_inference_steps", 8) # --- 任務前:重設峰值統計,記錄基準 VRAM --- torch.cuda.reset_peak_memory_stats() vram_start = torch.cuda.memory_allocated() / 1024**3 print(f"\n==================================================") print(f">> [Task {idx}] 開始生成: {task.width}x{task.height}, {task.num_frames}f, {steps} steps") print(f" 起始 Allocated VRAM: {vram_start:.2f} GB (預期 < 0.10 GB)") print(f"==================================================") ref_data = torch.load(f"result1_ref_{idx:02d}.pt", weights_only=False) ref_unit.data = ref_data pipe.text_encoder = ReplayTextEncoder(f"result2_text_{idx:02d}.pt") pipe.video_vae = SaveLatentVideoVAE(idx) pipe.audio_vae = SaveLatentAudioVAE(idx) # 2. 徹底關閉梯度與歷史追蹤 with torch.inference_mode(): pipe( prompt=prompt, height=task.height, width=task.width, num_frames=task.num_frames, num_inference_steps=steps, seed=seed, **({'cfg_scale': 1.0} if use_turbo_guidance else {}), ) # --- 任務完成:抓取本次任務的 VRAM 峰值 --- peak_allocated = torch.cuda.max_memory_allocated() / 1024**3 peak_reserved = torch.cuda.max_memory_reserved() / 1024**3 print(f"\n>> [Task {idx} VRAM 報告 (調參參考)]") print(f" 🔥 Peak Allocated: {peak_allocated:.2f} GB / 24 GB (實際張量最高佔用)") print(f" 📦 Peak Reserved: {peak_reserved:.2f} GB / 24 GB (ROCm 驅動預留池)") print(f">> [SUCCESS] Task {idx} 生成完畢。") # 3. 解除任務特定引用 ref_unit.data = None pipe.text_encoder = None pipe.video_vae = None pipe.audio_vae = None del ref_data # 4. 穿透式檢查:強制將 DiT 所有殘留在 GPU 的 Tensor 趕回 CPU if hasattr(pipe, "dit") and pipe.dit is not None: for param in pipe.dit.parameters(): if param.device.type == "cuda": param.data = param.data.to("cpu") for buf in pipe.dit.buffers(): if buf.device.type == "cuda": buf.data = buf.data.to("cpu") # 5. 強制觸發 GC 與顯存釋放 gc.collect() torch.cuda.empty_cache() torch.cuda.ipc_collect() vram_after = torch.cuda.memory_allocated() / 1024**3 print(f">> [顯存歸零確認] 清理後 Allocated VRAM: {vram_after:.2f} GB") last_completed_idx = idx with open(".restart", "w") as f: f.write(str(last_completed_idx)) done += 1 print(f"\n========== [REF2VA STAGE 3] 全部任務完成 ==========") if __name__ == "__main__": main()