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
+96
View File
@@ -0,0 +1,96 @@
#!/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
# 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
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 move_to_cuda(obj):
if isinstance(obj, torch.Tensor): return obj.to("cuda")
if isinstance(obj, dict): return {k: move_to_cuda(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)): return type(obj)(move_to_cuda(x) for x in obj)
return obj
def main():
print("\n========== [FL2VA STAGE 1] Text Encoder 批處理 ==========")
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_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,
)
enabled_ids = get_enabled_tasks()
num_iterations = RUN_CONFIG.get("num_iterations", 1)
for loop_idx in range(num_iterations):
for task_idx in enabled_ids:
task = TASK_REGISTRY[task_idx]
prompt = task.prompts[0] if task.prompts else ""
save_name = f"result1_te_{task_idx}_l{loop_idx}.pt"
print(f">> [Loop {loop_idx}][Task {task_idx}] Encoding: {prompt[:50]}...")
with torch.no_grad():
from diffsynth.models.minimax_h3_text_encoder import presentation_t2va
# 1. Get Token IDs and text_token_tags
input_ids, text_token_tags = presentation_t2va(pipe.tokenizer, prompt)
ids = input_ids.unsqueeze(0).to(pipe.device)
kwargs = {"input_ids": ids, "attention_mask": torch.ones_like(ids)}
# 2. Call Text Encoder to get features
hidden = pipe.text_encoder(**kwargs)
# Save both prompt_embeds and text_token_tags as a dict
torch.save({
"prompt_embeds": hidden.detach().cpu(),
"text_token_tags": text_token_tags.cpu()
}, save_name)
print(f">> [SUCCESS] Saved to {save_name}")
print("\n========== [FL2VA STAGE 1] 所有任務完成! ==========")
if __name__ == "__main__":
main()