239 lines
8.8 KiB
Python
239 lines
8.8 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 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:02d}.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:02d}.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 drop_file_cache(filepath):
|
|
"""
|
|
告知內核不需要快取該檔案的內容,釋放 Page Cache。
|
|
"""
|
|
try:
|
|
with open(filepath, 'rb') as f:
|
|
fd = f.fileno()
|
|
os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)
|
|
print(f">> [Cache] Dropped page cache for {filepath}")
|
|
except Exception as e:
|
|
print(f">> [Cache] Failed to drop cache for {filepath}: {e}")
|
|
|
|
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:02d}.pt"):
|
|
print(f">> [Error] Task {idx} 缺少 result1_ref_{idx:02d}.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,
|
|
)
|
|
|
|
# 釋放權重檔的 Page Cache,避免 DRAM 雙倍佔用
|
|
text_encoder_path = os.path.join(MODELS_DIR, "text_encoders/minimax-h3-text-encoder-nf4.safetensors")
|
|
drop_file_cache(text_encoder_path)
|
|
|
|
# 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:02d}.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:02d}.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()
|