onnx_model_utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. # Copyright (c) Microsoft Corporation. All rights reserved.
  2. # Licensed under the MIT License.
  3. from __future__ import annotations
  4. import logging
  5. import pathlib
  6. import onnx
  7. from onnx import version_converter
  8. import onnxruntime as ort
  9. def iterate_graph_per_node_func(graph, per_node_func, **func_args):
  10. """
  11. Iterate the graph including subgraphs calling the per_node_func for each node.
  12. :param graph: Graph to iterate
  13. :param per_node_func: Function to call for each node. Signature is fn(node: onnx:NodeProto, **kwargs)
  14. :param func_args: The keyword args to pass through.
  15. """
  16. for node in graph.node:
  17. per_node_func(node, **func_args)
  18. # recurse into subgraph for control flow nodes (Scan/Loop/If)
  19. for attr in node.attribute:
  20. if attr.HasField("g"):
  21. iterate_graph_per_node_func(attr.g, per_node_func, **func_args)
  22. def iterate_graph_per_graph_func(graph, per_graph_func, **func_args):
  23. """
  24. Iterate the graph including subgraphs calling the per_graph_func for each Graph.
  25. :param graph: Graph to iterate
  26. :param per_graph_func: Function to call for each graph. Signature is fn(graph: onnx:GraphProto, **kwargs)
  27. :param func_args: The keyword args to pass through.
  28. """
  29. per_graph_func(graph, **func_args)
  30. for node in graph.node:
  31. # recurse into subgraph for control flow nodes (Scan/Loop/If)
  32. for attr in node.attribute:
  33. if attr.HasField("g"):
  34. iterate_graph_per_graph_func(attr.g, per_graph_func, **func_args)
  35. def get_opsets_imported(model: onnx.ModelProto):
  36. """
  37. Get the opsets imported by the model
  38. :param model: Model to check.
  39. :return: Map of domain to opset.
  40. """
  41. opsets = {}
  42. for entry in model.opset_import:
  43. # if empty it's ai.onnx
  44. domain = entry.domain or "ai.onnx"
  45. opsets[domain] = entry.version
  46. return opsets
  47. def update_onnx_opset(
  48. model_path: pathlib.Path,
  49. opset: int,
  50. out_path: pathlib.Path | None = None,
  51. logger: logging.Logger | None = None,
  52. ):
  53. """
  54. Helper to update the opset of a model using onnx version_converter. Target opset must be greater than current opset.
  55. :param model_path: Path to model to update
  56. :param opset: Opset to update model to
  57. :param out_path: Optional output path for updated model to be saved to.
  58. :param logger: Optional logger for diagnostic output
  59. :returns: Updated onnx.ModelProto
  60. """
  61. model_path_str = str(model_path.resolve(strict=True))
  62. if logger:
  63. logger.info("Updating %s to opset %d", model_path_str, opset)
  64. model = onnx.load(model_path_str)
  65. new_model = version_converter.convert_version(model, opset)
  66. if out_path:
  67. onnx.save(new_model, str(out_path))
  68. if logger:
  69. logger.info("Saved updated model to %s", out_path)
  70. return new_model
  71. def optimize_model(
  72. model_path: pathlib.Path,
  73. output_path: pathlib.Path,
  74. level: ort.GraphOptimizationLevel = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC,
  75. log_level: int = 3,
  76. use_external_initializers: bool = False,
  77. ):
  78. """
  79. Optimize an ONNX model using ONNX Runtime to the specified level
  80. :param model_path: Path to ONNX model
  81. :param output_path: Path to save optimized model to.
  82. :param level: onnxruntime.GraphOptimizationLevel to use. Default is ORT_ENABLE_BASIC.
  83. :param log_level: Log level. Defaults to Error (3) so we don't get output about unused initializers being removed.
  84. Warning (2) or Info (1) may be desirable in some scenarios.
  85. :param use_external_initializers: Set flag to write initializers to an external file. Required if model > 2GB.
  86. Requires onnxruntime 1.17+
  87. """
  88. so = ort.SessionOptions()
  89. so.optimized_model_filepath = str(output_path.resolve())
  90. so.graph_optimization_level = level
  91. so.log_severity_level = log_level
  92. # save using external initializers so models > 2 GB are handled
  93. if use_external_initializers:
  94. major, minor, rest = ort.__version__.split(".", 3)
  95. if (int(major), int(minor)) >= (1, 17):
  96. so.add_session_config_entry("session.optimized_model_external_initializers_file_name", "external_data.pb")
  97. else:
  98. raise ValueError(
  99. "ONNX Runtime 1.17 or higher required to save initializers as external data when optimizing model. "
  100. f"Current ONNX Runtime version is {ort.__version__}"
  101. )
  102. # create session to optimize. this will write the updated model to output_path
  103. _ = ort.InferenceSession(str(model_path.resolve(strict=True)), so, providers=["CPUExecutionProvider"])
  104. def _replace_symbolic_dim_value(graph: onnx.GraphProto, **kwargs):
  105. param_to_replace = kwargs["dim_param"]
  106. value = kwargs["value"]
  107. def update_dim_values(value_infos):
  108. for vi in value_infos:
  109. if vi.type.HasField("tensor_type"):
  110. shape = vi.type.tensor_type.shape
  111. if shape:
  112. for dim in shape.dim:
  113. if dim.HasField("dim_param") and dim.dim_param == param_to_replace:
  114. dim.Clear()
  115. dim.dim_value = value
  116. update_dim_values(graph.input)
  117. update_dim_values(graph.output)
  118. update_dim_values(graph.value_info)
  119. def _remove_invalid_dim_values_impl(graph: onnx.GraphProto):
  120. def clear_invalid_values(value):
  121. if value.type.HasField("tensor_type"):
  122. shape = value.type.tensor_type.shape
  123. if shape:
  124. for dim in shape.dim:
  125. if dim.HasField("dim_value") and dim.dim_value < 1:
  126. dim.Clear()
  127. for i in graph.input:
  128. clear_invalid_values(i)
  129. for o in graph.output:
  130. clear_invalid_values(o)
  131. for vi in graph.value_info:
  132. clear_invalid_values(vi)
  133. def remove_invalid_dim_values(graph: onnx.GraphProto):
  134. """
  135. Iterate the graph and subgraphs, unsetting any dim_value entries that have a value of less than 1.
  136. These are typically erroneously inserted by a converter to represent a dynamic dimension.
  137. :param graph: GraphProto to update
  138. """
  139. iterate_graph_per_graph_func(graph, _remove_invalid_dim_values_impl)
  140. def make_dim_param_fixed(graph: onnx.GraphProto, param_name: str, value: int):
  141. """
  142. Iterate all values in the graph, replacing dim_param in a tensor shape with the provided value.
  143. :param graph: GraphProto to update
  144. :param param_name: dim_param to set
  145. :param value: value to use
  146. """
  147. iterate_graph_per_graph_func(graph, _replace_symbolic_dim_value, dim_param=param_name, value=value)
  148. def make_input_shape_fixed(graph: onnx.GraphProto, input_name: str, fixed_shape: [int]):
  149. """
  150. Update the named graph input to set shape to the provided value. This can be used to set unknown dims as well
  151. as to replace dim values.
  152. If setting the input shape replaces a dim_param, update any other values in the graph that use the dim_param.
  153. :param graph: Graph to update
  154. :param input_name: Name of graph input to update.
  155. :param fixed_shape: Shape to use.
  156. """
  157. # remove any invalid dim values first. typically this is a dim_value of -1.
  158. remove_invalid_dim_values(graph)
  159. for i in graph.input:
  160. if i.name == input_name:
  161. if not i.type.HasField("tensor_type"):
  162. raise ValueError(f"Input {input_name} is not a tensor")
  163. # graph inputs are required to have a shape to provide the rank
  164. shape = i.type.tensor_type.shape
  165. if len(shape.dim) != len(fixed_shape):
  166. raise ValueError(f"Rank mismatch. Existing:{len(shape.dim)} Replacement:{len(fixed_shape)}")
  167. for idx, dim in enumerate(shape.dim):
  168. # check any existing fixed dims match
  169. if dim.HasField("dim_value"):
  170. if dim.dim_value != fixed_shape[idx]:
  171. raise ValueError(
  172. f"Can't replace existing fixed size of {dim.dim_value} with {fixed_shape[idx]} "
  173. f"for dimension {idx + 1}"
  174. )
  175. elif dim.HasField("dim_param"):
  176. # replacing a dim_param so have to do that through the entire graph
  177. make_dim_param_fixed(graph, dim.dim_param, fixed_shape[idx])
  178. else:
  179. # replacing an unknown dim
  180. dim.Clear()
  181. dim.dim_value = fixed_shape[idx]
  182. return
  183. raise ValueError(
  184. f"Input {input_name} was not found in graph inputs. "
  185. f"Valid input names are: {','.join([i.name for i in graph.input])}"
  186. )
  187. def fix_output_shapes(model: onnx.ModelProto):
  188. """
  189. Update the output shapesof a model where the input shape/s were made fixed, if possible.
  190. This is mainly to make the model usage clearer if the output shapes can be inferred from the new input shapes.
  191. :param model: Model that had input shapes fixed.
  192. """
  193. # get a version of the model with shape inferencing info in it. this will provide fixed output shapes if possible.
  194. m2 = onnx.shape_inference.infer_shapes(model)
  195. onnx.checker.check_model(m2)
  196. for idx, o in enumerate(model.graph.output):
  197. if not is_fixed_size_tensor(o):
  198. new_o = m2.graph.output[idx]
  199. if is_fixed_size_tensor(new_o):
  200. o.type.tensor_type.shape.CopyFrom(new_o.type.tensor_type.shape)
  201. def _create_producer_consumer_link(
  202. node_to_producers: dict, node_to_consumers: dict, producer: onnx.NodeProto, consumer: onnx.NodeProto
  203. ):
  204. """
  205. Create links between two nodes for a value produced by one and consumed by the other.
  206. :param node_to_producers: Map of NodeProto to set of nodes that produce values the node consumes as inputs.
  207. :param node_to_consumers: Map of NodeProto to set of nodes that consume values the node produces as outputs.
  208. :param producer: Producer node
  209. :param consumer: Consumer node
  210. """
  211. if consumer not in node_to_producers:
  212. node_to_producers[consumer] = set()
  213. if producer not in node_to_consumers:
  214. node_to_consumers[producer] = set()
  215. # add entry mapping this node to the producer of this input
  216. node_to_producers[consumer].add(producer)
  217. node_to_consumers[producer].add(consumer)
  218. def _map_node_dependencies(graph: onnx.GraphProto, node_to_producers: dict, node_to_consumers: dict):
  219. graph_inputs = {i.name for i in graph.input}
  220. initializers = {i.name for i in graph.initializer}
  221. # map of value name to node that creates it. copy parent values but override if values get shadowed
  222. producers = {}
  223. implicit_inputs = set()
  224. def is_local_value(value):
  225. return value in producers or value in initializers or value in graph_inputs
  226. for node in graph.node:
  227. inputs = list(node.input)
  228. for attr in node.attribute:
  229. if attr.HasField("g"):
  230. subgraph_implicit_inputs = _map_node_dependencies(attr.g, node_to_producers, node_to_consumers)
  231. inputs += subgraph_implicit_inputs
  232. for i in inputs:
  233. if not i:
  234. # missing optional input
  235. continue
  236. if is_local_value(i):
  237. if i in producers:
  238. producer = producers[i]
  239. _create_producer_consumer_link(node_to_producers, node_to_consumers, producer, node)
  240. else:
  241. implicit_inputs.add(i)
  242. for o in node.output:
  243. producers[o] = node
  244. return implicit_inputs
  245. def get_producer_consumer_maps(graph: onnx.GraphProto):
  246. """
  247. Get maps for connections between the node that produces each value and the nodes that consume the value.
  248. Processing includes subgraphs. As the map key is a Node instance from the Graph there should be no ambiguity.
  249. :param graph: Graph to process.
  250. :return: Tuple with two maps.
  251. First is node_to_producers map of a node to set of all nodes producing input it consumes.
  252. Second is node_to_consumers map of a node to set of all nodes consuming output it creates.
  253. e.g. NodeA and NodeB provide inputs to NodeC. NodeC provides input to NodeD
  254. node_to_consumers[NodeA] = set([NodeC])
  255. node_to_consumers[NodeB] = set([NodeC])
  256. node_to_producers[NodeC] = set([NodeA, NodeB])
  257. node_to_consumers[NodeC] = set([NodeD])
  258. node_to_producers[NodeD] = set([NodeC])
  259. """
  260. # use a hash of the object id for NodeProto.
  261. # we need this for the partitioning checker where we keep maps with nodes as the key.
  262. onnx.NodeProto.__hash__ = lambda self: id(self)
  263. node_to_producers = {} # map of node instance to nodes producing input values it consumes
  264. node_to_consumers = {} # map of node instance to nodes consuming output values it produces
  265. implicit_inputs = _map_node_dependencies(graph, node_to_producers, node_to_consumers)
  266. # top level graph should have no implicit inputs
  267. if implicit_inputs:
  268. raise ValueError(
  269. f"This appears to be an invalid model with missing inputs of {','.join(sorted(implicit_inputs))}"
  270. )
  271. return node_to_producers, node_to_consumers
  272. def is_fixed_size_tensor(value: onnx.ValueInfoProto):
  273. """
  274. Check if value is a tensor with a fixed shape.
  275. :param value: onnx.ValueInfoProto to check
  276. :return: True if value is a tensor, with a shape, where all dimensions have fixed values.
  277. """
  278. is_fixed = False
  279. if value.type.HasField("tensor_type"):
  280. shape = value.type.tensor_type.shape
  281. if shape:
  282. is_fixed = True # scalar has no dims so set to True and unset if we hit a dim without a valid value
  283. for dim in shape.dim:
  284. if dim.HasField("dim_value") and dim.dim_value > 0:
  285. continue
  286. # anything else means it's a dynamic value
  287. is_fixed = False
  288. break
  289. return is_fixed
  290. def get_optimization_level(level):
  291. """Convert string to GraphOptimizationLevel."""
  292. if level == "disable":
  293. return ort.GraphOptimizationLevel.ORT_DISABLE_ALL
  294. if level == "basic":
  295. # Constant folding and other optimizations that only use ONNX operators
  296. return ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
  297. if level == "extended":
  298. # Optimizations using custom operators, excluding NCHWc and NHWC layout optimizers
  299. return ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED
  300. if level == "layout":
  301. # NCHWc and NHWC layout optimizers
  302. return ort.GraphOptimizationLevel.ORT_ENABLE_LAYOUT
  303. if level == "all":
  304. return ort.GraphOptimizationLevel.ORT_ENABLE_ALL
  305. raise ValueError("Invalid optimization level of " + level)
  306. class ModelProtoWithShapeInfo:
  307. """
  308. Class to load an ONNX model and run shape inferencing on it to populate the ValueInfo.
  309. The model_with_shape_info property will contain the updated model.
  310. If the model is > 2GB and uses external data a temporary file is required to run shape inferencing successfully.
  311. This helper class handles automatic removal of the temporary file.
  312. """
  313. def __init__(self, model_path: pathlib.Path):
  314. """
  315. :param model_path: Path to ONNX model to load and run shape inferencing on.
  316. """
  317. self.model_path = model_path
  318. model = onnx.load(str(model_path))
  319. self.model_with_shape_info = onnx.shape_inference.infer_shapes(model, strict_mode=True)
  320. # ONNX has a silent failure from the call to infer_shapes when the model is > 2GB.
  321. # We detect that by checking the nodes in the returned model.
  322. self._tmp_model_path = None
  323. if len(model.graph.node) > 0 and len(self.model_with_shape_info.graph.node) == 0:
  324. self._tmp_model_path = pathlib.Path(model_path).with_suffix(".temp_with_shapeinf.onnx")
  325. onnx.shape_inference.infer_shapes_path(str(model_path), str(self._tmp_model_path), strict_mode=True)
  326. self.model_with_shape_info = onnx.load(str(self._tmp_model_path))
  327. def __del__(self):
  328. if self._tmp_model_path:
  329. self._tmp_model_path.unlink(missing_ok=True)