"""Two-pass MatMulNBits: nodes whose name matches --lo get LO bits, all other constant-weight MatMuls HI bits. usage: quant_mixed.py PART SRC OUT HI_BITS LO_BITS LO_REGEX [--block 32]""" import sys, re, logging, time from pathlib import Path import onnx from onnxruntime.quantization.matmul_nbits_quantizer import DefaultWeightOnlyQuantConfig, MatMulNBitsQuantizer logging.basicConfig(level=logging.WARNING) part, src, out, hi, lo, rx = sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]), re.compile(sys.argv[6]) t0 = time.time() m = onnx.load(str(src / part / f"{part}.onnx")) const = {i.name: i for i in m.graph.initializer} mm = [n for n in m.graph.node if n.op_type == "MatMul" and n.input[1] in const and len(const[n.input[1]].dims) == 2] lo_nodes = {n.name for n in mm if rx.search(n.name)}; hi_nodes = {n.name for n in mm} - lo_nodes def run(model, bits, include): ex = [n.name for n in model.graph.node if n.op_type == "MatMul" and n.name not in include] q = MatMulNBitsQuantizer(model, bits=bits, block_size=32, is_symmetric=False, nodes_to_exclude=ex, algo_config=DefaultWeightOnlyQuantConfig(block_size=32, is_symmetric=False, bits=bits)) q.process(); return q.model.model m = run(m, hi, hi_nodes); m = run(m, lo, lo_nodes) d = out / part; d.mkdir(parents=True, exist_ok=True) for f in d.glob("*"): f.unlink() onnx.save_model(m, str(d / f"{part}.onnx"), save_as_external_data=True, all_tensors_to_one_file=True, location=f"{part}.onnx.data", size_threshold=1024) print(f"{part}: hi={len(hi_nodes)}@q{hi} lo={len(lo_nodes)}@q{lo} {sum(f.stat().st_size for f in d.glob('*'))/1e6:.0f} MB in {time.time()-t0:.0f}s", flush=True)