File size: 3,397 Bytes
4a1ea7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export the MOSS-Image text encoder (Qwen3.5-9B language model) as 4 OpenVINO IRs of 8 decoder layers each.

Also writes the token-embedding table as fp16 .npy (gather on host), plus a tiny json with the layout.
Usage: python te_export.py [--parts 0,1,2,3] [--dtype f16]  (CPU only, ~8 GB RAM per part)
"""
import argparse
import json
import os
import sys

import numpy as np
import torch

# ov.convert_model traces with check_trace=True, which re-runs the whole fp16 CPU forward (minutes under CPU
# contention). The tracing result is validated against the references afterwards, so skip the redundant check.
_orig_trace = torch.jit.trace
torch.jit.trace = lambda *a, **k: _orig_trace(*a, **{**k, "check_trace": False})

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


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--parts", default="0,1,2,3")
    ap.add_argument("--dtype", default="f16", choices=["f16", "f32"])
    ap.add_argument("--out", default=f"{MODELS}/te")
    args = ap.parse_args()
    import openvino as ov
    from openvino.frontend.pytorch import ConversionExtension, ModuleExtension

    from te_build import build_part, ST
    from te_ops import RecurrentAttentionCell, convert_recurrent_attention_cell

    dtype = torch.float16 if args.dtype == "f16" else torch.float32
    os.makedirs(args.out, exist_ok=True)
    st = ST(TE_DIR, "model.safetensors.index.json")

    # token embeddings -> fp16 npy (2 GB) for host-side gather
    emb_path = f"{args.out}/embed_tokens_f16.npy"
    if not os.path.exists(emb_path):
        with Timer("embed table"):
            e = st.get_f32("language_model.embed_tokens.weight")
            np.save(emb_path, e.astype(np.float16))
            del e

    L = 16
    cos, sin = text_rope(L)
    for k in [int(x) for x in args.parts.split(",")]:
        with Timer(f"build part {k}"):
            part = build_part(k, dtype, patch=True, st=st, cast_io=True)
        print(f"[mem] hwm after build: {hwm_gb():.1f} GB", flush=True)
        ex = (torch.randn(1, L, 4096), torch.from_numpy(cos), torch.from_numpy(sin))
        with Timer(f"convert part {k}"):
            m = ov.convert_model(
                part,
                example_input=ex,
                input=[([1, -1, 4096], ov.Type.f32), ([1, -1, 64], ov.Type.f32), ([1, -1, 64], ov.Type.f32)],
                extension=[
                    ModuleExtension(RecurrentAttentionCell, "RecurrentAttentionCellOp"),
                    ConversionExtension("RecurrentAttentionCellOp", convert_recurrent_attention_cell),
                ],
            )
        print(f"[mem] hwm after convert: {hwm_gb():.1f} GB", flush=True)
        for i, name in enumerate(["hidden", "cos", "sin"]):
            m.inputs[i].get_tensor().set_names({name})
        m.outputs[0].get_tensor().set_names({"out"})
        path = f"{args.out}/te_part{k}.xml"
        with Timer(f"save part {k}"):
            ov.save_model(m, path, compress_to_fp16=(args.dtype == "f16"))
        print("[saved]", path, flush=True)
        del m, part
    json.dump({"parts": TE_PARTS_INFO, "dtype": args.dtype}, open(f"{args.out}/layout.json", "w"))


TE_PARTS_INFO = [{"layers": [8 * k, 8 * k + 7], "final_norm": k == 3} for k in range(4)]

if __name__ == "__main__":
    main()