Initial commit: source code for minimax-h3
This commit is contained in:
Executable
+199
@@ -0,0 +1,199 @@
|
||||
#!/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 4] VAE 像素還原 (video + audio VAE)
|
||||
================================================================
|
||||
權重: video_vae_nf4.safetensors (~1.6GB) + audio_vae_nf4.safetensors (~0.28GB)
|
||||
|
||||
可在本地 (24G VRAM) 執行的輕量速度步驟:
|
||||
- Video/Audio VAE 小型模型,全駐 VRAM 還有大量餘量
|
||||
- VRAM 成本: 1.9G (二個小 VAE)
|
||||
|
||||
每個任務:
|
||||
1. 載入 step3 落盤的 latent (result3_video/audio_{idx}.pt)
|
||||
格式: {"args": [latents], "kwargs": {dtype, tiled, tile_size, tile_overlap}}
|
||||
2. video VAE 解碼 → 像素幀
|
||||
3. audio VAE 解碼 → 音訊波形
|
||||
4. write_video_audio 輸出 mp4 到 OUTPUT_DIR
|
||||
|
||||
斷點續傳: 輸出 mp4 已存在即跳過該任務
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import gc
|
||||
import importlib.util
|
||||
|
||||
# ==============================================================================
|
||||
# 動態加載專案配置
|
||||
# ==============================================================================
|
||||
config_path = os.path.abspath("config.py")
|
||||
if not os.path.exists(config_path):
|
||||
# 如果在 /home/mikehu/data/AI/minimax-h3 目錄,嘗試切換到 outputs/cat
|
||||
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()}")
|
||||
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.RUN_CONFIG
|
||||
TASK_REGISTRY = config.TASK_REGISTRY
|
||||
# VIDEO_SETTINGS = config.VIDEO_SETTINGS # 註解掉,改為使用預設值
|
||||
OUTPUT_DIR = config.OUTPUT_DIR if hasattr(config, "OUTPUT_DIR") else os.path.dirname(config_path) or os.getcwd()
|
||||
RUN_CONFIG = config.RUN_CONFIG
|
||||
|
||||
|
||||
def get_enabled_tasks():
|
||||
return config.get_enabled_tasks()
|
||||
|
||||
import torch
|
||||
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):
|
||||
"""Recursively move objects to CUDA device."""
|
||||
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("\n========== [R2V STAGE 4] VAE 像素還原 ==========")
|
||||
print(f">> [Config] 專案配置: {config_path}")
|
||||
print(f">> [Config] 輸出路徑: {OUTPUT_DIR}")
|
||||
|
||||
enabled_ids = get_enabled_tasks()
|
||||
print(f">> [Config] 啟用任務: {enabled_ids}")
|
||||
|
||||
# 檢查 step3 輸出存在
|
||||
allReady = True
|
||||
for idx in enabled_ids:
|
||||
if not os.path.exists(f"result3_video_{idx}.pt") or not os.path.exists(f"result3_audio_{idx}.pt"):
|
||||
print(f">> [Error] Task {idx}: 缺少 result3_video_{idx}.pt 或 result3_audio_{idx}.pt")
|
||||
allReady = False
|
||||
|
||||
if not allReady:
|
||||
print("\n>> 請先執行 step3 生成 DiT 丟噪 latents")
|
||||
sys.exit(1)
|
||||
|
||||
print(">> [INFO] 所有步驟 3 輸出均已就緒,開始初始化 VAE...")
|
||||
|
||||
# 小 VAE 全駐 GPU (1.9G 對 24GB 無壓力)
|
||||
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",
|
||||
}
|
||||
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, "DiffSynth-Studio/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, "DiffSynth-Studio/vae/audio_vae_nf4.safetensors"),
|
||||
**vram_config
|
||||
),
|
||||
],
|
||||
processor_config=None, # 解碼不需 tokenizer/processor
|
||||
vram_limit=18.0,
|
||||
)
|
||||
|
||||
video_vae = pipe.video_vae
|
||||
audio_vae = pipe.audio_vae
|
||||
|
||||
print(f">> [OK] VAE 初始化完成 (video_vae: {type(video_vae).__name__}, audio_vae: {type(audio_vae).__name__})")
|
||||
|
||||
done = 0
|
||||
for task_idx in enabled_ids:
|
||||
task = TASK_REGISTRY[task_idx]
|
||||
out_path = os.path.join(OUTPUT_DIR, f"r2v_output_{task_idx}_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}.pt"
|
||||
audio_pt = f"result3_audio_{task_idx}.pt"
|
||||
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))
|
||||
|
||||
# Video decode
|
||||
print(">> [Task] 解碼 Video VAE...")
|
||||
video_vae.to("cuda")
|
||||
with torch.no_grad():
|
||||
video_raw = video_vae.decode_video(*video_data["args"], **video_data["kwargs"])
|
||||
video_vae.to("cpu")
|
||||
video = pipe.vae_output_to_video(video_raw, min_value=0, max_value=1)
|
||||
|
||||
# Audio decode
|
||||
print(">> [Task] 解碼 Audio VAE...")
|
||||
audio_vae.to("cuda")
|
||||
with torch.no_grad():
|
||||
audio_raw = audio_vae.decode_audio(*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
|
||||
|
||||
print(f">> [Task] 儲存影片: {out_path}")
|
||||
print(f">> - 影片: {len(video)} 幀")
|
||||
print(f">> - 音訊: {tuple(audio.shape) if isinstance(audio, torch.Tensor) else 'None'}")
|
||||
|
||||
write_video_audio(
|
||||
video=video, audio=audio, output_path=out_path,
|
||||
fps=24, # 使用 config.py 中的 fps 24
|
||||
audio_sample_rate=24000, # 默認音頻採樣率
|
||||
)
|
||||
print(f">> [SUCCESS] Task {task_idx} 完成!")
|
||||
|
||||
# 清理
|
||||
del video_data, audio_data, video_raw, audio_raw, video, audio
|
||||
gc.collect()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
done += 1
|
||||
|
||||
print(f"\n========== [R2V STAGE 4] 完成 {done}/{len(enabled_ids)} 個任務 ==========")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user