calibrate.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  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 add_reduce_min_max(tensor_name, reduce_op_name):
  303. # When doing ReduceMax/ReduceMin, ORT can't reduce on dim with value of 0 if 'keepdims' is false.
  304. # To make the code simple, we always let keepdims to be 1.
  305. keepdims = 1
  306. # Adding ReduceMin/ReduceMax nodes: ReduceMin/ReduceMax -> Reshape-> (output)
  307. reduce_output = tensor_name + "_" + reduce_op_name
  308. intermediate_output = reduce_output + "_Reshape"
  309. reduce_node = onnx.helper.make_node(
  310. reduce_op_name, [tensor_name], [intermediate_output], keepdims=keepdims, name=reduce_output
  311. )
  312. reshape_node = onnx.helper.make_node(
  313. "Reshape",
  314. inputs=[intermediate_output, reshape_shape_name],
  315. outputs=[reduce_output],
  316. name=intermediate_output,
  317. )
  318. value_infos = {vi.name: vi for vi in self.model.graph.value_info}
  319. value_infos.update({o.name: o for o in self.model.graph.output})
  320. value_infos.update({i.name: i for i in self.model.graph.input})
  321. if tensor_name in value_infos:
  322. onnx_type = value_infos[tensor_name].type.tensor_type.elem_type
  323. else:
  324. raise ValueError(
  325. f"Unable to guess tensor type for tensor {tensor_name!r}, "
  326. "running shape inference before quantization may resolve this issue."
  327. )
  328. # Include axes in reduce_op when per_channel, always keeping axis=1
  329. if self.per_channel:
  330. tensor_rank = len(value_infos[tensor_name].type.tensor_type.shape.dim)
  331. reduced_axes = [0, *range(2, tensor_rank)]
  332. # Depending on opset version, axes in ReduceMin/ReduceMax are in attribute or inputs
  333. if get_op_version(reduce_op_name, self.model) < 18:
  334. reduce_node.attribute.append(helper.make_attribute("axes", reduced_axes))
  335. else:
  336. reduce_axes_name = str(uuid.uuid4())
  337. reduce_axes = numpy_helper.from_array(np.array(reduced_axes, dtype=np.int64), reduce_axes_name)
  338. reduce_node.input.append(reduce_axes_name)
  339. self.model.graph.initializer.append(reduce_axes)
  340. self.model.graph.node.extend([reduce_node, reshape_node])
  341. self.model.graph.output.append(helper.make_tensor_value_info(reduce_output, onnx_type, [None]))
  342. for tensor in tensors:
  343. add_reduce_min_max(tensor, "ReduceMin")
  344. add_reduce_min_max(tensor, "ReduceMax")
  345. onnx.save(
  346. self.model,
  347. self.augmented_model_path,
  348. save_as_external_data=self.use_external_data_format,
  349. )
  350. def clear_collected_data(self):
  351. self.intermediate_outputs = []
  352. def collect_data(self, data_reader: CalibrationDataReader):
  353. while True:
  354. inputs = data_reader.get_next()
  355. if not inputs:
  356. break
  357. self.intermediate_outputs.append(self.infer_session.run(None, inputs))
  358. if (
  359. self.max_intermediate_outputs is not None
  360. and len(self.intermediate_outputs) == self.max_intermediate_outputs
  361. ):
  362. self.clear_collected_data()
  363. if len(self.intermediate_outputs) == 0 and self.calibrate_tensors_range is None:
  364. raise ValueError("No data is collected.")
  365. t = self.compute_data()
  366. if not isinstance(t, TensorsData):
  367. raise TypeError(f"compute_data must return a TensorsData not {type(t)}.")
  368. self.clear_collected_data()
  369. def merge_range(self, old_range, new_range):
  370. if not old_range:
  371. return new_range
  372. for key, value in old_range.items():
  373. # Handling for structured data types with TensorData
  374. if isinstance(value, TensorData):
  375. old_min = value.range_value[0]
  376. old_max = value.range_value[1]
  377. else:
  378. old_min, old_max = value
  379. if isinstance(new_range[key], TensorData):
  380. new_min = new_range[key].range_value[0]
  381. new_max = new_range[key].range_value[1]
  382. else:
  383. new_min, new_max = new_range[key]
  384. if self.moving_average:
  385. min_value = old_min + self.averaging_constant * (new_min - old_min)
  386. max_value = old_max + self.averaging_constant * (new_max - old_max)
  387. else:
  388. min_value = min(old_min, new_min)
  389. max_value = max(old_max, new_max)
  390. # If structured as TensorData, wrap the result accordingly
  391. if isinstance(value, TensorData) or isinstance(new_range[key], TensorData):
  392. new_range[key] = TensorData(lowest=min_value, highest=max_value)
  393. else:
  394. new_range[key] = (min_value, max_value)
  395. return new_range
  396. def compute_data(self) -> TensorsData:
  397. """
  398. Compute the min-max range of tensor
  399. :return: dictionary mapping: {added node names: (ReduceMin, ReduceMax) pairs }
  400. """
  401. if len(self.intermediate_outputs) == 0:
  402. return self.calibrate_tensors_range
  403. output_names = [self.infer_session.get_outputs()[i].name for i in range(len(self.intermediate_outputs[0]))]
  404. output_dicts_list = [
  405. dict(zip(output_names, intermediate_output, strict=False))
  406. for intermediate_output in self.intermediate_outputs
  407. ]
  408. merged_output_dict = {}
  409. for d in output_dicts_list:
  410. for k, v in d.items():
  411. merged_output_dict.setdefault(k, []).append(v)
  412. added_output_names = output_names[self.num_model_outputs :]
  413. calibrate_tensor_names = [
  414. added_output_names[i].rpartition("_")[0] for i in range(0, len(added_output_names), 2)
  415. ] # output names
  416. merged_added_output_dict = {
  417. i: merged_output_dict[i] for i in merged_output_dict if i not in self.model_original_outputs
  418. }
  419. pairs = []
  420. for i in range(0, len(added_output_names), 2):
  421. if self.moving_average:
  422. min_value_array = np.nanmean(merged_added_output_dict[added_output_names[i]], axis=0)
  423. max_value_array = np.nanmean(merged_added_output_dict[added_output_names[i + 1]], axis=0)
  424. else:
  425. min_value_array = np.nanmin(merged_added_output_dict[added_output_names[i]], axis=0)
  426. max_value_array = np.nanmax(merged_added_output_dict[added_output_names[i + 1]], axis=0)
  427. if self.symmetric:
  428. max_absolute_value = np.nanmax([np.abs(min_value_array), np.abs(max_value_array)], axis=0)
  429. pairs.append((-max_absolute_value, max_absolute_value))
  430. else:
  431. pairs.append((min_value_array, max_value_array))
  432. new_calibrate_tensors_range = TensorsData(
  433. CalibrationMethod.MinMax, dict(zip(calibrate_tensor_names, pairs, strict=False))
  434. )
  435. if self.calibrate_tensors_range:
  436. self.calibrate_tensors_range = self.merge_range(self.calibrate_tensors_range, new_calibrate_tensors_range)
  437. else:
  438. self.calibrate_tensors_range = new_calibrate_tensors_range
  439. return self.calibrate_tensors_range
  440. class HistogramCalibrater(CalibraterBase):
  441. def __init__(
  442. self,
  443. model_path: str | Path,
  444. op_types_to_calibrate: Sequence[str] | None = None,
  445. augmented_model_path="augmented_model.onnx",
  446. use_external_data_format=False,
  447. method="percentile",
  448. symmetric=False,
  449. num_bins=128,
  450. num_quantized_bins=2048,
  451. percentile=99.999,
  452. scenario="same",
  453. ):
  454. """
  455. :param model_path: ONNX model to calibrate. It is a model path.
  456. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  457. :param augmented_model_path: save augmented model to this path.
  458. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  459. :param method: A string. One of ['entropy', 'percentile'].
  460. :param symmetric: make range of tensor symmetric (central point is 0).
  461. :param num_bins: number of bins to create a new histogram for collecting tensor values.
  462. :param num_quantized_bins: number of quantized bins. Default 128.
  463. :param percentile: A float number between [0, 100]. Default 99.99.
  464. :param scenario: see :class:`DistributionCalibrater`
  465. """
  466. super().__init__(
  467. model_path,
  468. op_types_to_calibrate=op_types_to_calibrate,
  469. augmented_model_path=augmented_model_path,
  470. symmetric=symmetric,
  471. use_external_data_format=use_external_data_format,
  472. )
  473. self.intermediate_outputs = []
  474. self.calibrate_tensors_range = None
  475. self.num_model_outputs = len(self.model.graph.output)
  476. self.model_original_outputs = {output.name for output in self.model.graph.output}
  477. self.collector = None
  478. self.method = method
  479. self.num_bins = num_bins
  480. self.num_quantized_bins = num_quantized_bins
  481. self.percentile = percentile
  482. self.tensors_to_calibrate = None
  483. self.scenario = scenario
  484. def augment_graph(self):
  485. """
  486. make all quantization_candidates op type nodes as part of the graph output.
  487. :return: augmented ONNX model
  488. """
  489. self.tensors_to_calibrate, value_infos = self.select_tensors_to_calibrate(self.model)
  490. for tensor in self.tensors_to_calibrate:
  491. if tensor not in self.model_original_outputs:
  492. self.model.graph.output.append(value_infos[tensor])
  493. onnx.save(
  494. self.model,
  495. self.augmented_model_path,
  496. save_as_external_data=self.use_external_data_format,
  497. )
  498. def clear_collected_data(self):
  499. self.intermediate_outputs = []
  500. def collect_data(self, data_reader: CalibrationDataReader):
  501. """
  502. Entropy Calibrator collects operators' tensors as well as generates tensor histogram for each operator.
  503. """
  504. input_names_set = {node_arg.name for node_arg in self.infer_session.get_inputs()}
  505. output_names = [node_arg.name for node_arg in self.infer_session.get_outputs()]
  506. while True:
  507. inputs = data_reader.get_next()
  508. if not inputs:
  509. break
  510. outputs = self.infer_session.run(None, inputs)
  511. # Copy np.ndarray only for graph outputs that are also graph inputs to workaround bug:
  512. # https://github.com/microsoft/onnxruntime/issues/21922
  513. fixed_outputs = []
  514. for output_index, output in enumerate(outputs):
  515. if output_names[output_index] in input_names_set:
  516. fixed_outputs.append(copy.copy(output))
  517. else:
  518. fixed_outputs.append(output)
  519. self.intermediate_outputs.append(fixed_outputs)
  520. if len(self.intermediate_outputs) == 0:
  521. raise ValueError("No data is collected.")
  522. output_dicts_list = [
  523. dict(zip(output_names, intermediate_output, strict=False))
  524. for intermediate_output in self.intermediate_outputs
  525. ]
  526. merged_dict = {}
  527. for d in output_dicts_list:
  528. for k, v in d.items():
  529. merged_dict.setdefault(k, []).append(v)
  530. clean_merged_dict = {i: merged_dict[i] for i in merged_dict if i in self.tensors_to_calibrate}
  531. if not self.collector:
  532. self.collector = HistogramCollector(
  533. method=self.method,
  534. symmetric=self.symmetric,
  535. num_bins=self.num_bins,
  536. num_quantized_bins=self.num_quantized_bins,
  537. percentile=self.percentile,
  538. scenario=self.scenario,
  539. )
  540. self.collector.collect(clean_merged_dict)
  541. self.clear_collected_data()
  542. def compute_data(self) -> TensorsData:
  543. """
  544. Compute the min-max range of tensor
  545. :return: dictionary mapping: {tensor name: (min value, max value)}
  546. """
  547. if not self.collector:
  548. raise ValueError("No collector created and can't generate calibration data.")
  549. if isinstance(self, EntropyCalibrater):
  550. cal = CalibrationMethod.Entropy
  551. elif isinstance(self, PercentileCalibrater):
  552. cal = CalibrationMethod.Percentile
  553. elif isinstance(self, DistributionCalibrater):
  554. cal = CalibrationMethod.Distribution
  555. else:
  556. raise TypeError(f"Unknown calibrater {type(self)}. This method must be overwritten.")
  557. return TensorsData(cal, self.collector.compute_collection_result())
  558. class EntropyCalibrater(HistogramCalibrater):
  559. def __init__(
  560. self,
  561. model_path: str | Path,
  562. op_types_to_calibrate: Sequence[str] | None = None,
  563. augmented_model_path="augmented_model.onnx",
  564. use_external_data_format=False,
  565. method="entropy",
  566. symmetric=False,
  567. num_bins=128,
  568. num_quantized_bins=128,
  569. ):
  570. """
  571. :param model_path: ONNX model to calibrate. It is a model path
  572. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  573. :param augmented_model_path: save augmented model to this path.
  574. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  575. :param method: A string. One of ['entropy', 'percentile', 'distribution'].
  576. :param symmetric: make range of tensor symmetric (central point is 0).
  577. :param num_bins: number of bins to create a new histogram for collecting tensor values.
  578. :param num_quantized_bins: number of quantized bins. Default 128.
  579. """
  580. super().__init__(
  581. model_path,
  582. op_types_to_calibrate,
  583. augmented_model_path,
  584. use_external_data_format,
  585. method=method,
  586. symmetric=symmetric,
  587. num_bins=num_bins,
  588. num_quantized_bins=num_quantized_bins,
  589. )
  590. class PercentileCalibrater(HistogramCalibrater):
  591. def __init__(
  592. self,
  593. model_path: str | Path,
  594. op_types_to_calibrate: Sequence[str] | None = None,
  595. augmented_model_path="augmented_model.onnx",
  596. use_external_data_format=False,
  597. method="percentile",
  598. symmetric=False,
  599. num_bins=2048,
  600. percentile=99.999,
  601. ):
  602. """
  603. :param model_path: ONNX model to calibrate. It is a model path
  604. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  605. :param augmented_model_path: save augmented model to this path.
  606. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  607. :param method: A string. One of ['entropy', 'percentile', 'distribution'].
  608. :param symmetric: make range of tensor symmetric (central point is 0).
  609. :param num_quantized_bins: number of quantized bins. Default 128.
  610. :param percentile: A float number between [0, 100]. Default 99.99.
  611. """
  612. super().__init__(
  613. model_path,
  614. op_types_to_calibrate,
  615. augmented_model_path,
  616. use_external_data_format,
  617. method=method,
  618. symmetric=symmetric,
  619. num_bins=num_bins,
  620. percentile=percentile,
  621. )
  622. class DistributionCalibrater(HistogramCalibrater):
  623. def __init__(
  624. self,
  625. model_path: str | Path,
  626. op_types_to_calibrate: Sequence[str] | None = None,
  627. augmented_model_path="augmented_model.onnx",
  628. use_external_data_format=False,
  629. method="distribution",
  630. num_bins=128,
  631. scenario="same",
  632. ):
  633. """
  634. :param model_path: ONNX model to calibrate. It is a model path
  635. :param op_types_to_calibrate: operator types to calibrate. By default, calibrate all the float32/float16 tensors.
  636. :param augmented_model_path: save augmented model to this path.
  637. :param use_external_data_format: use external data format to store model which size is >= 2Gb
  638. :param method: A string. One of ['entropy', 'percentile', 'distribution'].
  639. :param symmetric: make range of tensor symmetric (central point is 0).
  640. :param num_bins: number of bins to create a new histogram for collecting tensor values.
  641. :param scenario: for float 8 only, if `scenario="same"`,
  642. the algorithm weights and float 8 follow the same distribution,
  643. if `scenario="p3"`, it assumes the weights follow
  644. a gaussian law and float 8 ~ X^3 where X is a gaussian law
  645. """
  646. super().__init__(
  647. model_path,
  648. op_types_to_calibrate,
  649. augmented_model_path,
  650. use_external_data_format,
  651. method=method,
  652. num_bins=num_bins,
  653. scenario=scenario,
  654. )
  655. class CalibrationDataCollector(metaclass=abc.ABCMeta):
  656. """
  657. Base class for collecting data for calibration-based quantization.
  658. """
  659. @abc.abstractmethod
  660. def collect(self, name_to_arr):
  661. """
  662. Generate informative data based on given data.
  663. name_to_arr : dict
  664. tensor name to NDArray data
  665. """
  666. raise NotImplementedError
  667. @abc.abstractmethod
  668. def compute_collection_result(self):
  669. """
  670. Get the optimal result among collection data.
  671. """
  672. raise NotImplementedError
  673. class HistogramCollector(CalibrationDataCollector):
  674. """
  675. Collecting histogram for each tensor. Percentile and Entropy method are supported.
  676. ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py
  677. ref: https://docs.nvidia.com/deeplearning/tensorrt/pytorch-quantization-toolkit/docs/_modules/
  678. pytorch_quantization/calib/histogram.html
  679. """
  680. def __init__(self, method, symmetric, num_bins, num_quantized_bins, percentile, scenario):
  681. self.histogram_dict = {}
  682. self.method = method
  683. self.symmetric = symmetric
  684. self.num_bins = num_bins
  685. self.num_quantized_bins = num_quantized_bins
  686. self.percentile = percentile
  687. self.scenario = scenario
  688. def get_histogram_dict(self):
  689. return self.histogram_dict
  690. def collect(self, name_to_arr):
  691. print("Collecting tensor data and making histogram ...")
  692. # TODO: Currently we have different collect() for entropy and percentile method respectively.
  693. # Need unified collect in the future.
  694. if self.method in {"distribution", "entropy"}:
  695. return self.collect_value(name_to_arr)
  696. elif self.method == "percentile":
  697. if self.symmetric:
  698. return self.collect_absolute_value(name_to_arr)
  699. else:
  700. return self.collect_value(name_to_arr)
  701. else:
  702. raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
  703. def collect_absolute_value(self, name_to_arr):
  704. """
  705. Collect histogram on absolute value
  706. """
  707. for tensor, data_arr in name_to_arr.items():
  708. if isinstance(data_arr, list):
  709. for arr in data_arr:
  710. assert isinstance(arr, np.ndarray), f"Unexpected type {type(arr)} for tensor={tensor!r}"
  711. dtypes = {a.dtype for a in data_arr}
  712. assert len(dtypes) == 1, (
  713. f"The calibration expects only one element type but got {dtypes} for tensor={tensor!r}"
  714. )
  715. data_arr_np = np.asarray(data_arr)
  716. elif not isinstance(data_arr, np.ndarray):
  717. raise ValueError(f"Unexpected type {type(data_arr)} for tensor={tensor!r}")
  718. else:
  719. data_arr_np = data_arr
  720. data_arr_np = data_arr_np.flatten()
  721. if data_arr_np.size > 0:
  722. min_value = np.nanmin(data_arr_np)
  723. max_value = np.nanmax(data_arr_np)
  724. else:
  725. min_value = np.array(0, dtype=data_arr_np.dtype)
  726. max_value = np.array(0, dtype=data_arr_np.dtype)
  727. data_arr_np = np.absolute(data_arr_np) # only consider absolute value
  728. if tensor not in self.histogram_dict:
  729. # first time it uses num_bins to compute histogram.
  730. hist, hist_edges = np.histogram(data_arr_np, bins=self.num_bins)
  731. hist_edges = hist_edges.astype(data_arr_np.dtype)
  732. assert data_arr_np.dtype != np.float64, (
  733. "only float32 or float16 is supported, every constant must be explicitly typed"
  734. )
  735. self.histogram_dict[tensor] = (hist, hist_edges, min_value, max_value)
  736. else:
  737. old_histogram = self.histogram_dict[tensor]
  738. old_min = old_histogram[2]
  739. old_max = old_histogram[3]
  740. assert hasattr(old_min, "dtype"), f"old_min should be a numpy array but is {type(old_min)}"
  741. assert hasattr(old_max, "dtype"), f"old_min should be a numpy array but is {type(old_max)}"
  742. old_hist = old_histogram[0]
  743. old_hist_edges = old_histogram[1]
  744. temp_amax = np.nanmax(data_arr_np)
  745. if temp_amax > old_hist_edges[-1]:
  746. # increase the number of bins
  747. width = old_hist_edges[1] - old_hist_edges[0]
  748. # NOTE: np.arange may create an extra bin after the one containing temp_amax
  749. new_bin_edges = np.arange(old_hist_edges[-1] + width, temp_amax + width, width)
  750. old_hist_edges = np.hstack((old_hist_edges, new_bin_edges))
  751. hist, hist_edges = np.histogram(data_arr_np, bins=old_hist_edges)
  752. hist_edges = hist_edges.astype(data_arr_np.dtype)
  753. hist[: len(old_hist)] += old_hist
  754. assert data_arr_np.dtype != np.float64, (
  755. "only float32 or float16 is supported, every constant must be explicitly typed"
  756. )
  757. self.histogram_dict[tensor] = (hist, hist_edges, min(old_min, min_value), max(old_max, max_value))
  758. def collect_value(self, name_to_arr):
  759. """
  760. Collect histogram on real value
  761. """
  762. for tensor, data_arr in name_to_arr.items():
  763. data_arr = np.asarray(data_arr) # noqa: PLW2901
  764. data_arr = data_arr.flatten() # noqa: PLW2901
  765. if data_arr.size > 0:
  766. min_value = np.nanmin(data_arr)
  767. max_value = np.nanmax(data_arr)
  768. else:
  769. min_value = np.array(0, dtype=data_arr.dtype)
  770. max_value = np.array(0, dtype=data_arr.dtype)
  771. threshold = np.array(max(abs(min_value), abs(max_value)), dtype=data_arr.dtype)
  772. if tensor in self.histogram_dict:
  773. old_histogram = self.histogram_dict[tensor]
  774. self.histogram_dict[tensor] = self.merge_histogram(
  775. old_histogram, data_arr, min_value, max_value, threshold
  776. )
  777. else:
  778. hist, hist_edges = np.histogram(data_arr, self.num_bins, range=(-threshold, threshold))
  779. self.histogram_dict[tensor] = (
  780. hist,
  781. hist_edges,
  782. min_value,
  783. max_value,
  784. threshold,
  785. )
  786. def merge_histogram(self, old_histogram, data_arr, new_min, new_max, new_threshold):
  787. (old_hist, old_hist_edges, old_min, old_max, old_threshold) = old_histogram
  788. if new_threshold <= old_threshold:
  789. new_hist, _ = np.histogram(data_arr, len(old_hist), range=(-old_threshold, old_threshold))
  790. return (
  791. new_hist + old_hist,
  792. old_hist_edges,
  793. min(old_min, new_min),
  794. max(old_max, new_max),
  795. old_threshold,
  796. )
  797. else:
  798. if old_threshold == 0:
  799. hist, hist_edges = np.histogram(data_arr, len(old_hist), range=(-new_threshold, new_threshold))
  800. hist += old_hist
  801. else:
  802. old_num_bins = len(old_hist)
  803. old_stride = 2 * old_threshold / old_num_bins
  804. half_increased_bins = int((new_threshold - old_threshold) // old_stride + 1)
  805. new_num_bins = old_num_bins + 2 * half_increased_bins
  806. new_threshold = half_increased_bins * old_stride + old_threshold
  807. hist, hist_edges = np.histogram(data_arr, new_num_bins, range=(-new_threshold, new_threshold))
  808. hist[half_increased_bins : new_num_bins - half_increased_bins] += old_hist
  809. return (
  810. hist,
  811. hist_edges,
  812. min(old_min, new_min),
  813. max(old_max, new_max),
  814. new_threshold,
  815. )
  816. def compute_collection_result(self):
  817. if not self.histogram_dict or len(self.histogram_dict) == 0:
  818. raise ValueError("Histogram has not been collected. Please run collect() first.")
  819. print(f"Finding optimal threshold for each tensor using {self.method!r} algorithm ...")
  820. if self.method == "entropy":
  821. return self.compute_entropy()
  822. elif self.method == "percentile":
  823. return self.compute_percentile()
  824. elif self.method == "distribution":
  825. return self.compute_distribution()
  826. else:
  827. raise ValueError("Only 'entropy', 'percentile' or 'distribution' methods are supported")
  828. def compute_percentile(self):
  829. if self.percentile < 0 or self.percentile > 100:
  830. raise ValueError("Invalid percentile. Must be in range 0 <= percentile <= 100.")
  831. histogram_dict = self.histogram_dict
  832. percentile = self.percentile
  833. thresholds_dict = {} # per tensor thresholds
  834. print(f"Number of tensors : {len(histogram_dict)}")
  835. print(f"Number of histogram bins : {self.num_bins}")
  836. print(f"Percentile : ({100.0 - percentile},{percentile})")
  837. for tensor, histogram in histogram_dict.items():
  838. hist = histogram[0]
  839. hist_edges = histogram[1]
  840. total = hist.sum()
  841. cdf = np.cumsum(hist / total)
  842. if self.symmetric:
  843. idx_right = np.searchsorted(cdf, percentile / 100.0)
  844. thresholds_dict[tensor] = (
  845. -np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
  846. np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
  847. )
  848. else:
  849. percent_to_cut_one_side = (100.0 - percentile) / 200.0
  850. idx_right = np.searchsorted(cdf, 1.0 - percent_to_cut_one_side)
  851. idx_left = np.searchsorted(cdf, percent_to_cut_one_side)
  852. thresholds_dict[tensor] = (
  853. np.array(hist_edges[idx_left], dtype=hist_edges.dtype),
  854. np.array(hist_edges[idx_right], dtype=hist_edges.dtype),
  855. )
  856. min_value = histogram[2]
  857. max_value = histogram[3]
  858. if thresholds_dict[tensor][0] < min_value:
  859. thresholds_dict[tensor] = (min_value, thresholds_dict[tensor][1])
  860. if thresholds_dict[tensor][1] > max_value:
  861. thresholds_dict[tensor] = (thresholds_dict[tensor][0], max_value)
  862. thresholds_dict[tensor] = (*thresholds_dict[tensor], *hist[:2])
  863. # Plot histogram for debug only
  864. if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
  865. apply_plot(hist, hist_edges)
  866. return thresholds_dict
  867. def compute_entropy(self):
  868. histogram_dict = self.histogram_dict
  869. num_quantized_bins = self.num_quantized_bins
  870. thresholds_dict = {} # per tensor thresholds
  871. print(f"Number of tensors : {len(histogram_dict)}")
  872. print(f"Number of histogram bins : {self.num_bins} (The number may increase depends on the data it collects)")
  873. print(f"Number of quantized bins : {self.num_quantized_bins}")
  874. for tensor, histogram in histogram_dict.items():
  875. optimal_threshold = self.get_entropy_threshold(histogram, num_quantized_bins)
  876. thresholds_dict[tensor] = optimal_threshold
  877. thresholds_dict[tensor] = (*optimal_threshold, *histogram[:2])
  878. # Plot histogram for debug only
  879. if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
  880. apply_plot(histogram[0], histogram[1])
  881. return thresholds_dict
  882. @staticmethod
  883. def _avg_std(hist, hist_edges, power=1):
  884. if power <= 0:
  885. raise ValueError(f"power={power} <= 0 is invalid.")
  886. values = (hist_edges[:-1] + hist_edges[1:]) * 0.5
  887. if power == 1:
  888. avg = (hist * values).sum() / hist.sum()
  889. std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
  890. return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
  891. if int(power) == power and int(power) % 2 == 1:
  892. avg = (hist * values**power).sum() / hist.sum()
  893. std = ((hist * (values**power - avg) ** 2).sum() / hist.sum()) ** 0.5
  894. return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
  895. fact = np.abs(values) / values
  896. fact[np.isnan(fact)] = 1
  897. fact[np.isinf(fact)] = 1
  898. values = np.abs(values) ** power * fact
  899. avg = (hist * values).sum() / hist.sum()
  900. std = ((hist * values**2).sum() / hist.sum() - avg**2) ** 0.5
  901. return np.array(avg, dtype=hist_edges.dtype), np.array(std, dtype=hist_edges.dtype)
  902. def compute_distribution(self):
  903. if self.num_bins < 512:
  904. raise ValueError("Invalid num_bins. Must be in range 512 <= num_bins.")
  905. histogram_dict = self.histogram_dict
  906. thresholds_dict = {} # per tensor thresholds
  907. print(f"Number of tensors : {len(histogram_dict)}")
  908. print(f"Number of histogram bins : {self.num_bins}")
  909. print(f"Scenario : {self.scenario!r})")
  910. for tensor, histogram in histogram_dict.items():
  911. hist = histogram[0]
  912. hist_edges = histogram[1]
  913. assert hist_edges.dtype != np.float64
  914. if self.scenario == "same":
  915. avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1)
  916. elif self.scenario == "p3":
  917. avg_coef, std_coef = self._avg_std(hist, hist_edges, power=1.0 / 3.0)
  918. else:
  919. raise ValueError("Invalid scenario. Must be in {'same', 'p3'}.")
  920. assert avg_coef.dtype != np.float64
  921. assert std_coef.dtype != np.float64
  922. assert hist_edges.dtype != np.float64
  923. thresholds_dict[tensor] = TensorData(
  924. avg=avg_coef,
  925. std=std_coef,
  926. hist=hist,
  927. hist_edges=hist_edges,
  928. lowest=hist_edges.min(),
  929. highest=hist_edges.max(),
  930. )
  931. # Plot histogram for debug only
  932. if os.environ.get("QUANTIZATION_DEBUG", "0") in (1, "1"):
  933. apply_plot(hist, hist_edges)
  934. return thresholds_dict
  935. def get_entropy_threshold(self, histogram, num_quantized_bins):
  936. """Given a dataset, find the optimal threshold for quantizing it.
  937. The reference distribution is `q`, and the candidate distribution is `p`.
  938. `q` is a truncated version of the original distribution.
  939. Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf
  940. """
  941. hist = histogram[0]
  942. hist_edges = histogram[1]
  943. num_bins = hist.size
  944. zero_bin_index = num_bins // 2
  945. num_half_quantized_bin = num_quantized_bins // 2
  946. dtype = histogram[1].dtype
  947. kl_divergence = np.zeros(zero_bin_index - num_half_quantized_bin + 1)
  948. thresholds = [(np.array(0, dtype=dtype), np.array(0, dtype=dtype)) for i in range(kl_divergence.size)]
  949. # <------------ num bins ---------------->
  950. # <--- quantized bins ---->
  951. # |======|===========|===========|=======|
  952. # zero bin index
  953. # ^ ^
  954. # | |
  955. # start index end index (start of iteration)
  956. # ^ ^
  957. # | |
  958. # start index end index ...
  959. # ^ ^
  960. # | |
  961. # start index end index (end of iteration)
  962. for i in range(num_half_quantized_bin, zero_bin_index + 1, 1):
  963. start_index = zero_bin_index - i
  964. end_index = min(zero_bin_index + i + 1, num_bins)
  965. thresholds[i - num_half_quantized_bin] = (hist_edges[start_index], hist_edges[end_index])
  966. sliced_distribution = copy.deepcopy(hist[start_index:end_index])
  967. # reference distribution p
  968. p = sliced_distribution.copy() # a copy of np array
  969. left_outliers_count = sum(hist[:start_index])
  970. right_outliers_count = sum(hist[end_index:])
  971. p[0] += left_outliers_count
  972. p[-1] += right_outliers_count
  973. # nonzeros[i] incidates whether p[i] is non-zero
  974. nonzeros = (p != 0).astype(np.int64)
  975. # quantize p.size bins into quantized bins (default 128 bins)
  976. quantized_bins = np.zeros(num_quantized_bins, dtype=np.int64)
  977. num_merged_bins = sliced_distribution.size // num_quantized_bins
  978. # merge bins into quantized bins
  979. for index in range(num_quantized_bins):
  980. start = index * num_merged_bins
  981. end = start + num_merged_bins
  982. quantized_bins[index] = sum(sliced_distribution[start:end])
  983. quantized_bins[-1] += sum(sliced_distribution[num_quantized_bins * num_merged_bins :])
  984. # in order to compare p and q, we need to make length of q equals to length of p
  985. # expand quantized bins into p.size bins
  986. q = np.zeros(p.size, dtype=np.int64)
  987. for index in range(num_quantized_bins):
  988. start = index * num_merged_bins
  989. end = start + num_merged_bins
  990. norm = sum(nonzeros[start:end])
  991. if norm != 0:
  992. q[start:end] = quantized_bins[index] / norm
  993. p = smooth_distribution(p)
  994. q = smooth_distribution(q)
  995. if p is None or q is None:
  996. div = np.array(np.inf, dtype=dtype)
  997. else:
  998. div = np.array(entropy(p, q), dtype=dtype)
  999. kl_divergence[i - num_half_quantized_bin] = div
  1000. min_kl_divergence_idx = np.argmin(kl_divergence)
  1001. optimal_threshold = thresholds[min_kl_divergence_idx]
  1002. min_value = histogram[2]
  1003. max_value = histogram[3]
  1004. if optimal_threshold[0] < min_value:
  1005. optimal_threshold = (min_value, optimal_threshold[1])
  1006. if optimal_threshold[1] > max_value:
  1007. optimal_threshold = (optimal_threshold[0], max_value)
  1008. assert hasattr(optimal_threshold[0], "dtype")
  1009. assert hasattr(optimal_threshold[1], "dtype")
  1010. return optimal_threshold
  1011. def create_calibrator(
  1012. model: str | Path,
  1013. op_types_to_calibrate: Sequence[str] | None = None,
  1014. augmented_model_path="augmented_model.onnx",
  1015. calibrate_method=CalibrationMethod.MinMax,
  1016. use_external_data_format=False,
  1017. providers=None,
  1018. extra_options={}, # noqa: B006
  1019. ):
  1020. calibrator = None
  1021. if calibrate_method == CalibrationMethod.MinMax:
  1022. # default settings for min-max algorithm
  1023. symmetric = extra_options.get("symmetric", False)
  1024. moving_average = extra_options.get("moving_average", False)
  1025. averaging_constant = extra_options.get("averaging_constant", 0.01)
  1026. max_intermediate_outputs = extra_options.get("max_intermediate_outputs", None)
  1027. per_channel = extra_options.get("per_channel", False)
  1028. calibrator = MinMaxCalibrater(
  1029. model,
  1030. op_types_to_calibrate,
  1031. augmented_model_path,
  1032. use_external_data_format=use_external_data_format,
  1033. symmetric=symmetric,
  1034. moving_average=moving_average,
  1035. averaging_constant=averaging_constant,
  1036. max_intermediate_outputs=max_intermediate_outputs,
  1037. per_channel=per_channel,
  1038. )
  1039. elif calibrate_method == CalibrationMethod.Entropy:
  1040. # default settings for entropy algorithm
  1041. num_bins = extra_options.get("num_bins", 128)
  1042. num_quantized_bins = extra_options.get("num_quantized_bins", 128)
  1043. symmetric = extra_options.get("symmetric", False)
  1044. calibrator = EntropyCalibrater(
  1045. model,
  1046. op_types_to_calibrate,
  1047. augmented_model_path,
  1048. use_external_data_format=use_external_data_format,
  1049. symmetric=symmetric,
  1050. num_bins=num_bins,
  1051. num_quantized_bins=num_quantized_bins,
  1052. )
  1053. elif calibrate_method == CalibrationMethod.Percentile:
  1054. # default settings for percentile algorithm
  1055. num_bins = extra_options.get("num_bins", 2048)
  1056. percentile = extra_options.get("percentile", 99.999)
  1057. symmetric = extra_options.get("symmetric", True)
  1058. calibrator = PercentileCalibrater(
  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. percentile=percentile,
  1066. )
  1067. elif calibrate_method == CalibrationMethod.Distribution:
  1068. # default settings for percentile algorithm
  1069. num_bins = extra_options.get("num_bins", 2048)
  1070. scenario = extra_options.get("scenario", "same")
  1071. calibrator = DistributionCalibrater(
  1072. model,
  1073. op_types_to_calibrate,
  1074. augmented_model_path,
  1075. use_external_data_format=use_external_data_format,
  1076. num_bins=num_bins,
  1077. scenario=scenario,
  1078. )
  1079. if calibrator:
  1080. calibrator.augment_graph()
  1081. if providers:
  1082. calibrator.execution_providers = providers
  1083. calibrator.create_inference_session()
  1084. return calibrator
  1085. raise ValueError(f"Unsupported calibration method {calibrate_method}")