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
+17
View File
@@ -0,0 +1,17 @@
# Exclude large directories
backups/
models/
outputs/
DiffSynth-Studio/
MiniMax-H3/
# Exclude cache and temporary files
__pycache__/
*.log
*.pt
*.safetensors
*.mkv
*.mp4
*.jpg
*.png
+113
View File
@@ -0,0 +1,113 @@
# ==============================================================================
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 Project Configuration Template (T2V/FL2VA)
# 🎞️ MiniMax-H3 Project Configuration Template (T2V/FL2VA)
# ==============================================================================
# 使用指南 (For Prompt Engineering AI):
# 1. 此文件為專案「基因錨點」,定義了所有生成參數。
# 2. 每個專案只需修改 TASK_REGISTRY 中的內容。
# 3. Prompt 撰寫規範 (Base Mode - T2VA/I2VA/FL2VA/L2VA):
# - 語言:描述必須使用 English;對白/歌詞保留原語言 (e.g. [對白: ...])。
# - 時長:建議 4-15 秒。
# - 必備欄位:
# * integrated_multimodal_description: 整合視覺與動作的詳細時間軸描述。
# * overall_soundscape: 整體環境音效、氛圍描述。
# * non_diegetic_music: 背景音樂、配樂描述。
# - 標記 Flag:使用 <Picture 1>, <Video 1>, <Audio 1> 等標記同步多模態內容。
# 4. 參數規範:
# - name: 任務名稱 (用於紀錄與辨識)
# - prompts: 必須是 [List[str]] 格式。即便只有一個 Prompt,也請放在方括號內。
# - enabled: True (執行) / False (跳過)
# - num_frames: 影片總幀數 (建議 124, 必須滿足 num_frames % 17 == 5)
# - width: 寬度 (Low: 832, Mid: 1024, High: 1344)
# - height: 高度 (Low: 480, Mid: 576, High: 768)
# - steps: 步數 (Turbo LoRA: Low=8, Mid=12, High=16)
# - first_frame: 首幀參考圖路徑 (Optional)
# - last_frame: 末幀參考圖路徑 (Optional)
# ==============================================================================
import os
import torch
from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any
# 基礎路徑 (禁止修改)
MODELS_DIR = "/home/mikehu/data/AI/minimax-h3/DiffSynth-Studio/models"
OUTPUT_DIR = "/home/mikehu/data/AI/minimax-h3/outputs/<project_name>"
# VRAM 設定 (確保 CPU Offload 以避免 OOM)
VRAM_CONFIG = {
"onload_device": "cpu",
"offload_device": "cpu",
"preparing_device": "cpu",
"vram_limit": 8.0
}
# 影片基礎設定
VIDEO_SETTINGS = {
"default_fps": 24,
"default_audio_sample_rate": 32000,
}
# 運行配置 (Required for fl2va_step2.py)
RUN_CONFIG = {
"model_name": "fl2va",
"device": "cuda",
"use_half": True,
"default_num_inference_steps": 8,
}
@dataclass
class TaskConfig:
name: str
prompts: List[str]
enabled: bool = True
num_frames: int = 124
width: int = 832
height: int = 480
steps: int = 8
first_frame: Optional[str] = None
last_frame: Optional[str] = None
# ------------------------------------------------------------------------------
# 🎯 任務註冊表 (在此定義您的劇本)
# 格式: { ID: TaskConfig(name=\"...\", prompts=[\"...\"], enabled=True, ...) }
# ------------------------------------------------------------------------------
TASK_REGISTRY = {
0: TaskConfig(
name="Example_Scene_01",
prompts=["A high-oblique wide angle shot of a beautiful East Asian woman..."],
enabled=True,
num_frames=124,
width=832,
height=480,
steps=8,
first_frame=None,
last_frame=None,
),
}
# ------------------------------------------------------------------------------
# --- 內部 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) -> 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,
"steps": task.steps,
}
+202
View File
@@ -0,0 +1,202 @@
#!/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"],
}
+172
View File
@@ -0,0 +1,172 @@
#!/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)
Executable
+96
View File
@@ -0,0 +1,96 @@
#!/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 計算
import os
import sys
import torch
# Add both the project root and current directory to path
sys.path.insert(0, "/home/mikehu/data/AI/minimax-h3")
sys.path.insert(0, os.getcwd()) # For config.py in current directory
try:
from config import MODELS_DIR, TASK_REGISTRY, get_enabled_tasks, VRAM_CONFIG, VIDEO_SETTINGS, RUN_CONFIG
except ModuleNotFoundError:
# Fallback: import from dancing_cat directory
import importlib.util
spec = importlib.util.spec_from_file_location("config", "/home/mikehu/data/AI/minimax-h3/outputs/dancing_cat/config.py")
config = importlib.util.module_from_spec(spec)
spec.loader.exec_module(config)
MODELS_DIR = config.MODELS_DIR
TASK_REGISTRY = config.TASK_REGISTRY
get_enabled_tasks = config.get_enabled_tasks
VRAM_CONFIG = config.VRAM_CONFIG
VIDEO_SETTINGS = config.VIDEO_SETTINGS
RUN_CONFIG = config.RUN_CONFIG
from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig
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_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
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("\n========== [FL2VA STAGE 1] Text Encoder 批處理 ==========")
pipe = MiniMaxH3Pipeline.from_pretrained(
torch_dtype=torch.bfloat16, device="cuda",
model_configs=[
ModelConfig(model_id="DiffSynth-Studio/MiniMax-H3-NF4", origin_file_pattern="minimax-h3-text-encoder-nf4.safetensors", path=os.path.join(MODELS_DIR, "text_encoders/minimax-h3-text-encoder-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=18.0,
)
enabled_ids = get_enabled_tasks()
num_iterations = RUN_CONFIG.get("num_iterations", 1)
for loop_idx in range(num_iterations):
for task_idx in enabled_ids:
task = TASK_REGISTRY[task_idx]
prompt = task.prompts[0] if task.prompts else ""
save_name = f"result1_te_{task_idx}_l{loop_idx}.pt"
print(f">> [Loop {loop_idx}][Task {task_idx}] Encoding: {prompt[:50]}...")
with torch.no_grad():
from diffsynth.models.minimax_h3_text_encoder import presentation_t2va
# 1. Get Token IDs and text_token_tags
input_ids, text_token_tags = presentation_t2va(pipe.tokenizer, prompt)
ids = input_ids.unsqueeze(0).to(pipe.device)
kwargs = {"input_ids": ids, "attention_mask": torch.ones_like(ids)}
# 2. Call Text Encoder to get features
hidden = pipe.text_encoder(**kwargs)
# Save both prompt_embeds and text_token_tags as a dict
torch.save({
"prompt_embeds": hidden.detach().cpu(),
"text_token_tags": text_token_tags.cpu()
}, save_name)
print(f">> [SUCCESS] Saved to {save_name}")
print("\n========== [FL2VA STAGE 1] 所有任務完成! ==========")
if __name__ == "__main__":
main()
+217
View File
@@ -0,0 +1,217 @@
#!/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 計算
import os
import sys
import torch
import gc
# Add both the project root and current directory to path
sys.path.insert(0, "/home/mikehu/data/AI/minimax-h3")
sys.path.insert(0, os.getcwd()) # For config.py in current directory
try:
from config import MODELS_DIR, TASK_REGISTRY, get_enabled_tasks, VRAM_CONFIG, VIDEO_SETTINGS, RUN_CONFIG
except ModuleNotFoundError:
# Fallback: import from dancing_cat directory
import importlib.util
spec = importlib.util.spec_from_file_location("config", "/home/mikehu/data/AI/minimax-h3/outputs/dancing_cat/config.py")
config = importlib.util.module_from_spec(spec)
spec.loader.exec_module(config)
MODELS_DIR = config.MODELS_DIR
TASK_REGISTRY = config.TASK_REGISTRY
get_enabled_tasks = config.get_enabled_tasks
VRAM_CONFIG = config.VRAM_CONFIG
VIDEO_SETTINGS = config.VIDEO_SETTINGS
RUN_CONFIG = config.RUN_CONFIG
from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig
from diffsynth.models.model_loader import ModelPool
from PIL import Image
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_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
def main():
print("\n========== [FL2VA STAGE 2] DiT + Turbo LoRA (VRAM optimized, separate VAEs) ==========")
# VRAM optimized config: layer-wise hotload, offload to CPU
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",
}
print(">> Loading DiT model with VRAM optimization...")
pipe = MiniMaxH3Pipeline.from_pretrained(
torch_dtype=torch.bfloat16, device="cuda",
model_configs=[
ModelConfig(
model_id="DiffSynth-Studio/MiniMax-H3-NF4",
origin_file_pattern="minimax-h3-fl2va-nf4.safetensors",
path=os.path.join(MODELS_DIR, "diffusion_models/minimax-h3-fl2va-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=18.0,
)
print(">> DiT loaded!")
# Load Turbo LoRA
lora_path = os.path.join(MODELS_DIR, "loras/minimax_h3_turbo_v4_step600_ema.safetensors")
if os.path.exists(lora_path):
print(f">> [LoRA] Loading Turbo LoRA: {lora_path}")
pipe.load_lora(pipe.dit, lora_config=lora_path, alpha=1.0, verbose=1)
print(">> [LoRA] Turbo LoRA loaded!")
else:
print(f">> [WARN] Turbo LoRA not found: {lora_path}")
# Load VAEs separately using ModelPool (to use VRAM_CONFIG)
print(">> Loading Video VAE...")
vae_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,
),
]
vae_pool = pipe.download_and_load_models(vae_configs, vram_limit=18.0)
pipe.video_vae = vae_pool.fetch_model("minimax_h3_video_vae")
pipe.audio_vae = vae_pool.fetch_model("minimax_h3_audio_vae")
print(">> Video VAE & Audio VAE loaded!")
# Wrap VAE decode methods to save latents
enabled_ids = get_enabled_tasks()
if enabled_ids:
idx = enabled_ids[0]
original_decode_video = pipe.video_vae.decode_video
original_decode_audio = pipe.audio_vae.decode_audio
def save_and_decode_video(*args, **kwargs):
torch.save({"args": move_to_cpu(args), "kwargs": move_to_cpu(kwargs)}, f"result2_video_{idx}_l0.pt")
return original_decode_video(*args, **kwargs)
def save_and_decode_audio(*args, **kwargs):
torch.save({"args": move_to_cpu(args), "kwargs": move_to_cpu(kwargs)}, f"result2_audio_{idx}_l0.pt")
return original_decode_audio(*args, **kwargs)
pipe.video_vae.decode_video = save_and_decode_video
pipe.audio_vae.decode_audio = save_and_decode_audio
torch.cuda.empty_cache()
gc.collect()
print(">> All models loaded and ready!")
last_completed_idx = -1
if os.path.exists(".restart"):
try:
with open(".restart", "r") as f:
last_completed_idx = int(f.read().strip())
print(f"\n[RESUME] Continuing from task ID > {last_completed_idx}")
except Exception as e:
print(f"\n[WARN] Failed to read .restart: {e}, starting from beginning.")
num_iterations = RUN_CONFIG.get("num_iterations", 1)
for loop_idx in range(num_iterations):
for idx in enabled_ids:
if idx <= last_completed_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 SIGNAL] Checkpoint saved to .restart at progress {last_completed_idx}")
return
task = TASK_REGISTRY[idx]
first_frame_path = getattr(task, "first_frame", None)
last_frame_path = getattr(task, "last_frame", None)
print(f"\n>> [Loop {loop_idx}][Task {idx}] Starting Fl2VA generation...")
if first_frame_path:
print(f" First Frame: {first_frame_path}")
if not os.path.exists(first_frame_path):
print(f" ERROR: First frame file does not exist!")
sys.exit(1)
try:
test_img = Image.open(first_frame_path).convert("RGB")
print(f" First Frame loaded: size={test_img.size}")
except Exception as e:
print(f" ERROR: Failed to load first frame: {e}")
sys.exit(1)
if last_frame_path: print(f" Last Frame: {last_frame_path}")
# Load pre-computed text embeddings
data = torch.load(f"result1_te_{idx}_l0.pt", map_location="cpu")
text_embedding = data["prompt_embeds"].to("cuda").to(torch.bfloat16)
print(f" Text embedding shape: {text_embedding.shape}")
keyframes = []
keyframe_indices = []
if first_frame_path:
keyframes.append(Image.open(first_frame_path).convert("RGB"))
keyframe_indices.append(0)
if last_frame_path:
keyframes.append(Image.open(last_frame_path).convert("RGB"))
keyframe_indices.append(-1)
# Use task.steps (from config: 8 for Turbo LoRA)
steps = task.steps if hasattr(task, 'steps') else RUN_CONFIG.get("default_num_inference_steps", 8)
print(f" Steps: {steps}")
pipe(
prompt=None,
keyframes=keyframes,
keyframe_indices=keyframe_indices,
height=task.height,
width=task.width,
num_frames=task.num_frames,
num_inference_steps=steps,
seed=42,
text_embedding=text_embedding
)
print(f">> [SUCCESS] Saved result2_video_{idx}_l0.pt and result2_audio_{idx}_l0.pt")
last_completed_idx = idx
torch.cuda.empty_cache()
gc.collect()
print("\n========== [FL2VA STAGE 2] All tasks completed! ==========")
if __name__ == "__main__":
main()
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()
+89
View File
@@ -0,0 +1,89 @@
#!/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
from config import PROJECT_ROOT, MODELS_DIR, FL2VA_TASKS, VRAM_CONFIG, VIDEO_SETTINGS, OUTPUT_DIR
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("\n========== [FL2VA STAGE 3 PNG] 像素還原 (無損輸出) ==========")
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,
)
for idx, task in enumerate(FL2VA_TASKS):
print(f"\n>> [Task {idx}] 正在解碼 VAE -> PNG...")
video_data = move_to_cuda(torch.load(f"result2_video_{idx}.pt"))
audio_data = move_to_cuda(torch.load(f"result2_audio_{idx}.pt"))
video_vae = pipe.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)
frames_dir = os.path.join(OUTPUT_DIR, f"fl2va_pngs_{idx}")
os.makedirs(frames_dir, exist_ok=True)
for f_idx, frame in enumerate(video):
frame.save(os.path.join(frames_dir, f"frame_{f_idx:04d}.png"))
audio_vae = pipe.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
raw_mp4 = os.path.join(OUTPUT_DIR, f"fl2va_raw_audio_{idx}.mp4")
write_video_audio(video=video, audio=audio, output_path=raw_mp4, fps=VIDEO_SETTINGS["fps"], audio_sample_rate=VIDEO_SETTINGS["audio_sample_rate"])
print(f">> [SUCCESS] Task {idx} PNGs 儲存至 {frames_dir}")
print(f">> [SUCCESS] 草稿音軌儲存至 {raw_mp4}")
print(f"\n--- [ffmpeg 合併指令 for Task {idx}] ---")
print(f"ffmpeg -r {VIDEO_SETTINGS['fps']} -i {frames_dir}/frame_%04d.png -i {raw_mp4} -map 0:v -map 1:a -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest {OUTPUT_DIR}/fl2va_final_{idx}.mp4")
print("--------------------------------------------")
torch.cuda.empty_cache()
print("\n========== [FL2VA STAGE 3 PNG] 所有任務完成! ==========")
if __name__ == "__main__":
main()
Executable
+372
View File
@@ -0,0 +1,372 @@
#!/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 1] Video VAE 編碼參考檔 → ref_blocks + anchors
================================================================
R2V 模式: Reference-to-Video - 使用影片/圖片作為參考來源,支援混合影像+影片
不修改框架源碼的解決方案:直接呼叫 _build_block 然後手動合併 anchors
每個任務一次跑完:
1. 用 config.load_task_references(idx) 載入參考檔
2. 手動呼叫 _build_block() 為每個 reference 編碼
3. 手動合併 visual_anchor 和 audio_anchor
4. 落盤 result1_ref_{idx}.pt
說明:和 ref2va_step1.py 一樣,但 for R2V
單權重策略: Video VAE (NF4 量化, ~1.6GB VRAM)
下一階段: r2v_step2.py (Text Encoder) → r2v_step3.py (DiT) → r2v_step4.py (VAE Decoder)
"""
import os
import sys
import gc
import importlib.util
import torch
from PIL import Image
# ==============================================================================
# 動態加載專案配置
# ==============================================================================
config_path = os.path.abspath("config.py")
if not os.path.exists(config_path):
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()}")
print(">> 請透過 run_r2v_h3.sh <project> 執行 (會 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 sorted(TASK_REGISTRY.keys())
def load_task_references(task):
return config.load_task_references(task)
from diffsynth.pipelines.minimax_h3_audio_video import (
MiniMaxH3Pipeline, ModelConfig, MiniMaxH3Unit_ReferenceEncoder,
)
from diffsynth.models.minimax_h3_dit import patchify_video, unpack_audio
os.environ["DIFFSYNTH_SKIP_DOWNLOAD"] = "True"
os.environ["HIP_VISIBLE_DEVICES"] = "0"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ["HSA_OVERRIDE_GFX_VERSION"] = "11.0.0"
MAX_IMAGE_REFS = 9
def manual_build_reference_blocks(pipe, ref_unit, references, num_frames, seed):
"""
Step1 的手動版處理:改用 reference 的 frames 或 image 的好的 shape
直接用 _encode_video_ref 或 _encode_image_ref 而不需要 video_latents
"""
device = pipe.device
ref_image_short_edge = 768
ref_video_short_edge = 768
ref_video_max_pixels = 768*1344
# 逐個處理每個 reference,直接呼叫 _encode_*_ref
ref_blocks_out = []
for ref in references:
kind = ref["type"]
if kind == "image":
img = ref["image"]
# 直接呼叫 _encode_image_ref
rows, lh, lw, prepared = ref_unit._encode_image_ref(
pipe, img, ref_image_short_edge
)
block = {
"kind": kind,
"visual_clean": rows,
"latent_t": 1,
"latent_h": lh,
"latent_w": lw,
"prepared_image": prepared,
"ref_audio_t": 0
}
ref_blocks_out.append(block)
elif kind in ("video", "video_audio"):
frames = ref["video"]
# 直接呼叫 _encode_video_ref
rows, lt, lh, lw, prepared = ref_unit._encode_video_ref(
pipe, frames, num_frames, ref_video_short_edge, ref_video_max_pixels
)
block = {
"kind": kind,
"visual_clean": rows,
"latent_t": lt,
"latent_h": lh,
"latent_w": lw,
"prepared_frames": prepared,
"ref_audio_t": 0
}
if kind == "video_audio":
# 如果有 audio,這裡需要補上,但我們 config 沒提供 audio,所以省略
pass
ref_blocks_out.append(block)
# 手動合併 visual_anchor
# 參考: process() 中的邏輯,但 Step1 不需要 video_latents
# 我們直接用 block 的 latent 信息生成 noise
visual_blocks = [b for b in ref_blocks_out if "visual_clean" in b]
visual_parts = []
for i, block in enumerate(visual_blocks):
clean = block.pop("visual_clean").to(device=device, dtype=pipe.torch_dtype)
if pipe.imgvid_cond_noise_aug == 1.0:
anchor = clean
else:
# Step1 的特殊處理:沒有 video_latents,用 num_frames + i (index)
# 簡化版:用 block 自身的 latent_t
latent_t = int(block["latent_t"])
latent_h = int(block["latent_h"])
latent_w = int(block["latent_w"])
# 生成 noise
noise_shape = (1, 24, latent_t, latent_h, latent_w)
noise = pipe.generate_noise(
noise_shape,
seed=seed + i,
rand_device="cpu",
rand_torch_dtype=pipe.torch_dtype,
device="cpu",
torch_dtype=pipe.torch_dtype
)
noise_rows = patchify_video(noise).to(device=device, dtype=pipe.torch_dtype)
ts = torch.tensor(pipe.imgvid_cond_noise_aug, dtype=pipe.torch_dtype, device=device)
anchor = ts * clean + (1.0 - ts) * noise_rows
visual_parts.append(anchor)
# 手動合併 audio_anchor (我們沒有 audio,所以可以忽略)
audio_parts = []
for block in ref_blocks_out:
# 新增 audio support if exists
if "audio_clean" not in block or int(block.get("ref_audio_t", 0)) <= 0:
continue
clean = block.pop("audio_clean").to(device=device, dtype=pipe.torch_dtype)
if pipe.audio_cond_noise_aug == 1.0:
anchor = clean
else:
noise = pipe.generate_noise(
clean.shape,
seed=seed + len(visual_blocks),
rand_device="cpu",
rand_torch_dtype=pipe.torch_dtype,
device=device,
torch_dtype=pipe.torch_dtype
)
ts = torch.tensor(pipe.audio_cond_noise_aug, dtype=pipe.torch_dtype, device=device)
anchor = ts * clean + (1.0 - ts) * noise
audio_parts.append(anchor)
return {
"ref_blocks": ref_blocks_out,
"ref_visual_anchor": torch.cat(visual_parts, dim=0) if visual_parts else None,
"ref_audio_anchor": torch.cat(audio_parts, dim=0) if audio_parts else None,
}
def main():
enabled_ids = get_enabled_tasks()
if not enabled_ids:
print(">> [Error] 沒有啟用的任務")
sys.exit(1)
print("\n========== [R2V STAGE 1] Video VAE 編碼參考檔 (混合影像+影片) ==========")
print(f">> [Config] 專案配置: {config_path}")
#--- 前置檢查 ---
for idx in enabled_ids:
task = TASK_REGISTRY[idx]
n = len(task.references or [])
if n == 0:
print(f">> [Error] Task {idx} 沒有 references。R2V 至少需要 1 個參考檔。")
sys.exit(1)
if n > MAX_IMAGE_REFS:
print(f">> [Error] Task {idx} 有 {n} 個參考檔, 超過官方上限 {MAX_IMAGE_REFS} 個。")
sys.exit(1)
# Clean GPU cache
torch.cuda.empty_cache()
gc.collect()
# 單一權重: video VAE 全駐 GPU
vae_cp = os.path.join(MODELS_DIR, "DiffSynth-Studio/vae/video_vae_nf4.safetensors")
if not os.path.exists(vae_cp):
vae_cp = os.path.join(MODELS_DIR, "vae/video_vae_nf4.safetensors")
print(f">> [VAE] 使用模型: {vae_cp}")
if not os.path.exists(vae_cp):
print(f">> [Error] VAE 模型不存在: {vae_cp}")
sys.exit(1)
pipe = MiniMaxH3Pipeline.from_pretrained(
torch_dtype=torch.bfloat16,
device="cuda",
model_configs=[
ModelConfig(
path=vae_cp,
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",
),
],
processor_config=None,
vram_limit=18.0,
)
# 使用 pipeline 內建的 ReferenceEncoder
ref_unit = MiniMaxH3Unit_ReferenceEncoder()
seed = RUN_CONFIG.default_seed if hasattr(RUN_CONFIG, "default_seed") else 42
# 斷點續傳
last_completed_idx = -1
output_dir = os.path.dirname(config_path) if config_path != "config.py" else os.getcwd()
if os.path.exists(".restart"):
try:
with open(".restart") as f:
last_completed_idx = int(f.read().strip())
print(f"\n[RESUME] 偵測到續傳, 從任務 ID > {last_completed_idx} 開始。")
except Exception:
pass
done = 0
for idx in enabled_ids:
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。進度已存至 .restart。")
return
task = TASK_REGISTRY[idx]
nf = task.frame_end - task.frame_start + 1
# 載入參考檔
refs = load_task_references(task)
num_refs = len(refs)
if num_refs == 0:
print(f">> [Error] Task {idx} 沒有參考檔")
continue
# 顯示參考類型
detected_types = []
for ref in refs:
if "image" in ref:
detected_types.append("image")
elif "video" in ref:
detected_types.append("video")
print(f"\n>> [Task {idx}] 編碼 {num_refs} 個參考檔 (目標 {task.width}x{task.height}, {nf}f)...")
print(f" 參考類型: {detected_types}")
try:
# 🎯 使用手動版,直接呼叫 _encode_*_ref
ref_output = manual_build_reference_blocks(
pipe=pipe,
ref_unit=ref_unit,
references=refs,
num_frames=nf,
seed=seed + idx, # 每個 task 不同 seed
)
save_name = f"result1_ref_{idx}.pt"
save_path = os.path.join(output_dir, save_name)
# 移除不需要落盤的大型 tensors
if "ref_visual_anchor" in ref_output and ref_output["ref_visual_anchor"] is not None:
ref_output["ref_visual_anchor"] = move_to_cpu(ref_output["ref_visual_anchor"])
if "ref_audio_anchor" in ref_output and ref_output["ref_audio_anchor"] is not None:
ref_output["ref_audio_anchor"] = move_to_cpu(ref_output["ref_audio_anchor"])
# 保存
torch.save({
"ref_blocks": ref_output["ref_blocks"],
"ref_visual_anchor": ref_output.get("ref_visual_anchor"),
"ref_audio_anchor": ref_output.get("ref_audio_anchor"),
"task_config": {
"width": task.width,
"height": task.height,
"fps": task.fps,
"num_frames": nf,
"frame_start": task.frame_start,
"frame_end": task.frame_end,
},
"seed": seed + idx,
}, save_path)
# 顯示結果
block_types = [b['kind'] for b in ref_output['ref_blocks']]
print(f">> [成功] Task {idx} ({task.name}) 已儲存至 {save_path}")
print(f" ref_blocks types: {block_types}")
if ref_output.get("ref_visual_anchor") is not None:
print(f" ref_visual_anchor shape: {ref_output['ref_visual_anchor'].shape}")
last_completed_idx = idx
done += 1
except Exception as e:
print(f">> [ERROR] Task {idx} 失敗: {e}")
import traceback
traceback.print_exc()
# 嘗試清理 GPU
try:
torch.cuda.empty_cache()
gc.collect()
except:
pass
continue
# Clean GPU cache between tasks
torch.cuda.empty_cache()
gc.collect()
print("\n" + "="*60)
print("[R2V STAGE 1] 完成!可以執行 Step2 (text encoder)")
print("="*60)
def move_to_cpu(obj):
"""递歸地將 tensor 移到 CPU"""
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
if __name__ == "__main__":
main()
Executable
+212
View File
@@ -0,0 +1,212 @@
#!/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 2] Text Encoder 編碼 prompt (R2V 主路徑, 全視頻 batch)
================================================================
唯一大權重: minimax-h3-text-encoder-nf4.safetensors (~15GB NF4)
不載入 DiT / video VAE / audio VAE。
每個任務 (全部 N 個視頻在這次載入中一次跑完, text encoder 只載入一次):
1. 讀 step1 落盤的 result1_ref_{idx}.pt → ref_blocks (含 prepared_image)
2. 直接呼叫 pipeline 內建的 MiniMaxH3Unit_PromptEmbedder.process
(R2V 主路徑: preprocess_ref_blocks → image_token_counts → presentation_ref2va)
→ 回傳 {"prompt_embeds": hidden [seq, hidden], "text_token_tags": [seq] (0/1 混合)}
3. 落盤 result2_text_{idx}.pt: {hidden, text_token_tags}
單權重策略: 任一時刻 DRAM/VRAM 只有 text encoder 一個權重。
下一階段: r2v_step3.py (DiT 去噪)
"""
import os
import sys
import gc
import importlib.util
import torch
# 設定 ROCm 環境變數以避免 kernel crash
os.environ["AMD_SERIALIZE_KERNEL"] = "3"
os.environ["HSA_OVERRIDE_GFX_VERSION"] = "11.0.0"
# ==============================================================================
# 動態加載專案配置
# ==============================================================================
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()}")
print(">> 請透過 run_r2v_h3.sh <project> 執行 (會 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()
import torch
from diffsynth.pipelines.minimax_h3_audio_video import (
MiniMaxH3Pipeline, ModelConfig, MiniMaxH3Unit_PromptEmbedder,
)
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_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
def main():
print("\n========== [R2V STAGE 2] Text Encoder 編碼 prompt (單權重版) ==========")
print(f">> [Config] 專案配置: {config_path}")
enabled_ids = get_enabled_tasks()
# 上游檢查
for idx in enabled_ids:
if not os.path.exists(f"result1_ref_{idx}.pt"):
print(f">> [Error] Task {idx} 缺少 result1_ref_{idx}.pt, 請先執行 step1。")
sys.exit(1)
torch.cuda.empty_cache()
gc.collect()
# 單一權重: text encoder (15GB NF4)
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="minimax-h3-text-encoder-nf4.safetensors",
path=os.path.join(MODELS_DIR, "DiffSynth-Studio/text_encoders/minimax-h3-text-encoder-nf4.safetensors"),
**vram_config,
),
],
# processor 是 tokenizer/preprocessor 檔案 (幾 MB), 非模型權重。
# R2V 主路徑需要它算 image_token_counts / presentation_ref2va。
processor_config=ModelConfig(
model_id="MiniMax/MiniMax-H3",
origin_file_pattern="FL2VA/processor/",
path=os.path.join(MODELS_DIR, "DiffSynth-Studio/text_encoders/config"),
),
vram_limit=18.0,
)
# pipeline 內建的 PromptEmbedder (R2V 主路徑邏輯與官方完全一致)
text_unit = MiniMaxH3Unit_PromptEmbedder()
# --- 斷點續傳 ---
last_completed_idx = -1
if os.path.exists(".restart"):
try:
with open(".restart") as f:
last_completed_idx = int(f.read().strip())
print(f"\n[RESUME] 偵測到續傳標記,將從任務 ID > {last_completed_idx} 開始。")
except Exception:
pass
done = 0
for idx in enabled_ids:
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
save_name = f"result2_text_{idx}.pt"
if os.path.exists(save_name):
print(f">> [SKIP] Task {idx} 已有 {save_name}。")
last_completed_idx = idx
continue
task = TASK_REGISTRY[idx]
prompt = task.prompts[0] if task.prompts else ""
if not prompt:
print(f">> [Error] Task {idx} prompt 為空。")
sys.exit(1)
data = torch.load(f"result1_ref_{idx}.pt", weights_only=False)
ref_blocks = data["ref_blocks"]
print(f"\n>> [Task {idx}] 編碼 prompt ({len(ref_blocks)} 個 ref blocks)...")
print(f" Prompt: {prompt[:60]}...")
with torch.no_grad():
out = text_unit.process(
pipe,
prompt=prompt,
keyframes=None,
ref_blocks=ref_blocks,
height=task.height,
width=task.width,
text_embedding=None,
)
hidden = out["prompt_embeds"].detach()
tags = out["text_token_tags"].detach()
n_text = int((tags == 1).sum().item())
n_ref = int((tags == 0).sum().item())
torch.save(move_to_cpu({
"hidden": hidden,
"text_token_tags": tags,
"seq_len": int(hidden.shape[0]),
"n_text_tokens": n_text,
"n_ref_tokens": n_ref,
}), save_name)
print(f">> [SUCCESS] Task {idx} 已儲存 {save_name} "
f"(hidden {tuple(hidden.shape)}, seq {hidden.shape[0]}, "
f"text tokens {n_text}, ref tokens {n_ref})")
del data, ref_blocks, out, hidden, tags
gc.collect()
torch.cuda.empty_cache()
last_completed_idx = idx
with open(".restart", "w") as f:
f.write(str(last_completed_idx))
done += 1
print(f"\n========== [R2V STAGE 2] 完成 {done}/{len(enabled_ids)} 個任務 ==========")
print(">> 下一步: r2v_step3.py (DiT 去噪)")
if __name__ == "__main__":
main()
Executable
+338
View File
@@ -0,0 +1,338 @@
#!/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 計算
"""
[R2V STAGE 3] DiT 去噪生成 (R2V 權重 + 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)。
pipe.text_encoder = ReplayTextEncoder: 回放 step2 落盤的 hidden,
並對照即時 input_ids 長度 (不一致 → 明確錯誤, 防靜默错位)。
3. R2V 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 模型空間)。
"""
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()}")
print(">> 請透過 run_r2v_h3.sh <project> 執行 (會 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()
import torch
from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig
from diffsynth.diffusion.base_pipeline import PipelineUnit
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_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 權重)
# PromptEmbedder 主路徑重跑 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,
# 回【精確形狀】的 dummy (讓 vae_output_to_video / audio check 正常通過)。
# ==============================================================================
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}.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}.pt "
f"(latent {tuple(latents.shape)} → pixel dummy (1,3,{T_dec},{H2*16},{W2*16}))")
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}.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}.pt "
f"(latent {tuple(latents.shape)} → waveform dummy (2,{Ta*800}))")
return torch.zeros((2, Ta * 800))
def decode(self, *args, **kwargs):
return self.decode_audio(*args, **kwargs)
def main():
print("\n========== [R2V STAGE 3] DiT 去噪生成 (ref2va 權重, 單權重版) ==========")
print(f">> [Config] 專案配置: {config_path}")
enabled_ids = get_enabled_tasks()
# 上游檢查
for idx in enabled_ids:
if not os.path.exists(f"result1_ref_{idx}.pt"):
print(f">> [Error] Task {idx} 缺少 result1_ref_{idx}.pt, 請先執行 step1。")
sys.exit(1)
if not os.path.exists(f"result2_text_{idx}.pt"):
print(f">> [Error] Task {idx} 缺少 result2_text_{idx}.pt, 請先執行 step2。")
sys.exit(1)
torch.cuda.empty_cache()
gc.collect()
# DiT 使用 layer-wise hotload 配置
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 = 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="minimax-h3-ref2va-nf4.safetensors",
path=os.path.join(MODELS_DIR, "DiffSynth-Studio/diffusion_models/minimax-h3-ref2va-nf4.safetensors"),
**vram_config,
),
],
# processor 仍需載入: PromptEmbedder 主路徑要用 tokenizer/processor 重跑
# presentation_ref2va (只算 token 序列與 vision token 數, 不載入 15GB 權重)
processor_config=ModelConfig(
model_id="MiniMax/MiniMax-H3",
origin_file_pattern="FL2VA/processor/",
path=os.path.join(MODELS_DIR, "DiffSynth-Studio/text_encoders/config"),
),
vram_limit=24.0,
)
# 加載 Turbo LoRA 到 DiT 模型中
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] 正在加載 Turbo LoRA: {lora_path}")
pipe.load_lora(pipe.dit, lora_config=lora_path, alpha=1.0, verbose=1)
print(">> [LoRA] Turbo LoRA 加載成功!")
else:
print(f">> [Warning] Turbo LoRA 不存在: {lora_path}")
# in-place 替換 ReferenceEncoder 單元
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
assert ref_unit is not None, "找不到 MiniMaxH3Unit_ReferenceEncoder"
# --- 斷點續傳 ---
last_completed_idx = -1
if os.path.exists(".restart"):
try:
with open(".restart") as f:
last_completed_idx = int(f.read().strip())
print(f"\n[RESUME] 偵測到續傳標記,將從任務 ID > {last_completed_idx} 開始。")
except Exception:
pass
seed = RUN_CONFIG.default_seed if hasattr(RUN_CONFIG, "default_seed") else 42
done = 0
for idx in enabled_ids:
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 ""
if not prompt:
print(f">> [Error] Task {idx} prompt 為空。")
sys.exit(1)
# 計算 nf 和 steps
nf = task.frame_end - task.frame_start + 1
if nf % 17 != 5:
nf = (nf - 5 + 16) // 17 * 17 + 5
# 使用 task.num_inference_steps (config.py 中已設為 8)
steps = task.num_inference_steps if hasattr(task, "num_inference_steps") else 8
print(f"\n>> [Task {idx}] 開始 R2V 去噪 ({task.width}x{task.height}, "
f"{nf}f, {steps} steps, seed {seed})...")
print(f" Prompt: {prompt[:60]}...")
# 因為我們使用手動 _build_block,不需要 video_latent_shape 交叉驗證
ref_data = torch.load(f"result1_ref_{idx}.pt", weights_only=False)
# 綁定本 task 的 proxy / stub
ref_unit.data = ref_data
pipe.text_encoder = ReplayTextEncoder(f"result2_text_{idx}.pt")
pipe.video_vae = SaveLatentVideoVAE(idx)
pipe.audio_vae = SaveLatentAudioVAE(idx)
pipe(
prompt=prompt,
height=task.height,
width=task.width,
num_frames=nf,
num_inference_steps=steps,
seed=seed,
)
print(f">> [SUCCESS] Task {idx} 已儲存
# --- 迴圈任務間徹底清空 6.5GB 動態區 ---
ref_unit.data = None
pipe.text_encoder = None
pipe.video_vae = None
pipe.audio_vae = None
del ref_data
gc.collect()
torch.cuda.empty_cache()
torch.cuda.ipc_collect() result3_video_{idx}.pt 與 result3_audio_{idx}.pt")
ref_unit.data = None
pipe.text_encoder = None
pipe.video_vae = None
pipe.audio_vae = None
del ref_data
gc.collect()
torch.cuda.empty_cache()
last_completed_idx = idx
with open(".restart", "w") as f:
f.write(str(last_completed_idx))
done += 1
print(f"\n========== [R2V STAGE 3] 完成 {done}/{len(enabled_ids)} 個任務 ==========")
print(">> 下一步: r2v_step4.py (VAE 解碼)")
if __name__ == "__main__":
main()
Executable
+199
View File
@@ -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()
+233
View File
@@ -0,0 +1,233 @@
#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
"""
[REF2VA STEP1 共識檢查] 同源參考圖的 result1_ref_*.pt 多數決驗證
================================================================
同一張參考圖 (相同 image bytes + 相同 metadata) 的 result1_ref_{idx}.pt
理論上應一致。step1 已做 VAE 去重 (同圖 + 同參數只編一次, 冷啟動首次
encode 燃燒), 所以同源檔案應 bit 相同; 但歷史檔案 / 不同版本 step1
產出的檔案仍可能離群, 故仍需本檢查:
三階段判定 (使用者指定):
1) 階段 1 binary cmp: 對同組 (相同參考圖 + 相同參數) 檔案做內容摘要分組
(zip 各 entry payload md5 — torch.save 的 .data/serialization_id 是
每次存檔的隨機 UUID, 整檔 md5 會誤判), 有明確多數 (>50%) →
少數派視為異常, 刪除。
2) 階段 2 內容檢查: 無明確多數時 (內容摘要全不同 / 平分), 載入 tensor:
硬門檻 = NaN/Inf / shape 不一致; 軟門檻 = 對同組 anchor 中位數的
最大偏差 > max(8*baseline, 3.0) → 離群, 刪除。
3) 階段 3: 離群者超過多數派 (無法決定誰是好的) → 全部刪除 + exit 11。
重跑 step1 後再檢查, 仍失敗 → 準備重跑整批。
刪除異常檔後, 重跑 ref2va_step1.py 會因既有檔跳過、只補跑被刪的 task。
用法:
python ref2va_check_refs.py # 檢查 (可刪除異常檔), 見 exit code
python ref2va_check_refs.py --dry-run # 只報告不刪除
Exit codes:
0 = 全部健康 (或本次刪除後已無異常, 應重跑 step1 再驗證)
10 = 發現並刪除異常檔 → 請重跑 ref2va_step1.py 再檢查
11 = 無多數且離群 > 多數派 (無法決定) → 已刪除該組全部檔案, 需重跑
12 = 無法判定 / 組內檔案不足 → 需重跑
"""
import hashlib
import importlib.util
import os
import sys
import torch
# ── 與 ref2va_step1.py 相同的 snap 邏輯 (noise full_t 依此決定, 需一致) ──
TIME_DIV, TIME_REM = 17, 5
REF_VIDEO_SHORT_EDGE = 768
REF_VIDEO_MAX_PIXELS = 768 * 1344
def snap_num_frames(nf):
if nf % TIME_DIV == TIME_REM:
return nf
return (nf - TIME_REM + TIME_DIV - 1) // TIME_DIV * TIME_DIV + TIME_REM
def load_config():
config_path = os.path.join(os.getcwd(), "config.py")
if not os.path.exists(config_path):
print(f">> [Error] 找不到 {config_path}, 請 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)
return config
def img_bytes(block):
img = block.get("prepared_image")
try:
return img.tobytes()
except Exception:
return str(img).encode("utf-8")
def meta_repr(block):
return repr(sorted((k, v) for k, v in block.items() if k != "prepared_image"))
def anchor_stats(a):
f = a.float()
return (
int(torch.isnan(f).sum()),
int(torch.isinf(f).sum()),
float(f.std().item()),
float(f.abs().max().item()),
)
def group_key(task, data):
"""同一參考圖 + 同一編碼參數 → 同組 (理論上應一致)。"""
imgs = hashlib.md5()
meta = hashlib.md5()
for b in data.get("ref_blocks", []):
imgs.update(img_bytes(b))
meta.update(meta_repr(b).encode("utf-8"))
# 1) 先算 nf → 2) 再算 full_t (與 step1 process 內 noise shape 一致):
# full_t = video_latents.shape[2] + 影像 block 數 = lt + len(blocks)。
# (nf 與 lt 一一同價, 一併入 key 只是讓除錯時直觀)
nf = snap_num_frames(task.num_frames)
lt = data.get("video_latent_shape", [0, 0, 0, 0, 0])[2]
full_t = lt + len(data.get("ref_blocks", []))
return (
imgs.hexdigest(),
meta.hexdigest(),
task.width,
task.height,
nf,
full_t,
getattr(task, "ref_image_short_edge", 2048),
REF_VIDEO_SHORT_EDGE,
REF_VIDEO_MAX_PIXELS,
)
def content_digest(f):
"""內容摘要 (決定性, 與檔名/序列化 UUID 無關):
zip: 每個 entry 的 name + payload md5; 舊格式: 整檔 md5。
torch.save 的 .data/serialization_id 是每次存檔的隨機 UUID,
直接 md5 整檔會因此誤判 → 必須比 payload 內容。"""
import zipfile
h = hashlib.md5()
try:
with zipfile.ZipFile(f) as z:
for i in sorted(z.infolist(), key=lambda x: x.filename):
h.update(i.filename.encode("utf-8"))
h.update(hashlib.md5(z.read(i.filename)).hexdigest().encode("ascii"))
return "zip:" + h.hexdigest()
except zipfile.BadZipFile:
return "raw:" + hashlib.md5(open(f, "rb").read()).hexdigest()
def check_group(gidx):
"""回傳 (outlier_ids, reason)。無異常 → ([], '')。"""
files = {i: f"result1_ref_{i}.pt" for i in gidx}
hashes = {i: content_digest(files[i]) for i in gidx}
# ── 階段 1: binary cmp (內容摘要分組: zip payload md5, 免 UUID 誤判) ──
groups = {}
for i, h in hashes.items():
groups.setdefault(h, []).append(i)
sizes = sorted(groups.values(), key=len, reverse=True)
n = len(gidx)
if len(sizes[0]) * 2 > n and len(sizes) > 1:
majority = set(sizes[0])
return (set(gidx) - majority, "binary (內容摘要) 少數派")
# ── 階段 2: 內容檢查 (載入 tensor) ──
data = {i: torch.load(files[i], map_location="cpu", weights_only=False) for i in gidx}
# 2a. 硬門檻: shape
shapes = {i: tuple(data[i]["ref_visual_anchor"].shape) for i in gidx}
if len(set(shapes.values())) > 1:
bad = [i for i in gidx if shapes[i] != shapes[max(gidx)]]
return (bad, f"anchor shape 不一致: {shapes}")
# 2b. 硬門檻: NaN / Inf
stats = {i: anchor_stats(data[i]["ref_visual_anchor"]) for i in gidx}
bad = [i for i in gidx if stats[i][0] or stats[i][1]]
if bad:
return (bad, f"NaN/Inf: {[(i, stats[i][:2]) for i in bad]}")
# 2c. 軟門檻: 對組內 anchor 中位數的偏差
med = None
for i in gidx:
med = data[i]["ref_visual_anchor"].clone() if med is None else torch.stack(
[med, data[i]["ref_visual_anchor"]]
).mean(dim=0)
diffs = {i: (data[i]["ref_visual_anchor"].float() - med.float()).abs().max().item() for i in gidx}
ordered = sorted(diffs.values())
baseline = ordered[min(1, len(ordered) - 1)] # 多數派互差 (N=2 時取 0)
thr = max(baseline * 8.0, 3.0)
outliers = [i for i in gidx if diffs[i] > thr]
if outliers:
return (outliers,
f"anchor 偏差離群 (thr={thr:.2f}, baseline={baseline:.4f}): "
f"{[(i, round(diffs[i], 3)) for i in outliers]}")
return ([], "")
def main():
dry = "--dry-run" in sys.argv
config = load_config()
enabled = [i for i, t in config.TASK_REGISTRY.items() if t.enabled]
print(f">> [CHECK] enabled tasks: {enabled}")
groups = {}
missing = []
for idx in enabled:
f = f"result1_ref_{idx}.pt"
if not os.path.exists(f):
missing.append(idx)
continue
data = torch.load(f, map_location="cpu", weights_only=False)
groups.setdefault(group_key(config.TASK_REGISTRY[idx], data), []).append(idx)
if missing:
print(f">> [WARN] 尚無檔案 (未跑 step1?): {missing} → 先跑 step1。")
sys.exit(0 if not groups else 10)
total_bad = 0
undecided = 0
for key, gidx in groups.items():
if len(gidx) == 1:
print(f">> [GROUP {gidx[0]}] 單檔組, 無同儕可比較 (跳過)。")
continue
outliers, reason = check_group(gidx)
if not outliers:
print(f">> [GROUP {sorted(gidx)}] ✓ 一致 ({len(gidx)} 檔)。")
continue
majority_ok = len(outliers) * 2 <= len(gidx)
if not majority_ok:
undecided += 1
print(f">> [GROUP {sorted(gidx)}] ✗ 無法決定: {reason} (離群 {sorted(outliers)} "
f">= 多數) → 刪除整組 {sorted(gidx)} 重跑。")
else:
print(f">> [GROUP {sorted(gidx)}] ✗ 異常: {reason} → 刪除 {sorted(outliers)}。")
for i in (outliers if majority_ok else gidx):
f = f"result1_ref_{i}.pt"
if dry:
print(f" [dry-run] 將刪除 {f}")
else:
os.remove(f)
print(f" 已刪除 {f}")
total_bad += len(outliers if majority_ok else gidx)
if undecided:
print(f"\n>> [CHECK] 無法判定 (exit 11): 已刪除整組, 重跑 step1 後再檢查。")
sys.exit(11)
if total_bad:
print(f"\n>> [CHECK] 發現 {total_bad} 個異常檔 (exit 10): 請重跑 ref2va_step1.py "
f"(會跳過既有檔, 只補跑被刪的)。")
sys.exit(10)
print(f"\n>> [CHECK] 全部健康 (exit 0)。")
sys.exit(0)
if __name__ == "__main__":
main()
+290
View File
@@ -0,0 +1,290 @@
#!/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 計算
"""
[REF2VA STAGE 1] Video VAE 編碼參考圖 → ref_blocks + anchors
================================================================
唯一大權重: video_vae_nf4.safetensors (~1.6GB)。(image-only refs 完全不
碰 audio VAE — ReferenceEncoder 的 audio 分支只在 ref_audio_t>0 時才跑,
所以本 step 只需載入 video VAE, 單一權重。)
不載入 DiT / text encoder。
每個任務 (全部 N 個視頻在這次載入中一次跑完, video VAE 只載入一次):
1. 用 config.load_task_references(idx) 載入參考圖 (PIL RGB)
2. 直接呼叫 pipeline 內建的 MiniMaxH3Unit_ReferenceEncoder.process
(縮放短邊到 32 倍數 → video VAE encode → imgvid_cond_noise_aug 加噪)
→ 回傳 {"ref_blocks", "ref_visual_anchor", "ref_audio_anchor"}
注意: process 會 pop 掉每個 block 的 visual_clean (已併入 anchor),
所以 ref_blocks 落盤時只剩 metadata + prepared_image。
3. 落盤 result1_ref_{idx}.pt:
- ref_blocks: 每個 block {kind, latent_t, latent_h, latent_w,
prepared_image(PIL), ref_audio_t}
- ref_visual_anchor: DiT 條件錨點 (加噪後的 rows), step3 replay
- ref_audio_anchor: None (image-only)
- video_latent_shape / audio_latent_shape: 目標 latent 形狀
(step3 noise 與 step4 decode 對齊用)
單權重策略: 任一時刻 DRAM/VRAM 只有 video VAE 一個權重。
下一階段: ref2va_step2.py (text encoder 編 prompt, 用本步的 prepared_image)
"""
import os
import sys
import gc
import hashlib
import importlib.util
# ==============================================================================
# 動態加載專案配置 (與 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 <project> 執行 (會 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()
def load_task_references(idx):
return config.load_task_references(idx)
import torch
from diffsynth.pipelines.minimax_h3_audio_video import (
MiniMaxH3Pipeline, ModelConfig, MiniMaxH3Unit_ReferenceEncoder,
)
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"
MAX_MIXED_REFS = 12 # 官方 Ref2VA 混合檔上限
MAX_IMAGE_REFS = 9 # 官方 Ref2VA 圖片上限
# num_frames snap 到 17n+5 (與 BasePipeline.check_resize_height_width 完全一致)
TIME_DIV, TIME_REM = 17, 5
def snap_num_frames(nf: int) -> int:
if nf % TIME_DIV == TIME_REM:
return nf
return (nf - TIME_REM + TIME_DIV - 1) // TIME_DIV * TIME_DIV + TIME_REM
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 # PIL.Image 原樣 (torch.save 原生支援)
def latent_shapes(task):
"""與 MiniMaxH3Unit_NoiseInitializer 完全一致的目標 latent 形狀。
注意: num_frames 先 snap 到 17n+5 (pipeline 的 ShapeChecker 會這麼做)。"""
nf = snap_num_frames(task.num_frames)
video_latent_t = ((nf - 5) // 17) * 5 + 2
latent_h, latent_w = task.height // 16, task.width // 16
audio_latent_t = round(nf / 24.0 * 40.0)
return (1, 24, video_latent_t, latent_h, latent_w), (2, 32, audio_latent_t), nf
def main():
print("\n========== [REF2VA STAGE 1] Video VAE 編碼參考圖 (單權重版) ==========")
print(f">> [Config] 專案配置: {config_path}")
# 步驟一致性檢查
# config.validate_steps_consistency()
enabled_ids = get_enabled_tasks()
# 預先檢查: ref2va 必須有參考圖, 且不超過官方上限
for idx in enabled_ids:
n = len(TASK_REGISTRY[idx].references or [])
if n == 0:
print(f">> [Error] Task {idx} 沒有 references。Ref2VA 至少需要 1 張參考圖。")
sys.exit(1)
if n > MAX_IMAGE_REFS:
print(f">> [Error] Task {idx} 有 {n} 張圖片參考, 超過官方上限 {MAX_IMAGE_REFS} 張。")
sys.exit(1)
if n > MAX_MIXED_REFS:
print(f">> [Error] Task {idx} 有 {n} 個參考檔, 超過官方混合上限 {MAX_MIXED_REFS}。")
sys.exit(1)
torch.cuda.empty_cache()
gc.collect()
# 單一權重: video VAE (1.6GB) 全駐 GPU (1.6G 對 24GB 完全沒壓力,
# 全 cuda 避免 layer-wise hotload 拖慢 N 張參考圖的編碼)
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",
}
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, "vae/video_vae_nf4.safetensors"),
**vram_config,
),
],
processor_config=None, # ReferenceEncoder 不需 processor / tokenizer
vram_limit=18.0,
)
# pipeline 內建的 ReferenceEncoder (縮放+編碼+加噪邏輯與官方完全一致)
ref_unit = MiniMaxH3Unit_ReferenceEncoder()
# ── 同一張圖 VAE 去重 + 冷啟動燃燒 (共識驗算前提) ─────────────────────────
# ROCm bf16 編碼路徑 (split-K atomics / flash sdp) 受首次運算的記憶體配置
# 影響: 實測同一 process 內, 首次 encode (task 0) 的 anchor 離群, 第二次起
# bit 級一致。noise 的 seed 已固定 (RUN_CONFIG.default_seed), resize /
# preprocess 是純 CPU 決定性運算 → 只要 VAE clean 被 memoize, 整條 anchor
# 就完全可重現: 同一張圖 + 同解析度 + 同幀數 = bit 相同的 result1_ref_*.pt,
# 之後 ref2va_check_refs.py 的 binary cmp 多數決才有意義。
_enc_cache = {}
_orig_encode_video = pipe.video_vae.encode_video
_cold_burned = [False]
def _memoized_encode_video(tensor, **kwargs):
t = tensor.detach().to("cpu", copy=False).contiguous()
key = (tuple(t.shape), str(t.dtype), kwargs.get("process_image"),
hashlib.md5(t.view(torch.uint8).numpy().tobytes()).hexdigest())
if key not in _enc_cache:
z = _orig_encode_video(t.to(pipe.device), **kwargs)
if not _cold_burned[0]:
# 冷啟動燃燒: 丟棄 process 首次 encode, 以第二次為準
# (與原 run 中第二次起的穩定值對齊)
z = _orig_encode_video(t.to(pipe.device), **kwargs)
_cold_burned[0] = True
print(">> [VAE 去重] 冷啟動燃燒完成 (首次 encode 已丟棄)")
_enc_cache[key] = z.detach().cpu()
print(f">> [VAE 去重] 新 encode {tuple(t.shape)} (累計 {len(_enc_cache)} 個)")
else:
print(f">> [VAE 去重] 重用先前 encode {tuple(t.shape)} (累計 {len(_enc_cache)} 個, 省下 1 次 VAE 運算)")
return _enc_cache[key].to(device=pipe.device, dtype=pipe.torch_dtype)
pipe.video_vae.encode_video = _memoized_encode_video
seed = RUN_CONFIG.get("default_seed", 42)
ref_video_short_edge = 768
ref_video_max_pixels = 768 * 1344
# --- 斷點續傳 (與 fl2va 一致) ---
last_completed_idx = -1
if os.path.exists(".restart"):
try:
with open(".restart") as f:
last_completed_idx = int(f.read().strip())
print(f"\n[RESUME] 偵測到續傳標記,將從任務 ID > {last_completed_idx} 開始。")
except Exception:
pass
done = 0
for idx in enabled_ids:
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
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
save_name = f"result1_ref_{idx}.pt"
if os.path.exists(save_name):
print(f">> [SKIP] Task {idx} 已有 {save_name}。")
last_completed_idx = idx
continue
task = TASK_REGISTRY[idx]
refs = load_task_references(idx)
short_edge = getattr(task, "ref_image_short_edge", 2048)
v_shape, a_shape, nf = latent_shapes(task)
references = [{"type": "image", "image": img} for img in refs]
print(f"\n>> [Task {idx}] 編碼 {len(refs)} 張參考圖 (短邊 {short_edge}, "
f"目標 {task.width}x{task.height}, {nf}f)..."
+ (f" (原 {task.num_frames}f → snap {nf}f)" if nf != task.num_frames else ""))
with torch.no_grad():
out = ref_unit.process(
pipe,
references=references,
seed=seed,
# 佔位 shape: anchor 加噪只讀 video_latents.shape[2]
video_latents=torch.zeros(v_shape),
num_frames=nf,
ref_image_short_edge=short_edge,
ref_video_short_edge=ref_video_short_edge,
ref_video_max_pixels=ref_video_max_pixels,
)
payload = move_to_cpu({
"ref_blocks": out["ref_blocks"],
"ref_visual_anchor": out["ref_visual_anchor"],
"ref_audio_anchor": out["ref_audio_anchor"],
"video_latent_shape": v_shape,
"audio_latent_shape": a_shape,
})
# 決定性: torch.save 的 ZIP 檔頭 CRC 取自檔案名稱 (實測 torch 2.13),
# 檔名固定 + 內容 bit 相同 → md5 相同 → ref2va_check_refs.py 的
# 階段 1 binary cmp 可直接判定。
torch.save(payload, save_name)
n_blocks = len(out["ref_blocks"])
anchor_shape = None if out["ref_visual_anchor"] is None else tuple(out["ref_visual_anchor"].shape)
print(f">> [SUCCESS] Task {idx} 已儲存 {save_name} "
f"(ref_blocks {n_blocks} 個, ref_visual_anchor {anchor_shape}, "
f"video_latent {v_shape}, audio_latent {a_shape})")
del refs, references, out, payload
gc.collect()
torch.cuda.empty_cache()
last_completed_idx = idx
with open(".restart", "w") as f:
f.write(str(last_completed_idx))
done += 1
print(f"\n========== [REF2VA STAGE 1] 完成 {done}/{len(enabled_ids)} 個任務 ==========")
print(">> 下一步: ref2va_step2.py (text encoder)")
if __name__ == "__main__":
main()
+222
View File
@@ -0,0 +1,222 @@
#!/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 計算
"""
[REF2VA STAGE 2] Text Encoder 編碼 prompt (ref2va 主路徑, 全視頻 batch)
================================================================
唯一大權重: minimax-h3-text-encoder-nf4.safetensors (~15GB NF4) + 輕量
processor/tokenizer (幾 MB, 非模型權重)。
不載入 DiT / video VAE / audio VAE。
每個任務 (全部 N 個視頻在這次載入中一次跑完, text encoder 只載入一次):
1. 讀 step1 落盤的 result1_ref_{idx}.pt → ref_blocks (含 prepared_image)
2. 直接呼叫 pipeline 內建的 MiniMaxH3Unit_PromptEmbedder.process
(ref2va 主路徑:
preprocess_ref_blocks → image_token_counts(processor, prepared_images)
→ presentation_ref2va(tokenizer, prompt, condition_labels, image_counts)
→ text_encoder(input_ids, pixel_values, image_grid_thw))
→ 回傳 {"prompt_embeds": hidden [seq, hidden], "text_token_tags": [seq] (0/1 混合)}
⚠️ 不能走 __call__ 的 text_embedding 快速路徑 (那會回全 1 的 tags,
DiT 的 ADALN 靠 0/1 混合 tags 區分 text/vision token)。
3. 落盤 result2_text_{idx}.pt: {hidden, text_token_tags}
單權重策略: 任一時刻 DRAM/VRAM 只有 text encoder 一個權重。
下一階段: ref2va_step3.py (DiT 去噪, replay 本步的 hidden + tags)
"""
import os
import sys
import gc
import importlib.util
# ==============================================================================
# 動態加載專案配置 (與 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 <project> 執行 (會 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()
import torch
from diffsynth.pipelines.minimax_h3_audio_video import (
MiniMaxH3Pipeline, ModelConfig, MiniMaxH3Unit_PromptEmbedder,
)
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_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
def main():
print("\n========== [REF2VA STAGE 2] Text Encoder 編碼 Prompt (單權重版) ==========")
print(f">> [Config] 專案配置: {config_path}")
# 步驟一致性檢查
# config.validate_steps_consistency()
enabled_ids = get_enabled_tasks()
# 上游檢查
for idx in enabled_ids:
if not os.path.exists(f"result1_ref_{idx}.pt"):
print(f">> [Error] Task {idx} 缺少 result1_ref_{idx}.pt, 請先執行 step1。")
sys.exit(1)
torch.cuda.empty_cache()
gc.collect()
# 單一權重: text encoder (15GB NF4)。
# fl2va step1 實跑驗證的 hotload 配置 (offload 到 cpu, 計算在 cuda) —
# 15GB 全駐 24GB GPU 太擠 (activation + processor 前向), hotload 更穩。
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="minimax-h3-text-encoder-nf4.safetensors",
path=os.path.join(MODELS_DIR, "text_encoders/minimax-h3-text-encoder-nf4.safetensors"),
**vram_config,
),
],
# processor 是 tokenizer/preprocessor 檔案 (幾 MB), 非模型權重。
# ref2va 主路徑需要它算 image_token_counts / presentation_ref2va。
processor_config=ModelConfig(
model_id="MiniMax/MiniMax-H3",
origin_file_pattern="FL2VA/processor/",
path=os.path.join(MODELS_DIR, "text_encoders/config"),
),
vram_limit=18.0,
)
# pipeline 內建的 PromptEmbedder (ref2va 主路徑邏輯與官方完全一致)
text_unit = MiniMaxH3Unit_PromptEmbedder()
# --- 斷點續傳 (與 fl2va 一致) ---
last_completed_idx = -1
if os.path.exists(".restart"):
try:
with open(".restart") as f:
last_completed_idx = int(f.read().strip())
print(f"\n[RESUME] 偵測到續傳標記,將從任務 ID > {last_completed_idx} 開始。")
except Exception:
pass
done = 0
for idx in enabled_ids:
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
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
save_name = f"result2_text_{idx}.pt"
if os.path.exists(save_name):
print(f">> [SKIP] Task {idx} 已有 {save_name}。")
last_completed_idx = idx
continue
task = TASK_REGISTRY[idx]
prompt = task.prompts[0] if task.prompts else ""
if not prompt:
print(f">> [Error] Task {idx} prompt 為空。")
sys.exit(1)
data = torch.load(f"result1_ref_{idx}.pt", weights_only=False)
ref_blocks = data["ref_blocks"]
print(f"\n>> [Task {idx}] 編碼 prompt ({len(ref_blocks)} 個 ref blocks)...")
print(f" Prompt: {prompt[:60]}...")
with torch.no_grad():
out = text_unit.process(
pipe,
prompt=prompt,
keyframes=None,
ref_blocks=ref_blocks,
height=task.height,
width=task.width,
text_embedding=None,
)
hidden = out["prompt_embeds"].detach()
tags = out["text_token_tags"].detach()
n_text = int((tags == 1).sum().item())
n_ref = int((tags == 0).sum().item())
torch.save(move_to_cpu({
"hidden": hidden,
"text_token_tags": tags,
"seq_len": int(hidden.shape[0]),
"n_text_tokens": n_text,
"n_ref_tokens": n_ref,
}), save_name)
print(f">> [SUCCESS] Task {idx} 已儲存 {save_name} "
f"(hidden {tuple(hidden.shape)}, seq {hidden.shape[0]}, "
f"text tokens {n_text}, ref tokens {n_ref})")
del data, ref_blocks, out, hidden, tags
gc.collect()
torch.cuda.empty_cache()
last_completed_idx = idx
with open(".restart", "w") as f:
f.write(str(last_completed_idx))
done += 1
print(f"\n========== [REF2VA STAGE 2] 完成 {done}/{len(enabled_ids)} 個任務 ==========")
print(">> 下一步: ref2va_step3.py (DiT 去噪)")
if __name__ == "__main__":
main()
+352
View File
@@ -0,0 +1,352 @@
#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
import os
import sys
import gc
import psutil
import importlib.util
# ==============================================================================
# 【新增】將 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)
# ==============================================================================
# 環境變數設定
# ==============================================================================
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"
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 計算
"""
[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 <project> 執行 (會 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 權重)
# PromptEmbedder 主路徑重跑 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}.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}.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}.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}.pt")
return torch.zeros((2, Ta * 800))
def decode(self, *args, **kwargs):
return self.decode_audio(*args, **kwargs)
def main():
print("\n========== [REF2VA STAGE 3] DiT 去噪生成 (ref2va 權重, 單權重版) ==========")
# 步驟一致性檢查
# config.validate_steps_consistency()
enabled_ids = get_enabled_tasks()
for idx in enabled_ids:
if not os.path.exists(f"result1_ref_{idx}.pt") or not os.path.exists(f"result2_text_{idx}.pt"):
print(f">> [Error] Task {idx} 缺少前置 pt 檔案。")
sys.exit(1)
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",
}
# 1. 權重只在啟動時從 HDD 載入一次到系統記憶體 (DRAM)
pipe = MiniMaxH3Pipeline.from_pretrained(
torch_dtype=torch.bfloat16, device="cuda",
model_configs=[
ModelConfig(
model_id="DiffSynth-Studio/MiniMax-H3-NF4",
origin_file_pattern="minimax-h3-ref2va-nf4.safetensors",
path=os.path.join(MODELS_DIR, "diffusion_models/minimax-h3-ref2va-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=14.0,
)
seed = RUN_CONFIG.get("default_seed", 42)
# 根據每個任務的 steps 決定是否載入 Turbo LoRA
# 注意:由於 validate_steps_consistency 已保證所有任務都在同一側 (<=23 或 >23),
# 我們只需檢查第一個可用任務或 RUN_CONFIG 即可決定單次運行是否載入 LoRA。
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)
if effective_steps <= 23:
lora_path = os.path.join(MODELS_DIR, "loras/minimax_h3_turbo_v4_step600_ema.safetensors")
if os.path.exists(lora_path):
print(f">> [LoRA] 檢測到步驟 {effective_steps} <= 23, 載入 Turbo LoRA: {os.path.basename(lora_path)}")
pipe.load_lora(pipe.dit, lora_config=lora_path, alpha=1.0, verbose=1)
else:
print(f">> [Warning] LoRA 檔案不存在: {lora_path}")
else:
print(f">> [LoRA] 檢測到步驟 {effective_steps} > 23, 跳過 Turbo LoRA 載入")
# --- 額外 LoRA (由專案 config.py 的 EXTRA_LORAS 指定; 格式: (檔案名, strength)) ---
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:
# 檔案存在即跳過 (與 step1/step2 一致): 已產出 result3 latent 的 task
# 不再重跑。這樣「只重跑單一 task」(刪掉該 task 的 result3 檔) 時,
# 其餘 task 會自動跳過, 不需要靠 .restart 計數器或改 config。
if os.path.exists(f"result3_video_{idx}.pt") and os.path.exists(f"result3_audio_{idx}.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 ""
# 優先讀取 task 的 steps,否則使用 RUN_CONFIG
steps = task.num_inference_steps if task.num_inference_steps is not None else RUN_CONFIG.get("default_num_inference_steps", 8)
# --- 任務前:重設峰值統計,記錄基準 VRAM ---
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}.pt", weights_only=False)
ref_unit.data = ref_data
pipe.text_encoder = ReplayTextEncoder(f"result2_text_{idx}.pt")
pipe.video_vae = SaveLatentVideoVAE(idx)
pipe.audio_vae = SaveLatentAudioVAE(idx)
# 2. 徹底關閉梯度與歷史追蹤
with torch.inference_mode():
pipe(
prompt=prompt,
height=task.height,
width=task.width,
num_frames=task.num_frames,
num_inference_steps=steps,
seed=seed,
)
# --- 任務完成:抓取本次任務的 VRAM 峰值 ---
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} 生成完畢。")
# 3. 解除任務特定引用
ref_unit.data = None
pipe.text_encoder = None
pipe.video_vae = None
pipe.audio_vae = None
del ref_data
# 4. 穿透式檢查:強制將 DiT 所有殘留在 GPU 的 Tensor 趕回 CPU
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")
# 5. 強制觸發 GC 與顯存釋放
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()
+306
View File
@@ -0,0 +1,306 @@
#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
import gc
import os
import sys
import time
import importlib.util
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)
"""
[REF2VA STAGE 4] VAE 像素還原 (video + audio VAE)
- 權重常駐 GPU,不反覆搬移回 CPU
- 進入迴圈前以 Task 0 規格執行 Dummy 預熱與極限測試
- 修正 Audio 維度相容性 (嚴格保證 [2, S] 格式)
- 保持原本的任務略過邏輯
"""
# ==============================================================================
# 動態加載專案配置
# ==============================================================================
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)
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
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.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, dtype=None):
"""Recursively move objects to CUDA device and optionally cast dtype."""
if isinstance(obj, torch.Tensor):
obj = obj.to("cuda")
if dtype is not None:
obj = obj.to(dtype)
return obj
if isinstance(obj, dict):
return {k: move_to_cuda(v, dtype) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return type(obj)(move_to_cuda(x, dtype) for x in obj)
return obj
def format_audio_for_output(audio_raw, is_dummy=False):
"""
音訊標準化處理:
嚴格保證回傳張量形狀為 [2, Samples] (DiffSynth 規定的雙聲道格式),
並處理 NaN/Inf 與音量正規化。
"""
if not isinstance(audio_raw, torch.Tensor):
return audio_raw
audio = audio_raw.detach().cpu().float()
# 1. 清理 NaN / Inf
if torch.isnan(audio).any() or torch.isinf(audio).any():
if not is_dummy:
print(">> [Warning] 檢測到 Audio 解碼輸出包含 NaN/Inf!進行數值清理...")
audio = torch.nan_to_num(audio, nan=0.0, posinf=1.0, neginf=-1.0)
# 2. 徹底消除前綴的 Batch 維度 (例如 [1, 2, S] -> [2, S])
while audio.ndim > 2 and audio.shape[0] == 1:
audio = audio.squeeze(0)
# 3. 確保維度為 [2, Samples]
if audio.ndim == 1:
# 單聲道 [S] -> 複製為雙聲道 [2, S]
audio = audio.unsqueeze(0).repeat(2, 1)
elif audio.ndim == 2:
# 若形狀為 [S, 2],轉置為 [2, S]
if audio.shape[0] not in (1, 2) and audio.shape[1] in (1, 2):
audio = audio.transpose(0, 1)
# 若形狀為 [1, S],複製為雙聲道 [2, S]
if audio.shape[0] == 1:
audio = audio.repeat(2, 1)
# 4. 音量正規化
max_val = audio.abs().max()
if max_val > 1.0:
audio = audio / max_val
elif max_val == 0.0 and not is_dummy:
print(">> [Warning] Audio 輸出全為 0 (靜音)!請檢查 Step 3 生成的 audio latent。")
return audio
def run_pre_dummy_test(pipe, video_vae, audio_vae, fps):
"""在正式 Loop 前執行一次 Dummy 測試,固定參考 Task 0 的規格 (權重已常駐 GPU)"""
task0 = TASK_REGISTRY[0]
target_w = task0.width
target_h = task0.height
target_frames = task0.num_frames
print("\n" + "=" * 68)
print(f">> [PRE-LOOP TEST] 執行 VAE 空畫面預熱與解碼測試...")
print(f">> 參考 Task 0 規格: {target_w}x{target_h}, {target_frames} 幀 (FPS: {fps})")
print("=" * 68)
dummy_out_path = os.path.join(OUTPUT_DIR, f"dummy_test_{target_w}x{target_h}_{target_frames}f.mp4")
video_pt_0 = "result3_video_0.pt"
audio_pt_0 = "result3_audio_0.pt"
if os.path.exists(video_pt_0) and os.path.exists(audio_pt_0):
print(f">> [Dummy] 發現 {video_pt_0},沿用其結構克隆全 0 特徵張量...")
raw_v = torch.load(video_pt_0, weights_only=False)
video_data = move_to_cuda({
"args": [torch.zeros_like(a) if isinstance(a, torch.Tensor) else a for a in raw_v.get("args", [])],
"kwargs": {k: (torch.zeros_like(v) if isinstance(v, torch.Tensor) else v) for k, v in raw_v.get("kwargs", {}).items()}
})
raw_a = torch.load(audio_pt_0, weights_only=False)
audio_data = move_to_cuda({
"args": [torch.zeros_like(a) if isinstance(a, torch.Tensor) else a for a in raw_a.get("args", [])],
"kwargs": {k: (torch.zeros_like(v) if isinstance(v, torch.Tensor) else v) for k, v in raw_a.get("kwargs", {}).items()}
}, dtype=torch.float32)
else:
print(f">> [Dummy] 未發現 Task 0 的 pt 檔,直接以數學公式推算全 0 張量...")
w_lat = target_w // 16
h_lat = target_h // 16
t_lat = ((target_frames - 5) // 17 * 5 + 2) if target_frames > 5 else 1
dummy_v_latent = torch.zeros((1, 24, t_lat, h_lat, w_lat), device="cuda", dtype=torch.bfloat16)
video_data = {"args": [dummy_v_latent], "kwargs": {}}
ta_lat = int((target_frames / fps) * 40)
dummy_a_latent = torch.zeros((2, 32, ta_lat), device="cuda", dtype=torch.float32)
audio_data = {"args": [dummy_a_latent], "kwargs": {}}
torch.cuda.reset_peak_memory_stats()
t0 = time.time()
# 直接解碼,不搬移權重
print(">> [Dummy] 解碼 Video VAE...")
with torch.no_grad():
video_raw = video_vae.decode_video(*video_data["args"], **video_data["kwargs"])
video = pipe.vae_output_to_video(video_raw, min_value=0, max_value=1)
video_time = time.time() - t0
print(">> [Dummy] 解碼 Audio VAE...")
with torch.no_grad():
kwargs = audio_data.get("kwargs", {}).copy()
if "dtype" in kwargs:
kwargs["dtype"] = torch.float32
audio_raw = audio_vae.decode_audio(*audio_data["args"], **kwargs)
# 關鍵修正:透過共用函式統一正規化為 [2, Samples]
audio = format_audio_for_output(audio_raw, is_dummy=True)
sample_rate = getattr(audio_vae, "sample_rate", 32000)
write_video_audio(
video=video,
audio=audio,
output_path=dummy_out_path,
fps=fps,
audio_sample_rate=sample_rate,
)
peak_vram = torch.cuda.max_memory_allocated() / (1024**3)
print(f">> [Dummy 完成] 測試檔案已存至: {dummy_out_path}")
print(f">> [Dummy 報告] 解碼耗時: {video_time:.2f} 秒 | 顯存峰值: {peak_vram:.2f} GB")
print("=" * 68 + "\n")
# 僅刪除產出資料的變數參照,模型權重留在 GPU 內
del video_data, audio_data, video_raw, audio_raw, video, audio
def main():
print("\n========== [REF2VA STAGE 4] VAE 像素還原 ==========")
print(f">> [Config] 專案配置: {config_path}")
print(f">> [Config] 輸出路徑: {OUTPUT_DIR}")
enabled_ids = get_enabled_tasks()
print(f">> [Config] 啟用任務: {enabled_ids}")
fps = VIDEO_SETTINGS.get("default_fps", 24)
# 載入 Pipeline
print(">> [INFO] 開始初始化 VAE...")
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, "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=None,
vram_limit=18.0,
)
# 關鍵優化:權重一次性常駐 GPU
video_vae = pipe.video_vae.to("cuda")
audio_vae = pipe.audio_vae.to("cuda", dtype=torch.float32)
print(f">> [OK] VAE 已常駐 GPU 顯存 (video_vae: {type(video_vae).__name__}, audio_vae: {type(audio_vae).__name__})")
# =========================================================================
# 【前置步驟】在進入原本的 for-loop 之前,先執行一次 Dummy 測試
# =========================================================================
ENABLE_DUMMY_TEST = True # 不需要時改為 False 即可完全關閉
if ENABLE_DUMMY_TEST:
run_pre_dummy_test(pipe, video_vae, audio_vae, fps)
# =========================================================================
# 正式任務迴圈 (原本的檢查與跳過邏輯)
# =========================================================================
done = 0
for task_idx in enabled_ids:
task = TASK_REGISTRY[task_idx]
out_path = os.path.join(OUTPUT_DIR, f"ref2va_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"
if not os.path.exists(video_pt) or not os.path.exists(audio_pt):
print(f">> [Skip] 缺少 {video_pt} 或 {audio_pt}")
continue
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), dtype=torch.float32)
# ----------------- Video Decode -----------------
print(">> [Task] 解碼 Video VAE...")
with torch.no_grad():
video_raw = video_vae.decode_video(*video_data["args"], **video_data["kwargs"])
video = pipe.vae_output_to_video(video_raw, min_value=0, max_value=1)
# ----------------- Audio Decode -----------------
print(">> [Task] 解碼 Audio VAE...")
with torch.no_grad():
kwargs = audio_data.get("kwargs", {}).copy()
if "dtype" in kwargs:
kwargs["dtype"] = torch.float32
audio_raw = audio_vae.decode_audio(*audio_data["args"], **kwargs)
# ----------------- 音訊後處理與健全檢查 -----------------
audio = format_audio_for_output(audio_raw, is_dummy=False)
sample_rate = getattr(audio_vae, "sample_rate", 32000)
if sample_rate is None:
sample_rate = VIDEO_SETTINGS.get("default_audio_sample_rate", 32000)
print(f">> [Task] 儲存影片: {out_path}")
print(f">> - 影片幀數: {len(video)} 幀 (FPS: {fps})")
print(f">> - 音訊規格: Shape={tuple(audio.shape) if isinstance(audio, torch.Tensor) else None}, SampleRate={sample_rate}")
write_video_audio(
video=video,
audio=audio,
output_path=out_path,
fps=fps,
audio_sample_rate=sample_rate,
)
print(f">> [SUCCESS] Task {task_idx} 完成!")
# 僅清理本次生成的資料張量,權重繼續留在 GPU
del video_data, audio_data, video_raw, audio_raw, video, audio
done += 1
print(f"\n========== [REF2VA STAGE 4] 完成 {done}/{len(enabled_ids)} 個任務 ==========")
if __name__ == "__main__":
main()
Executable
+110
View File
@@ -0,0 +1,110 @@
#!/bin/bash
set -e
# ==============================================================================
# MiniMax-H3 FL2VA 3-step runner (使用 ref2va_step4.py 兼容 VAE 解碼)
# 用法: ./run_flh3.sh <project_name> [step]
# step 省略 = 依序跑全部 3 步
# 1 = Text encoder 編碼 prompt (text encoder 15G) → result1_te_*.pt
# 2 = DiT 去噪 (fl2va DiT 16G) → result2_video/audio_*.pt
# 3 = Video+Audio VAE 解碼 (video+audio VAE 1.9G)→ fl2va_output_*.mp4
#
# 注意: Step3 使用 ref2va_step4.py 取代原 fl2va_step3.py (功能完全相同)
# 保留原檔案以便 rollback 交叉測試
# ==============================================================================
if [ -z "$1" ]; then
echo "Usage: ./run_flh3.sh <project_name> [step]"
echo "Example: ./run_flh3.sh secretary_tease_5s 3"
echo "Step options (3-step architecture with ref2va_step4 for VAE decode):"
echo " 1 = Text encoder encode prompts (text encoder NF4 ~15GB) -> result1_te_*.pt"
echo " 2 = DiT denoise (fl2va NF4 ~16GB) -> result2_video/audio_*.pt"
echo " 3 = Video+Audio VAE decode using ref2va_step4.py (VAEs ~1.9GB)-> fl2va_output_*.mp4"
echo "Omit step to run all 3 in order."
echo ""
echo "Note: Original fl2va_step3.py is preserved for rollback testing."
exit 1
fi
PROJECT_NAME=$1
STEP=$2
BASE_DIR="/home/mikehu/data/AI/minimax-h3"
PROJECT_DIR="$BASE_DIR/outputs/$PROJECT_NAME"
VENV_PYTHON="$BASE_DIR/.venv/bin/python"
echo "----------------------------------------------------------------"
echo "🚀 Initializing MiniMax-H3 FL2VA Project: $PROJECT_NAME"
echo "📂 Project Dir: $PROJECT_DIR"
echo "🔧 Using ref2va_step4.py for Step 3 (VAE decode)"
echo "----------------------------------------------------------------"
# Create project directory
mkdir -p "$PROJECT_DIR"
# Copy template config.py to the project directory if it doesn't exist
if [ ! -f "$PROJECT_DIR/config.py" ]; then
cp "$BASE_DIR/config_template.py" "$PROJECT_DIR/config.py"
echo "📝 Copied template config.py to project folder. Please edit it for specific settings."
else
echo "📄 Using existing project config.py."
fi
# CRITICAL: Change working directory to the project folder
# This ensures that 'import config' finds the project-specific config.py
# and all relative paths like 'result1_te_*.pt' are saved/loaded here.
cd "$PROJECT_DIR"
export PYTHONPATH="$BASE_DIR:$PYTHONPATH"
# Validate step argument if provided
if [ -n "$STEP" ] && [[ ! "$STEP" =~ ^[1-3]$ ]]; then
echo "Error: Step must be 1, 2, or 3."
exit 1
fi
echo -e "\n----------------------------------------------------------------"
if [ -z "$STEP" ] || [ "$STEP" == "1" ]; then
echo -e "\n[1/3] Step 1: Text Encoding (fl2va_step1.py)..."
$VENV_PYTHON $BASE_DIR/fl2va_step1.py
fi
if [ -z "$STEP" ] || [ "$STEP" == "2" ]; then
echo -e "\n[2/3] Step 2: DiT Denoising (fl2va_step2.py)..."
$VENV_PYTHON $BASE_DIR/fl2va_step2.py
fi
if [ -z "$STEP" ] || [ "$STEP" == "3" ]; then
echo -e "\n[3/3] Step 3: VAE Decoding using ref2va_step4.py..."
# --- Path & File Alignment Fix ---
# 1. Align Output Directory
if [ -f "config.py" ]; then
CONF_OUTPUT_DIR=$(grep "OUTPUT_DIR =" config.py | sed -E 's/.*"([^"]+)".*/\1/')
if [ -n "$CONF_OUTPUT_DIR" ] && [ "$CONF_OUTPUT_DIR" != "$PROJECT_DIR" ]; then
echo "🔗 Aligning project path: $CONF_OUTPUT_DIR -> $PROJECT_DIR"
ln -sfn "$PROJECT_DIR" "$CONF_OUTPUT_DIR"
fi
fi
# 2. Align File Names (result2_..._l0.pt -> result3_....pt)
# ref2va_step4.py expects result3_video_0.pt and result3_audio_0.pt
for file in result2_{video,audio}_*_l0.pt; do
if [ -f "$file" ]; then
new_name=$(echo "$file" | sed -E 's/result2_(video|audio)_.*_l0\.pt/result3_\1_0.pt/')
echo "📝 Renaming $file -> $new_name"
cp -p "$file" "$new_name"
fi
done
# --------------------------
# Use ref2va_step4.py for FL2VA Step 3
# It reads result3_video/audio_*.pt and outputs fl2va_output_*.mp4
$VENV_PYTHON $BASE_DIR/ref2va_step4.py
fi
echo -e "\n----------------------------------------------------------------"
echo "✅ FL2VA Project $PROJECT_NAME Completed Successfully!"
echo "All assets (config, .pt, .mp4) are located in: $PROJECT_DIR"
echo "Note: Original fl2va_step3.py preserved for rollback testing."
echo "----------------------------------------------------------------"
date
Executable
+70
View File
@@ -0,0 +1,70 @@
#!/bin/bash
set -e
# Check for project name argument
if [ -z "$1" ]; then
echo "Usage: ./run_h3.sh <project_name> [step]"
echo "Example: ./run_h3.sh surf_girl_v1 3"
echo "Step options: 1 (Text Encoding), 2 (DiT Denoising), 3 (VAE Decoding), or omit to run all."
exit 1
fi
PROJECT_NAME=$1
STEP=$2
BASE_DIR="/home/mikehu/data/AI/minimax-h3"
BASE_DIR="/home/mikehu/data/AI/minimax-h3"
PROJECT_DIR="$BASE_DIR/outputs/$PROJECT_NAME"
VENV_PYTHON="$BASE_DIR/.venv/bin/python"
echo "----------------------------------------------------------------"
echo "🚀 Initializing MiniMax-H3 Project: $PROJECT_NAME"
echo "📂 Project Root: $PROJECT_DIR"
echo "----------------------------------------------------------------"
# Create project directory
mkdir -p "$PROJECT_DIR"
# Copy template config.py to the project directory if it doesn't exist
if [ ! -f "$PROJECT_DIR/config.py" ]; then
cp "$BASE_DIR/config_template.py" "$PROJECT_DIR/config.py"
echo "📝 Copied template config.py to project folder. Please edit it for specific settings."
else
echo "📄 Using existing project config.py."
fi
# CRITICAL: Change working directory to the project folder
# This ensures that 'import config' finds the project-specific config.py
# and all relative paths like 'result1_te_*.pt' are saved/loaded here.
cd "$PROJECT_DIR"
export PYTHONPATH="$BASE_DIR:$PYTHONPATH"
echo -e "\n----------------------------------------------------------------"
if [ -z "$STEP" ] || [ "$STEP" == "1" ]; then
if [ -n "$STEP" ] && [ "$STEP" != "1" ] && [ "$STEP" != "2" ] && [ "$STEP" != "3" ]; then echo "Invalid step $STEP"; exit 1; fi
echo -e "\n[1/3] Running Step 1: Text Encoding..."
$VENV_PYTHON $BASE_DIR/fl2va_step1.py
fi
if [ -z "$STEP" ] || [ "$STEP" == "2" ]; then
if [ -n "$STEP" ] && [ "$STEP" != "1" ] && [ "$STEP" != "2" ] && [ "$STEP" != "3" ]; then echo "Invalid step $STEP"; exit 1; fi
echo -e "\n[2/3] Running Step 2: DiT Denoising..."
$VENV_PYTHON $BASE_DIR/fl2va_step2.py
fi
if [ -z "$STEP" ] || [ "$STEP" == "3" ]; then
if [ -n "$STEP" ] && [ "$STEP" != "1" ] && [ "$STEP" != "2" ] && [ "$STEP" != "3" ]; then echo "Invalid step $STEP"; exit 1; fi
echo -e "\n[3/3] Running Step 3: VAE Decoding..."
$VENV_PYTHON $BASE_DIR/fl2va_step3.py
fi
# Validate step argument if provided
if [ -n "$STEP" ] && [[ ! "$STEP" =~ ^[1-3]$ ]]; then
echo "Error: Step must be 1, 2, or 3."
exit 1
fi
echo -e "\n----------------------------------------------------------------"
echo "✅ Project $PROJECT_NAME Completed Successfully!"
echo "All assets (config, .pt, .mp4) are located in: $PROJECT_DIR"
echo "----------------------------------------------------------------"
date
Executable
+179
View File
@@ -0,0 +1,179 @@
#!/bin/bash
set -e
# ==============================================================================
# MiniMax-H3 R2V 4-step runner (Reference-to-Video 模式, 單權重架構)
# 用法: ./run_r2v_h3.sh <project_name> [step]
# step 省略 = 依序跑全部 4 步
# 1 = Video VAE 編碼參考影片 (video VAE 1.6G) -> result1_ref_*.pt
# 2 = Text encoder 編 prompt (text encoder 15G) -> result2_text_*.pt
# 3 = DiT 去噪 (ref2va DiT 16G) -> result3_video/audio_*.pt
# 4 = Video+Audio VAE 解碼 (video+audio VAE 1.9G)-> r2v_output_*.mp4
#
# R2V 模式: Reference-to-Video - 使用影片作為參考來源
# 單權重保證: 每個 step 是獨立 process, 任一時刻 DRAM/VRAM 只有一個大權重。
# 多視頻保證: 每 step 內 for-loop 跑完全部 N 個視頻, 權重只載入一次。
# ==============================================================================
if [ -z "$1" ]; then
echo "Usage: ./run_r2v_h3.sh <project_name> [step]"
echo "Example: ./run_r2v_h3.sh cat 3"
echo "Step options (4-step single-weight architecture for R2V):"
echo " 1 = Video VAE encode reference videos (video VAE ~1.6GB) -> result1_ref_*.pt"
echo " 2 = Text encoder encode prompts (text encoder NF4 ~15GB) -> result2_text_*.pt"
echo " 3 = DiT denoise (ref2va NF4 ~16GB) -> result3_video/audio_*.pt"
echo " 4 = Video+Audio VAE decode (VAEs ~1.9GB) -> r2v_output_*.mp4"
echo "Omit step to run all 4 in order."
exit 1
fi
PROJECT_NAME=$1
STEP=$2
BASE_DIR="/home/mikehu/data/AI/minimax-h3"
PROJECT_DIR="$BASE_DIR/outputs/$PROJECT_NAME"
VENV_PYTHON="$BASE_DIR/.venv/bin/python"
echo "----------------------------------------------------------------"
echo "🚀 Initializing MiniMax-H3 R2V Project: $PROJECT_NAME"
echo "📂 Project Dir: $PROJECT_DIR"
echo "----------------------------------------------------------------"
# Create project directory
mkdir -p "$PROJECT_DIR"
# Copy template config.py to the project directory if it doesn't exist
if [ ! -f "$PROJECT_DIR/config.py" ]; then
cp "$BASE_DIR/config_template_r2v.py" "$PROJECT_DIR/config.py"
echo "📝 Copied R2V template config.py to project folder. Please edit it (especially 'references' and 'reference_types')."
else
echo "📄 Using existing project config.py."
fi
# R2V 專屬提示: references 為空時 R2V 無法運作 (至少 1 個參考檔)
if ! grep -q 'cat.mp4' "$PROJECT_DIR/config.py"; then
echo "⚠️ config.py 的 'references' 是空的 — R2V 需要至少 1 個參考檔。"
echo " 請編輯 $PROJECT_DIR/config.py 填入 1~9 個參考檔路徑,並指定 reference_types。"
exit 1
fi
# Validate step argument if provided
if [ -n "$STEP" ] && [[ ! "$STEP" =~ ^[1-4]$ ]]; then
echo "Error: Step must be 1, 2, 3, or 4."
exit 1
fi
# =============================================================================
# 資源檢查 (僅在執行全部步驟或 Step 1 時檢查 VRAM/存儲)
# =============================================================================
VRAM_OK=true
if [ -z "$STEP" ] || [ "$STEP" == "1" ]; then
echo ""
echo "🔍檢查 GPU VRAM 狀態..."
# 檢查 GPU 管理工具
if command -v rocm-smi &>/dev/null; then
GPU_TOOL="rocm-smi"
TOTAL_MEM=25753026560 # 24.2GB in bytes for RX7900XTX
USED_MEM=$(rocm-smi --showmeminfo vram -d 0 2>/dev/null | grep "VRAM Total Used Memory" | awk '{print $NF}')
elif command -v nvidia-smi &>/dev/null; then
GPU_TOOL="nvidia-smi"
MEM_INFO=$(nvidia-smi --query-gpu=memory.used,memory.total --format=csv,noheader 2>/dev/null)
USED_MEM=$(echo "$MEM_INFO" | awk -F', ' '{print $1}')
TOTAL_MEM=$(echo "$MEM_INFO" | awk -F', ' '{print $2}')
else
GPU_TOOL=""
echo "⚠️ 未找到 GPU 管理工具 (rocm-smi/nvidia-smi),跳過 VRAM 檢查"
fi
# 檢查 VRAM
if [ -n "$GPU_TOOL" ] && [ -n "$USED_MEM" ] && [ -n "$TOTAL_MEM" ]; then
FREE_MEM=$((TOTAL_MEM - USED_MEM))
MIN_FREE_VRAM=$((6 * 1024 * 1024 * 1024)) # 6GB
VRAM_FREE_GB=$((FREE_MEM / 1024 / 1024 / 1024))
VRAM_USED_GB=$((USED_MEM / 1024 / 1024 / 1024))
VRAM_TOTAL_GB=$((TOTAL_MEM / 1024 / 1024 / 1024))
echo " GPU 使用: ${VRAM_USED_GB}GB / ${VRAM_TOTAL_GB}GB"
echo " 可用 VRAM: ${VRAM_FREE_GB}GB"
if [ $FREE_MEM -lt $MIN_FREE_VRAM ]; then
echo "❌ VRAM 不足 (需要 >6GB free),取消執行"
VRAM_OK=false
else
echo "✅ VRAM 充足"
fi
else
echo "⚠️ 無法解析 GPU 記憶體狀態,繼續嘗試..."
fi
# 檢查存儲空間
echo ""
echo "🔍檢查存儲空間..."
if [ -d "$PROJECT_DIR" ]; then
DISK_FREE_KB=$(df "$PROJECT_DIR" | awk 'NR==2 {print $4}')
DISK_FREE_GB=$((DISK_FREE_KB / 1024 / 1024))
MIN_DISK_GB=50
echo " 可用存儲: ${DISK_FREE_GB}GB"
if [ $DISK_FREE_GB -lt $MIN_DISK_GB ]; then
echo "❌ 存儲空間不足 (需要 >${MIN_DISK_GB}GB free)"
VRAM_OK=false
else
echo "✅ 存儲空間充足"
fi
fi
fi
# 若資源不足,直接退出
if [ "$VRAM_OK" = false ]; then
echo ""
echo "❌ 系統資源不足,無法繼續執行"
exit 1
fi
echo -e "\n----------------------------------------------------------------"
# =============================================================================
# 切換到專案目錄,並清理 .restart .stop
# =============================================================================
cd "$PROJECT_DIR"
rm -f ".restart" ".stop" 2>/dev/null
# =============================================================================
# 4-Step Pipeline 執行
# =============================================================================
if [ -z "$STEP" ] || [ "$STEP" == "1" ]; then
echo -e "\n[1/4] Step 1: Video VAE 編碼參考影片 (video VAE ~1.6GB)"
echo "💾 輸出: result1_ref_*.pt"
$VENV_PYTHON $BASE_DIR/r2v_step1.py
rm -f ".restart" 2>/dev/null
fi
if [ -z "$STEP" ] || [ "$STEP" == "2" ]; then
echo -e "\n[2/4] Step 2: Text encoder 編碼 prompt (text encoder NF4 ~15GB)"
echo "💾 輸出: result2_text_*.pt"
$VENV_PYTHON $BASE_DIR/r2v_step2.py
rm -f ".restart" 2>/dev/null
fi
if [ -z "$STEP" ] || [ "$STEP" == "3" ]; then
echo -e "\n[3/4] Step 3: DiT 去噪 (ref2va NF4 ~16GB)"
echo "💾 輸出: result3_video_*.pt, result3_audio_*.pt"
$VENV_PYTHON $BASE_DIR/r2v_step3.py
rm -f ".restart" 2>/dev/null
fi
if [ -z "$STEP" ] || [ "$STEP" == "4" ]; then
echo -e "\n[4/4] Step 4: Video+Audio VAE 解碼 -> mp4 (video VAE ~1.6GB + audio VAE ~0.27GB)"
echo "💾 輸出: r2v_output_*.mp4"
$VENV_PYTHON $BASE_DIR/r2v_step4.py
rm -f ".restart" 2>/dev/null
fi
echo ""
echo "🎉 All steps completed!"
echo "結束: $(date)"
Executable
+112
View File
@@ -0,0 +1,112 @@
#!/bin/bash
set -e
# ==============================================================================
# MiniMax-H3 REF2VA 4-step runner (單權重架構)
# 用法: ./run_refh3.sh <project_name> [step]
# step 省略 = 依序跑全部 4 步
# 1 = Video VAE 編碼參考圖 (video VAE 1.6G) → result1_ref_*.pt
# 2 = Text encoder 編 prompt (text encoder 15G) → result2_text_*.pt
# 3 = DiT 去噪 (ref2va DiT 16G) → result3_video/audio_*.pt
# 4 = Video+Audio VAE 解碼 (video+audio VAE 1.9G)→ ref2va_output_*.mp4
#
# 單權重保證: 每個 step 是獨立 process, 任一時刻 DRAM/VRAM 只有一個大權重。
# 多視頻保證: 每 step 內 for-loop 跑完全部 N 個視頻, 權重只載入一次。
# ==============================================================================
if [ -z "$1" ]; then
echo "Usage: ./run_refh3.sh <project_name> [step]"
echo "Example: ./run_refh3.sh Du 3"
echo "Step options (4-step single-weight architecture):"
echo " 1 = Video VAE encode reference images (video VAE ~1.6GB) -> result1_ref_*.pt"
echo " 2 = Text encoder encode prompts (text encoder NF4 ~15GB) -> result2_text_*.pt"
echo " 3 = DiT denoise (ref2va NF4 ~16GB) -> result3_video/audio_*.pt"
echo " 4 = Video+Audio VAE decode (VAEs ~1.9GB) -> ref2va_output_*.mp4"
echo "Omit step to run all 4 in order."
exit 1
fi
PROJECT_NAME=$1
STEP=$2
BASE_DIR="/home/mikehu/data/AI/minimax-h3"
PROJECT_DIR="$BASE_DIR/outputs/$PROJECT_NAME"
VENV_PYTHON="$BASE_DIR/.venv/bin/python"
export PYTORCH_CUDA_ALLOC_CONF="max_split_size_mb:256,garbage_collection_threshold:0.8"
echo "----------------------------------------------------------------"
echo "🚀 Initializing MiniMax-H3 REF2VA Project: $PROJECT_NAME"
echo "📂 Project Dir: $PROJECT_DIR"
echo "----------------------------------------------------------------"
# Create project directory
mkdir -p "$PROJECT_DIR"
# Copy template config.py to the project directory if it doesn't exist
if [ ! -f "$PROJECT_DIR/config.py" ]; then
cp "$BASE_DIR/config_template_ref2va.py" "$PROJECT_DIR/config.py"
echo "📝 Copied ref2va template config.py to project folder. Please edit it (especially 'references')."
else
echo "📄 Using existing project config.py."
fi
# CRITICAL: Change working directory to the project folder
# This ensures that the steps read ./config.py and all relative
# result*.pt paths are saved/loaded in the project directory.
cd "$PROJECT_DIR"
# Ref2VA 專屬提示: references 為空時 Ref2VA 無法運作 (至少 1 張參考圖)
if ! grep -Eq "references[[:space:]]*=[[:space:]]*\\[[[:space:]]*['\"][^'\"]+" "$PROJECT_DIR/config.py"; then
echo "⚠️ config.py 的 'references' 是空的 — Ref2VA 需要至少 1 張參考圖。"
echo " 請編輯 $PROJECT_DIR/config.py 填入 1~9 張參考圖路徑。"
fi
# Validate step argument if provided
if [ -n "$STEP" ] && [[ ! "$STEP" =~ ^[1-4]$ ]]; then
echo "Error: Step must be 1, 2, 3, or 4."
exit 1
fi
echo -e "\n----------------------------------------------------------------"
if [ -z "$STEP" ] || [ "$STEP" == "1" ]; then
echo -e "\n[1/4] Step 1: Video VAE 編碼參考圖 (video VAE ~1.6GB)"
$VENV_PYTHON $BASE_DIR/ref2va_step1.py
# 共識驗算: 同源參考圖的 result1_ref_*.pt 多數決檢查 (binary cmp → 內容 → error)
# exit 10 = 已刪異常檔 → 重跑 step1 補跑後再查; exit 11 = 無法決定, 需人工介入
CHECK_EXIT=0
$VENV_PYTHON $BASE_DIR/ref2va_check_refs.py || CHECK_EXIT=$?
if [ "$CHECK_EXIT" == "10" ]; then
echo ">> [CHECK] 發現異常檔, 重跑 step1 補跑被刪的 task..."
$VENV_PYTHON $BASE_DIR/ref2va_step1.py
$VENV_PYTHON $BASE_DIR/ref2va_check_refs.py || CHECK_EXIT=$?
fi
if [ "$CHECK_EXIT" -ge "11" ]; then
echo ">> [CHECK] exit $CHECK_EXIT: 無法判定, 請人工檢查後重跑 step1。"
exit $CHECK_EXIT
fi
rm -f ".restart" 2>/dev/null
fi
if [ -z "$STEP" ] || [ "$STEP" == "2" ]; then
echo -e "\n[2/4] Step 2: Text encoder 編碼 prompt (text encoder NF4 ~15GB)"
$VENV_PYTHON $BASE_DIR/ref2va_step2.py
rm -f ".restart" 2>/dev/null
fi
if [ -z "$STEP" ] || [ "$STEP" == "3" ]; then
echo -e "\n[3/4] Step 3: DiT 去噪 (ref2va NF4 ~16GB)"
$VENV_PYTHON $BASE_DIR/ref2va_step3.py
rm -f ".restart" 2>/dev/null
fi
if [ -z "$STEP" ] || [ "$STEP" == "4" ]; then
echo -e "\n[4/4] Step 4: Video+Audio VAE 解碼 -> mp4 (video VAE ~1.6GB + audio VAE ~0.27GB)"
$VENV_PYTHON $BASE_DIR/ref2va_step4.py
rm -f ".restart" 2>/dev/null
fi
echo -e "\n----------------------------------------------------------------"
echo "✅ Ref2VA Project $PROJECT_NAME Completed Successfully!"
echo "All assets (config, .pt, .mp4) are located in: $PROJECT_DIR"
echo "----------------------------------------------------------------"
date
+111
View File
@@ -0,0 +1,111 @@
# 劇本:《最後的航線:建華之約》
本劇本設計用於 MiniMax H3 (Audio+Video) 模型,強調視覺特徵的固定與音效的沉浸感。
## 第一部分:視覺錨點 (Visual Anchors)
### 1. 核心物件:【榮貴其眉】畫作
- **視覺描述**:一幅具有民初風格的中國傳統水墨畫,筆觸靈動,意境高雅,畫風清麗且富有文人氣息。畫上帶有「余靜芝」的印章與題字。
- **關鍵詞**:`Traditional early 20th century Chinese ink wash painting, elegant brushwork, scholarly style, with red seal and calligraphy \"Yu Jingzhi\", vintage rice paper texture.`
### 2. 王恭 (4th Grandfather)
- **特徵描述**:中年男子,約 43 歲。面容清瘦但眼神銳利堅定,典型 1940 年代中國軍官風範。留著整齊的短髮,眉骨較高,唇線緊閉。
- **固定服裝**:深藍色空軍軍官制服,領口挺拔,佩戴軍階肩章。
- **關鍵詞**:`Sharp gaze, determined expression, 1940s Chinese Air Force officer, lean face, short neat hair.`
### 3. 王行 (字稚倫) (Grandfather)
- **特徵描述**:約 33 歲。面相較為溫潤,眼神中透露出對家人的深切關懷與焦慮。
- **固定服裝**:深色中式棉麻長衫或當時的平民便裝。
- **關鍵詞**:`Kind but anxious eyes, traditional 1940s Chinese civilian cotton clothes, gentle facial features.`
### 4. 吳建華 (Wu Jianhua)
- **特徵描述**:氣場強大,面相威嚴且成熟。作為飛行隊長,同時是王恭的大學同學(杭州筧橋空軍官校),看向王恭時眼神中帶著複雜的情誼。
- **固定服裝**:空軍飛行隊長制服,佩戴多枚勳章,著黑色軍靴。
- **關鍵詞**:`Authoritative presence, mature face, high-ranking Air Force commander, stern but emotional eyes.`
### 5. 華潔如與駱夫人 (Grandmother & 4th Grandmother)
- **特徵描述**:典型的 1940 年代江南名門女性,面容清秀但憔悴,頭髮盤起,舉止端莊,帶著名門閨秀的氣韻。
- **固定服裝**:深色素色旗袍或簡單的布衫,披著深色披肩。
- **關鍵詞**:`Traditional 1940s Chinese women, hair tied in a bun, simple dark-colored qipao or cotton dress.`
### 6. 王家大女兒 (10歲) (Eldest Aunt)
- **特徵描述**:10 歲小女孩,圓臉,大眼睛,眼神中充滿恐懼與不安。
- **固定服裝**:簡單的棉質童裝,紮著兩根小辮子。
- **關鍵詞**:`10-year-old Chinese girl, round face, wide frightened eyes, two small pigtails, simple vintage cotton child clothing.`
---
## 第二部分:分場劇本
**語言**:中文普通話
**音效風格**:溫馨 $\rightarrow$ 壓抑 $\rightarrow$ 極度緊張 $\rightarrow$ 釋然
### 【序幕:時光的禮物】
- **視覺場景**:
- **畫面 1**:【極近特寫】鏡頭緩慢地在水墨畫的紋理上掃過,聚焦在「榮貴其眉」的題字與「余靜芝」的紅印上。
- **畫面 2**:【淡入/切換】畫作逐漸轉化為現實場景 $\rightarrow$ 民國 37 年春,杭州的一場婚禮。紅色的喜字、喧鬧的人群,年輕的王行與華潔如相視而笑,滿臉幸福。
- **畫面 3**:【切換】婚禮會場的一角,王恭穿著挺拔的軍裝,與王行 (稚倫)熱情握手、拍肩打招呼,背景是春意盎然的杭州街頭。
- **畫面 4**:【快速蒙太奇】畫面快速切換 $\rightarrow$ 飛機在藍天白雲中飛翔 $\rightarrow$ 王恭熟練地操作儀表 $\rightarrow$ 飛機降落在基隆,搬運平凡的米糧木箱。[旁白:民國 37 年,抗戰勝利。王行 (稚倫)回到了杭州,迎娶了華潔如。那一年,生活像春天一樣充滿希望。]
- **音效設計**:
- **SFX**:輕柔的古箏或琵琶聲 $\rightarrow$ 轉為嘈雜歡快的婚禮鑼鼓聲 $\rightarrow$ 轉為飛機引擎的穩定轟鳴聲。
### 第一幕:禁忌的發現
- **視覺場景**:
- **畫面 1**:機艙內,昏暗的黃色燈光。王恭在搬運物資,周圍是堆積如山的木箱。
- **畫面 2**:一個木箱在搬運中意外鬆脫,蓋子開了一條縫。王恭好奇地看向內部。
- **畫面 3**:【特寫】箱內不是米糧,而是包裹在絲綢中的**精美青銅器與古舊卷軸**,在微光下閃著幽光(故宮國寶)。
- **畫面 4**:王恭臉上的表情從疑惑 $\rightarrow$ 震驚 $\rightarrow$ 恐懼。[對白(王恭低聲驚呼):這不是物資……這是國寶。這不是普通的搬運……他們是要全面撤退到台灣了!]
- **音效設計**:
- **SFX**:沉重的木箱摩擦聲 $\rightarrow$ 木蓋開啟的細微吱呀聲 $\rightarrow$ 心跳加速的強烈鼓點聲。
### 第二幕:抗命的決斷
- **視覺場景**:
- **畫面 1**:基隆機場跑道,強風吹過,旗幟獵獵作響。王恭與吳建華面對面激烈爭論。
- **畫面 2**:隊長吳建華面色鐵青,大聲斥責,手指著地面(下令原地待命)。[對白(吳建華大吼):你瘋了!現在回去就是死路一條!原地待命是命令!]
- **畫面 3**:王恭激動地揮手,眼神中帶著絕望的堅定。[對白(王恭嘶吼):我的家人還在杭州!我必須回去!]
- **畫面 4**:王恭轉身,毅然登上飛機,關上機艙門。
- **畫面 5**:飛機在油量不足的情況下,強行加速起飛,機身劇烈搖晃,向西衝向雲海。
- **音效設計**:
- **SFX**:巨大的風聲 $\rightarrow$ 激烈的爭吵聲 $\rightarrow$ 飛機引擎發動的轟鳴聲 $\rightarrow$ 輪胎摩擦跑道的尖叫聲。
### 第三幕:黑暗中的逃亡
- **視覺場景**:
- **畫面 1**:杭州家中,昏暗的燈光。王行 (稚倫)與駱夫人急促地將衣物塞入舊皮箱。
- **畫面 2**:【特寫】華潔如在混亂中看到牆上掛著的那幅**《榮貴其眉》**。她停頓了一秒,眼神中流露出不捨與眷戀。
- **畫面 3**:華潔如小心翼翼地將畫作取下,用綢布層層包裹,緊緊抱在懷中,將其塞進最安全的皮箱底部。
- **畫面 4**:王行 (稚倫)的父母站在陰影中,面色凝重地搖頭,身影顯得格外單薄。
- **畫面 5**:夜晚的樹林,一輛黑色的車熄燈移動著,僅靠月光前進。車子差一點衝入西湖,還好即時發現緊急煞車,沒有讓車子衝進湖中。
- **畫面 6**:車內特寫——華潔如緊緊抱著襁褓中的嬰兒(王貽媺),駱夫人懷中抱著另一個嬰兒(王緒),10 歲的大女兒在後座瑟瑟發抖。[對白(家屬低聲問):為什麼不開車燈?]
- **畫面 7**:驚險一幕——車頭幾乎觸碰到西湖的水面,王行 (稚倫)在黑暗中猛打方向盤,車身劇烈傾斜。[對白(王行低聲回答):因為要避免被敵軍發現燈光,不然對方會朝這個方向開火]
- **音效設計**:
- **SFX**:急促的呼吸聲 $\rightarrow$ 綢布包裹畫作的摩擦聲 $\rightarrow$ 汽車引擎低沉的喘息聲 $\rightarrow$ 遠處傳來的隱約槍炮聲。
### 第四幕:生死加油站
- **視覺場景**:
- **畫面 1**:凌晨的杭州機場,天空是壓抑的深紫色。飛機停在跑道上,四周空無一人。
- **畫面 2**:混亂的場景——王行 (稚倫)催促著家人瘋狂奔向機艙。[對白(王行 (稚倫)大喊):快!快上飛機!]
- **畫面 3**:【特寫/慢動作】王行 (稚倫) 吃力地舉著生鏽的鐵製汽油桶,在飛機油箱口處,劇烈地將汽油倒入。[對白(王行 (稚倫)低聲催促):快點!就差這一桶!快快快!]
- **畫面 4**:【特寫】王行 (稚倫) 盯著油嘴和油孔,確保汽油盡量不要灑出來;而鏡頭切換到駕駛艙內,王恭面色凝重,死死盯著飛機的油表,手指焦躁地敲擊著儀表板,等待油量達標。
- **畫面 5**:遠方地平線突然亮起紅光,共軍的黑色卡車與士兵衝入機場,封鎖線迅速合攏。
- **音效設計**:
- **SFX**:沉重的腳步奔跑聲 $\rightarrow$ 汽油倒入油箱的「咕嚕咕嚕」聲 $\rightarrow$ 遠方如雷鳴般的卡車引擎聲 $\rightarrow$ 士兵的吶喊聲。
### 第五幕:炮火中的新生
- **視覺場景**:
- **畫面 1**:飛機在跑道上瘋狂加速。隨後鏡頭切到駕駛艙內,王恭用力拉起操作桿,飛機前端猛然抬高。
- **畫面 2**:起飛的一瞬間,剛剛衝進機場的士兵從後方用步槍射擊,試圖阻止飛機起飛。
- **畫面 3**:飛機起飛之後,地面高射砲火也跟著開砲,巨大的橘紅色火球在機翼旁炸開。飛機在炮火中劇烈顛簸,像一隻受驚的鳥,拼命向上盤旋穿透雲層。
- **畫面 4**:俯視視角——杭州城的火光在下方漸漸變小,直到被厚厚的白雲遮蓋。
- **畫面 5**:最終畫面——飛機在台灣的陽光下緩緩降落,家人們走出機艙,眼神中從恐懼轉為深深的釋然。[旁白:在炮火中,他們逃出了那個時代的毀滅。這一次起飛,決定了我們家族之後的命運。]
- **音效設計**:
- **SFX**:引擎達到極限的轟鳴聲 $\rightarrow$ 震耳欲聾的高射砲爆炸聲 $\rightarrow$ 劇烈的機身抖動聲 $\rightarrow$ 逐漸轉為寧靜的風聲 $\rightarrow$ 輕柔的背景音樂起。
### 【尾聲:傳承】
- **視覺場景**:
- **畫面 1**:【淡出/切換】從飛機降落在台灣的陽光中 $\rightarrow$ 畫面漸變 $\rightarrow$ 切換到 2026 年現代家中。
- **畫面 2**:【慢速推近】鏡頭對準家中牆上端正掛著的那幅**《榮貴其眉》**。畫作雖然有了歲月的痕跡,但依然高雅。
- **畫面 3**:鏡頭拉遠,可以看到家人在畫作前交談的背影,陽光灑在畫作上。
- **畫面 4**:畫面漸黑,出現最後一行字。
- **音效設計**:
- **SFX**:飛機引擎聲漸弱 $\rightarrow$ 轉為溫馨的現代居家環境音 $\rightarrow$ 溫暖的鋼琴曲收尾。
- **結尾文字**:建華新村,以那位在生死關頭選擇情誼與勇氣的長官命名。而這幅畫,記錄了我們從杭州到台灣的生存與記憶。
+46
View File
@@ -0,0 +1,46 @@
# 🏄‍♀️ 衝浪女孩 (Surf Girl) 影片生產劇本
## 1. 視覺錨點 (Visual Anchor)
**核心角色定義**:
> 一位美麗的東亞女性,留著長而順滑的黑髮,皮膚呈現健康的古銅色,體態健美且具有運動感,身穿一件亮眼的**青綠色 (Turquoise) 繫帶比基尼**。
**環境定義**:
> 熱帶海灘,純淨的白色沙灘,清澈透明的青綠色大海,極致的 4K 真實感。
---
## 2. 分鏡腳本 (Storyboard)
### Stage 1: 登場 (Introduction)
* **畫面描述**:電影級寬幅鏡頭。女性站在白色沙灘上,面向大海,海風輕輕吹動黑髮,展現出對大海的嚮往與寧靜。
* **核心 Prompt**:`A cinematic wide shot of a beautiful East Asian woman with long sleek black hair, tanned skin, athletic build, wearing a turquoise string bikini, standing on a white sandy beach, looking at the ocean, high quality, 4k, realistic.`
* **預期氛圍**:寧靜、開端。
### Stage 2: 準備 (Preparation)
* **畫面描述**:特寫鏡頭。她正專注地為衝浪板打蠟,眼神堅定,背景是模糊的白色沙灘,光影細膩。
* **核心 Prompt**:`Close up of the woman waxing her surfboard, determined expression, turquoise string bikini, white sandy beach background, cinematic lighting, 4k, realistic.`
* **預期氛圍**:專注、準備就緒。
### Stage 3: 等待 (The Wait) —— **關鍵片段**
* **畫面描述**:從斜上方拍攝的寬幅高角度鏡頭。海中聚集了來自不同國籍(英、日、韓)的衝浪者。她處於人群之中,遠方一道巨大的、充滿力量的青綠色巨浪正穩定地向岸邊推進。
* **核心 Prompt**:`A high-oblique wide angle shot from slightly above. A crowd of surfers (men and women) from different nationalities (English, Japanese, Korean) are waiting in the water. The woman in a turquoise string bikini is among them. In the distance, a massive, powerful turquoise wave is steadily moving towards the shore. Cinematic epic scale, 4k, highly detailed ocean foam.`
* **建議時長**:175 幀
* **預期氛圍**:史詩感、緊張的鋪墊。
### Stage 4: 起乘 (The Pop-up) —— **核心高潮**
* **畫面描述**:極具衝擊力的動作鏡頭。巨大的白色浪花與流體動力將她向上推起,她以爆發性的速度與力量完成 pop-up 動作,迅速從俯臥轉為站立。水花四濺,充滿速度感。
* **核心 Prompt**:`An intense action shot. A massive wall of white water foam and hydrodynamic lift pushes the woman in a turquoise string bikini upward. She pops up from the water with explosive speed and power, transitioning into a standing position on her board. High speed, motion blur, water splashes everywhere, cinematic 4k, extreme energy.`
* **預期氛圍**:爆發力、速度、巔峰動作。
### Stage 5: 馭浪 (Riding the Wave)
* **畫面描述**:中景追隨鏡頭。她熟練地在巨浪的管壁上滑行,身體與衝浪板保持完美平衡,切開水面,周圍飛濺起晶瑩的浪花。
* **核心 Prompt**:`The woman in a turquoise string bikini is skillfully riding the giant turquoise wave, balanced perfectly on her surfboard, cutting through the water, epic spray, cinematic 4k, realistic water physics.`
* **預期氛圍**:優雅、掌控力、巔峰享受。
---
## 3. 技術執行參數 (Technical Specs)
* **解析度**:$1344 \times 768$ (高清)
* **幀數**:預設 $124 \text{ 幀}$ (確保 VRAM 穩定),若有 **建議時長** 則使用該時長,並做出可能會OOM的提示
* **量化**:NF4 (DiT & VAE)
* **Seed**:42 (維持角色一致性)