File size: 2,613 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
60
61
62
63
64
65
66
67
68
69
70
"""Which layers make INT8 weight-only lossy? Compress dit_c (blocks 23-41 + head) with different ignored scopes, run cases A/B/C
(inputs = the fp32 reference activations, so only this segment's error is measured) and print the velocity error.
Usage: python exp_int8.py [--segment dit_c] [--configs name1,name2]"""
import argparse
import sys
import time

import numpy as np

sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
from common import MODELS, WORK  # noqa: E402
from dit_ops import rope_table, time_mod  # noqa: E402

T = {"A": 1000.0, "B": 500.0, "C": 100.0}
SKIP = {"A": False, "B": True, "C": False}
CTX = {"A": "ctx_scene", "B": "ctx_empty", "C": "ctx_scene"}
CONFIGS = {
    "asym": dict(mode="INT8_ASYM"),
    "g128": dict(group=128),
    "g64": dict(group=64),
    "g32": dict(group=32),
}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--segment", default="dit_c")
    ap.add_argument("--configs", default=",".join(CONFIGS))
    a = ap.parse_args()
    import nncf
    import openvino as ov

    ref = np.load(f"{WORK}/dit_ref_sft.npz")
    hw = dict(np.load(f"{MODELS}/dit_sft/host_weights.npz"))
    lat = ref["latents"]
    h, w = lat.shape[2:]
    N = h * w
    core = ov.Core()
    for cname in a.configs.split(","):
        cfg = CONFIGS[cname]
        t = time.time()
        m = core.read_model(f"{MODELS}/dit_sft/{a.segment}.xml")
        if cfg.get("group"):
            from int8group import compress

            print("  weights changed:", compress(m, cfg["group"]), flush=True)
            mc = m
        else:
            mc = nncf.compress_weights(m, mode=getattr(nncf.CompressWeightsMode, cfg["mode"]))
        t_c = time.time() - t
        cm = core.compile_model(mc, "GPU")
        req = cm.create_infer_request()
        row = []
        for case in "ABC":
            ctx = ref[CTX[case]]
            L = ctx.shape[1]
            rope = rope_table(h, w, L)
            mod, head = time_mod(hw, T[case])
            x_in = ref[f"after_21_{case}"] if SKIP[case] else ref[f"after_22_{case}"]
            v = np.array(next(iter(req.infer({"x": x_in, "rope": rope, "mod": mod, "head": head, "n_img": np.zeros((1, N, 1), np.float32)}).values())))
            v = v.transpose(0, 2, 1).reshape(1, 128, h, w)
            r = ref[f"v_{case}"]
            row.append(float(np.linalg.norm(v - r) / np.linalg.norm(r)))
        print(f"[exp] {a.segment} {cname:24s} rel_l2 A {row[0]:.4f}  B {row[1]:.4f}  C {row[2]:.4f}   (compress {t_c:.0f} s)", flush=True)
        del cm, req, mc, m


if __name__ == "__main__":
    main()