File size: 4,445 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
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
"""Group-wise INT8 weight-only compression of an OpenVINO IR, written by hand because NNCF's INT8 modes are per-channel only
("Default values of `ratio` and `group_size` cannot be overridden").

Every MatMul whose weight input is a constant (Constant, or Constant -> Convert) gets the same decompression sub-graph NNCF writes for grouped INT4:
    Constant(u8 [out, in/g, g]) -> Convert(f16) -> Subtract(zero point u8 [out, in/g, 1] -> f16) -> Multiply(scale f16 [out, in/g, 1])
    -> Reshape([out, in]) -> Convert(f32)  -> MatMul
which the GPU plugin fuses into the matmul. Asymmetric (min/max per group), 8 bit. Weights whose input size is not a multiple of g use one group per row.

Library:  compress(model, group) -> number of weights changed.
CLI:      python int8group.py SRC_DIR DST_DIR [--files a.xml,b.xml] [--group 128]     (copies the .npz files next to the result)
"""
import argparse
import glob
import os
import shutil
import sys
import time

import numpy as np

sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))


def _weight_const(node):
    """The numpy f32 weights behind a MatMul's second input, or None when it is not a constant."""
    import openvino.opset13 as ops  # noqa: F401

    src = node.input_value(1).get_node()
    conv = None
    if src.get_type_name() == "Convert":
        conv = src
        src = src.input_value(0).get_node()
    if src.get_type_name() != "Constant":
        return None, None
    return src, conv


def compress(model, group=128):
    import openvino as ov
    import openvino.opset13 as ops

    changed = 0
    for node in list(model.get_ordered_ops()):
        if node.get_type_name() != "MatMul":
            continue
        const, conv = _weight_const(node)
        if const is None:
            continue
        target = node.get_input_element_type(1)      # what the MatMul consumed before: f16 (traced in f16) or f32
        w = np.asarray(const.data).astype(np.float32)
        if w.ndim != 2:
            continue
        tb = node.get_attributes().get("transpose_b", False)
        if not tb:
            w = np.ascontiguousarray(w.T)       # work as [out, in]; written back transposed below
        out_dim, in_dim = w.shape
        g = group if (group > 0 and in_dim % group == 0) else in_dim
        wg = w.reshape(out_dim, in_dim // g, g)
        lo, hi = wg.min(-1, keepdims=True), wg.max(-1, keepdims=True)
        lo, hi = np.minimum(lo, 0.0), np.maximum(hi, 0.0)               # the zero point must stay representable
        scale = np.maximum((hi - lo) / 255.0, 1e-12)
        zp = np.clip(np.round(-lo / scale), 0, 255)
        q = np.clip(np.round(wg / scale) + zp, 0, 255).astype(np.uint8)
        c_q = ops.constant(q)
        x = ops.convert(c_q, np.float16)
        x = ops.subtract(x, ops.convert(ops.constant(zp.astype(np.uint8)), np.float16))
        x = ops.multiply(x, ops.constant(scale.astype(np.float16)))
        x = ops.reshape(x, ops.constant(np.array([out_dim, in_dim], np.int64)), special_zero=False)
        if not tb:
            x = ops.transpose(x, ops.constant(np.array([1, 0], np.int64)))
        if target != x.get_output_element_type(0):
            x = ops.convert(x, target)
        node.input(1).replace_source_output(x.output(0))
        changed += 1
    model.validate_nodes_and_infer_types()
    return changed


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("src")
    ap.add_argument("dst")
    ap.add_argument("--files", default="")
    ap.add_argument("--group", type=int, default=128)
    a = ap.parse_args()
    import openvino as ov

    os.makedirs(a.dst, exist_ok=True)
    files = a.files.split(",") if a.files else sorted(os.path.basename(x) for x in glob.glob(f"{a.src}/*.xml"))
    for f in os.listdir(a.src):
        if f.endswith(".npz") and not os.path.exists(f"{a.dst}/{f}"):
            shutil.copy(f"{a.src}/{f}", f"{a.dst}/{f}")
    core = ov.Core()
    for f in files:
        t = time.time()
        m = core.read_model(f"{a.src}/{f}")
        n = compress(m, a.group)
        out = f"{a.dst}/{f}"
        ov.save_model(m, out, compress_to_fp16=True)
        print(f"[int8g{a.group}] {f}: {n} weights, {os.path.getsize(f'{a.src}/{f}'.replace('.xml', '.bin')) / 1e9:.2f} GB -> "
              f"{os.path.getsize(out.replace('.xml', '.bin')) / 1e9:.2f} GB ({time.time() - t:.0f} s)", flush=True)
        del m


if __name__ == "__main__":
    main()