291 lines
12 KiB
Python
291 lines
12 KiB
Python
#!/home/mikehu/data/AI/minimax-h3/.venv/bin/python
|
|
import gc
|
|
import torch
|
|
|
|
# 強制啟用 PyTorch ROCm 的記憶體高效與 Flash 注意力後端
|
|
torch.backends.cuda.enable_flash_sdp(True)
|
|
torch.backends.cuda.enable_mem_efficient_sdp(True)
|
|
torch.backends.cuda.enable_math_sdp(False) # 關閉最吃顯存的原生 Math 計算
|
|
|
|
"""
|
|
[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()
|