File size: 2,215 Bytes
565b868
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export the MOSS-Image DiT (SFT or Base) as 4 OpenVINO IRs (text_refine, dit_a, dit_b, dit_c). CPU only.

Usage: python dit_export.py --which sft [--segs text_refine,dit_a,dit_b,dit_c] [--dtype f16]
"""
import argparse
import json
import os
import sys

import numpy as np
import torch

sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
from common import MODELS, Timer, hwm_gb  # noqa: E402


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--which", default="sft", choices=["sft", "base"])
    ap.add_argument("--segs", default="text_refine,dit_a,dit_b,dit_c")
    ap.add_argument("--dtype", default="f16", choices=["f16", "f32"])
    args = ap.parse_args()
    import openvino as ov

    from dit_ops import build_segments, host_weights

    dtype = torch.float16 if args.dtype == "f16" else torch.float32
    out = f"{MODELS}/dit_{args.which}"
    os.makedirs(out, exist_ok=True)
    torch.set_num_threads(8)
    for name in args.segs.split(","):
        with Timer(f"build {name}"):
            segs = build_segments(args.which, dtype, only=name)
        mod, ex, specs, outnames = segs[name]
        print(f"[mem] hwm after build: {hwm_gb():.1f} GB", flush=True)
        with Timer(f"convert {name}"):
            m = ov.convert_model(
                mod,
                example_input=ex,
                input=[(shape, ov.Type.f32) for _, shape in specs],
            )
        print(f"[mem] hwm after convert: {hwm_gb():.1f} GB", flush=True)
        for i, (nm, _) in enumerate(specs):
            m.inputs[i].get_tensor().set_names({nm})
        m.outputs[0].get_tensor().set_names({outnames[0]})
        path = f"{out}/{name}.xml"
        with Timer(f"save {name}"):
            ov.save_model(m, path, compress_to_fp16=(args.dtype == "f16"))
        print("[saved]", path, os.path.getsize(path.replace(".xml", ".bin")) / 1e9, "GB", flush=True)
        del m, mod, segs
    # host weights for time embedding / modulation (fp32 numpy)
    if not os.path.exists(f"{out}/host_weights.npz"):
        np.savez(f"{out}/host_weights.npz", **host_weights(args.which))
        print("[saved] host_weights.npz")


if __name__ == "__main__":
    main()