File size: 3,341 Bytes
011a287 | 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 | """Weight-only MatMulNBits quantization of one exported detector part.
usage: quant_det.py PART SRC_DIR OUT_DIR BITS BLOCK [--sym] [--skip REGEX]
Constant-weight Gemm nodes become MatMul + Add first (the quantizer only handles MatMul).
MatMul nodes whose name matches --skip stay fp32. Writes OUT_DIR/PART/PART.onnx(+.data).
"""
from __future__ import annotations
import argparse
import logging
import re
import time
from pathlib import Path
import numpy as np
import onnx
from onnx import helper, numpy_helper
from onnxruntime.quantization.matmul_nbits_quantizer import DefaultWeightOnlyQuantConfig, MatMulNBitsQuantizer
logging.basicConfig(level=logging.WARNING)
ap = argparse.ArgumentParser()
ap.add_argument("part")
ap.add_argument("src", type=Path)
ap.add_argument("out", type=Path)
ap.add_argument("bits", type=int)
ap.add_argument("block", type=int)
ap.add_argument("--sym", action="store_true")
ap.add_argument("--skip", default=None)
a = ap.parse_args()
t0 = time.time()
src, dst = a.src / a.part / f"{a.part}.onnx", a.out / a.part / f"{a.part}.onnx"
dst.parent.mkdir(parents=True, exist_ok=True)
model = onnx.load(str(src))
g = model.graph
inits = {i.name: i for i in g.initializer}
nodes = []
for n in g.node:
if n.op_type != "Gemm" or n.input[1] not in inits:
nodes.append(n)
continue
at = {x.name: helper.get_attribute_value(x) for x in n.attribute}
assert at.get("alpha", 1.0) == 1.0 and at.get("beta", 1.0) == 1.0 and not at.get("transA", 0)
w = numpy_helper.to_array(inits[n.input[1]])
w = w.T if at.get("transB", 0) else w
wn = f"gemm_w_{len(nodes)}"
g.initializer.append(numpy_helper.from_array(np.ascontiguousarray(w), wn))
mo = n.output[0] + "_mm" if len(n.input) > 2 else n.output[0]
nodes.append(helper.make_node("MatMul", [n.input[0], wn], [mo], name=f"{n.name}_mm"))
if len(n.input) > 2:
nodes.append(helper.make_node("Add", [mo, n.input[2]], [n.output[0]], name=f"{n.name}_add"))
del g.node[:]
g.node.extend(nodes)
used = {i for n in g.node for i in n.input}
keep = [i for i in g.initializer if i.name in used]
del g.initializer[:]
g.initializer.extend(keep)
const = {i.name: i for i in g.initializer}
skip = re.compile(a.skip) if a.skip else None
# only 2-D constant weights with K divisible by the block are worth quantizing
exclude = [n.name for n in g.node if n.op_type == "MatMul" and (
n.input[1] not in const or len(const[n.input[1]].dims) != 2 or (skip and skip.search(n.name)))]
cfg = DefaultWeightOnlyQuantConfig(block_size=a.block, is_symmetric=a.sym, bits=a.bits)
q = MatMulNBitsQuantizer(model, bits=a.bits, block_size=a.block, is_symmetric=a.sym, nodes_to_exclude=exclude, algo_config=cfg)
q.process()
model = q.model.model
for f in dst.parent.glob("*"):
f.unlink()
onnx.save_model(model, str(dst), save_as_external_data=True, all_tensors_to_one_file=True,
location=f"{a.part}.onnx.data", size_threshold=1024)
ops: dict[str, int] = {}
for n in model.graph.node:
ops[n.op_type] = ops.get(n.op_type, 0) + 1
size = sum(f.stat().st_size for f in dst.parent.glob("*")) / 1e6
print(f"{a.part} q{a.bits} b{a.block}{' sym' if a.sym else ''}: {size:.0f} MB, MatMulNBits={ops.get('MatMulNBits', 0)} "
f"MatMul left={ops.get('MatMul', 0)} Gemm left={ops.get('Gemm', 0)} in {time.time()-t0:.0f}s", flush=True)
|