Initial commit: source code for minimax-h3
This commit is contained in:
Executable
+212
@@ -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()
|
||||
Reference in New Issue
Block a user