matmul_nbits_quantizer.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License. See License.txt in the project root for
  4. # license information.
  5. # --------------------------------------------------------------------------
  6. from __future__ import annotations
  7. import argparse
  8. import copy
  9. import logging
  10. import os
  11. import numpy as np
  12. import numpy.typing as npt
  13. import onnx
  14. from onnx.onnx_pb import GraphProto, ModelProto, NodeProto, TensorProto
  15. from onnxruntime.capi._pybind_state import quantize_matmul_4bits, quantize_matmul_8bits, quantize_qdq_matmul_4bits
  16. from .calibrate import CalibrationDataReader
  17. from .neural_compressor import gptq_quantize, rtn_quantize
  18. from .onnx_model import ONNXModel
  19. from .quant_utils import QuantFormat, attribute_to_kwarg
  20. logging.basicConfig(format="%(asctime)s %(name)s [%(levelname)s] - %(message)s", level=logging.INFO)
  21. logger = logging.getLogger(__name__)
  22. class WeightOnlyQuantConfig:
  23. def __init__(
  24. self,
  25. algorithm: str,
  26. quant_format: QuantFormat,
  27. op_types_to_quantize: tuple[str, ...] | None = None,
  28. quant_axes: tuple[tuple[str, int], ...] | None = None,
  29. customized_weight_config: dict | None = None,
  30. ):
  31. """This is the Base class for Weight Only blockwise quantization Configuration.
  32. Args:
  33. algorithm:
  34. weight only quantize algorithm name.
  35. quant_format: QuantFormat{QOperator, QDQ}.
  36. QOperator format quantizes the model with quantized operators directly.
  37. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
  38. op_types_to_quantize (optional):
  39. set of operator types to quantize. Default {MatMul}
  40. quant_axes (dict[str, int], optional):
  41. op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
  42. customized_weight_config:
  43. customized weight config for nodes if needed. It is dictionary with node name as key,
  44. and the value is a dict of customized config.
  45. """
  46. self.algorithm = algorithm
  47. self.quant_format = quant_format
  48. self.op_types_to_quantize = set(op_types_to_quantize) if op_types_to_quantize else {"MatMul"}
  49. self.quant_axes = dict(quant_axes) if quant_axes else {"MatMul": 0, "Gather": 1}
  50. self.customized_weight_config = customized_weight_config
  51. class RTNWeightOnlyQuantConfig(WeightOnlyQuantConfig):
  52. def __init__(
  53. self,
  54. ratios=None,
  55. quant_format=QuantFormat.QOperator,
  56. op_types_to_quantize: tuple[str, ...] | None = None,
  57. customized_weight_config: dict | None = None,
  58. ):
  59. """
  60. This is a class for round-to-nearest (RTN) algorithm Weight Only Quant Configuration.
  61. RTN is the most straightforward way to quantize weight using scale maps.
  62. Args:
  63. ratios:
  64. percentile of clip. Defaults to {}.
  65. quant_format (QuantFormat{QOperator, QDQ}, optional):
  66. QOperator format quantizes the model with quantized operators directly.
  67. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
  68. Defaults to QuantFormat.QOperator.
  69. op_types_to_quantize (optional):
  70. set of operator types to quantize.
  71. customized_weight_config:
  72. customized weight config for nodes if needed. It is dictionary with node name as key,
  73. and the value is a dict of customized config.
  74. """
  75. assert quant_format == QuantFormat.QOperator, "RTN only supports QOperator format"
  76. if ratios is None:
  77. ratios = {}
  78. super().__init__(
  79. algorithm="RTN",
  80. quant_format=quant_format,
  81. op_types_to_quantize=op_types_to_quantize,
  82. customized_weight_config=customized_weight_config,
  83. )
  84. self.ratios = ratios
  85. class KQuantWeightOnlyQuantConfig(WeightOnlyQuantConfig):
  86. def __init__(
  87. self,
  88. ratios=None,
  89. quant_format=QuantFormat.QOperator,
  90. op_types_to_quantize: tuple[str, ...] | None = None,
  91. customized_weight_config: dict | None = None,
  92. ):
  93. """
  94. This is a class for k-quant algorithm Weight Only Quant Configuration.
  95. Args:
  96. ratios:
  97. percentile of clip. Defaults to {}.
  98. quant_format (QuantFormat{QOperator, QDQ}, optional):
  99. QOperator format quantizes the model with quantized operators directly.
  100. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
  101. Defaults to QuantFormat.QOperator.
  102. op_types_to_quantize (optional):
  103. set of operator types to quantize.
  104. """
  105. assert quant_format == QuantFormat.QOperator, "k-quant only supports QOperator format"
  106. if ratios is None:
  107. ratios = {}
  108. super().__init__(
  109. algorithm="k_quant",
  110. quant_format=quant_format,
  111. op_types_to_quantize=op_types_to_quantize,
  112. customized_weight_config=customized_weight_config,
  113. )
  114. self.ratios = ratios
  115. class GPTQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
  116. def __init__(
  117. self,
  118. calibration_data_reader: CalibrationDataReader | None = None,
  119. percdamp=0.01,
  120. block_size=128,
  121. actorder=False,
  122. mse=False,
  123. perchannel=True,
  124. quant_format=QuantFormat.QOperator,
  125. op_types_to_quantize: tuple[str, ...] | None = None,
  126. ):
  127. """
  128. This is a class for GPTQ algorithm Weight Only Quant Configuration.
  129. GPTQ algorithm provides more accurate quantization but requires more computational resources.
  130. Args:
  131. calibration_data_reader:
  132. a calibration data reader. It enumerates calibration data and generates inputs for the original model.
  133. percdamp:
  134. percent of the average Hessian diagonal to use for dampening.
  135. block_size (int, optional):
  136. channel number in one block to execute a GPTQ quantization iteration.
  137. actorder (bool, optional):
  138. whether rearrange Hessian matrix considering the diag's value.
  139. mse (bool, optional):
  140. whether get scale and zero point with mse error.
  141. perchannel (bool, optional):
  142. whether quantize weight per-channel.
  143. quant_format (QuantFormat{QOperator, QDQ}, optional):
  144. QOperator format quantizes the model with quantized operators directly.
  145. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
  146. Defaults to QuantFormat.QOperator.
  147. op_types_to_quantize (optional):
  148. set of operator types to quantize.
  149. """
  150. assert quant_format == QuantFormat.QOperator, "GPTQ only supports QOperator format"
  151. super().__init__(
  152. algorithm="GPTQ",
  153. quant_format=quant_format,
  154. op_types_to_quantize=op_types_to_quantize,
  155. )
  156. self.calibration_data_reader = calibration_data_reader
  157. self.percdamp = percdamp
  158. self.block_size = block_size
  159. self.actorder = actorder
  160. self.mse = mse
  161. self.perchannel = perchannel
  162. class HQQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
  163. def __init__(
  164. self,
  165. block_size=128,
  166. bits=4,
  167. axis=1,
  168. quant_format=QuantFormat.QOperator,
  169. op_types_to_quantize: tuple[str, ...] | None = None,
  170. quant_axes: tuple[tuple[str, int], ...] | None = None,
  171. ):
  172. """
  173. This is a class for HQQ algorithm Weight Only Quant Configuration.
  174. HQQ algorithm quant weight without needing calibrate data.
  175. Args:
  176. block_size (int, optional):
  177. channel number in one block to execute a HQQ quantization iteration.
  178. bits (int, optional):
  179. how many bits to represent weight.
  180. axis (int, optional):
  181. 0 or 1. which axis to quantize. https://arxiv.org/pdf/2309.15531.pdf
  182. quant_format (QuantFormat{QOperator, QDQ}, optional):
  183. QOperator format quantizes the model with quantized operators directly.
  184. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
  185. Defaults to QuantFormat.QOperator.
  186. op_types_to_quantize (optional):
  187. set of operator types to quantize.
  188. quant_axes (dict[str, int], optional):
  189. op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
  190. """
  191. assert quant_format == QuantFormat.QOperator, "HQQ only supports QOperator format"
  192. super().__init__(
  193. algorithm="HQQ",
  194. quant_format=quant_format,
  195. op_types_to_quantize=op_types_to_quantize,
  196. quant_axes=quant_axes,
  197. )
  198. self.block_size = block_size
  199. self.bits = bits
  200. self.axis = axis
  201. class DefaultWeightOnlyQuantConfig(WeightOnlyQuantConfig):
  202. def __init__(
  203. self,
  204. block_size: int = 128,
  205. is_symmetric: bool = False,
  206. accuracy_level: int | None = None,
  207. quant_format=QuantFormat.QOperator,
  208. op_types_to_quantize: tuple[str, ...] | None = None,
  209. quant_axes: tuple[tuple[str, int], ...] | None = None,
  210. bits: int = 4,
  211. channel_wised_quantize: bool = False,
  212. ):
  213. """
  214. This is a class for weight only affine quantization configuration.
  215. Args:
  216. block_size (int, optional):
  217. channel number in one block to execute an affine quantization iteration.
  218. is_symmetric (bool, optional):
  219. whether quantize weight symmetrically.
  220. accuracy_level (int, optional):
  221. Accuracy level of the 4-bit quantized MatMul computation.
  222. Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details.
  223. (https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits)
  224. quant_format (QuantFormat{QOperator, QDQ}, optional):
  225. QOperator format quantizes the model with quantized operators directly.
  226. QDQ format quantize the model by inserting QuantizeLinear/DeQuantizeLinear on the tensor.
  227. Defaults to QuantFormat.QOperator.
  228. op_types_to_quantize (optional):
  229. set of operator types to quantize.
  230. quant_axes (dict[str, int], optional):
  231. op:axis, which axis to quantize for an op. Default {MatMul: 0, Gather: 1}
  232. bits (int, optional):
  233. number of bits per element after quantization. Default 4.
  234. """
  235. super().__init__(
  236. algorithm="DEFAULT",
  237. quant_format=quant_format,
  238. op_types_to_quantize=op_types_to_quantize,
  239. quant_axes=quant_axes,
  240. )
  241. self.block_size = block_size
  242. self.is_symmetric = is_symmetric
  243. self.bits = bits
  244. self.accuracy_level = accuracy_level
  245. self.channel_wised_quantize = channel_wised_quantize
  246. if channel_wised_quantize and quant_format == QuantFormat.QOperator:
  247. raise NotImplementedError("QuantFormat.QOperator is not supported channel_wised_quantize yet")
  248. class NVAWQWeightOnlyQuantConfig(WeightOnlyQuantConfig):
  249. def __init__(
  250. self,
  251. tokenizer_dir,
  252. dataset_name="cnn",
  253. cache_dir="./cache",
  254. calibration_method="awq_lite",
  255. ):
  256. """
  257. Configuration for the nvidia_awq quantization method.
  258. Args:
  259. tokenizer_dir (str): pathof the tokenizer dir.
  260. dataset_name (str): Name of the dataset.
  261. cache_dir (str): Directory for caching.
  262. calibration_method (str): calib method for nvidia_awq.
  263. """
  264. # Import torch and DataLoader
  265. try:
  266. import torch # noqa: PLC0415
  267. from torch.utils.data import DataLoader # noqa: PLC0415
  268. self.torch = torch
  269. self.DataLoader = DataLoader
  270. except ImportError:
  271. print(
  272. "Error: The 'torch' library is required but not installed. Please install it using 'pip install torch'."
  273. )
  274. raise ImportError("torch is not installed. Exiting.") from None
  275. # Import datasets
  276. try:
  277. from datasets import load_dataset # noqa: PLC0415
  278. self.load_dataset = load_dataset
  279. except ImportError:
  280. print(
  281. "Error: The 'datasets' library is required but not installed. Please install it using 'pip install datasets'."
  282. )
  283. raise ImportError("datasets is not installed. Exiting.") from None
  284. # Import transformers
  285. try:
  286. from transformers import AutoConfig, AutoTokenizer # noqa: PLC0415
  287. self.AutoConfig = AutoConfig
  288. self.AutoTokenizer = AutoTokenizer
  289. except ImportError:
  290. print(
  291. "Error: The 'transformers' library is required but not installed. Please install it using 'pip install transformers'."
  292. )
  293. raise ImportError("transformers is not installed. Exiting.") from None
  294. super().__init__(
  295. algorithm="nvidia_awq",
  296. quant_format=QuantFormat.QDQ,
  297. op_types_to_quantize=None, # Assuming op_types_to_quantize is handled elsewhere
  298. quant_axes=None, # Assuming quant_axes is handled elsewhere
  299. )
  300. # Determine the device
  301. device = self.torch.device("cuda" if self.torch.cuda.is_available() else "cpu")
  302. calib_inputs = self.get_calib_inputs(
  303. dataset_name=dataset_name,
  304. model_name=tokenizer_dir,
  305. cache_dir=cache_dir,
  306. calib_size=32,
  307. batch_size=1,
  308. block_size=512,
  309. device=device,
  310. use_fp16=True,
  311. use_buffer_share=False,
  312. add_past_kv_inputs=True,
  313. max_calib_rows_to_load=128,
  314. add_position_ids=True,
  315. )
  316. self.calibration_data_reader = calib_inputs
  317. self.calibration_method = calibration_method
  318. def make_model_input(
  319. self,
  320. config,
  321. input_ids_arg,
  322. attention_mask_arg,
  323. add_past_kv_inputs,
  324. device,
  325. use_fp16,
  326. use_buffer_share,
  327. add_position_ids,
  328. ):
  329. # Access torch from the instance variable
  330. torch = self.torch
  331. input_ids = input_ids_arg
  332. attention_mask = attention_mask_arg
  333. if isinstance(input_ids_arg, list):
  334. input_ids = torch.tensor(input_ids_arg, device=device, dtype=torch.int64)
  335. attention_mask = torch.tensor(attention_mask_arg, device=device, dtype=torch.int64)
  336. inputs = {
  337. "input_ids": input_ids.contiguous(),
  338. "attention_mask": attention_mask.contiguous(),
  339. }
  340. if add_position_ids:
  341. position_ids = attention_mask.long().cumsum(-1) - 1
  342. position_ids.masked_fill_(attention_mask == 0, 1)
  343. inputs["position_ids"] = position_ids.contiguous()
  344. if add_past_kv_inputs:
  345. torch_dtype = torch.float16 if use_fp16 else torch.float32
  346. batch_size, sequence_length = input_ids.shape
  347. max_sequence_length = config.max_position_embeddings
  348. num_heads, head_size = (
  349. config.num_key_value_heads,
  350. config.hidden_size // config.num_attention_heads,
  351. )
  352. for i in range(config.num_hidden_layers):
  353. past_key = torch.zeros(
  354. batch_size,
  355. num_heads,
  356. max_sequence_length if use_buffer_share else 0,
  357. head_size,
  358. device=device,
  359. dtype=torch_dtype,
  360. )
  361. past_value = torch.zeros(
  362. batch_size,
  363. num_heads,
  364. max_sequence_length if use_buffer_share else 0,
  365. head_size,
  366. device=device,
  367. dtype=torch_dtype,
  368. )
  369. inputs.update(
  370. {
  371. f"past_key_values.{i}.key": past_key.contiguous(),
  372. f"past_key_values.{i}.value": past_value.contiguous(),
  373. }
  374. )
  375. return inputs
  376. def get_calib_inputs(
  377. self,
  378. dataset_name,
  379. model_name,
  380. cache_dir,
  381. calib_size,
  382. batch_size,
  383. block_size,
  384. device,
  385. use_fp16,
  386. use_buffer_share,
  387. add_past_kv_inputs,
  388. max_calib_rows_to_load,
  389. add_position_ids,
  390. ):
  391. # Access transformers and datasets from the instance variables
  392. auto_config = self.AutoConfig
  393. auto_tokenizer = self.AutoTokenizer
  394. load_dataset = self.load_dataset
  395. config = auto_config.from_pretrained(
  396. model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True
  397. )
  398. tokenizer = auto_tokenizer.from_pretrained(
  399. model_name, use_auth_token=True, cache_dir=cache_dir, trust_remote_code=True
  400. )
  401. tokenizer.add_special_tokens({"pad_token": "[PAD]"})
  402. tokenizer.pad_token = tokenizer.eos_token
  403. assert calib_size <= max_calib_rows_to_load, "calib size should be no more than max_calib_rows_to_load"
  404. if "cnn" in dataset_name:
  405. dataset2 = load_dataset("cnn_dailymail", name="3.0.0", split="train").select(range(max_calib_rows_to_load))
  406. column = "article"
  407. elif "pile" in dataset_name:
  408. dataset2 = load_dataset("mit-han-lab/pile-val-backup", split="validation")
  409. column = "text"
  410. else:
  411. raise ValueError(f'dataset "{dataset_name}" not supported')
  412. dataset2 = dataset2[column][:calib_size]
  413. batch_encoded = tokenizer.batch_encode_plus(
  414. dataset2, return_tensors="pt", padding=True, truncation=True, max_length=block_size
  415. )
  416. batch_encoded = batch_encoded.to(device)
  417. batch_encoded_input_ids = batch_encoded["input_ids"]
  418. batch_encoded_attention_mask = batch_encoded["attention_mask"]
  419. # Access DataLoader from the instance variable
  420. data_loader = self.DataLoader
  421. calib_dataloader_input_ids = data_loader(batch_encoded_input_ids, batch_size=batch_size, shuffle=False)
  422. calib_dataloader_attention_mask = data_loader(
  423. batch_encoded_attention_mask, batch_size=batch_size, shuffle=False
  424. )
  425. assert len(calib_dataloader_input_ids.dataset) == len(calib_dataloader_attention_mask.dataset)
  426. assert len(calib_dataloader_input_ids) == len(calib_dataloader_attention_mask)
  427. number_of_batched_samples = calib_size // batch_size
  428. batched_input_ids = []
  429. for idx, data in enumerate(calib_dataloader_input_ids):
  430. batched_input_ids.append(data)
  431. if idx == (number_of_batched_samples - 1):
  432. break
  433. batched_attention_mask = []
  434. for idx, data in enumerate(calib_dataloader_attention_mask):
  435. batched_attention_mask.append(data)
  436. if idx == (number_of_batched_samples - 1):
  437. break
  438. print(
  439. f"\n--Quantize-Script-- number_of_batched_samples={number_of_batched_samples}, "
  440. f"batch-input-ids-list-len={len(batched_input_ids)}, batched_attention_mask={len(batched_attention_mask)}\n"
  441. )
  442. batched_inputs_list = []
  443. for i in range(number_of_batched_samples):
  444. input_ids = batched_input_ids[i]
  445. attention_mask = batched_attention_mask[i]
  446. inputs = self.make_model_input(
  447. config,
  448. input_ids,
  449. attention_mask,
  450. add_past_kv_inputs,
  451. device,
  452. use_fp16,
  453. use_buffer_share,
  454. add_position_ids,
  455. )
  456. inputs = {input_name: torch_tensor.cpu().numpy() for input_name, torch_tensor in inputs.items()}
  457. batched_inputs_list.append(inputs)
  458. print(f"\n--Quantize-Script-- number of batched inputs = {len(batched_inputs_list)}\n")
  459. return batched_inputs_list
  460. def is_divisible(val1, val2):
  461. return int(val2 * np.ceil(val1 / val2)) == val1
  462. class HQQWeightOnlyQuantizer:
  463. def __init__(
  464. self,
  465. config: HQQWeightOnlyQuantConfig,
  466. ):
  467. self.config = config
  468. # Proximal solver || weight - dequantize(quantize(weight))||_p^p
  469. @staticmethod
  470. def optimize_weights(
  471. tensor,
  472. scale,
  473. zero,
  474. min_max: list[int],
  475. axis: int = 0,
  476. opt_params: dict | None = None,
  477. verbose=False,
  478. ):
  479. import torch # noqa: PLC0415
  480. opt_params = {"lp_norm": 0.7, "beta": 1e1, "kappa": 1.01, "iters": 20} if opt_params is None else opt_params
  481. lp_norm, beta, kappa, iters = (
  482. opt_params["lp_norm"],
  483. opt_params["beta"],
  484. opt_params["kappa"],
  485. opt_params["iters"],
  486. )
  487. dtype = torch.float16 if tensor.is_cuda else torch.float32
  488. w_f = tensor.to(dtype)
  489. scale = scale.to(dtype)
  490. zero = zero.to(dtype)
  491. def shrink_op(x, beta, p=lp_norm):
  492. if p == 1:
  493. return torch.sign(x) * torch.nn.functional.relu(torch.abs(x) - 1.0 / beta)
  494. else:
  495. return torch.sign(x) * torch.nn.functional.relu(
  496. torch.abs(x) - (1.0 / beta) * torch.pow(torch.abs(x) + 1e-8, p - 1)
  497. )
  498. best_error = 1e4
  499. for i in range(iters):
  500. w_q = torch.round(w_f * scale + zero).clamp(min_max[0], min_max[1])
  501. w_r = (w_q - zero) / scale
  502. w_e = shrink_op(w_f - w_r, beta)
  503. zero = torch.mean(w_q - (w_f - w_e) * scale, axis=axis, keepdim=True)
  504. beta *= kappa
  505. current_error = float(torch.abs(w_f - w_r).mean())
  506. if verbose:
  507. print(i, np.round(current_error, 6))
  508. if current_error < best_error:
  509. best_error = current_error
  510. else:
  511. break
  512. del w_f, w_q, w_r, w_e
  513. return scale, zero
  514. @staticmethod
  515. def pack_on_row_fast_248bit(pack_tensor, ori_int_tensor, bits):
  516. if pack_tensor.shape[0] == ori_int_tensor.shape[0]:
  517. ori_int_tensor = ori_int_tensor.T
  518. pack_tensor = pack_tensor.T
  519. if bits in [2, 4, 8]:
  520. compress_ratio = pack_tensor.element_size() * 8 // bits
  521. for j in range(compress_ratio):
  522. pack_tensor[0:] |= ori_int_tensor[j::compress_ratio] << (bits * (j))
  523. else:
  524. raise NotImplementedError("Only 2,4,8 bits are supported.")
  525. # from Official implementation of Half-Quadratic Quantization (HQQ)
  526. def quantize_internal(
  527. self, tensor, bits=4, channel_wise=True, group_size=64, optimize=True, round_zero=True, axis=1
  528. ):
  529. import torch # noqa: PLC0415
  530. weight = tensor.float()
  531. ori_shape = weight.shape
  532. pad_len = (group_size - ori_shape[axis] % group_size) % group_size
  533. if axis == 1:
  534. weight = torch.nn.functional.pad(weight, (0, pad_len), "constant", 0)
  535. else:
  536. weight = torch.nn.functional.pad(weight, (0, 0, 0, pad_len), "constant", 0)
  537. shape = weight.shape
  538. # Reshape for grouping
  539. if (group_size is not None) and channel_wise:
  540. weight = weight.reshape([-1, group_size]) if (axis == 1) else weight.reshape([group_size, -1])
  541. # Get min/max values
  542. if channel_wise is False:
  543. _min, _max = weight.min(), weight.max()
  544. optimize = False
  545. else:
  546. _min = weight.min(axis=axis, keepdim=True)[0]
  547. _max = weight.max(axis=axis, keepdim=True)[0]
  548. max_v = 2**bits - 1
  549. min_v = 0
  550. min_max = [min_v, max_v]
  551. # Note: here we work with the inverse of the scale to avoid division and quantize instead via weight*scale + zero, the scale is inverted later on.
  552. # clamp to avoid half-precision problems
  553. scale = (max_v / (_max - _min)).clamp(max=2e4)
  554. #!!!!!!!!!!!!!!!
  555. min_max_axis = _max - _min
  556. if (min_max_axis == 0).sum().item() > 0:
  557. min_max_axis[min_max_axis == 0] = max_v
  558. scale = (max_v / min_max_axis).clamp(max=2e4)
  559. zero = -_min * scale
  560. if round_zero:
  561. zero = torch.round(zero)
  562. # Fine-tune weights
  563. if optimize:
  564. scale, zero = self.optimize_weights(tensor=weight, scale=scale, zero=zero, min_max=min_max, axis=axis)
  565. # Quantize
  566. # Necessary for fake quantization backprop
  567. w_q = torch.round(weight * scale + zero).clamp(min_max[0], min_max[1])
  568. w_q = w_q.reshape(shape).int()
  569. scale = 1.0 / scale
  570. if axis == 1:
  571. scale = scale.reshape(shape[0], -1)
  572. zero = zero.reshape(shape[0], -1)
  573. else:
  574. scale = scale.reshape(-1, shape[-1])
  575. zero = zero.reshape(-1, shape[-1])
  576. # cleanup
  577. del weight, _min, _max
  578. return w_q, scale.to(tensor.dtype), zero.to(tensor.dtype)
  579. def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
  580. """
  581. Target node: QOperator node: QDQ nodes:
  582. MatMul MatMulNBits DeQuantizeLinear -> MatMul
  583. Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
  584. If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and
  585. return the new nodes.
  586. If QOperator format, return the corresponding QOperator nodes.
  587. If QDQ format, return the corresdponging QDQ nodes.
  588. Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is
  589. not supported yet because Gather does not support int4 data.
  590. """
  591. # With HQQ, zero points are in float. Current GatherBlockQuantized does not support float zero points.
  592. if node.op_type == "Gather":
  593. raise NotImplementedError("Gather quantization is not supported yet in HQQ")
  594. import torch # noqa: PLC0415
  595. logger.info(f"start to quantize {node.name} ...")
  596. input_b = node.input[1]
  597. b_pb, bs_graph = get_initializer(input_b, graph_stack)
  598. if b_pb is None:
  599. logger.info("MatMul doesn't have const weight. Skip to quantize")
  600. return [node] # only care about constant weight
  601. b_array = onnx.numpy_helper.to_array(b_pb)
  602. if len(b_array.shape) != 2:
  603. logger.info("MatMul weight is not 2D. Skip to quantize")
  604. return [node] # can only process 2-D matrix
  605. b_array_torch = torch.from_numpy(b_array)
  606. if torch.cuda.is_available():
  607. b_array_torch = b_array_torch.cuda()
  608. bits = self.config.bits
  609. quant_weight_torch, scales_torch, zero_points_torch = self.quantize_internal(
  610. b_array_torch.T, bits=bits, group_size=self.config.block_size
  611. )
  612. quant_weight_torch = quant_weight_torch.contiguous()
  613. scales_torch = scales_torch.contiguous()
  614. zero_points_torch = zero_points_torch.contiguous()
  615. packed_size = 8 // bits # number of elements packed into one byte
  616. packed_torch = torch.zeros(
  617. (quant_weight_torch.shape[0], quant_weight_torch.shape[1] // packed_size),
  618. dtype=torch.uint8,
  619. device=quant_weight_torch.device,
  620. )
  621. self.pack_on_row_fast_248bit(packed_torch, quant_weight_torch, bits)
  622. scales = scales_torch.cpu().numpy()
  623. zero_points = zero_points_torch.cpu().numpy()
  624. # reshape to the predefined shape in MatmulNbits
  625. scales = scales.reshape(-1)
  626. zero_points = zero_points.reshape(-1)
  627. rows, cols = b_array_torch.shape
  628. block_size = self.config.block_size
  629. blob_size = block_size // packed_size
  630. k_blocks = (rows + block_size - 1) // block_size
  631. packed_torch = packed_torch.reshape(cols, k_blocks, blob_size)
  632. b_quant = onnx.numpy_helper.from_array(packed_torch.cpu().numpy())
  633. b_quant.name = b_pb.name + "_Q" + str(bits)
  634. for input in bs_graph.input:
  635. if input.name == input_b:
  636. bs_graph.input.remove(input)
  637. break
  638. scales_tensor = onnx.numpy_helper.from_array(scales)
  639. scales_tensor.name = b_pb.name + "_scales"
  640. bs_graph.initializer.extend([b_quant, scales_tensor])
  641. input_names = [node.input[0], b_quant.name, scales_tensor.name]
  642. zp_tensor = onnx.numpy_helper.from_array(zero_points)
  643. zp_tensor.name = b_pb.name + "_zero_points"
  644. bs_graph.initializer.extend([zp_tensor])
  645. input_names.append(zp_tensor.name)
  646. kwargs = {}
  647. rows, cols = b_array.shape
  648. kwargs["K"] = rows
  649. kwargs["N"] = cols
  650. kwargs["bits"] = bits
  651. kwargs["block_size"] = self.config.block_size
  652. matmul_q_node = onnx.helper.make_node(
  653. "MatMulNBits",
  654. inputs=input_names,
  655. outputs=[node.output[0]],
  656. name=node.name + "_Q" + str(bits) if node.name else "",
  657. domain="com.microsoft",
  658. **kwargs,
  659. )
  660. logger.info(f"complete quantization of {node.name} ...")
  661. return [matmul_q_node]
  662. def get_initializer(name, graph_path: list[GraphProto]) -> tuple[TensorProto, GraphProto]:
  663. for gid in range(len(graph_path) - 1, -1, -1):
  664. graph = graph_path[gid]
  665. for tensor in graph.initializer:
  666. if tensor.name == name:
  667. return tensor, graph
  668. return None, None
  669. # transpose int4 matrix (packed as uint8)
  670. def transpose_packed_int4_matrix(packed, rows, cols):
  671. # unpack to int4 matrix
  672. total = rows * cols
  673. high = (packed >> 4) & 0x0F
  674. low = packed & 0x0F
  675. int4_vals = np.empty(total, dtype=np.uint8)
  676. int4_vals[0::2] = low
  677. int4_vals[1::2] = high
  678. int4_matrix = int4_vals.reshape((rows, cols))
  679. # transpose int4 matrix
  680. int4_matrix_transposed = int4_matrix.T
  681. # pack to uint8
  682. flat = int4_matrix_transposed.reshape(-1)
  683. packed = ((flat[1::2] << 4) & 0xF0) | (flat[0::2] & 0x0F)
  684. return packed.astype(np.uint8)
  685. class DefaultWeightOnlyQuantizer:
  686. def __init__(self, config: DefaultWeightOnlyQuantConfig):
  687. self.config = config
  688. def qbits_block_quant(self, fp32weight: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
  689. """4b/8b quantize fp32 weight to int4 using C++ kernels."""
  690. qbits = self.config.bits
  691. kpack = 8 // qbits
  692. if len(fp32weight.shape) != 2:
  693. raise ValueError("Current int4 block quantization only supports 2D tensors!")
  694. rows, cols = fp32weight.shape
  695. block_size = self.config.block_size
  696. k_blocks = (rows + block_size - 1) // block_size
  697. if self.config.quant_format == QuantFormat.QOperator:
  698. blob_size = (block_size + kpack - 1) // kpack
  699. padded_rows = k_blocks * block_size
  700. pad_len = padded_rows - rows
  701. if pad_len > 0:
  702. fp32weight = np.pad(fp32weight, ((0, pad_len), (0, 0)), "constant")
  703. # block wise quantization, each block comes from a single column
  704. packed = np.zeros((cols, k_blocks, blob_size), dtype="uint8")
  705. zero_point = np.zeros(cols * ((k_blocks + kpack - 1) // kpack), dtype="uint8")
  706. scales = np.zeros((cols * k_blocks), dtype=fp32weight.dtype)
  707. if qbits == 8:
  708. quantize_matmul_8bits(
  709. packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
  710. )
  711. else:
  712. quantize_matmul_4bits(
  713. packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
  714. )
  715. else:
  716. # block size equal to rows (K) if channel wised quantize enabled
  717. block_size = rows if self.config.channel_wised_quantize else self.config.block_size
  718. k_blocks = (rows + block_size - 1) // block_size
  719. assert qbits == 4, "QDQ format only support 4 bits quantization"
  720. packed = np.zeros((rows * cols + 1) // 2, dtype="uint8")
  721. zero_point = np.zeros((cols * k_blocks + 1) // 2, dtype="uint8")
  722. scales = np.zeros((k_blocks, cols), dtype=fp32weight.dtype)
  723. quantize_qdq_matmul_4bits(
  724. packed, fp32weight, scales, zero_point, block_size, cols, rows, self.config.is_symmetric
  725. )
  726. return (packed, scales, zero_point)
  727. def quantize_matmul(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
  728. """
  729. Quantize weight B of MatMul node to int4 or int8.
  730. Currently only support 2D constant matrix and axis 0 blockwise quantization.
  731. """
  732. bits = self.config.bits
  733. if bits == 8:
  734. qtype = TensorProto.INT8 if self.config.is_symmetric else TensorProto.UINT8
  735. else:
  736. qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4
  737. input_b = node.input[1]
  738. b_tensor, b_graph = get_initializer(input_b, graph_stack)
  739. if b_tensor is None:
  740. logger.info("MatMul doesn't have const weight. Skip to quantize")
  741. return [node] # only care about constant weight
  742. b_ndarray = onnx.numpy_helper.to_array(b_tensor)
  743. if len(b_ndarray.shape) != 2:
  744. logger.info("MatMul weight is not 2D. Skip to quantize")
  745. return [node] # can only process 2-D matrix
  746. packed, scales, zero_points = self.qbits_block_quant(b_ndarray)
  747. if self.config.quant_format == QuantFormat.QOperator:
  748. b_quant = onnx.numpy_helper.from_array(packed, b_tensor.name + f"_Q{bits}")
  749. scales_tensor = onnx.numpy_helper.from_array(scales, b_tensor.name + "_scales")
  750. else:
  751. b_quant = onnx.helper.make_tensor(
  752. b_tensor.name + f"_DQ_Q{bits}", qtype, b_ndarray.shape, packed.tobytes(), True
  753. )
  754. scales_tensor = onnx.numpy_helper.from_array(scales, b_tensor.name + "_DQ_scales")
  755. # if QDQ, CW and SYM enabled, optimize for Intel NPU, tranpose the weight to NHWC format will increase performance
  756. qdq_opt_for_intel_npu_enabled = (
  757. self.config.quant_format == QuantFormat.QDQ
  758. and self.config.channel_wised_quantize
  759. and self.config.is_symmetric
  760. )
  761. if qdq_opt_for_intel_npu_enabled:
  762. rows, cols = b_ndarray.shape
  763. packed = transpose_packed_int4_matrix(packed, rows, cols)
  764. scales = scales.reshape((cols, 1)) # (cols, 1)
  765. b_quant = onnx.helper.make_tensor(
  766. b_tensor.name + f"_DQ_Q{bits}", qtype, [cols, rows], packed.tobytes(), True
  767. )
  768. scales_tensor = onnx.numpy_helper.from_array(scales, b_tensor.name + "_DQ_scales")
  769. for input in b_graph.input:
  770. if input.name == input_b:
  771. b_graph.input.remove(input)
  772. break
  773. b_graph.initializer.extend([b_quant, scales_tensor])
  774. output_nodes = []
  775. if self.config.quant_format == QuantFormat.QOperator:
  776. input_names = [node.input[0], b_quant.name, scales_tensor.name]
  777. if not self.config.is_symmetric:
  778. zp_tensor = onnx.numpy_helper.from_array(zero_points, b_tensor.name + "_zero_points")
  779. input_names.append(zp_tensor.name)
  780. b_graph.initializer.extend([zp_tensor])
  781. kwargs = {}
  782. rows, cols = b_ndarray.shape
  783. kwargs["K"] = rows
  784. kwargs["N"] = cols
  785. kwargs["bits"] = bits
  786. kwargs["block_size"] = self.config.block_size
  787. # Do not output accuracy_level if it is 0 since the attribute is optional and is not supported by most EPs.
  788. if self.config.accuracy_level:
  789. kwargs["accuracy_level"] = self.config.accuracy_level
  790. matmul_qbit_node = onnx.helper.make_node(
  791. "MatMulNBits",
  792. inputs=input_names,
  793. outputs=[node.output[0]],
  794. name=node.name + f"_Q{bits}" if node.name else "",
  795. domain="com.microsoft",
  796. **kwargs,
  797. )
  798. output_nodes.append(matmul_qbit_node)
  799. else:
  800. dq_input_names = [b_quant.name, scales_tensor.name]
  801. dq_output_names = [b_quant.name + "_output"]
  802. tp_input_names = [dq_output_names[0]]
  803. tp_output_names = [dq_output_names[0] + "_transposed"]
  804. matmul_input_names = [
  805. node.input[0],
  806. tp_output_names[0] if qdq_opt_for_intel_npu_enabled else dq_output_names[0],
  807. ]
  808. matmul_output_names = [node.output[0]]
  809. if not self.config.is_symmetric:
  810. zp_tensor = onnx.helper.make_tensor(
  811. b_tensor.name + "_DQ_zero_points", qtype, scales.shape, zero_points.tobytes(), True
  812. )
  813. dq_input_names.append(zp_tensor.name)
  814. b_graph.initializer.extend([zp_tensor])
  815. rows, cols = b_ndarray.shape
  816. dq_kwargs = {
  817. "axis": 1 if qdq_opt_for_intel_npu_enabled else 0,
  818. "block_size": rows if self.config.channel_wised_quantize else self.config.block_size,
  819. }
  820. dq_node = onnx.helper.make_node(
  821. "DequantizeLinear",
  822. inputs=dq_input_names,
  823. outputs=dq_output_names,
  824. name=node.name + f"_DQ_Q{bits}" if node.name else "",
  825. **dq_kwargs,
  826. )
  827. matmul_node = onnx.helper.make_node(
  828. "MatMul",
  829. inputs=matmul_input_names,
  830. outputs=matmul_output_names,
  831. name=node.name + f"_matmul_Q{bits}" if node.name else "",
  832. )
  833. if qdq_opt_for_intel_npu_enabled:
  834. tp_node = onnx.helper.make_node(
  835. "Transpose",
  836. inputs=tp_input_names,
  837. outputs=tp_output_names,
  838. perm=[1, 0],
  839. )
  840. output_nodes.extend([dq_node, tp_node, matmul_node])
  841. else:
  842. output_nodes.extend([dq_node, matmul_node])
  843. return output_nodes
  844. @staticmethod
  845. def quant_slice_symmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
  846. max_val = np.max(data, axis=1, keepdims=True)
  847. min_val = np.min(data, axis=1, keepdims=True)
  848. abs_max = np.where(np.abs(max_val) > np.abs(min_val), max_val, min_val)
  849. scale = abs_max / -8.0 # if max == min, max may be clipped
  850. quantized_slice = np.where(scale == 0, 0, data / scale).round().clip(-8, 7).astype(np.int8)
  851. return quantized_slice, scale
  852. @staticmethod
  853. def quant_slice_asymmetric(data: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
  854. min_val = np.minimum(data.min(axis=1, keepdims=True), 0)
  855. max_val = np.maximum(data.max(axis=1, keepdims=True), 0)
  856. scale = (max_val - min_val) / 15.0
  857. zero_point = np.where(scale == 0, 8, -min_val / scale).round().clip(0, 15).astype(np.uint8)
  858. quantized_slice = np.where(scale == 0, 8, data / scale + zero_point).round().clip(0, 15).astype(np.uint8)
  859. return quantized_slice, scale, zero_point
  860. @staticmethod
  861. def pack_int8_to_int4(data: np.ndarray) -> np.ndarray:
  862. """Pack int8 data to int4 and store in uint8 ndarray."""
  863. data_flat = data.reshape(-1)
  864. if len(data_flat) % 2 != 0:
  865. data_flat = np.append(data_flat, 0)
  866. quant_data_int4 = (data_flat[::2] & 0xF) | ((data_flat[1::2] & 0xF) << 4)
  867. return quant_data_int4.astype("uint8")
  868. @staticmethod
  869. def quantize_ndarray(
  870. data: np.ndarray,
  871. quantize_axis: int,
  872. block_size: int,
  873. is_symmetric: bool,
  874. ) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]:
  875. """Quantize ndarray data to int4 using numpy, return (quantized data, scales, zero points)."""
  876. # Get the shape of the matrix
  877. m = 1 # dimension of the matrix before the quantize axis
  878. k = data.shape[quantize_axis] # dimension of the matrix along the quantize axis
  879. n = 1 # dimension of the matrix after the quantize axis
  880. for i, dim in enumerate(data.shape):
  881. if i < quantize_axis:
  882. m *= dim
  883. elif i > quantize_axis:
  884. n *= dim
  885. k_blocks = (k + block_size - 1) // block_size
  886. scales_shape = list(data.shape)
  887. scales_shape[quantize_axis] = k_blocks
  888. data_reshape = data.reshape((m, k, n))
  889. scales = np.zeros((m, k_blocks, n), dtype=data.dtype)
  890. if is_symmetric:
  891. quant_data_int8 = np.zeros((m, k, n), dtype="int8")
  892. else:
  893. quant_data_int8 = np.zeros((m, k, n), dtype="uint8")
  894. zero_point_int8 = np.zeros((m, k_blocks, n), dtype="uint8")
  895. # slice and quantize
  896. for i in range(0, k, block_size):
  897. end_idx = min(i + block_size, k)
  898. slice = data_reshape[:, i:end_idx, :]
  899. if is_symmetric:
  900. quantized_slice_int8, scale_slice = DefaultWeightOnlyQuantizer.quant_slice_symmetric(slice)
  901. else:
  902. quantized_slice_int8, scale_slice, zero_point_slice_int8 = (
  903. DefaultWeightOnlyQuantizer.quant_slice_asymmetric(slice)
  904. )
  905. quant_data_int8[:, i:end_idx, :] = quantized_slice_int8
  906. j = i // block_size
  907. scales[:, j : (j + 1), :] = scale_slice
  908. if not is_symmetric:
  909. zero_point_int8[:, j : (j + 1), :] = zero_point_slice_int8
  910. # pack int8 to int4
  911. quant_data_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(quant_data_int8)
  912. zero_point_int4 = None
  913. if not is_symmetric:
  914. zero_point_int4 = DefaultWeightOnlyQuantizer.pack_int8_to_int4(zero_point_int8)
  915. scales = scales.reshape(scales_shape)
  916. return quant_data_int4, scales, zero_point_int4
  917. def quantize_gather(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
  918. """Quantize weight data of Gather node to int4."""
  919. assert self.config.quant_format == QuantFormat.QOperator, "Gather only supports QOperator format currently."
  920. qtype = TensorProto.INT4 if self.config.is_symmetric else TensorProto.UINT4
  921. data_arg = node.input[0]
  922. data_tensorproto, data_graphproto = get_initializer(data_arg, graph_stack)
  923. if data_tensorproto is None:
  924. logger.info("Gather doesn't have const weight. Skip quantization.")
  925. return [node] # only care about constant weight
  926. data_ndarray = onnx.numpy_helper.to_array(data_tensorproto)
  927. data_rank = len(data_ndarray.shape)
  928. quantize_axis = self.config.quant_axes.get("Gather", 1)
  929. block_size = self.config.block_size
  930. assert quantize_axis < data_rank and quantize_axis >= -data_rank, "Invalid quantize axis for Gather node."
  931. assert block_size >= 16 and ((block_size - 1) & block_size == 0), "Invalid block size for Gather node."
  932. quantize_axis = (quantize_axis + data_rank) % data_rank
  933. quantized_data, scales, zero_points = self.quantize_ndarray(
  934. data_ndarray, quantize_axis, block_size, self.config.is_symmetric
  935. )
  936. for input in data_graphproto.input:
  937. if input.name == data_arg:
  938. data_graphproto.input.remove(input)
  939. break
  940. quantized_data_tensorproto = onnx.helper.make_tensor(
  941. data_tensorproto.name + "_Q4", qtype, data_ndarray.shape, quantized_data.tobytes(), True
  942. )
  943. scales_tensorproto = onnx.numpy_helper.from_array(scales, data_tensorproto.name + "_scales")
  944. input_names = [quantized_data_tensorproto.name, node.input[1], scales_tensorproto.name]
  945. data_graphproto.initializer.extend([quantized_data_tensorproto, scales_tensorproto])
  946. if not self.config.is_symmetric:
  947. zp_tensorproto = onnx.helper.make_tensor(
  948. data_tensorproto.name + "_zero_points", qtype, scales.shape, zero_points.tobytes(), True
  949. )
  950. input_names.append(zp_tensorproto.name)
  951. data_graphproto.initializer.extend([zp_tensorproto])
  952. try:
  953. gather_axis = onnx.helper.get_node_attr_value(node, "axis")
  954. except ValueError:
  955. gather_axis = 0
  956. kwargs = {
  957. "gather_axis": gather_axis,
  958. "quantize_axis": quantize_axis,
  959. "block_size": block_size,
  960. }
  961. gather_q4_node = onnx.helper.make_node(
  962. "GatherBlockQuantized",
  963. inputs=input_names,
  964. outputs=[node.output[0]],
  965. name=node.name + "_Q4" if node.name else "",
  966. domain="com.microsoft",
  967. **kwargs,
  968. )
  969. return [gather_q4_node]
  970. def quantize(self, node: NodeProto, graph_stack: list[GraphProto]) -> list[NodeProto]:
  971. """
  972. Target node: QOperator node: QDQ nodes:
  973. MatMul MatMulNBits DeQuantizeLinear -> MatMul
  974. Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
  975. If the node is target node with fp32 or fp16 const weight, quantize the weight to int4 and
  976. return the new nodes.
  977. If QOperator format, return the corresponding QOperator nodes.
  978. If QDQ format, return the corresdponging QDQ nodes.
  979. Gather (quantized data) + Gather (scales) + Gather (optional, zero points) -> DequantizeLinear is
  980. not supported yet because Gather does not support int4 data.
  981. """
  982. logger.info(f"start to quantize {node.name} ...")
  983. bits = self.config.bits
  984. if node.op_type == "MatMul":
  985. if bits == 8 and self.config.quant_format == QuantFormat.QDQ:
  986. logger.error("MatMul only supports QOperator format for 8 bits quantization.")
  987. return [node]
  988. results = self.quantize_matmul(node, graph_stack)
  989. elif node.op_type == "Gather":
  990. if self.config.bits != 4:
  991. logger.error("Gather only supports 4 bits quantization.")
  992. return [node]
  993. results = self.quantize_gather(node, graph_stack)
  994. else:
  995. logger.error(f"Unsupported operator {node.op_type} for weight only quantization. Skip quantization.")
  996. return [node]
  997. logger.info(f"complete quantization of {node.name} with {self.config.bits} bits ...")
  998. return results
  999. class NVAWQWeightOnlyQuantizer:
  1000. def __init__(
  1001. self,
  1002. config: NVAWQWeightOnlyQuantConfig,
  1003. ):
  1004. self.config = config
  1005. def quantize_awq(self, model: ModelProto | str) -> ModelProto:
  1006. """
  1007. Perform nvidia_awq quantization using ModelOpt's int4 quantize function.
  1008. Args:
  1009. model (ModelProto): The ONNX model to quantize.
  1010. Returns:
  1011. ModelProto: The quantized ONNX model.
  1012. """
  1013. try:
  1014. from modelopt.onnx.quantization.int4 import quantize as quantize_int4 # noqa: PLC0415
  1015. except ImportError:
  1016. print(
  1017. "Please ensure that the 'modelopt' package is installed. Please install it using pip install nvidia_modelopt."
  1018. )
  1019. raise ImportError(
  1020. "modelopt is not installed. Please install it using pip install nvidia_modelopt. Exiting."
  1021. ) from None
  1022. logger.info("Starting nvidia_awq quantization...")
  1023. # Prepare calibration inputs
  1024. calib_inputs = self.config.calibration_data_reader
  1025. # Perform quantization using ModelOpt's int4 quantize function
  1026. quantized_model = quantize_int4(
  1027. model,
  1028. calibration_method=self.config.calibration_method,
  1029. calibration_data_reader=calib_inputs,
  1030. )
  1031. logger.info("Completed nvidia_awq quantization.")
  1032. return quantized_model
  1033. class MatMulNBitsQuantizer:
  1034. """
  1035. Target node: QOperator node: QDQ nodes:
  1036. MatMul MatMulNBits DeQuantizeLinear -> MatMul
  1037. Gather GatherBlockQuantized Gather, Gather, Gather (optional) -> DequantizeLinear
  1038. Perform 4/8 bits quantization of constant weights for target nodes.
  1039. If algo_config.quant_format is QOperator:
  1040. - nodes are replaced by the corresponding QOperator nodes.
  1041. - quantized weights are stored in the contrib ops.
  1042. If algo_config.quant_format is QDQ:
  1043. - the quantized weight is stored in a standard onnx node. For MatMul, it is DequantizeLinear. For Gather,
  1044. it is the three Gathers, one for quantized data, one for scales and one for optional zero points.
  1045. - The nodes are replaced by the corresponding QDQ nodes.
  1046. - currently Gather is not supported in QDQ because Gather does not support int4 yet.
  1047. Note:
  1048. - for quantized gather, the memory usage of "DequantizeLinear + Gather" is the same as the original Gather
  1049. during runtime. Therefor it is not recommended.
  1050. - when a node is in nodes_to_exclude, and the node configuration in algo_config.customized_weight_config will be ignored.
  1051. """
  1052. def __init__(
  1053. self,
  1054. model: ModelProto | str,
  1055. block_size: int = 128,
  1056. is_symmetric: bool = False,
  1057. accuracy_level: int | None = None,
  1058. nodes_to_exclude=None,
  1059. nodes_to_include: list[str] | None = None,
  1060. quant_format=QuantFormat.QOperator,
  1061. op_types_to_quantize: tuple[str, ...] | None = None,
  1062. quant_axes: tuple[tuple[str, int], ...] | None = None,
  1063. channel_wised_quantize: bool = False,
  1064. algo_config: WeightOnlyQuantConfig | None = None,
  1065. ):
  1066. if nodes_to_exclude is None:
  1067. nodes_to_exclude = []
  1068. self.model = ONNXModel(onnx.load(model)) if isinstance(model, str) else ONNXModel(model)
  1069. self.model_path = model if isinstance(model, str) else None
  1070. self.block_size = block_size
  1071. self.is_symmetric = is_symmetric
  1072. self.accuracy_level = accuracy_level
  1073. self.nodes_to_exclude = set(nodes_to_exclude)
  1074. self.nodes_to_include = set(nodes_to_include) if nodes_to_include else None
  1075. self.node_quantizer = None
  1076. if algo_config is None:
  1077. algo_config = DefaultWeightOnlyQuantConfig(
  1078. block_size=block_size,
  1079. is_symmetric=is_symmetric,
  1080. accuracy_level=accuracy_level,
  1081. quant_format=quant_format,
  1082. op_types_to_quantize=op_types_to_quantize,
  1083. quant_axes=quant_axes,
  1084. bits=4, # default to 4 bits
  1085. channel_wised_quantize=channel_wised_quantize,
  1086. )
  1087. self.algo_config = algo_config
  1088. if hasattr(self.algo_config, "bits"):
  1089. assert self.algo_config.bits in [4, 8], "Only support 4 or 8 bits quantization"
  1090. if algo_config.algorithm == "HQQ":
  1091. self.node_quantizer = HQQWeightOnlyQuantizer(self.algo_config)
  1092. elif algo_config.algorithm == "DEFAULT":
  1093. self.node_quantizer = DefaultWeightOnlyQuantizer(self.algo_config)
  1094. elif algo_config.algorithm == "nvidia_awq":
  1095. self.node_quantizer = NVAWQWeightOnlyQuantizer(self.algo_config)
  1096. def _process_subgraph(self, graph_stack: list[GraphProto]):
  1097. new_nodes = []
  1098. graph = graph_stack[-1]
  1099. for node in graph.node:
  1100. graph_attrs = [
  1101. attr
  1102. for attr in node.attribute
  1103. if attr.type == onnx.AttributeProto.GRAPH or attr.type == onnx.AttributeProto.GRAPHS
  1104. ]
  1105. if graph_attrs:
  1106. kwargs = {}
  1107. for attr in node.attribute:
  1108. if attr.type == onnx.AttributeProto.GRAPH:
  1109. # recursive call to take care of sub-graph
  1110. graph_stack.append(attr.g)
  1111. kv = {attr.name: self._process_subgraph(graph_stack)}
  1112. elif attr.type == onnx.AttributeProto.GRAPHS:
  1113. value = []
  1114. for subgraph in attr.graphs:
  1115. # recursive call to take care of sub-graph
  1116. graph_stack.append(subgraph)
  1117. value.extend([self._process_subgraph(graph_stack)])
  1118. kv = {attr.name: value}
  1119. else:
  1120. kv = attribute_to_kwarg(attr)
  1121. kwargs.update(kv)
  1122. node = onnx.helper.make_node( # noqa: PLW2901
  1123. node.op_type, node.input, node.output, name=node.name, **kwargs
  1124. )
  1125. out_nodes = []
  1126. if node.name in self.nodes_to_exclude:
  1127. logger.info(f"exclude to quantize {node.name} as specified by nodes_to_exclude...")
  1128. out_nodes = [node]
  1129. elif (self.nodes_to_include and node.name in self.nodes_to_include) or (
  1130. node.op_type in self.algo_config.op_types_to_quantize
  1131. ):
  1132. out_nodes = self.node_quantizer.quantize(node, graph_stack)
  1133. else:
  1134. logger.info(f"skip to quantize {node.name} ...")
  1135. out_nodes = [node]
  1136. new_nodes.extend(out_nodes)
  1137. graph.ClearField("node")
  1138. graph.node.extend(new_nodes)
  1139. graph_stack.pop()
  1140. return graph
  1141. def _generate_q4_node_config(self):
  1142. """Generate weight only quant configuration for nodes."""
  1143. q4_node_config = {}
  1144. for node in self.model.model.graph.node:
  1145. if node.op_type in ["MatMul"]:
  1146. if not all(self.model.get_initializer(i) is None for i in node.input):
  1147. template_config_q4 = {
  1148. "bits": 4,
  1149. "group_size": self.block_size,
  1150. "scheme": "sym" if self.is_symmetric else "asym",
  1151. }
  1152. if (
  1153. self.algo_config.customized_weight_config
  1154. and node.name in self.algo_config.customized_weight_config
  1155. ):
  1156. for key, value in self.algo_config.customized_weight_config[node.name].items():
  1157. if key in template_config_q4:
  1158. template_config_q4[key] = value
  1159. q4_node_config[node.name] = template_config_q4
  1160. return q4_node_config
  1161. def int4_quant_algo(self):
  1162. """4b quantize a model with RTN or GPTQ algorithm. Please refer to
  1163. https://github.com/intel/neural-compressor/blob/master/docs/source/quantization_weight_only.md
  1164. for more details on weight only quantization using Intel® Neural Compressor.
  1165. """
  1166. def inc_dataloader():
  1167. data_reader = copy.deepcopy(self.algo_config.calibration_data_reader)
  1168. for data in data_reader:
  1169. yield data, None
  1170. kwargs = {}
  1171. if self.accuracy_level is not None:
  1172. kwargs["accuracy_level"] = self.accuracy_level
  1173. weight_only_node_config = self._generate_q4_node_config()
  1174. algorithm = self.algo_config.algorithm
  1175. logger.info(f"start to quantize model with {algorithm} algorithm...")
  1176. if algorithm in ["RTN", "k_quant"]:
  1177. kwargs["ratios"] = self.algo_config.ratios
  1178. kwargs["algorithm"] = algorithm
  1179. """
  1180. We uses fp32 to represent the node that skip quantization, it does not mean this node is fp32 type though.
  1181. """
  1182. for n in self.nodes_to_exclude:
  1183. weight_only_node_config[n] = "fp32"
  1184. self.model = rtn_quantize(
  1185. model=self.model_path if self.model_path is not None else self.model.model,
  1186. weight_config=weight_only_node_config,
  1187. **kwargs,
  1188. )
  1189. elif algorithm == "GPTQ":
  1190. kwargs["percdamp"] = self.algo_config.percdamp
  1191. kwargs["blocksize"] = self.algo_config.block_size
  1192. kwargs["actorder"] = self.algo_config.actorder
  1193. kwargs["mse"] = self.algo_config.mse
  1194. kwargs["perchannel"] = self.algo_config.perchannel
  1195. kwargs["n_samples"] = -1
  1196. dataloader = inc_dataloader()
  1197. self.model = gptq_quantize(
  1198. model=self.model_path if self.model_path is not None else self.model.model,
  1199. weight_config=weight_only_node_config,
  1200. dataloader=dataloader,
  1201. **kwargs,
  1202. )
  1203. logger.info(f"complete quantization of model with {algorithm} algorithm.")
  1204. def process(self):
  1205. if self.algo_config.algorithm in ["HQQ", "DEFAULT"]:
  1206. # use a stack to keep track of sub-graphs
  1207. graph_stack = [self.model.graph()]
  1208. # Update domain opset
  1209. if self.algo_config.quant_format == QuantFormat.QOperator:
  1210. self.model.set_opset_import("com.microsoft", 1)
  1211. if self.algo_config.quant_format == QuantFormat.QDQ or "Gather" in self.algo_config.op_types_to_quantize:
  1212. opset_import = self.model.opset_import()
  1213. for opset in opset_import:
  1214. if opset.domain in [None, "ai.onnx", ""] and opset.version < 21:
  1215. logger.warning(
  1216. "The opset of the input model is under 21 and doesn't support int4 data type. "
  1217. "Force to update it to opset 21, but the generated model may not be a valid model."
  1218. )
  1219. self.model.set_opset_import(opset.domain, 21)
  1220. self._process_subgraph(graph_stack)
  1221. self.model.clean_initializers()
  1222. elif self.algo_config.algorithm == "nvidia_awq":
  1223. # Handle nvidia_awq quantization
  1224. logger.info("Processing nvidia_awq quantization...")
  1225. self.model = self.node_quantizer.quantize_awq(
  1226. self.model.model if self.model_path is None else self.model_path
  1227. )
  1228. logger.info("Completed nvidia_awq quantization.")
  1229. self.model = ONNXModel(self.model) # Ensure the model is wrapped back into ONNXModel
  1230. self.model.clean_initializers()
  1231. else:
  1232. # RTN or GPTQ weight-only quantize algorithm
  1233. self.int4_quant_algo()
  1234. def ort_convert_str_to_bool(value):
  1235. return value.lower() in ("true", "1")
  1236. # Custom function to parse str:int pairs
  1237. def parse_key_value_pair(s):
  1238. key, value = s.split(":")
  1239. return key, int(value)
  1240. def parse_args():
  1241. parser = argparse.ArgumentParser(
  1242. description="""Blockwise int4 quantization for MatMul 2D weight matrices.
  1243. A weight matrix is partitioned into into blocks, where each block is a
  1244. continguous subset inside each column. Each block is quantized into a
  1245. set of 4b integers with a scaling factor and an optional offset.
  1246. """
  1247. )
  1248. parser.add_argument("--input_model", required=True, help="Path to the input model file")
  1249. parser.add_argument("--output_model", required=True, help="Path to the output model file")
  1250. parser.add_argument("--block_size", required=False, default=32, type=int, help="Block size for quantization")
  1251. parser.add_argument(
  1252. "--quant_method",
  1253. default="default",
  1254. type=str,
  1255. choices=["default", "hqq", "rtn", "k_quant", "gptq", "nvidia_awq"],
  1256. help="the algorithm used to quantize weight, \nrtn and gptq leverage Intel® Neural Compressor",
  1257. )
  1258. parser.add_argument("--bits", default=4, type=int, help="the target bits to represent weight")
  1259. parser.add_argument(
  1260. "--symmetric",
  1261. required=False,
  1262. default=True,
  1263. const=True,
  1264. nargs="?",
  1265. type=ort_convert_str_to_bool,
  1266. choices=[True, False],
  1267. help="Indicate whether to quantize the model symmetrically, symmetric is not supported by hqq",
  1268. )
  1269. parser.add_argument(
  1270. "--accuracy_level",
  1271. required=False,
  1272. type=int,
  1273. help="Accuracy level of the 4-bit quantized MatMul computation. "
  1274. "Refer to the MatMulNBits contrib op's 'accuracy_level' attribute for details "
  1275. "(https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits).",
  1276. )
  1277. parser.add_argument("-v", "--verbose", required=False, action="store_true")
  1278. parser.set_defaults(verbose=False)
  1279. parser.add_argument(
  1280. "--nodes_to_exclude",
  1281. nargs="+",
  1282. type=str,
  1283. required=False,
  1284. default=[],
  1285. help="Specify the nodes to be excluded from quantization with node names",
  1286. )
  1287. parser.add_argument(
  1288. "--nodes_to_include",
  1289. nargs="+",
  1290. type=str,
  1291. required=False,
  1292. help="Specify the specific nodes to be included from quantization with node names",
  1293. )
  1294. parser.add_argument(
  1295. "--quant_format",
  1296. default="QOperator",
  1297. type=str,
  1298. choices=["QOperator", "QDQ"],
  1299. help="QuantFormat {QOperator, QDQ}"
  1300. "QOperator format quantizes the model with quantized operators directly."
  1301. "QDQ format quantize the model by inserting DeQuantizeLinear before the MatMul.",
  1302. )
  1303. parser.add_argument(
  1304. "--op_types_to_quantize",
  1305. type=str,
  1306. nargs="+",
  1307. choices=["MatMul", "Gather"],
  1308. help="op_types_to_quantize {MatMul, Gather}. Operators to quantize. Default is MatMul.",
  1309. )
  1310. parser.add_argument(
  1311. "--quant_axes",
  1312. type=parse_key_value_pair,
  1313. nargs="+",
  1314. required=False,
  1315. help="Key-value pairs in op_type:axis_to_quantize separated by space."
  1316. "Specify the axis to quantize for an op. Default {MatMul:0, Gather:1}"
  1317. "Example: --quant_axes MatMul:0 Gather:1",
  1318. )
  1319. # Group arguments specific to nvidia_awq
  1320. nv_awq_config = parser.add_argument_group("nvidia_awq", "Arguments specific to nvidia_awq quantization")
  1321. nv_awq_config.add_argument(
  1322. "--calib_dataset_name",
  1323. type=str,
  1324. default="cnn",
  1325. help="Name of the calibration dataset for nvidia_awq.",
  1326. )
  1327. nv_awq_config.add_argument(
  1328. "--tokenizer_dir",
  1329. type=str,
  1330. required=False,
  1331. help="Path of the tokenizer dir.",
  1332. )
  1333. nv_awq_config.add_argument(
  1334. "--calibration_method",
  1335. type=str,
  1336. required=False,
  1337. choices=["awq", "awq_clip"],
  1338. help="Support two options, awq implementation and weight clipping.",
  1339. )
  1340. nv_awq_config.add_argument(
  1341. "--cache_dir",
  1342. type=str,
  1343. default="./cache",
  1344. help="Cache directory for calibration data.",
  1345. )
  1346. return parser.parse_args()
  1347. if __name__ == "__main__":
  1348. args = parse_args()
  1349. if args.verbose:
  1350. logger.setLevel(logging.DEBUG)
  1351. input_model_path = args.input_model
  1352. output_model_path = args.output_model
  1353. quant_format = QuantFormat[args.quant_format]
  1354. op_types_to_quantize = tuple(args.op_types_to_quantize) if args.op_types_to_quantize else ("MatMul",)
  1355. quant_axes = tuple(args.quant_axes) if args.quant_axes else None
  1356. if os.path.exists(output_model_path):
  1357. logger.error(f"file {output_model_path} already exists")
  1358. raise Exception(f"file {output_model_path} already exists")
  1359. if args.symmetric and args.quant_method == "hqq":
  1360. logger.warning("symmetric is not supportted by hqq, will force to symmetric=False")
  1361. args.symmetric = False
  1362. model = onnx.load(input_model_path)
  1363. if args.quant_method == "hqq":
  1364. quant_config = HQQWeightOnlyQuantConfig(
  1365. block_size=args.block_size, bits=args.bits, op_types_to_quantize=op_types_to_quantize, quant_axes=quant_axes
  1366. )
  1367. elif args.quant_method == "default":
  1368. quant_config = DefaultWeightOnlyQuantConfig(
  1369. block_size=args.block_size,
  1370. is_symmetric=args.symmetric,
  1371. accuracy_level=args.accuracy_level,
  1372. quant_format=quant_format,
  1373. op_types_to_quantize=op_types_to_quantize,
  1374. quant_axes=quant_axes,
  1375. bits=args.bits,
  1376. )
  1377. elif args.quant_method == "rtn":
  1378. quant_config = RTNWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize)
  1379. elif args.quant_method == "k_quant":
  1380. quant_config = KQuantWeightOnlyQuantConfig(op_types_to_quantize=op_types_to_quantize)
  1381. elif args.quant_method == "gptq":
  1382. quant_config = GPTQWeightOnlyQuantConfig(block_size=args.block_size, op_types_to_quantize=op_types_to_quantize)
  1383. elif args.quant_method == "nvidia_awq":
  1384. if quant_format == QuantFormat.QOperator:
  1385. logger.warning("QOperator is not applicable to nvidia_awq. overriding the value to QDQ")
  1386. quant_format = QuantFormat.QDQ
  1387. model = input_model_path
  1388. if args.calibration_method is not None:
  1389. if args.calibration_method == "awq":
  1390. calibration_method = "awq_lite"
  1391. else:
  1392. calibration_method = "awq_clip"
  1393. else:
  1394. calibration_method = "awq_lite"
  1395. quant_config = NVAWQWeightOnlyQuantConfig(
  1396. dataset_name=args.calib_dataset_name,
  1397. tokenizer_dir=args.tokenizer_dir,
  1398. cache_dir=args.cache_dir,
  1399. calibration_method=calibration_method,
  1400. )
  1401. else:
  1402. raise ValueError(f"Unsupported quantization method: {args.quant_method}")
  1403. quant = MatMulNBitsQuantizer(
  1404. model=model,
  1405. accuracy_level=args.accuracy_level,
  1406. nodes_to_exclude=args.nodes_to_exclude,
  1407. nodes_to_include=args.nodes_to_include,
  1408. algo_config=quant_config,
  1409. )
  1410. quant.process()
  1411. quant.model.save_model_to_file(output_model_path, True)