"""Weight-only MatMulNBits quantization of one exported part. usage: quant.py PART OUT_DIR BITS BLOCK [--sym] [--hi REGEX] [--hi-bits 8] Constant-weight Gemm nodes are rewritten as MatMul + Add first (the quantizer only handles MatMul). Nodes whose weight name matches --hi get --hi-bits (default 8); the rest get BITS. Writes OUT_DIR/PART/PART.onnx + 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) SP = Path("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad") ap = argparse.ArgumentParser() ap.add_argument("part") ap.add_argument("out_dir", type=Path) ap.add_argument("bits", type=int) ap.add_argument("block", type=int) ap.add_argument("--sym", action="store_true") ap.add_argument("--hi", default=r"Gemm_mm") ap.add_argument("--hi-bits", type=int, default=8) ap.add_argument("--hi-block", type=int, default=32) ap.add_argument("--src", default="onnx_fp32h") a = ap.parse_args() src = SP / a.src / a.part / f"{a.part}.onnx" dst = a.out_dir / a.part / f"{a.part}.onnx" dst.parent.mkdir(parents=True, exist_ok=True) t0 = time.time() model = onnx.load(str(src)) g = model.graph inits = {i.name: i for i in g.initializer} # Gemm(A, B, C) with constant B -> MatMul(A, B') + C new_nodes = [] for node in g.node: if node.op_type != "Gemm" or node.input[1] not in inits: new_nodes.append(node) continue attrs = {x.name: helper.get_attribute_value(x) for x in node.attribute} assert attrs.get("alpha", 1.0) == 1.0 and attrs.get("beta", 1.0) == 1.0 and not attrs.get("transA", 0) w = numpy_helper.to_array(inits[node.input[1]]) if attrs.get("transB", 0): w = w.T wname = f"gemm_w_{len(new_nodes)}" g.initializer.append(numpy_helper.from_array(np.ascontiguousarray(w), wname)) mm_out = node.output[0] + "_mm" new_nodes.append(helper.make_node("MatMul", [node.input[0], wname], [mm_out if len(node.input) > 2 else node.output[0]], name=f"{node.name}_mm")) if len(node.input) > 2: new_nodes.append(helper.make_node("Add", [mm_out, node.input[2]], [node.output[0]], name=f"{node.name}_add")) del g.node[:] g.node.extend(new_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) hi_re = re.compile(a.hi) const = {i.name for i in g.initializer} mm = [n for n in g.node if n.op_type == "MatMul" and n.input[1] in const] hi_nodes = [n.name for n in mm if hi_re.search(n.name)] lo_nodes = [n.name for n in mm if not hi_re.search(n.name)] def run(m, bits, block, include): # nodes_to_include is additive in this ORT version, so select by exclusion if not include: return m exclude = [n.name for n in m.graph.node if n.op_type == "MatMul" and n.name not in set(include)] cfg = DefaultWeightOnlyQuantConfig(block_size=block, is_symmetric=a.sym, bits=bits) q = MatMulNBitsQuantizer(m, bits=bits, block_size=block, is_symmetric=a.sym, nodes_to_exclude=exclude, algo_config=cfg) q.process() return q.model.model model = run(model, a.hi_bits, a.hi_block, hi_nodes) model = run(model, a.bits, a.block, lo_nodes) 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 node in model.graph.node: ops[node.op_type] = ops.get(node.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 ''} hi={len(hi_nodes)}@q{a.hi_bits}: " f"{size:.0f} MB, MatMulNBits={ops.get('MatMulNBits', 0)} MatMul left={ops.get('MatMul', 0)} " f"Gemm left={ops.get('Gemm', 0)} in {time.time()-t0:.0f}s", flush=True)