calibrate.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. #!/usr/bin/env python
  2. # -------------------------------------------------------------------------
  3. # Copyright (c) Microsoft, Intel Corporation. All rights reserved.
  4. # Licensed under the MIT License. See License.txt in the project root for
  5. # license information.
  6. # --------------------------------------------------------------------------
  7. import abc
  8. import copy
  9. import itertools
  10. import os
  11. import uuid
  12. from collections.abc import Sequence
  13. from enum import Enum
  14. from pathlib import Path
  15. import numpy as np
  16. import onnx
  17. from onnx import ModelProto, TensorProto, helper, numpy_helper
  18. import onnxruntime
  19. from .quant_utils import apply_plot, load_model_with_shape_infer, smooth_distribution
  20. def rel_entr(pk: np.ndarray, qk: np.ndarray) -> np.ndarray:
  21. """
  22. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.rel_entr.html#scipy.special.rel_entr.
  23. Python implementation.
  24. """
  25. res = np.empty(pk.shape, dtype=pk.dtype)
  26. res[:] = pk[:] * np.log(pk[:] / qk[:])
  27. c2 = (pk == 0) & (qk >= 0)
  28. res[c2] = 0
  29. c1 = (pk > 0) & (qk > 0)
  30. res[~c1] = np.inf
  31. return res
  32. def entropy(
  33. pk: np.ndarray,
  34. qk: np.ndarray,
  35. base: float | None = None,
  36. axis: int = 0,
  37. ) -> np.ndarray:
  38. """
  39. Simplifeied version of entropy.
  40. Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html.
  41. This avoids taking a dependency on scipy just for this function.
  42. """
  43. assert base is None or base > 0, "base={base} must be a positive number or `None`."
  44. assert qk is not None, "qk is None"
  45. pk = np.asarray(pk).astype(np.float32)
  46. pk = 1.0 * pk / np.sum(pk, axis=axis, keepdims=True)
  47. qk = np.asarray(qk).astype(np.float32)
  48. pk, qk = np.broadcast_arrays(pk, qk)
  49. qk = 1.0 * qk / np.sum(qk, axis=axis, keepdims=True)
  50. vec = rel_entr(pk, qk)
  51. s = np.sum(vec, axis=axis)
  52. if base is not None:
  53. s /= np.log(base)
  54. return s.astype(pk.dtype)
  55. class TensorData:
  56. _allowed = frozenset(["avg", "std", "lowest", "highest", "hist", "hist_edges", "bins"])
  57. _floats = frozenset(["avg", "std", "lowest", "highest", "hist_edges"])
  58. def __init__(self, **kwargs):
  59. self._attrs = list(kwargs.keys())
  60. for k, v in kwargs.items():
  61. if k not in TensorData._allowed:
  62. raise ValueError(f"Unexpected value {k!r} not in {TensorData._allowed}.")
  63. if k in TensorData._floats:
  64. if not hasattr(v, "dtype"):
  65. raise ValueError(f"Unexpected type {type(v)} for k={k!r}")
  66. if v.dtype not in (np.float16, np.float32):
  67. raise ValueError(f"Unexpected dtype {v.dtype} for k={k!r}")
  68. setattr(self, k, v)
  69. @property
  70. def range_value(self):
  71. if not hasattr(self, "lowest") or not hasattr(self, "highest"):
  72. raise AttributeError(f"Attributes 'lowest' and/or 'highest' missing in {dir(self)}.")
  73. return (self.lowest, self.highest)
  74. @property
  75. def avg_std(self):
  76. if not hasattr(self, "avg") or not hasattr(self, "std"):
  77. raise AttributeError(f"Attributes 'avg' and/or 'std' missing in {dir(self)}.")
  78. return (self.avg, self.std)
  79. def to_dict(self):
  80. # This is needed to serialize the data into JSON.
  81. data = {k: getattr(self, k) for k in self._attrs}
  82. data["CLS"] = self.__class__.__name__
  83. return data
  84. class TensorsData:
  85. def __init__(self, calibration_method, data: dict[str, TensorData | tuple]):
  86. self.calibration_method = calibration_method
  87. self.data = {}
  88. for k, v in data.items():
  89. if not isinstance(k, str):
  90. raise TypeError(f"Keys must be strings not {type(k)}.")
  91. if isinstance(v, tuple):
  92. if calibration_method == CalibrationMethod.MinMax and len(v) == 2:
  93. self.data[k] = TensorData(lowest=v[0], highest=v[1])
  94. continue
  95. if len(v) == 4:
  96. self.data[k] = TensorData(lowest=v[0], highest=v[1], hist=v[2], bins=v[3])
  97. continue
  98. raise TypeError(f"Unexpected tuple for {k:r}, it has {len(v)} elements: {v}.")
  99. if not isinstance(v, TensorData):
  100. raise TypeError(f"Values must be TensorData not {type(v)}.")
  101. self.data[k] = v
  102. def __iter__(self):
  103. yield from self.data
  104. def __contains__(self, key):
  105. return key in self.data
  106. def __getitem__(self, key):
  107. return self.data[key]
  108. def __setitem__(self, key, value):
  109. if key not in self.data:
  110. raise RuntimeError(f"Only an existing tensor can be modified, {key!r} is not.")
  111. self.data[key] = value
  112. def keys(self):
  113. return self.data.keys()
  114. def values(self):
  115. return self.data.values()
  116. def items(self):
  117. return self.data.items()
  118. def to_dict(self):
  119. # This is needed to serialize the data into JSON.
  120. data = {
  121. "CLS": self.__class__.__name__,
  122. "data": self.data,
  123. "calibration_method": self.calibration_method,
  124. }
  125. return data
  126. class CalibrationMethod(Enum):
  127. MinMax = 0
  128. Entropy = 1
  129. Percentile = 2
  130. Distribution = 3
  131. class CalibrationDataReader(metaclass=abc.ABCMeta):
  132. @classmethod
  133. def __subclasshook__(cls, subclass):
  134. return (hasattr(subclass, "get_next") and callable(subclass.get_next)) or NotImplemented
  135. @abc.abstractmethod
  136. def get_next(self) -> dict:
  137. """generate the input data dict for ONNXinferenceSession run"""
  138. raise NotImplementedError
  139. def __iter__(self):
  140. return self
  141. def __next__(self):
  142. result = self.get_next()
  143. if result is None:
  144. raise StopIteration
  145. return result
  146. def __len__(self):
  147. raise NotImplementedError
  148. def set_range(self, start_index: int, end_index: int):
  149. raise NotImplementedError
  150. class CalibraterBase:
  151. def __init__(
  152. self,
  153. model_path: str | Path,
  154. op_types_to_calibrate: Sequence[str] | None = None,
  155. augmented_model_path="augmented_model.onnx",
  156. symmetric=False,
  157. use_external_data_format=False,
  158. per_channel=False,
  159. ):
  160. """
  161. :param model_path: ONNX model to calibrate. It should be a model file path
  162. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  163. :param augmented_model_path: save augmented model to this path.
  164. :param symmetric: make range of tensor symmetric (central point is 0).
  165. :param use_external_data_format: use external data format to store model which size is >= 2Gb.
  166. :param per_channel: whether to compute ranges per each channel.
  167. """
  168. if isinstance(model_path, str):
  169. self.model = load_model_with_shape_infer(Path(model_path))
  170. elif isinstance(model_path, Path):
  171. self.model = load_model_with_shape_infer(model_path)
  172. else:
  173. raise ValueError("model_path should be model path.")
  174. self.op_types_to_calibrate = op_types_to_calibrate
  175. self.augmented_model_path = augmented_model_path
  176. self.symmetric = symmetric
  177. self.use_external_data_format = use_external_data_format
  178. self.per_channel = per_channel
  179. self.augment_model = None
  180. self.infer_session = None
  181. self.execution_providers = ["CPUExecutionProvider"]
  182. def set_execution_providers(self, execution_providers=["CPUExecutionProvider"]): # noqa: B006
  183. """
  184. reset the execution providers to execute the collect_data. It triggers to re-creating inference session.
  185. """
  186. self.execution_providers = execution_providers
  187. self.create_inference_session()
  188. def create_inference_session(self):
  189. """
  190. create an OnnxRuntime InferenceSession.
  191. """
  192. sess_options = onnxruntime.SessionOptions()
  193. sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
  194. self.infer_session = onnxruntime.InferenceSession(
  195. self.augmented_model_path,
  196. sess_options=sess_options,
  197. providers=self.execution_providers,
  198. )
  199. def select_tensors_to_calibrate(self, model: ModelProto):
  200. """
  201. select input/output tensors of candidate nodes to calibrate.
  202. returns:
  203. tensors (set): set of tensor name.
  204. value_infos (dict): tensor name to value info.
  205. """
  206. value_infos = {vi.name: vi for vi in model.graph.value_info}
  207. value_infos.update({ot.name: ot for ot in model.graph.output})
  208. value_infos.update({it.name: it for it in model.graph.input})
  209. initializer = {init.name for init in model.graph.initializer}
  210. tensors_to_calibrate = set()
  211. tensor_type_to_calibrate = {TensorProto.FLOAT, TensorProto.FLOAT16}
  212. for node in model.graph.node:
  213. if not self.op_types_to_calibrate or node.op_type in self.op_types_to_calibrate:
  214. for tensor_name in itertools.chain(node.input, node.output):
  215. if tensor_name in value_infos:
  216. vi = value_infos[tensor_name]
  217. if (
  218. vi.type.HasField("tensor_type")
  219. and (vi.type.tensor_type.elem_type in tensor_type_to_calibrate)
  220. and (tensor_name not in initializer)
  221. ):
  222. tensors_to_calibrate.add(tensor_name)
  223. return tensors_to_calibrate, value_infos
  224. def get_augment_model(self):
  225. """
  226. return: augmented onnx model. Call after calling augment_graph
  227. """
  228. return self.model
  229. def augment_graph(self):
  230. """
  231. abstract method: augment the input model to prepare for collecting data. It will:
  232. 1. augment the model to be able to collect desired statistics data
  233. 2. save augmented model to augmented_model_paths
  234. """
  235. raise NotImplementedError
  236. def collect_data(self, data_reader: CalibrationDataReader):
  237. """
  238. abstract method: collect the tensors that will be used for range computation. It can be called multiple times.
  239. """
  240. raise NotImplementedError
  241. def compute_data(self) -> TensorsData:
  242. """
  243. abstract method: compute data based on the calibration method stored in TensorsData
  244. """
  245. raise NotImplementedError
  246. class MinMaxCalibrater(CalibraterBase):
  247. def __init__(
  248. self,
  249. model_path: str | Path,
  250. op_types_to_calibrate: Sequence[str] | None = None,
  251. augmented_model_path="augmented_model.onnx",
  252. symmetric=False,
  253. use_external_data_format=False,
  254. moving_average=False,
  255. averaging_constant=0.01,
  256. max_intermediate_outputs=None,
  257. per_channel=False,
  258. ):
  259. """
  260. :param model_path: ONNX model to calibrate. It is a model path
  261. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  262. :param augmented_model_path: save augmented model to this path.
  263. :param symmetric: make range of tensor symmetric (central point is 0).
  264. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  265. :param moving_average: compute the moving average of the minimum and maximum values instead of the global minimum and maximum.
  266. :param averaging_constant: constant smoothing factor to use when computing the moving average.
  267. :param max_intermediate_outputs: maximum number of intermediate outputs before an intermediate range is computed.
  268. :param per_channel: whether to compute ranges per each channel.
  269. """
  270. super().__init__(
  271. model_path,
  272. op_types_to_calibrate=op_types_to_calibrate,
  273. augmented_model_path=augmented_model_path,
  274. symmetric=symmetric,
  275. use_external_data_format=use_external_data_format,
  276. per_channel=per_channel,
  277. )
  278. self.intermediate_outputs = []
  279. self.calibrate_tensors_range = None
  280. self.num_model_outputs = len(self.model.graph.output)
  281. self.model_original_outputs = {output.name for output in self.model.graph.output}
  282. self.moving_average = moving_average
  283. if moving_average and (averaging_constant < 0 or averaging_constant > 1):
  284. raise ValueError("Invalid averaging constant, which should not be < 0 or > 1.")
  285. self.averaging_constant = averaging_constant
  286. self.max_intermediate_outputs = max_intermediate_outputs
  287. def augment_graph(self):
  288. """
  289. Adds ReduceMin and ReduceMax nodes to all quantization_candidates op type nodes in
  290. model and ensures their outputs are stored as part of the graph output
  291. :return: augmented ONNX model
  292. """
  293. tensors, _ = self.select_tensors_to_calibrate(self.model)
  294. reshape_shape_name = str(uuid.uuid4())
  295. reshape_shape = numpy_helper.from_array(np.array([-1], dtype=np.int64), reshape_shape_name)
  296. self.model.graph.initializer.append(reshape_shape)
  297. def get_op_version(op_type, model):
  298. for opset_import in model.opset_import:
  299. if onnx.defs.has(op_type, opset_import.domain):
  300. return opset_import.version
  301. raise RuntimeError(f"Model does not contain a version for '{op_type}'.")
  302. def insert_nodes(tensor_name, new_nodes):
  303. index = next(
  304. (i for i, x in enumerate(self.model.graph.node) if tensor_name in x.input), len(self.model.graph.node)
  305. )
  306. for node in new_nodes:
  307. self.model.graph.node.insert(index, node)
  308. index += 1
  309. def add_reduce_min_max(tensor_name, reduce_op_name):
  310. # When doing ReduceMax/ReduceMin, ORT can't reduce on dim with value of 0 if 'keepdims' is false.
  311. # To make the code simple, we always let keepdims to be 1.
  312. keepdims = 1
  313. # Adding ReduceMin/ReduceMax nodes: ReduceMin/ReduceMax -> Reshape-> (output)
  314. reduce_output = tensor_name + "_" + reduce_op_name
  315. intermediate_output = reduce_output + "_Reshape"
  316. reduce_node = onnx.helper.make_node(
  317. reduce_op_name, [tensor_name], [intermediate_output], keepdims=keepdims, name=reduce_output
  318. )
  319. reshape_node = onnx.helper.make_node(
  320. "Reshape",
  321. inputs=[intermediate_output, reshape_shape_name],
  322. outputs=[reduce_output],
  323. name=intermediate_output,
  324. )
  325. value_infos = {vi.name: vi for vi in self.model.graph.value_info}
  326. value_infos.update({o.name: o for o in self.model.graph.output})
  327. value_infos.update({i.name: i for i in self.model.graph.input})
  328. if tensor_name in value_infos:
  329. onnx_type = value_infos[tensor_name].type.tensor_type.elem_type
  330. else:
  331. raise ValueError(
  332. f"Unable to guess tensor type for tensor {tensor_name!r}, "
  333. "running shape inference before quantization may resolve this issue."
  334. )
  335. # Include axes in reduce_op when per_channel, always keeping axis=1
  336. if self.per_channel:
  337. tensor_rank = len(value_infos[tensor_name].type.tensor_type.shape.dim)
  338. reduced_axes = [0, *range(2, tensor_rank)]
  339. # Depending on opset version, axes in ReduceMin/ReduceMax are in attribute or inputs
  340. if get_op_version(reduce_op_name, self.model) < 18:
  341. reduce_node.attribute.append(helper.make_attribute("axes", reduced_axes))
  342. else:
  343. reduce_axes_name = str(uuid.uuid4())
  344. reduce_axes = numpy_helper.from_array(np.array(reduced_axes, dtype=np.int64), reduce_axes_name)
  345. reduce_node.input.append(reduce_axes_name)
  346. self.model.graph.initializer.append(reduce_axes)
  347. insert_nodes(tensor_name, [reduce_node, reshape_node])
  348. self.model.graph.output.append(helper.make_tensor_value_info(reduce_output, onnx_type, [None]))
  349. for tensor in tensors:
  350. add_reduce_min_max(tensor, "ReduceMin")
  351. add_reduce_min_max(tensor, "ReduceMax")
  352. onnx.save(
  353. self.model,
  354. self.augmented_model_path,
  355. save_as_external_data=self.use_external_data_format,
  356. )
  357. def clear_collected_data(self):
  358. self.intermediate_outputs = []
  359. def collect_data(self, data_reader: CalibrationDataReader):
  360. while True:
  361. inputs = data_reader.get_next()
  362. if not inputs:
  363. break
  364. self.intermediate_outputs.append(
  365. [
  366. value if sess_o.name not in self.model_original_outputs else None
  367. for sess_o, value in zip(
  368. self.infer_session.get_outputs(), self.infer_session.run(None, inputs), strict=False
  369. )
  370. ]
  371. )
  372. if (
  373. self.max_intermediate_outputs is not None
  374. and len(self.intermediate_outputs) == self.max_intermediate_outputs
  375. ):
  376. self.clear_collected_data()
  377. if len(self.intermediate_outputs) == 0 and self.calibrate_tensors_range is None:
  378. raise ValueError("No data is collected.")
  379. t = self.compute_data()
  380. if not isinstance(t, TensorsData):
  381. raise TypeError(f"compute_data must return a TensorsData not {type(t)}.")
  382. self.clear_collected_data()
  383. def merge_range(self, old_range, new_range):
  384. if not old_range:
  385. return new_range
  386. for key, value in old_range.items():
  387. # Handling for structured data types with TensorData
  388. if isinstance(value, TensorData):
  389. old_min = value.range_value[0]
  390. old_max = value.range_value[1]
  391. else:
  392. old_min, old_max = value
  393. if isinstance(new_range[key], TensorData):
  394. new_min = new_range[key].range_value[0]
  395. new_max = new_range[key].range_value[1]
  396. else:
  397. new_min, new_max = new_range[key]
  398. if self.moving_average:
  399. min_value = old_min + self.averaging_constant * (new_min - old_min)
  400. max_value = old_max + self.averaging_constant * (new_max - old_max)
  401. else:
  402. min_value = min(old_min, new_min)
  403. max_value = max(old_max, new_max)
  404. # If structured as TensorData, wrap the result accordingly
  405. if isinstance(value, TensorData) or isinstance(new_range[key], TensorData):
  406. new_range[key] = TensorData(lowest=min_value, highest=max_value)
  407. else:
  408. new_range[key] = (min_value, max_value)
  409. return new_range
  410. def compute_data(self) -> TensorsData:
  411. """
  412. Compute the min-max range of tensor
  413. :return: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs }
  414. """
  415. if len(self.intermediate_outputs) == 0:
  416. return self.calibrate_tensors_range
  417. output_names = [self.infer_session.get_outputs()[i].name for i in range(len(self.intermediate_outputs[0]))]
  418. output_dicts_list = [
  419. dict(zip(output_names, intermediate_output, strict=False))
  420. for intermediate_output in self.intermediate_outputs
  421. ]
  422. merged_output_dict = {}
  423. for d in output_dicts_list:
  424. for k, v in d.items():
  425. merged_output_dict.setdefault(k, []).append(v)
  426. added_output_names = output_names[self.num_model_outputs :]
  427. calibrate_tensor_names = [
  428. added_output_names[i].rpartition("_")[0] for i in range(0, len(added_output_names), 2)
  429. ] # output names
  430. merged_added_output_dict = {
  431. i: merged_output_dict[i] for i in merged_output_dict if i not in self.model_original_outputs
  432. }
  433. pairs = []
  434. for i in range(0, len(added_output_names), 2):
  435. if self.moving_average:
  436. min_value_array = np.nanmean(merged_added_output_dict[added_output_names[i]], axis=0)
  437. max_value_array = np.nanmean(merged_added_output_dict[added_output_names[i + 1]], axis=0)
  438. else:
  439. min_value_array = np.nanmin(merged_added_output_dict[added_output_names[i]], axis=0)
  440. max_value_array = np.nanmax(merged_added_output_dict[added_output_names[i + 1]], axis=0)
  441. if self.symmetric:
  442. max_absolute_value = np.nanmax([np.abs(min_value_array), np.abs(max_value_array)], axis=0)
  443. pairs.append((-max_absolute_value, max_absolute_value))
  444. else:
  445. pairs.append((min_value_array, max_value_array))
  446. new_calibrate_tensors_range = TensorsData(
  447. CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs, strict=False))
  448. )
  449. if self.calibrate_tensors_range:
  450. self.calibrate_tensors_range = self.merge_range(self.calibrate_tensors_range, new_calibrate_tensors_range)
  451. else:
  452. self.calibrate_tensors_range = new_calibrate_tensors_range
  453. return self.calibrate_tensors_range
  454. class HistogramCalibrater(CalibraterBase):
  455. def __init__(
  456. self,
  457. model_path: str | Path,
  458. op_types_to_calibrate: Sequence[str] | None = None,
  459. augmented_model_path="augmented_model.onnx",
  460. use_external_data_format=False,
  461. method="percentile",
  462. symmetric=False,
  463. num_bins=128,
  464. num_quantized_bins=2048,
  465. percentile=99.999,
  466. scenario="same",
  467. ):
  468. """
  469. :param model_path: ONNX model to calibrate. It is a model path.
  470. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  471. :param augmented_model_path: save augmented model to this path.
  472. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  473. :param method: A string. One of ['entropy', 'percentile'].
  474. :param symmetric: make range of tensor symmetric (central point is 0).
  475. :param num_bins: number of bins to create a new histogram for collecting tensor values.
  476. :param num_quantized_bins: number of quantized bins. Default 128.
  477. :param percentile: A float number between [0, 100]. Default 99.99.
  478. :param scenario: see :class:`DistributionCalibrater`
  479. """
  480. super().__init__(
  481. model_path,
  482. op_types_to_calibrate=op_types_to_calibrate,
  483. augmented_model_path=augmented_model_path,
  484. symmetric=symmetric,
  485. use_external_data_format=use_external_data_format,
  486. )
  487. self.intermediate_outputs = []
  488. self.calibrate_tensors_range = None
  489. self.num_model_outputs = len(self.model.graph.output)
  490. self.model_original_outputs = {output.name for output in self.model.graph.output}
  491. self.collector = None
  492. self.method = method
  493. self.num_bins = num_bins
  494. self.num_quantized_bins = num_quantized_bins
  495. self.percentile = percentile
  496. self.tensors_to_calibrate = None
  497. self.scenario = scenario
  498. def augment_graph(self):
  499. """
  500. make all quantization_candidates op type nodes as part of the graph output.
  501. :return: augmented ONNX model
  502. """
  503. self.tensors_to_calibrate, value_infos = self.select_tensors_to_calibrate(self.model)
  504. for tensor in self.tensors_to_calibrate:
  505. if tensor not in self.model_original_outputs:
  506. self.model.graph.output.append(value_infos[tensor])
  507. onnx.save(
  508. self.model,
  509. self.augmented_model_path,
  510. save_as_external_data=self.use_external_data_format,
  511. )
  512. def clear_collected_data(self):
  513. self.intermediate_outputs = []
  514. def collect_data(self, data_reader: CalibrationDataReader):
  515. """
  516. Entropy Calibrator collects operators' tensors as well as generates tensor histogram for each operator.
  517. """
  518. input_names_set = {node_arg.name for node_arg in self.infer_session.get_inputs()}
  519. output_names = [node_arg.name for node_arg in self.infer_session.get_outputs()]
  520. while True:
  521. inputs = data_reader.get_next()
  522. if not inputs:
  523. break
  524. outputs = self.infer_session.run(None, inputs)
  525. # Copy np.ndarray only for graph outputs that are also graph inputs to workaround bug:
  526. # https://github.com/microsoft/onnxruntime/issues/21922
  527. fixed_outputs = []
  528. for output_index, output in enumerate(outputs):
  529. if output_names[output_index] in input_names_set:
  530. fixed_outputs.append(copy.copy(output))
  531. else:
  532. fixed_outputs.append(output)
  533. self.intermediate_outputs.append(fixed_outputs)
  534. if len(self.intermediate_outputs) == 0:
  535. raise ValueError("No data is collected.")
  536. output_dicts_list = [
  537. dict(zip(output_names, intermediate_output, strict=False))
  538. for intermediate_output in self.intermediate_outputs
  539. ]
  540. merged_dict = {}
  541. for d in output_dicts_list:
  542. for k, v in d.items():
  543. merged_dict.setdefault(k, []).append(v)
  544. clean_merged_dict = {i: merged_dict[i] for i in merged_dict if i in self.tensors_to_calibrate}
  545. if not self.collector:
  546. self.collector = HistogramCollector(
  547. method=self.method,
  548. symmetric=self.symmetric,
  549. num_bins=self.num_bins,
  550. num_quantized_bins=self.num_quantized_bins,
  551. percentile=self.percentile,
  552. scenario=self.scenario,
  553. )
  554. self.collector.collect(clean_merged_dict)
  555. self.clear_collected_data()
  556. def compute_data(self) -> TensorsData:
  557. """
  558. Compute the min-max range of tensor
  559. :return: dictionary mapping: {tensor name: (min value, max value)}
  560. """
  561. if not self.collector:
  562. raise ValueError("No collector created and can't generate calibration data.")
  563. if isinstance(self, EntropyCalibrater):
  564. cal = CalibrationMethod.Entropy
  565. elif isinstance(self, PercentileCalibrater):
  566. cal = CalibrationMethod.Percentile
  567. elif isinstance(self, DistributionCalibrater):
  568. cal = CalibrationMethod.Distribution
  569. else:
  570. raise TypeError(f"Unknown calibrater {type(self)}. This method must be overwritten.")
  571. return TensorsData(cal, self.collector.compute_collection_result())
  572. class EntropyCalibrater(HistogramCalibrater):
  573. def __init__(
  574. self,
  575. model_path: str | Path,
  576. op_types_to_calibrate: Sequence[str] | None = None,
  577. augmented_model_path="augmented_model.onnx",
  578. use_external_data_format=False,
  579. method="entropy",
  580. symmetric=False,
  581. num_bins=128,
  582. num_quantized_bins=128,
  583. ):
  584. """
  585. :param model_path: ONNX model to calibrate. It is a model path
  586. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  587. :param augmented_model_path: save augmented model to this path.
  588. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  589. :param method: A string. One of ['entropy', 'percentile', 'distribution'].
  590. :param symmetric: make range of tensor symmetric (central point is 0).
  591. :param num_bins: number of bins to create a new histogram for collecting tensor values.
  592. :param num_quantized_bins: number of quantized bins. Default 128.
  593. """
  594. super().__init__(
  595. model_path,
  596. op_types_to_calibrate,
  597. augmented_model_path,
  598. use_external_data_format,
  599. method=method,
  600. symmetric=symmetric,
  601. num_bins=num_bins,
  602. num_quantized_bins=num_quantized_bins,
  603. )
  604. class PercentileCalibrater(HistogramCalibrater):
  605. def __init__(
  606. self,
  607. model_path: str | Path,
  608. op_types_to_calibrate: Sequence[str] | None = None,
  609. augmented_model_path="augmented_model.onnx",
  610. use_external_data_format=False,
  611. method="percentile",
  612. symmetric=False,
  613. num_bins=2048,
  614. percentile=99.999,
  615. ):
  616. """
  617. :param model_path: ONNX model to calibrate. It is a model path
  618. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  619. :param augmented_model_path: save augmented model to this path.
  620. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  621. :param method: A string. One of ['entropy', 'percentile', 'distribution'].
  622. :param symmetric: make range of tensor symmetric (central point is 0).
  623. :param num_quantized_bins: number of quantized bins. Default 128.
  624. :param percentile: A float number between [0, 100]. Default 99.99.
  625. """
  626. super().__init__(
  627. model_path,
  628. op_types_to_calibrate,
  629. augmented_model_path,
  630. use_external_data_format,
  631. method=method,
  632. symmetric=symmetric,
  633. num_bins=num_bins,
  634. percentile=percentile,
  635. )
  636. class DistributionCalibrater(HistogramCalibrater):
  637. def __init__(
  638. self,
  639. model_path: str | Path,
  640. op_types_to_calibrate: Sequence[str] | None = None,
  641. augmented_model_path="augmented_model.onnx",
  642. use_external_data_format=False,
  643. method="distribution",
  644. num_bins=128,
  645. scenario="same",
  646. ):
  647. """
  648. :param model_path: ONNX model to calibrate. It is a model path
  649. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  650. :param augmented_model_path: save augmented model to this path.
  651. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  652. :param method: A string. One of ['entropy', 'percentile', 'distribution'].
  653. :param symmetric: make range of tensor symmetric (central point is 0).
  654. :param num_bins: number of bins to create a new histogram for collecting tensor values.
  655. :param scenario: for float 8 only, if `scenario="same"`,
  656. the algorithm weights and float 8 follow the same distribution,
  657. if `scenario="p3"`, it assumes the weights follow
  658. a gaussian law and float 8 ~ X^3 where X is a gaussian law
  659. """
  660. super().__init__(
  661. model_path,
  662. op_types_to_calibrate,
  663. augmented_model_path,
  664. use_external_data_format,
  665. method=method,
  666. num_bins=num_bins,
  667. scenario=scenario,
  668. )
  669. class CalibrationDataCollector(metaclass=abc.ABCMeta):
  670. """
  671. Base class for collecting data for calibration-based quantization.
  672. """
  673. @abc.abstractmethod
  674. def collect(self, name_to_arr):
  675. """
  676. Generate informative data based on given data.
  677. name_to_arr : dict
  678. tensor name to NDArray data
  679. """
  680. raise NotImplementedError
  681. @abc.abstractmethod
  682. def compute_collection_result(self):
  683. """
  684. Get the optimal result among collection data.
  685. """
  686. raise NotImplementedError
  687. class HistogramCollector(CalibrationDataCollector):
  688. """
  689. Collecting histogram for each tensor. Percentile and Entropy method are supported.
  690. ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py
  691. ref: https://docs.nvidia.com/deeplearning/tensorrt/pytorch-quantization-toolkit/docs/_modules/
  692. pytorch_quantization/calib/histogram.html
  693. """
  694. def __init__(self, method, symmetric, num_bins, num_quantized_bins, percentile, scenario):
  695. self.histogram_dict = {}
  696. self.method = method
  697. self.symmetric = symmetric
  698. self.num_bins = num_bins
  699. self.num_quantized_bins = num_quantized_bins
  700. self.percentile = percentile
  701. self.scenario = scenario
  702. def get_histogram_dict(self):
  703. return self.histogram_dict
  704. def collect(self, name_to_arr):
  705. print("Collecting tensor data and making histogram ...")
  706. # TODO: Currently we have different collect() for entropy and percentile method respectively.
  707. # Need unified collect in the future.
  708. if self.method in {"distribution", "entropy"}:
  709. return self.collect_value(name_to_arr)
  710. elif self.method == "percentile":
  711. if self.symmetric:
  712. return self.collect_absolute_value(name_to_arr)
  713. else:
  714. return self.collect_value(name_to_arr)
  715. else:
  716. raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
  717. def collect_absolute_value(self, name_to_arr):
  718. """
  719. Collect histogram on absolute value
  720. """
  721. for tensor, data_arr in name_to_arr.items():
  722. if isinstance(data_arr, list):
  723. for arr in data_arr:
  724. assert isinstance(arr, np.ndarray), f"Unexpected type {type(arr)} for tensor={tensor!r}"
  725. dtypes = {a.dtype for a in data_arr}
  726. assert len(dtypes) == 1, (
  727. f"The calibration expects only one element type but got {dtypes} for tensor={tensor!r}"
  728. )
  729. data_arr_np = np.asarray(data_arr)
  730. elif not isinstance(data_arr, np.ndarray):
  731. raise ValueError(f"Unexpected type {type(data_arr)} for tensor={tensor!r}")
  732. else:
  733. data_arr_np = data_arr
  734. data_arr_np = data_arr_np.flatten()
  735. if data_arr_np.size > 0:
  736. min_value = np.nanmin(data_arr_np)
  737. max_value = np.nanmax(data_arr_np)
  738. else:
  739. min_value = np.array(0, dtype=data_arr_np.dtype)
  740. max_value = np.array(0, dtype=data_arr_np.dtype)
  741. data_arr_np = np.absolute(data_arr_np) # only consider absolute value
  742. if tensor not in self.histogram_dict:
  743. # first time it uses num_bins to compute histogram.
  744. hist, hist_edges = np.histogram(data_arr_np, bins=self.num_bins)
  745. hist_edges = hist_edges.astype(data_arr_np.dtype)
  746. assert data_arr_np.dtype != np.float64, (
  747. "only float32 or float16 is supported, every constant must be explicitly typed"
  748. )
  749. self.histogram_dict[tensor] = (hist, hist_edges, min_value, max_value)
  750. else:
  751. old_histogram = self.histogram_dict[tensor]
  752. old_min = old_histogram[2]
  753. old_max = old_histogram[3]
  754. assert hasattr(old_min, "dtype"), f"old_min should be a numpy array but is {type(old_min)}"
  755. assert hasattr(old_max, "dtype"), f"old_min should be a numpy array but is {type(old_max)}"
  756. old_hist = old_histogram[0]
  757. old_hist_edges = old_histogram[1]
  758. temp_amax = np.nanmax(data_arr_np)
  759. if temp_amax > old_hist_edges[-1]:
  760. # increase the number of bins
  761. width = old_hist_edges[1] - old_hist_edges[0]
  762. # NOTE: np.arange may create an extra bin after the one containing temp_amax
  763. new_bin_edges = np.arange(old_hist_edges[-1] + width, temp_amax + width, width)
  764. old_hist_edges = np.hstack((old_hist_edges, new_bin_edges))
  765. hist, hist_edges = np.histogram(data_arr_np, bins=old_hist_edges)
  766. hist_edges = hist_edges.astype(data_arr_np.dtype)
  767. hist[: len(old_hist)] += old_hist
  768. assert data_arr_np.dtype != np.float64, (
  769. "only float32 or float16 is supported, every constant must be explicitly typed"
  770. )
  771. self.histogram_dict[tensor] = (hist, hist_edges, min(old_min, min_value), max(old_max, max_value))
  772. def collect_value(self, name_to_arr):
  773. """
  774. Collect histogram on real value
  775. """
  776. for tensor, data_arr in name_to_arr.items():
  777. data_arr = np.asarray(data_arr) # noqa: PLW2901
  778. data_arr = data_arr.flatten() # noqa: PLW2901
  779. if data_arr.size > 0:
  780. min_value = np.nanmin(data_arr)
  781. max_value = np.nanmax(data_arr)
  782. else:
  783. min_value = np.array(0, dtype=data_arr.dtype)
  784. max_value = np.array(0, dtype=data_arr.dtype)
  785. threshold = np.array(max(abs(min_value), abs(max_value)), dtype=data_arr.dtype)
  786. if tensor in self.histogram_dict:
  787. old_histogram = self.histogram_dict[tensor]
  788. self.histogram_dict[tensor] = self.merge_histogram(
  789. old_histogram, data_arr, min_value, max_value, threshold
  790. )
  791. else:
  792. hist, hist_edges = np.histogram(data_arr, self.num_bins, range=(-threshold, threshold))
  793. self.histogram_dict[tensor] = (
  794. hist,
  795. hist_edges,
  796. min_value,
  797. max_value,
  798. threshold,
  799. )
  800. def merge_histogram(self, old_histogram, data_arr, new_min, new_max, new_threshold):
  801. (old_hist, old_hist_edges, old_min, old_max, old_threshold) = old_histogram
  802. if new_threshold <= old_threshold:
  803. new_hist, _ = np.histogram(data_arr, len(old_hist), range=(-old_threshold, old_threshold))
  804. return (
  805. new_hist + old_hist,
  806. old_hist_edges,
  807. min(old_min, new_min),
  808. max(old_max, new_max),
  809. old_threshold,
  810. )
  811. else:
  812. if old_threshold == 0:
  813. hist, hist_edges = np.histogram(data_arr, len(old_hist), range=(-new_threshold, new_threshold))
  814. hist += old_hist
  815. else:
  816. old_num_bins = len(old_hist)
  817. old_stride = 2 * old_threshold / old_num_bins
  818. half_increased_bins = int((new_threshold - old_threshold) // old_stride + 1)
  819. new_num_bins = old_num_bins + 2 * half_increased_bins
  820. new_threshold = half_increased_bins * old_stride + old_threshold
  821. hist, hist_edges = np.histogram(data_arr, new_num_bins, range=(-new_threshold, new_threshold))
  822. hist[half_increased_bins : new_num_bins - half_increased_bins] += old_hist
  823. return (
  824. hist,
  825. hist_edges,
  826. min(old_min, new_min),
  827. max(old_max, new_max),
  828. new_threshold,
  829. )
  830. def compute_collection_result(self):
  831. if not self.histogram_dict or len(self.histogram_dict) == 0:
  832. raise ValueError("Histogram has not been collected. Please run collect() first.")
  833. print(f"Finding optimal threshold for each tensor using {self.method!r} algorithm ...")
  834. if self.method == "entropy":
  835. return self.compute_entropy()
  836. elif self.method == "percentile":
  837. return self.compute_percentile()
  838. elif self.method == "distribution":
  839. return self.compute_distribution()
  840. else:
  841. raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
  842. def compute_percentile(self):
  843. if self.percentile < 0 or self.percentile > 100:
  844. raise ValueError("Invalid percentile. Must be in range 0 <= percentile <= 100.")
  845. histogram_dict = self.histogram_dict
  846. percentile = self.percentile
  847. thresholds_dict = {} # per tensor thresholds
  848. print(f"Number of tensors : {len(histogram_dict)}")
  849. print(f"Number of histogram bins : {self.num_bins}")
  850. print(f"Percentile : ({100.0 - percentile},{percentile})")
  851. for tensor, histogram in histogram_dict.items():
  852. hist = histogram[0]
  853. hist_edges = histogram[1]
  854. total = hist.sum()
  855. cdf = np.cumsum(hist / total)
  856. if self.symmetric:
  857. idx_right = np.searchsorted(cdf, percentile / 100.0)
  858. thresholds_dict[tensor] = (
  859. -np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
  860. np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
  861. )
  862. else:
  863. percent_to_cut_one_side = (100.0 - percentile) / 200.0
  864. idx_right = np.searchsorted(cdf, 1.0 - percent_to_cut_one_side)
  865. idx_left = np.searchsorted(cdf, percent_to_cut_one_side)
  866. thresholds_dict[tensor] = (
  867. np.array(hist_edges[idx_left], dtype=hist_edges.dtype),
  868. np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
  869. )
  870. min_value = histogram[2]
  871. max_value = histogram[3]
  872. if thresholds_dict[tensor][0] < min_value:
  873. thresholds_dict[tensor] = (min_value, thresholds_dict[tensor][1])
  874. if thresholds_dict[tensor][1] > max_value:
  875. thresholds_dict[tensor] = (thresholds_dict[tensor][0], max_value)
  876. thresholds_dict[tensor] = (*thresholds_dict[tensor], *hist[:2])
  877. # Plot histogram for debug only
  878. if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
  879. apply_plot(hist, hist_edges)
  880. return thresholds_dict
  881. def compute_entropy(self):
  882. histogram_dict = self.histogram_dict
  883. num_quantized_bins = self.num_quantized_bins
  884. thresholds_dict = {} # per tensor thresholds
  885. print(f"Number of tensors : {len(histogram_dict)}")
  886. print(f"Number of histogram bins : {self.num_bins} (The number may increase depends on the data it collects)")
  887. print(f"Number of quantized bins : {self.num_quantized_bins}")
  888. for tensor, histogram in histogram_dict.items():
  889. optimal_threshold = self.get_entropy_threshold(histogram, num_quantized_bins)
  890. thresholds_dict[tensor] = optimal_threshold
  891. thresholds_dict[tensor] = (*optimal_threshold, *histogram[:2])
  892. # Plot histogram for debug only
  893. if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
  894. apply_plot(histogram[0], histogram[1])
  895. return thresholds_dict
  896. @staticmethod
  897. def _avg_std(hist, hist_edges, power=1):
  898. if power <= 0:
  899. raise ValueError(f"power={power} <= 0 is invalid.")
  900. values = (hist_edges[:-1] + hist_edges[1:]) * 0.5
  901. if power == 1:
  902. avg = (hist * values).sum() / hist.sum()
  903. std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
  904. return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
  905. if int(power) == power and int(power) % 2 == 1:
  906. avg = (hist * values**power).sum() / hist.sum()
  907. std = ((hist * (values**power - avg) ** 2).sum() / hist.sum()) ** 0.5
  908. return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
  909. fact = np.abs(values) / values
  910. fact[np.isnan(fact)] = 1
  911. fact[np.isinf(fact)] = 1
  912. values = np.abs(values) ** power * fact
  913. avg = (hist * values).sum() / hist.sum()
  914. std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
  915. return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
  916. def compute_distribution(self):
  917. if self.num_bins < 512:
  918. raise ValueError("Invalid num_bins. Must be in range 512 <= num_bins.")
  919. histogram_dict = self.histogram_dict
  920. thresholds_dict = {} # per tensor thresholds
  921. print(f"Number of tensors : {len(histogram_dict)}")
  922. print(f"Number of histogram bins : {self.num_bins}")
  923. print(f"Scenario : {self.scenario!r})")
  924. for tensor, histogram in histogram_dict.items():
  925. hist = histogram[0]
  926. hist_edges = histogram[1]
  927. assert hist_edges.dtype != np.float64
  928. if self.scenario == "same":
  929. avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1)
  930. elif self.scenario == "p3":
  931. avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1.0 / 3.0)
  932. else:
  933. raise ValueError("Invalid scenario. Must be in {'same', 'p3'}.")
  934. assert avg_coef.dtype != np.float64
  935. assert std_coef.dtype != np.float64
  936. assert hist_edges.dtype != np.float64
  937. thresholds_dict[tensor] = TensorData(
  938. avg=avg_coef,
  939. std=std_coef,
  940. hist=hist,
  941. hist_edges=hist_edges,
  942. lowest=hist_edges.min(),
  943. highest=hist_edges.max(),
  944. )
  945. # Plot histogram for debug only
  946. if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
  947. apply_plot(hist, hist_edges)
  948. return thresholds_dict
  949. def get_entropy_threshold(self, histogram, num_quantized_bins):
  950. """Given a dataset, find the optimal threshold for quantizing it.
  951. The reference distribution is `q`, and the candidate distribution is `p`.
  952. `q` is a truncated version of the original distribution.
  953. Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf
  954. """
  955. hist = histogram[0]
  956. hist_edges = histogram[1]
  957. num_bins = hist.size
  958. zero_bin_index = num_bins // 2
  959. num_half_quantized_bin = num_quantized_bins // 2
  960. dtype = histogram[1].dtype
  961. kl_divergence = np.zeros(zero_bin_index - num_half_quantized_bin + 1)
  962. thresholds = [(np.array(0, dtype=dtype), np.array(0, dtype=dtype)) for i in range(kl_divergence.size)]
  963. # <------------ num bins ---------------->
  964. # <--- quantized bins ---->
  965. # |======|===========|===========|=======|
  966. # zero bin index
  967. # ^ ^
  968. # | |
  969. # start index end index (start of iteration)
  970. # ^ ^
  971. # | |
  972. # start index end index ...
  973. # ^ ^
  974. # | |
  975. # start index end index (end of iteration)
  976. for i in range(num_half_quantized_bin, zero_bin_index + 1, 1):
  977. start_index = zero_bin_index - i
  978. end_index = min(zero_bin_index + i + 1, num_bins)
  979. thresholds[i - num_half_quantized_bin] = (hist_edges[start_index], hist_edges[end_index])
  980. sliced_distribution = copy.deepcopy(hist[start_index:end_index])
  981. # reference distribution p
  982. p = sliced_distribution.copy() # a copy of np array
  983. left_outliers_count = sum(hist[:start_index])
  984. right_outliers_count = sum(hist[end_index:])
  985. p[0] += left_outliers_count
  986. p[-1] += right_outliers_count
  987. # nonzeros[i] incidates whether p[i] is non-zero
  988. nonzeros = (p != 0).astype(np.int64)
  989. # quantize p.size bins into quantized bins (default 128 bins)
  990. quantized_bins = np.zeros(num_quantized_bins, dtype=np.int64)
  991. num_merged_bins = sliced_distribution.size // num_quantized_bins
  992. # merge bins into quantized bins
  993. for index in range(num_quantized_bins):
  994. start = index * num_merged_bins
  995. end = start + num_merged_bins
  996. quantized_bins[index] = sum(sliced_distribution[start:end])
  997. quantized_bins[-1] += sum(sliced_distribution[num_quantized_bins * num_merged_bins :])
  998. # in order to compare p and q, we need to make length of q equals to length of p
  999. # expand quantized bins into p.size bins
  1000. q = np.zeros(p.size, dtype=np.int64)
  1001. for index in range(num_quantized_bins):
  1002. start = index * num_merged_bins
  1003. end = start + num_merged_bins
  1004. norm = sum(nonzeros[start:end])
  1005. if norm != 0:
  1006. q[start:end] = quantized_bins[index] / norm
  1007. p = smooth_distribution(p)
  1008. q = smooth_distribution(q)
  1009. if p is None or q is None:
  1010. div = np.array(np.inf, dtype=dtype)
  1011. else:
  1012. div = np.array(entropy(p, q), dtype=dtype)
  1013. kl_divergence[i - num_half_quantized_bin] = div
  1014. min_kl_divergence_idx = np.argmin(kl_divergence)
  1015. optimal_threshold = thresholds[min_kl_divergence_idx]
  1016. min_value = histogram[2]
  1017. max_value = histogram[3]
  1018. if optimal_threshold[0] < min_value:
  1019. optimal_threshold = (min_value, optimal_threshold[1])
  1020. if optimal_threshold[1] > max_value:
  1021. optimal_threshold = (optimal_threshold[0], max_value)
  1022. assert hasattr(optimal_threshold[0], "dtype")
  1023. assert hasattr(optimal_threshold[1], "dtype")
  1024. return optimal_threshold
  1025. def create_calibrator(
  1026. model: str | Path,
  1027. op_types_to_calibrate: Sequence[str] | None = None,
  1028. augmented_model_path="augmented_model.onnx",
  1029. calibrate_method=CalibrationMethod.MinMax,
  1030. use_external_data_format=False,
  1031. providers=None,
  1032. extra_options={}, # noqa: B006
  1033. ):
  1034. calibrator = None
  1035. if calibrate_method == CalibrationMethod.MinMax:
  1036. # default settings for min-max algorithm
  1037. symmetric = extra_options.get("symmetric", False)
  1038. moving_average = extra_options.get("moving_average", False)
  1039. averaging_constant = extra_options.get("averaging_constant", 0.01)
  1040. max_intermediate_outputs = extra_options.get("max_intermediate_outputs", None)
  1041. per_channel = extra_options.get("per_channel", False)
  1042. calibrator = MinMaxCalibrater(
  1043. model,
  1044. op_types_to_calibrate,
  1045. augmented_model_path,
  1046. use_external_data_format=use_external_data_format,
  1047. symmetric=symmetric,
  1048. moving_average=moving_average,
  1049. averaging_constant=averaging_constant,
  1050. max_intermediate_outputs=max_intermediate_outputs,
  1051. per_channel=per_channel,
  1052. )
  1053. elif calibrate_method == CalibrationMethod.Entropy:
  1054. # default settings for entropy algorithm
  1055. num_bins = extra_options.get("num_bins", 128)
  1056. num_quantized_bins = extra_options.get("num_quantized_bins", 128)
  1057. symmetric = extra_options.get("symmetric", False)
  1058. calibrator = EntropyCalibrater(
  1059. model,
  1060. op_types_to_calibrate,
  1061. augmented_model_path,
  1062. use_external_data_format=use_external_data_format,
  1063. symmetric=symmetric,
  1064. num_bins=num_bins,
  1065. num_quantized_bins=num_quantized_bins,
  1066. )
  1067. elif calibrate_method == CalibrationMethod.Percentile:
  1068. # default settings for percentile algorithm
  1069. num_bins = extra_options.get("num_bins", 2048)
  1070. percentile = extra_options.get("percentile", 99.999)
  1071. symmetric = extra_options.get("symmetric", True)
  1072. calibrator = PercentileCalibrater(
  1073. model,
  1074. op_types_to_calibrate,
  1075. augmented_model_path,
  1076. use_external_data_format=use_external_data_format,
  1077. symmetric=symmetric,
  1078. num_bins=num_bins,
  1079. percentile=percentile,
  1080. )
  1081. elif calibrate_method == CalibrationMethod.Distribution:
  1082. # default settings for percentile algorithm
  1083. num_bins = extra_options.get("num_bins", 2048)
  1084. scenario = extra_options.get("scenario", "same")
  1085. calibrator = DistributionCalibrater(
  1086. model,
  1087. op_types_to_calibrate,
  1088. augmented_model_path,
  1089. use_external_data_format=use_external_data_format,
  1090. num_bins=num_bins,
  1091. scenario=scenario,
  1092. )
  1093. if calibrator:
  1094. calibrator.augment_graph()
  1095. if providers:
  1096. calibrator.execution_providers = providers
  1097. calibrator.create_inference_session()
  1098. return calibrator
  1099. raise ValueError(f"Unsupported calibration method {calibrate_method}")