Files
minimax-h3/config_template_r2v.py
T

203 lines
8.5 KiB
Python

#!/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 計算
# ==============================================================================
# 🎞️ MiniMax-H3 R2V Project Configuration (4-step 單權重架構)
# ==============================================================================
# 4-step 架構 (每 step 只載入 1 個權重, step 內 for-loop 跑完全部 N 個視頻):
# Step 1 video VAE (1.6G) → result1_ref_{idx}.pt (ref_blocks + anchors)
# Step 2 text encoder (15G) → result2_text_{idx}.pt (prompt_embeds + tags)
# Step 3 ref2va DiT (16G) → result3_video/audio_{idx}.pt (去噪後 latent)
# Step 4 video+audio VAE (1.9G)→ r2v_output_{idx}_l0.mp4 (像素還原)
#
# R2V 模式: Reference-to-Video - 使用視頻作為參考來源
# 官方 Ref2VA 限制: ≤9 個參考檔、≤3 段影片、≤3 段音訊、混合 ≤12 檔。
# 本模板支援圖片參考和視頻參考。
# ==============================================================================
import os
import torch
from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any
from PIL import Image
# --- 基礎路徑 ---
PROJECT_ROOT = "/home/mikehu/data/AI/minimax-h3"
MODELS_DIR = os.path.join(PROJECT_ROOT, "models/DiffSynth-Studio")
OUTPUT_DIR = os.path.join(PROJECT_ROOT, "outputs", "<PROJECT_NAME>") # ← 改成你的專案名
# --- VRAM 配置 (Step 4 的兩個小 VAE 用; 全駐 24GB GPU 完全沒壓力) ---
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",
}
# --- 影片基礎設定 ---
VIDEO_SETTINGS = {
"default_fps": 24,
"default_audio_sample_rate": 32000,
}
# --- 運行配置 ---
RUN_CONFIG = {
"num_iterations": 1,
"default_seed": 42,
"default_num_inference_steps": 25, # 832x480 建議 25 (skill 驗證值)
}
# ------------------------------------------------------------------------------
# 🎯 任務配置
# ------------------------------------------------------------------------------
@dataclass
class TaskConfig:
name: str
prompts: List[str] # 通常 1 條 (num_iterations>1 時輪替)
references: List[str] = field(default_factory=list) # 參考圖/視頻路徑 (1~9 個)
reference_types: List[str] = field(default_factory=list) # "image" 或 "video" 或 "video_audio"
enabled: bool = True
num_frames: int = 175 # R2V 測試: 175f @24fps (17*10+5=175, 符合官方要求)
width: int = 832 # 832x480 = 480p 安全解析度
height: int = 480
seed: Optional[int] = None # None → 用 RUN_CONFIG.default_seed
num_inference_steps: Optional[int] = None # None → 用 RUN_CONFIG
ref_image_short_edge: int = 2048 # 參考圖短邊縮放 (與官方預設一致)
# ------------------------------------------------------------------------------
# 📋 任務註冊表 (N 個視頻 = N 個 TaskConfig; 同一 step 內一次跑完)
# ------------------------------------------------------------------------------
TASK_REGISTRY = {
0: TaskConfig(
name="cat_r2v",
prompts=[
"[Style Lock: 超現實主義, 電影級, 8K UHD] [Era Anchor: 現代2026年] "
"[Identity Lock: face, hair, clothing, pose] "
"一隻可愛的貓咪在玩耍,動作自然流暢,背景清晰,光照柔和"
" [Ambience: 室內環境音] [SFX: 輕柔的貓咪聲音]"
],
references=[
"~/data/AI/minimax-h3/outputs/cat/cat.mp4", # ← R2V: 使用視頻作為參考
],
reference_types=[
"video", # 視頻參考
],
enabled=True,
num_frames=175, # R2V 測試: 175f @24fps (17*10+5=175, 符合官方要求)
width=832,
height=480,
seed=42,
num_inference_steps=25,
),
# 1: TaskConfig(name="video_1", prompts=["..."], references=["..."], ...),
# 2: TaskConfig(name="video_2", prompts=["..."], references=["..."], ...),
}
# ------------------------------------------------------------------------------
# 參考載入 (Step 1 呼叫)
# ------------------------------------------------------------------------------
def _resolve(path: str) -> str:
"""相對路徑 → 相對專案目錄 (OUTPUT_DIR) 解析。"""
if os.path.isabs(path):
return os.path.expanduser(path)
return os.path.join(OUTPUT_DIR, path)
def load_task_references(idx: int) -> List[Dict[str, Any]]:
"""回傳 task idx 的參考資料 (支援圖片和視頻)。
返回格式: List[Dict] 其中每個 Dict 可以是:
- {"type": "image", "image": PIL.Image} - 圖片參考
- {"type": "video", "video": VideoData} - 視頻參考 (無音頻)
- {"type": "video_audio", "video": VideoData, "audio": tensor, "sample_rate": int} - 視頻+音頻參考
"""
task = TASK_REGISTRY[idx]
refs = []
from diffsynth.utils.data.audio_video import read_video_audio
from diffsynth.utils.data import VideoData
for i, (path, ref_type) in enumerate(zip(task.references, task.reference_types)):
path = _resolve(path)
if not os.path.exists(path):
raise FileNotFoundError(f"Task {idx} 參考檔不存在: {path}")
if ref_type == "image":
refs.append({"type": "image", "image": Image.open(path).convert("RGB")})
if ref_type == "video":
# 讀取視頻作為參考 - 直接載入 PIL.Image.list
# 官方 Ref2VA 需要至少 22 幀
from diffsynth.utils.data import LowMemoryVideo
video_reader = LowMemoryVideo(path)
total_frames = len(video_reader)
# 只採樣前 175 幀 (使用者要求), 並均勻分佈取 22 幀
sample_range = min(total_frames, 175) # 只看前 175 幀
num_to_read = 22
# 均勻採樣: [0, (174//21), (348//21), ..., 174]
frame_indices = [i * (sample_range - 1) // (num_to_read - 1) if num_to_read > 1 else [0] for i in range(num_to_read)]
frames = []
for idx in frame_indices:
frame = video_reader[idx]
# ✅ 先旋轉 90 度 (豎屏 → 橫屏) 再 resize 到目標尺寸
frame = frame.rotate(90, expand=True) # 90° 旋轉
frame = frame.resize((task.width, task.height), Image.LANCZOS).convert("RGB")
frames.append(frame)
print(f">> [R2V] 影片參考: {len(frames)} 幀 (採樣自前 {sample_range}f, 均勻分佈, 旋轉+resize 到 {task.width}x{task.height})")
refs.append({"type": "video", "video": frames})
elif ref_type == "video_audio":
# 讀取視頻+音頻
video, audio, sample_rate = read_video_audio(
path,
height=task.height,
width=task.width,
num_frames=task.num_frames,
fps=VIDEO_SETTINGS["default_fps"],
audio_sample_rate=VIDEO_SETTINGS["default_audio_sample_rate"],
)
refs.append({
"type": "video_audio",
"video": video,
"audio": audio,
"sample_rate": sample_rate
})
else:
raise ValueError(f"Task {idx}: 未知的 reference_type: {ref_type}")
return refs
# ------------------------------------------------------------------------------
# --- 內部 API (禁止修改) ---
# ------------------------------------------------------------------------------
def get_enabled_tasks() -> List[int]:
return [idx for idx, task in TASK_REGISTRY.items() if task.enabled]
def get_task_params(task_idx: int, loop_idx: int = 0) -> Dict[str, Any]:
task = TASK_REGISTRY[task_idx]
prompt_idx = min(loop_idx, len(task.prompts) - 1)
return {
"name": task.name,
"prompt": task.prompts[prompt_idx],
"num_frames": task.num_frames,
"width": task.width,
"height": task.height,
"seed": task.seed or RUN_CONFIG["default_seed"],
"num_inference_steps": task.num_inference_steps or RUN_CONFIG["default_num_inference_steps"],
}