Files
minimax-h3/config_template_ref2va.py
T

173 lines
6.6 KiB
Python

#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
import gc
import torch
# ==============================================================================
# 🎞️ MiniMax-H3 REF2VA Project Configuration (4-step 單權重架構)
# ==============================================================================
# ✍️ Prompt 撰寫規範 (Full-Reference Mode):
# 1. 語言:描述部分必須使用 English;對白/歌詞保留原語言 (e.g. [對白: ...])。
# 2. 必備欄位 (Must be present in prompts string):
# - subject_definitions: 主體詳細定義 (外貌、服裝、特徵)。
# - summary: 畫面內容概要。
# - retention_analysis: 必須保持不變的視覺特徵分析 (Consistency Lock)。
# - detailed_description: 詳細的動作、構圖與視覺演進描述。
# - overall_soundscape: 整體環境音效與氛圍。
# - non_diegetic_music: 背景配樂描述。
# 3. 標記 Flag:使用 <Picture 1>, <Video 1>, <Audio 1> 等標記指引多模態時間軸。
# 4. 限制:參考圖 ≤9 張、影片/音訊參考各 ≤3 段。
# ==============================================================================
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 = {
"model_name": "minimax-h3-ref2va-nf4",
"num_iterations": 1,
"default_seed": 40,
"default_num_inference_steps": 12,
}
# ------------------------------------------------------------------------------
# 🎯 任務配置
# ------------------------------------------------------------------------------
@dataclass
class TaskConfig:
name: str
prompts: List[str] # 通常 1 條 (num_iterations>1 時輪替)
references: List[str] = field(default_factory=list) # 參考圖路徑 (1~9 張)
enabled: bool = True
num_frames: int = 175 # 建議 175 (24GB 安全上限, 1344x768)
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="video_0",
prompts=[
"""subject_definitions:
summary:
retention_analysis:
detailed_description:
overall_soundscape:
non_diegetic_music:
N/A"""
],
references=[
"reference_01.jpg", # ← 改成你的參考圖路徑 (相對本 config 或絕對路徑)
],
enabled=True,
num_frames=175,
width=832,
height=480,
seed=42,
),
# 1: TaskConfig(name="video_1", prompts=["..."], references=["..."], ...),
# 2: TaskConfig(name="video_2", prompts=["..."], references=["..."], ...),
}
# ------------------------------------------------------------------------------
# 參考載入 (Step 1 呼叫)
# ------------------------------------------------------------------------------
def _resolve(path: str) -> str:
"""相對路徑 → 相對專案目錄 (OUTPUT_DIR) 解析。"""
return path if os.path.isabs(path) else os.path.join(OUTPUT_DIR, path)
def load_task_references(idx: int) -> List[Image.Image]:
"""回傳 task idx 的參考圖 (PIL RGB)。Step 1 用它餵 ReferenceEncoder。
目前支援「圖片參考」。若要 video/audio 參考, 在 ref2va_step1.py 的
references 組裝處擴充 ({'type':'video','video':[PIL...]} 等)。
"""
task = TASK_REGISTRY[idx]
refs = []
for p in task.references:
p = _resolve(p)
if not os.path.exists(p):
raise FileNotFoundError(f"Task {idx} 參考圖不存在: {p}")
refs.append(Image.open(p).convert("RGB"))
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 if task.seed is not None else (RUN_CONFIG["default_seed"] + task_idx),
"num_inference_steps": task.num_inference_steps if task.num_inference_steps is not None else RUN_CONFIG["default_num_inference_steps"],
}
def validate_steps_consistency():
"""檢查所有啟用的任務,確保不會同時存在 <=23 和 >23 的 steps,以防止 Turbo LoRA 狀態污染。"""
enabled_ids = get_enabled_tasks()
steps_set = set()
for idx in enabled_ids:
task = TASK_REGISTRY[idx]
s = task.num_inference_steps if task.num_inference_steps is not None else RUN_CONFIG["default_num_inference_steps"]
steps_set.add(s)
if not steps_set:
return
has_turbo = any(s <= 23 for s in steps_set)
has_full = any(s > 23 for s in steps_set)
if has_turbo and has_full:
print("\n" + "!" * 60)
print(f">> [Error] 檢測到任務 steps 跨度過大: {sorted(list(steps_set))}")
print(">> Turbo LoRA (<=23) 與 Full-steps (>23) 不能在同一次運行中混合。")
print(">> 請將不同步數的任務分開在不同 Project 或分批執行。")
print("!" * 60 + "\n")
import sys
sys.exit(1)