File size: 4,579 Bytes
f2a1383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""Load the released E8T1-shared1 package with original FL2VA AdaLN.

The package is not a fused checkpoint. This loader reads the official FL2VA
shards, copies neuron triplets from init.json, injects the step-60 Router and
LoRA; block AdaLN stays in the original dense model.
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import torch

DEPLOY = Path(__file__).resolve().parent
PACKAGE = DEPLOY.parent
# The snapshot must win over any diffsynth already installed in the environment.
sys.path.insert(0, str(DEPLOY / "code"))
sys.path.insert(0, str(DEPLOY))

from shared_moe import apply_shared_e8t1

LORA_TARGET = r".*blocks\.(1[5-9]|2[0-9]|3[0-4])\.mlp\.(shared|experts\.[0-7])\.fc[12]"
MOE_LAYERS = tuple(range(15, 35))


def model_files(folder: Path) -> list[str]:
    files = sorted(folder.glob("model-*.safetensors"))
    if not files:
        raise FileNotFoundError(folder)
    return [str(p) for p in files]


def assert_snapshot_dit() -> str:
    import inspect
    from diffsynth.models.minimax_h3_dit import MiniMaxH3DiT

    source_file = inspect.getfile(MiniMaxH3DiT)
    expected = DEPLOY / "diffsynth" / "models" / "minimax_h3_dit.py"
    if Path(source_file).resolve() != expected.resolve():
        raise RuntimeError(
            "加载到的 MiniMaxH3DiT 不是本包的快照:"
            f"{source_file}。请让 {DEPLOY} 位于 PYTHONPATH 最前,"
            "不要用官方 DiffSynth 覆盖 deploy/diffsynth。"
        )
    return source_file


def load_pipeline(package: Path | None = None, device: str | torch.device = "cuda:0"):
    """Return (pipeline, info). info records the load that just happened."""
    package = Path(package) if package is not None else PACKAGE
    dit_file = assert_snapshot_dit()
    from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3Pipeline, ModelConfig
    from peft import LoraConfig, inject_adapter_in_model
    from safetensors.torch import load_file

    dev = torch.device(device)
    if dev.type != "cuda":
        raise ValueError("这条加载路径按单卡 CUDA 写,和 16 条评测相同")
    fl2va = package / "FL2VA"
    init_path = package / "init.json"
    checkpoint = package / "step-60.safetensors"
    for path in (fl2va, init_path, checkpoint):
        if not path.exists():
            raise FileNotFoundError(path)

    vram = dict(
        offload_dtype=torch.bfloat16, offload_device="cpu",
        onload_dtype=torch.bfloat16, onload_device="cpu",
        preparing_dtype=torch.bfloat16, preparing_device=dev,
        computation_dtype=torch.bfloat16, computation_device=dev,
    )
    pipe = MiniMaxH3Pipeline.from_pretrained(
        torch_dtype=torch.bfloat16, device=dev,
        model_configs=[
            ModelConfig(path=model_files(fl2va / "text_encoder"), **vram),
            ModelConfig(path=model_files(fl2va / "transformer"), **vram),
            ModelConfig(path=str(fl2va / "video_vae/source/model.safetensors"), **vram),
            ModelConfig(path=str(fl2va / "audio_vae/model.safetensors"), **vram),
        ],
        processor_config=ModelConfig(path=str(fl2va / "processor")),
        vram_limit=torch.cuda.mem_get_info(dev)[1] / (1024 ** 3) - 4,
    )
    dense_count = sum(p.numel() for p in pipe.dit.parameters())
    init = json.loads(init_path.read_text())
    apply_shared_e8t1(pipe.dit, init, MOE_LAYERS)
    pipe.dit = inject_adapter_in_model(
        LoraConfig(r=64, lora_alpha=64, target_modules=LORA_TARGET), pipe.dit)
    state = load_file(str(checkpoint), device="cpu")
    missing, unexpected = pipe.dit.load_state_dict(state, strict=False)
    if unexpected:
        raise RuntimeError(f"checkpoint key mismatch: {unexpected[:8]}")
    if any(k.endswith("mlp.router.weight") for k in missing):
        raise RuntimeError("checkpoint lacks trained routers")
    # Inserted after the CPU-offload wrap, so these modules do not move themselves.
    for i in MOE_LAYERS:
        pipe.dit.blocks[i].mlp.to(device=dev)
    pipe.dit.eval()

    original_ffn = 3 * 5376 * 14336
    active = dense_count - len(MOE_LAYERS) * original_ffn
    for i in MOE_LAYERS:
        spec = init[str(i)]
        active += 3 * 5376 * (len(spec["shared_indices"]) + len(spec["private_indices"][0]))
        active += 8 * 5376
    info = {
        "package": str(package),
        "dit_source": dit_file,
        "variant": "shared",
        "checkpoint": str(checkpoint),
        "active_main_dit_B": active / 1e9,
        "dense_main_dit_B": dense_count / 1e9,
        "cfg_scale": 1.0,
    }
    return pipe, info