#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python import os import sys import gc import psutil import importlib.util import logging import hashlib from safetensors.torch import load_file, save_file # ============================================================================== # 【新增】將 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) # 確保 Python logging 能輸出到 stdout/stderr (避免被 dup2 影響或未初始化) logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') # ============================================================================== # 環境變數設定 # ============================================================================== 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["TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL"] = "1" os.environ["DIFFSYNTH_ATTENTION_IMPLEMENTATION"] = "torch" import torch import logging logging.getLogger("comfy_kitchen.dispatch").setLevel(logging.DEBUG) # 強制啟用 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 權重) # PromptEmbedLatter 主路徑重跑 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): 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 prepare_lora_for_dit(pipe, lora_path, weight_type): cache_dir = "/tmp/ds_lora_cache" os.makedirs(cache_dir, exist_ok=True) path_hash = hashlib.sha256(f"{lora_path}:{weight_type}".encode()).hexdigest()[:16] cache_path = os.path.join(cache_dir, f"{path_hash}.safetensors") if os.path.exists(cache_path): return cache_path print(f">> [LoRA Prepare] Processing {os.path.basename(lora_path)}...") state_dict = load_file(lora_path) new_state_dict = {} module_map = {f"lora_unet_{name.replace('.', '_')}": name for name, _ in pipe.dit.named_modules()} bad_modules = set() # Pass 1: Shape Guard for key, tensor in state_dict.items(): clean_key = key if clean_key.startswith("diffusion_model."): clean_key = clean_key[len("diffusion_model."):] elif clean_key.startswith("transformer."): clean_key = clean_key[len("transformer."):] # Determine the base module name for shape checking base_name = clean_key suffix = "" for s in [".lora_down.weight", ".lora_up.weight", ".alpha", ".lora_A.weight", ".lora_B.weight"]: if s in clean_key: base_name = clean_key.replace(s, "") suffix = s break # Convert Kohya/Comfy style keys to dot-notation for pipe.dit.get_submodule lookup_name = base_name if lookup_name.startswith("lora_unet_"): lookup_name = lookup_name.replace("lora_unet_", "").replace("_", ".") # Note: This simple replace might be too aggressive if names have underscores, # but based on the error `lora_unet_blocks_24_attn_out_proj` -> `blocks.24.attn.out_proj`, it's what's needed. # A more robust way is using the module_map we built. if lookup_name in module_map: # This was wrong, module_map keys are the lora_unet_ versions pass # Use the pre-built module_map for accuracy actual_mod_name = None if base_name in module_map: actual_mod_name = module_map[base_name] elif f"lora_unet_{base_name.replace('.', '_')}" in module_map: actual_mod_name = module_map[f"lora_unet_{base_name.replace('.', '_')}"] elif base_name in [name for name, _ in pipe.dit.named_modules()]: actual_mod_name = base_name if actual_mod_name: mod = pipe.dit.get_submodule(actual_mod_name) target_weight = mod.module.weight if hasattr(mod, 'module') else getattr(mod, 'weight', None) if target_weight is not None: if ("lora_down" in suffix or "lora_A" in suffix) and tensor.shape[1] != target_weight.shape[1]: print(f" [Shape Guard] Skipping {base_name}: LoRA down {tensor.shape[1]} != model {target_weight.shape[1]}") bad_modules.add(base_name) elif ("lora_up" in suffix or "lora_B" in suffix) and tensor.shape[0] != target_weight.shape[0]: print(f" [Shape Guard] Skipping {base_name}: LoRA up {tensor.shape[0]} != model {target_weight.shape[0]}") bad_modules.add(base_name) # Pass 2: Build New Dict for key, tensor in state_dict.items(): clean_key = key if clean_key.startswith("diffusion_model."): clean_key = clean_key[len("diffusion_model."):] elif clean_key.startswith("transformer."): clean_key = clean_key[len("transformer."):] base_name = clean_key for s in [".lora_down.weight", ".lora_up.weight", ".alpha", ".lora_A.weight", ".lora_B.weight"]: if s in clean_key: base_name = clean_key.replace(s, "") break if base_name in bad_modules: continue final_key = clean_key if clean_key.startswith("lora_unet_"): for kohya_mod, dot_mod in module_map.items(): if clean_key.startswith(kohya_mod): final_key = clean_key.replace(kohya_mod, dot_mod) break new_state_dict[final_key] = tensor save_file(new_state_dict, cache_path) print(f">> [LoRA Prepare] Saved cached LoRA to {cache_path}") return cache_path def main(): print("\n========== [REF2VA STAGE 3] DiT 去噪生成 (ref2va 權重, 單權重版) ==========") # 強制啟用 comfy-kitchen 的 Triton 後端以避免掉回 eager 模式導致 INT8 效能低下 try: import importlib comfy_kitchen = importlib.import_module("comfy_kitchen") comfy_kitchen.enable_backend("triton") print(">> [Backend] comfy-kitchen: Triton backend enabled.") except ImportError: print(">> [Warning] comfy-kitchen not installed in this environment. INT8 performance may be degraded.") except Exception as e: print(f">> [Warning] Failed to enable Triton backend: {e}") 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) 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", } weight_type = "int8" w_cfg = { "id": "DiffSynth-Studio/MiniMax-H3-Int8-Pruned", "pattern": "minimax-h3-ref2va-pruned-int8_convrot.safetensors", "file": "/home/mikehu/data/AI/minimax-h3/models/Comfy-Org/diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors" } vram_limit = 21.0 print(f">> [Config] 權重類型: {weight_type.upper()}, 設定 VRAM 限制: {vram_limit} GB") pipe = MiniMaxH3Pipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ModelConfig( model_id=w_cfg["id"], origin_file_pattern=w_cfg["pattern"], path=os.path.join(MODELS_DIR, w_cfg["file"]), **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=vram_limit, ) dit_path = os.path.join(MODELS_DIR, w_cfg["file"]) drop_file_cache(dit_path) seed = RUN_CONFIG.get("default_seed", 42) 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 # LoRA support is_hotload = (weight_type == "int8") if effective_steps <= 23: lora_path = os.path.join(MODELS_DIR, "DiffSynth-Studio/loras/minimax_h3_turbo_v4_step600_ema.safetensors") if os.path.exists(lora_path): print(f">> [LoRA] 檢測到步驟 {effective_steps} <= 23, 準備載入 Turbo LoRA (INT8): {os.path.basename(lora_path)} (hotload=True)") processed_lora_path = prepare_lora_for_dit(pipe, lora_path, weight_type) pipe.load_lora(pipe.dit, lora_config=processed_lora_path, alpha=1.0, hotload=True, verbose=1) use_turbo_guidance = True else: print(f">> [Warning] INT8 Turbo LoRA 檔案不存在: {lora_path}") else: print(f">> [LoRA] 檢測到步驟 {effective_steps} > 23, 跳過 Turbo LoRA 載入") # Enable Extra LoRAs for lora_name, lora_strength in getattr(config, "EXTRA_LORAS", []): extra_path = os.path.join(MODELS_DIR, "DiffSynth-Studio/loras", lora_name) if os.path.exists(extra_path): print(f">> [LoRA] 載入額外 LoRA (INT8): {lora_name} (strength={lora_strength}, hotload=True)") processed_extra_path = prepare_lora_for_dit(pipe, extra_path, weight_type) pipe.load_lora(pipe.dit, lora_config=processed_extra_path, alpha=lora_strength, hotload=True, verbose=1) else: print(f">> [Warning] INT8 額外 LoRA 檔案不存在: {extra_path}") # --- LoRA 載入驗證探針 --- try: from collections import Counter patched_types = Counter() cpu_weights_count = 0 gpu_weights_count = 0 print("\n>> [Memory Audit] Checking weight devices...") for name, m in pipe.dit.named_modules(): if len(getattr(m, "lora_A_weights", [])) > 0: patched_types[type(m).__name__] += 1 # Check for weight residency if hasattr(m, 'module') and hasattr(m.module, 'weight'): dev = m.module.weight.device if dev.type == 'cpu': cpu_weights_count += 1 else: gpu_weights_count += 1 elif hasattr(m, 'weight'): dev = m.weight.device if dev.type == 'cpu': cpu_weights_count += 1 else: gpu_weights_count += 1 print(f">> [LoRA Probe] 掛載統計: {dict(patched_types)} (總計 {sum(patched_types.values())} 層)") print(f">> [Device Audit] 模組權重分佈: CPU={cpu_weights_count}, GPU={gpu_weights_count}") if weight_type == "int8" and sum(patched_types.values()) == 0: print(">> [Warning] INT8 模式下 LoRA 層數為 0,請檢查 vram_limit 設定或 LoRA Key 是否匹配。") except Exception as e: print(f">> [Warning] LoRA 驗證探針發生錯誤: {e}") # For now, disable extra LoRAs as they may be incompatible with S-INT8 quantized weights # 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: 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 "" steps = task.num_inference_steps if task.num_inference_steps is not None else RUN_CONFIG.get("default_num_inference_steps", 8) 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) with torch.no_grad(): 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 {}), ) 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} 生成完畢。") ref_unit.data = None pipe.text_encoder = None pipe.video_vae = None pipe.audio_vae = None del ref_data 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") 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()