Initial commit: source code for minimax-h3

This commit is contained in:
2026-09-28 18:15:15 +08:00
commit c31e52dcb9
23 changed files with 4184 additions and 0 deletions
Executable
+126
View File
@@ -0,0 +1,126 @@
#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "garbage_collection_threshold:0.8,max_split_size_mb:128"
os.environ["PYTORCH_HIP_ALLOC_CONF"] = "garbage_collection_threshold:0.8,max_split_size_mb:128"
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 計算
import os
import torch
import gc
import importlib.util
import sys
# ==============================================================================
# 動態加載專案配置 (防止讀到根目錄的舊 config.py)
# ==============================================================================
# 優先從當前工作目錄加載 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()}")
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)
# 將 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
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["PYTHONNOUSERSITE"] = "1"
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
os.environ["DIFFSYNTH_SKIP_DOWNLOAD"] = "True"
def move_to_cuda(obj):
if isinstance(obj, torch.Tensor): return obj.to("cuda")
if isinstance(obj, dict): return {k: move_to_cuda(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)): return type(obj)(move_to_cuda(x) for x in obj)
return obj
def main():
print(f"\n========== [FL2VA STAGE 3] VAE 像素還原 (動態配置版) ==========")
print(f">> [Config] 專案配置路徑: {config_path}")
print(f">> [Config] 輸出路徑設定為: {OUTPUT_DIR}")
pipe = vram_config = {"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"}
MiniMaxH3Pipeline.from_pretrained(vram_config=vram_config,
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=ModelConfig(model_id="MiniMax/MiniMax-H3", origin_file_pattern="FL2VA/processor/", path=os.path.join(MODELS_DIR, "text_encoders/config")),
vram_limit=24.0,
)
enabled_tasks = get_enabled_tasks()
print(f">> [Debug] get_enabled_tasks() 返回結果: {enabled_tasks}")
for task_idx in enabled_tasks:
task = TASK_REGISTRY[task_idx]
print(f"\n>> [Task {task_idx}] 開始處理: {task.name}...")
video_pt = f"result2_video_{task_idx}_l0.pt"
audio_pt = f"result2_audio_{task_idx}_l0.pt"
print(f">> [Task {task_idx}] 正在載入潛空間檔案: {video_pt}, {audio_pt}...")
if not os.path.exists(video_pt) or not os.path.exists(audio_pt):
print(f">> [Error] Missing latents {video_pt}, skipping.")
continue
video_data = move_to_cuda(torch.load(video_pt))
audio_data = move_to_cuda(torch.load(audio_pt))
video_vae = pipe.video_vae
audio_vae = pipe.audio_vae
print(f">> [Task {task_idx}] 正在解碼 Video VAE...")
video_vae.to("cuda")
with torch.no_grad():
video_raw = video_vae.decode_video(*video_data["args"], **video_data["kwargs"]) if hasattr(video_vae, "decode_video") else video_vae.decode(*video_data["args"], **video_data["kwargs"])
video_vae.to("cpu")
video = pipe.vae_output_to_video(video_raw, min_value=0, max_value=1)
print(f">> [Task {task_idx}] 正在解碼 Audio VAE...")
audio_vae.to("cuda")
with torch.no_grad():
audio_raw = audio_vae.decode_audio(*audio_data["args"], **audio_data["kwargs"]) if hasattr(audio_vae, "decode_audio") else audio_vae.decode(*audio_data["args"], **audio_data["kwargs"])
audio_vae.to("cpu")
if isinstance(audio_raw, torch.Tensor):
audio = audio_raw.detach().cpu()
if audio.ndim == 3 and audio.shape[0] == 1: audio = audio[0]
else: audio = audio_raw
out_path = os.path.join(OUTPUT_DIR, f"fl2va_output_{task_idx}_l0.mp4")
print(f">> [Task {task_idx}] 正在儲存影片至: {out_path}...")
write_video_audio(video=video, audio=audio, output_path=out_path, fps=VIDEO_SETTINGS["default_fps"], audio_sample_rate=VIDEO_SETTINGS["default_audio_sample_rate"])
print(f">> [SUCCESS] Task {task_idx} 完成!")
gc.collect()
torch.cuda.empty_cache()
print(f">> [Debug] Task {task_idx} 內存清理完成,準備檢查下一個任務...")
print("\n========== [FL2VA STAGE 3] 所有任務完成! ==========")
if __name__ == "__main__":
main()