float16.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License.
  4. # --------------------------------------------------------------------------
  5. # This file is modified from https://github.com/microsoft/onnxconverter-common/blob/master/onnxconverter_common/float16.py
  6. # Modifications:
  7. # (1) Update default value of min_positive_val and max_finite_val
  8. # (2) keep_io_types can be list of names
  9. # (3) convert initializers if needed to preserve precision
  10. # (4) add force_fp16_initializers option
  11. # (5) handle Resize and GroupNorm with mixed float inputs
  12. # (6) allow convert_float_to_float16 to accept model path
  13. import itertools
  14. import logging
  15. import os
  16. import tempfile
  17. import numpy as np
  18. import onnx
  19. from onnx import AttributeProto, GraphProto, ModelProto, NodeProto, TensorProto, helper, numpy_helper
  20. from onnx.shape_inference import infer_shapes, infer_shapes_path
  21. from packaging import version
  22. logger = logging.getLogger(__name__)
  23. def _npfloat16_to_int(np_list):
  24. """
  25. Convert numpy float16 to python int.
  26. :param np_list: numpy float16 list
  27. :return int_list: python int list
  28. """
  29. return [int(bin(_.view("H"))[2:].zfill(16), 2) for _ in np_list]
  30. def convert_np_to_float16(np_array, min_positive_val=5.96e-08, max_finite_val=65504.0):
  31. """
  32. Convert float32 numpy array to float16 without changing sign or finiteness.
  33. Positive values less than min_positive_val are mapped to min_positive_val.
  34. Positive finite values greater than max_finite_val are mapped to max_finite_val.
  35. Similar for negative values. NaN, 0, inf, and -inf are unchanged.
  36. """
  37. def between(a, b, c):
  38. return np.logical_and(a < b, b < c)
  39. if np_array[np.where(np_array > 0)].shape[0] > 0:
  40. positive_max = np_array[np.where(np_array > 0)].max()
  41. positive_min = np_array[np.where(np_array > 0)].min()
  42. if positive_max >= max_finite_val:
  43. logger.debug(f"the float32 number {positive_max} will be truncated to {max_finite_val}")
  44. if positive_min <= min_positive_val:
  45. logger.debug(f"the float32 number {positive_min} will be truncated to {min_positive_val}")
  46. if np_array[np.where(np_array < 0)].shape[0] > 0:
  47. negative_max = np_array[np.where(np_array < 0)].max()
  48. negative_min = np_array[np.where(np_array < 0)].min()
  49. if negative_min <= -max_finite_val:
  50. logger.debug(f"the float32 number {negative_min} will be truncated to {-max_finite_val}")
  51. if negative_max >= -min_positive_val:
  52. logger.debug(f"the float32 number {negative_max} will be truncated to {-min_positive_val}")
  53. np_array = np.where(between(0, np_array, min_positive_val), min_positive_val, np_array)
  54. np_array = np.where(between(-min_positive_val, np_array, 0), -min_positive_val, np_array)
  55. np_array = np.where(between(max_finite_val, np_array, float("inf")), max_finite_val, np_array)
  56. np_array = np.where(between(float("-inf"), np_array, -max_finite_val), -max_finite_val, np_array)
  57. return np.float16(np_array)
  58. def convert_tensor_float_to_float16(tensor, min_positive_val=5.96e-08, max_finite_val=65504.0):
  59. """Convert tensor float to float16.
  60. Args:
  61. tensor (TensorProto): the tensor to convert.
  62. min_positive_val (float, optional): minimal positive value. Defaults to 1e-7.
  63. max_finite_val (float, optional): maximal finite value. Defaults to 1e4.
  64. Raises:
  65. ValueError: input type is not TensorProto.
  66. Returns:
  67. TensorProto: the converted tensor.
  68. """
  69. if not isinstance(tensor, TensorProto):
  70. raise ValueError(f"Expected input type is an ONNX TensorProto but got {type(tensor)}")
  71. if tensor.data_type == TensorProto.FLOAT:
  72. tensor.data_type = TensorProto.FLOAT16
  73. # convert float_data (float type) to float16 and write to int32_data
  74. if tensor.float_data:
  75. float16_data = convert_np_to_float16(np.array(tensor.float_data), min_positive_val, max_finite_val)
  76. int_list = _npfloat16_to_int(float16_data)
  77. tensor.int32_data[:] = int_list
  78. tensor.float_data[:] = []
  79. # convert raw_data (bytes type)
  80. if tensor.raw_data:
  81. # convert n.raw_data to float
  82. float32_list = np.frombuffer(tensor.raw_data, dtype="float32")
  83. # convert float to float16
  84. float16_list = convert_np_to_float16(float32_list, min_positive_val, max_finite_val)
  85. # convert float16 to bytes and write back to raw_data
  86. tensor.raw_data = float16_list.tobytes()
  87. return tensor
  88. def make_value_info_from_tensor(tensor):
  89. shape = numpy_helper.to_array(tensor).shape
  90. return helper.make_tensor_value_info(tensor.name, tensor.data_type, shape)
  91. DEFAULT_OP_BLOCK_LIST = [
  92. "ArrayFeatureExtractor",
  93. "Binarizer",
  94. "CastMap",
  95. "CategoryMapper",
  96. "DictVectorizer",
  97. "FeatureVectorizer",
  98. "Imputer",
  99. "LabelEncoder",
  100. "LinearClassifier",
  101. "LinearRegressor",
  102. "Normalizer",
  103. "OneHotEncoder",
  104. "RandomUniformLike",
  105. "SVMClassifier",
  106. "SVMRegressor",
  107. "Scaler",
  108. "TreeEnsembleClassifier",
  109. "TreeEnsembleRegressor",
  110. "TreeEnsemble",
  111. "ZipMap",
  112. "NonMaxSuppression",
  113. "TopK",
  114. "RoiAlign",
  115. "Range",
  116. "CumSum",
  117. "Min",
  118. "Max",
  119. "Upsample",
  120. ]
  121. # Some operators has data type fixed as float for some inputs. Key is op_type, value is list of input indices
  122. # Note that DirectML allows float16 gamma and beta in GroupNorm. Use force_fp16_inputs parameter could overwrite this.
  123. ALWAYS_FLOAT_INPUTS = {"Resize": [2], "GroupNorm": [1, 2], "SkipGroupNorm": [1, 2]}
  124. class InitializerTracker:
  125. """Class for keeping track of initializer."""
  126. def __init__(self, initializer: TensorProto):
  127. self.initializer = initializer
  128. self.fp32_nodes = []
  129. self.fp16_nodes = []
  130. def add_node(self, node: NodeProto, is_node_blocked):
  131. if is_node_blocked:
  132. self.fp32_nodes.append(node)
  133. else:
  134. self.fp16_nodes.append(node)
  135. def convert_float_to_float16(
  136. model,
  137. min_positive_val=5.96e-08,
  138. max_finite_val=65504.0,
  139. keep_io_types=False,
  140. disable_shape_infer=False,
  141. op_block_list=None,
  142. node_block_list=None,
  143. force_fp16_initializers=False,
  144. force_fp16_inputs=None,
  145. use_bfloat16_as_blocked_nodes_dtype=False,
  146. ):
  147. """Convert tensor float type in the input ONNX model to tensor float16.
  148. Args:
  149. model (ModelProto or str): The ONNX model or path of the model to convert.
  150. min_positive_val (float, optional): minimal positive value. Defaults to 5.96e-08.
  151. max_finite_val (float, optional): maximal finite value of float16. Defaults to 65504.
  152. keep_io_types (Union[bool, List[str]], optional): It could be boolean or a list of float32 input/output names.
  153. If True, model inputs/outputs should be left as float32.
  154. Defaults to False.
  155. disable_shape_infer (bool, optional): Skips running onnx shape/type inference.
  156. Useful if shape inference has been done. Defaults to False.
  157. op_block_list (List[str], optional): List of op types to leave as float32.
  158. Defaults to None, which will use `float16.DEFAULT_OP_BLOCK_LIST`.
  159. node_block_list (List[str], optional): List of node names to leave as float32. Defaults to None.
  160. force_fp16_initializers(bool): force converting all float initializers to float16.
  161. Default to false, which will convert only the one needed to avoid precision loss.
  162. force_fp16_inputs(Dict[str, List[int]]): Force the conversion of the inputs of some operators to float16, even if
  163. this script's preference it to keep them in float32.
  164. Raises:
  165. ValueError: input type is not ModelProto.
  166. Returns:
  167. ModelProto: converted model.
  168. """
  169. assert min_positive_val >= 5.96e-08, (
  170. "invalid min_positive_val. smallest positive float16 value: subnormal 5.96e-08, and normalized 6.104e-05"
  171. )
  172. assert max_finite_val <= float(np.finfo(np.float16).max), "invalid max_finite_val. largest float16 value: 65504"
  173. force_fp16_inputs_dict = {} if force_fp16_inputs is None else force_fp16_inputs
  174. if isinstance(model, str):
  175. model_path = model
  176. if version.parse(onnx.__version__) >= version.parse("1.8.0") and not disable_shape_infer:
  177. # shape_infer_model_path should be in the same folder of model_path
  178. with tempfile.NamedTemporaryFile(dir=os.path.dirname(model_path)) as tmpfile:
  179. shape_infer_model_path = tmpfile.name
  180. # infer_shapes_path can be used for model >2GB, and infer_shapes cannot.
  181. infer_shapes_path(model_path, shape_infer_model_path)
  182. model = onnx.load(shape_infer_model_path)
  183. disable_shape_infer = True
  184. else:
  185. model = onnx.load(model_path)
  186. if not isinstance(model, ModelProto):
  187. raise ValueError(f"Expected an ONNX ModelProto but got {type(model)}")
  188. func_infer_shape = None
  189. if not disable_shape_infer and version.parse(onnx.__version__) >= version.parse("1.2.0"):
  190. try:
  191. func_infer_shape = infer_shapes
  192. finally:
  193. pass
  194. # create blocklists
  195. if op_block_list is None:
  196. op_block_list = DEFAULT_OP_BLOCK_LIST
  197. if node_block_list is None:
  198. node_block_list = []
  199. op_block_list = set(op_block_list)
  200. node_block_list = set(node_block_list)
  201. logger.debug(
  202. f"fp16 parameters: min_positive_val={min_positive_val} max_finite_val={max_finite_val} keep_io_types={keep_io_types} disable_shape_infer={disable_shape_infer} op_block_list={op_block_list} node_block_list={node_block_list} force_fp16_initializers={force_fp16_initializers}"
  203. )
  204. # create a queue for BFS
  205. queue = []
  206. value_info_list = []
  207. node_list = []
  208. # Some operators (Like Resize or GroupNorm) have data type fixed as float for some input.
  209. # When it is converted to float16, there are mixed types: some inputs are float32 and some are float16.
  210. # This list keeps track of such nodes that are not in block list.
  211. mixed_float_type_node_list = []
  212. # type inference on input model
  213. if func_infer_shape is not None:
  214. model = func_infer_shape(model)
  215. queue.append(model)
  216. name_mapping = {}
  217. graph_io_to_skip = set()
  218. io_casts = set()
  219. fp32_inputs = [n.name for n in model.graph.input if n.type.tensor_type.elem_type == TensorProto.FLOAT]
  220. fp32_outputs = [n.name for n in model.graph.output if n.type.tensor_type.elem_type == TensorProto.FLOAT]
  221. if isinstance(keep_io_types, list):
  222. fp32_inputs = [n for n in fp32_inputs if n in keep_io_types]
  223. fp32_outputs = [n for n in fp32_outputs if n in keep_io_types]
  224. elif not keep_io_types:
  225. fp32_inputs = []
  226. fp32_outputs = []
  227. for i, n in enumerate(model.graph.input):
  228. if n.name in fp32_inputs:
  229. output_name = "graph_input_cast_" + str(i)
  230. name_mapping[n.name] = output_name
  231. graph_io_to_skip.add(n.name)
  232. node_name = "graph_input_cast" + str(i)
  233. new_value_info = model.graph.value_info.add()
  234. new_value_info.CopyFrom(n)
  235. new_value_info.name = output_name
  236. new_value_info.type.tensor_type.elem_type = TensorProto.FLOAT16
  237. # add Cast node (from tensor(float) to tensor(float16) after graph input
  238. new_node = [helper.make_node("Cast", [n.name], [output_name], to=TensorProto.FLOAT16, name=node_name)]
  239. model.graph.node.extend(new_node)
  240. value_info_list.append(new_value_info)
  241. io_casts.add(node_name)
  242. for i, n in enumerate(model.graph.output):
  243. if n.name in fp32_outputs:
  244. input_name = "graph_output_cast_" + str(i)
  245. name_mapping[n.name] = input_name
  246. graph_io_to_skip.add(n.name)
  247. node_name = "graph_output_cast" + str(i)
  248. # add Cast node (from tensor(float16) to tensor(float) before graph output
  249. new_value_info = model.graph.value_info.add()
  250. new_value_info.CopyFrom(n)
  251. new_value_info.name = input_name
  252. new_value_info.type.tensor_type.elem_type = TensorProto.FLOAT16
  253. new_node = [helper.make_node("Cast", [input_name], [n.name], to=1, name=node_name)]
  254. model.graph.node.extend(new_node)
  255. value_info_list.append(new_value_info)
  256. io_casts.add(node_name)
  257. fp32_initializers: dict[str, InitializerTracker] = {}
  258. while queue:
  259. next_level = []
  260. for q in queue:
  261. # if q is model, push q.graph (GraphProto)
  262. if isinstance(q, ModelProto):
  263. next_level.append(q.graph)
  264. # if q is model.graph, push q.node.attribute (AttributeProto)
  265. if isinstance(q, GraphProto):
  266. for n in q.initializer: # TensorProto type
  267. if n.data_type == TensorProto.FLOAT:
  268. assert n.name not in fp32_initializers
  269. fp32_initializers[n.name] = InitializerTracker(n)
  270. for n in q.node:
  271. # if n is in the block list (doesn't support float16), no conversion for the node,
  272. # and save the node for further processing
  273. if n.name in io_casts:
  274. continue
  275. for i in range(len(n.input)):
  276. if n.input[i] in name_mapping:
  277. n.input[i] = name_mapping[n.input[i]]
  278. for i in range(len(n.output)):
  279. if n.output[i] in name_mapping:
  280. n.output[i] = name_mapping[n.output[i]]
  281. is_node_blocked = n.op_type in op_block_list or n.name in node_block_list
  282. for i, input_name in enumerate(n.input):
  283. if input_name in fp32_initializers:
  284. # For Resize/GroupNorm, only the first input can be float16
  285. use_fp32_weight = is_node_blocked or (
  286. i in ALWAYS_FLOAT_INPUTS.get(n.op_type, [])
  287. and i not in force_fp16_inputs_dict.get(n.op_type, [])
  288. )
  289. fp32_initializers[input_name].add_node(n, use_fp32_weight)
  290. if is_node_blocked:
  291. node_list.append(n)
  292. else:
  293. if n.op_type == "Cast":
  294. for attr in n.attribute:
  295. if attr.name == "to" and attr.i == TensorProto.FLOAT:
  296. attr.i = TensorProto.FLOAT16
  297. break
  298. if n.op_type in [
  299. "EyeLike",
  300. "Multinomial",
  301. "RandomNormal",
  302. "RandomNormalLike",
  303. "RandomUniform",
  304. "RandomUniformLike",
  305. "SequenceEmpty",
  306. "Bernoulli",
  307. ]:
  308. has_dtype = False
  309. for attr in n.attribute:
  310. if attr.name == "dtype":
  311. has_dtype = True
  312. if attr.i == TensorProto.FLOAT:
  313. attr.i = TensorProto.FLOAT16
  314. # The dtype attribute is optional and default is FLOAT in the following operators
  315. # so we need add dtype attribute to specify the data type float16
  316. if (n.op_type in ["RandomNormal", "RandomUniform", "SequenceEmpty"]) and not has_dtype:
  317. n.attribute.extend([helper.make_attribute("dtype", TensorProto.FLOAT16)])
  318. # For Resize/GroupNorm, attribute data type cannot be changed
  319. if n.op_type not in ALWAYS_FLOAT_INPUTS or n.op_type in force_fp16_inputs_dict:
  320. for attr in n.attribute:
  321. next_level.append(attr) # noqa: PERF402
  322. else:
  323. mixed_float_type_node_list.append(n)
  324. # if q is model.graph.node.attribute, push q.g and q.graphs (GraphProto)
  325. # and process node.attribute.t and node.attribute.tensors (TensorProto)
  326. if isinstance(q, AttributeProto):
  327. next_level.append(q.g)
  328. for n in q.graphs:
  329. next_level.append(n) # noqa: PERF402
  330. q.t.CopyFrom(convert_tensor_float_to_float16(q.t, min_positive_val, max_finite_val))
  331. for n in q.tensors:
  332. n = convert_tensor_float_to_float16(n, min_positive_val, max_finite_val) # noqa: PLW2901
  333. # if q is graph, process input, output and value_info (ValueInfoProto)
  334. if isinstance(q, GraphProto):
  335. # Note that float initializers tracked by fp32_initializers will be processed later.
  336. # for all ValueInfoProto with tensor(float) type in input, output and value_info, convert them to
  337. # tensor(float16) except map and seq(map). And save them in value_info_list for further processing
  338. for n in itertools.chain(q.input, q.output, q.value_info):
  339. if n.type.tensor_type.elem_type == TensorProto.FLOAT:
  340. if n.name not in graph_io_to_skip:
  341. n.type.tensor_type.elem_type = TensorProto.FLOAT16
  342. value_info_list.append(n)
  343. if n.type.HasField("sequence_type"):
  344. if n.type.sequence_type.elem_type.tensor_type.elem_type == TensorProto.FLOAT:
  345. if n.name not in graph_io_to_skip:
  346. n.type.sequence_type.elem_type.tensor_type.elem_type = TensorProto.FLOAT16
  347. value_info_list.append(n)
  348. queue = next_level
  349. for value in fp32_initializers.values():
  350. # By default, to avoid precision loss, do not convert an initializer to fp16 when it is used only by fp32 nodes.
  351. if force_fp16_initializers or value.fp16_nodes:
  352. value.initializer = convert_tensor_float_to_float16(value.initializer, min_positive_val, max_finite_val)
  353. value_info_list.append(make_value_info_from_tensor(value.initializer))
  354. if value.fp32_nodes and not force_fp16_initializers:
  355. logger.info(
  356. f"initializer is used by both fp32 and fp16 nodes. Consider add these nodes to block list:{value.fp16_nodes}"
  357. )
  358. # Some operators have data type fixed as float for some input. Add a float16 to float cast for those inputs.
  359. for node in mixed_float_type_node_list:
  360. for i, input_name in enumerate(node.input):
  361. if i not in ALWAYS_FLOAT_INPUTS[node.op_type] or i in force_fp16_inputs_dict.get(node.op_type, []):
  362. continue
  363. for value_info in value_info_list:
  364. if input_name == value_info.name:
  365. # create new value_info for current node's new input name
  366. new_value_info = model.graph.value_info.add()
  367. new_value_info.CopyFrom(value_info)
  368. output_name = node.name + "_input_cast_" + str(i)
  369. new_value_info.name = output_name
  370. new_value_info.type.tensor_type.elem_type = TensorProto.FLOAT
  371. # add Cast node (from tensor(float16) to tensor(float) before current node
  372. node_name = node.name + "_input_cast" + str(i)
  373. new_node = [helper.make_node("Cast", [input_name], [output_name], to=1, name=node_name)]
  374. model.graph.node.extend(new_node)
  375. # change current node's input name
  376. node.input[i] = output_name
  377. break
  378. accuracy_type = TensorProto.BFLOAT16 if use_bfloat16_as_blocked_nodes_dtype else TensorProto.FLOAT
  379. # process the nodes in block list that doesn't support tensor(float16)
  380. for node in node_list:
  381. # if input's name is in the value_info_list meaning input is tensor(float16) type,
  382. # insert a float16 to float Cast node before the node,
  383. # change current node's input name and create new value_info for the new name
  384. for i in range(len(node.input)):
  385. input_name = node.input[i]
  386. for value_info in value_info_list:
  387. if input_name == value_info.name:
  388. # create new value_info for current node's new input name
  389. new_value_info = model.graph.value_info.add()
  390. new_value_info.CopyFrom(value_info)
  391. output_name = node.name + "_input_cast_" + str(i)
  392. new_value_info.name = output_name
  393. new_value_info.type.tensor_type.elem_type = accuracy_type
  394. # add Cast node (from tensor(float16) to tensor(float) before current node
  395. node_name = node.name + "_input_cast" + str(i)
  396. new_node = [helper.make_node("Cast", [input_name], [output_name], to=accuracy_type, name=node_name)]
  397. model.graph.node.extend(new_node)
  398. # change current node's input name
  399. node.input[i] = output_name
  400. break
  401. # if output's name is in the value_info_list meaning output is tensor(float16) type, insert a float to
  402. # float16 Cast node after the node, change current node's output name and create new value_info for the new name
  403. for i in range(len(node.output)):
  404. output = node.output[i]
  405. for value_info in value_info_list:
  406. if output == value_info.name:
  407. # create new value_info for current node's new output
  408. new_value_info = model.graph.value_info.add()
  409. new_value_info.CopyFrom(value_info)
  410. input_name = node.name + "_output_cast_" + str(i)
  411. new_value_info.name = input_name
  412. new_value_info.type.tensor_type.elem_type = accuracy_type
  413. # add Cast node (from tensor(float) to tensor(float16) after current node
  414. node_name = node.name + "_output_cast" + str(i)
  415. new_node = [helper.make_node("Cast", [input_name], [output], to=10, name=node_name)]
  416. model.graph.node.extend(new_node)
  417. # change current node's input name
  418. node.output[i] = input_name
  419. break
  420. return model
  421. def float_to_float16_max_diff(tensor, min_positive_val=5.96e-08, max_finite_val=65504.0):
  422. """Measure the maximum absolute difference after converting a float tensor to float16."""
  423. if not isinstance(tensor, TensorProto):
  424. raise ValueError(f"Expected input type is an ONNX TensorProto but got {type(tensor)}")
  425. if tensor.data_type != TensorProto.FLOAT:
  426. raise ValueError("Expected tensor data type is float.")
  427. float32_data = None
  428. if tensor.float_data:
  429. float32_data = np.array(tensor.float_data)
  430. if tensor.raw_data:
  431. float32_data = np.frombuffer(tensor.raw_data, dtype="float32")
  432. if float32_data is None:
  433. raise RuntimeError("external data not loaded!")
  434. float16_data = convert_np_to_float16(float32_data, min_positive_val, max_finite_val)
  435. return np.amax(np.abs(float32_data - np.float32(float16_data)))