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
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()