218 lines
8.5 KiB
Python
218 lines
8.5 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 計算
|
|
|
|
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()
|