You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Define common utils."""
  16. import os
  17. import stat
  18. from importlib import import_module
  19. from typing import List, Tuple, Mapping
  20. from mindinsight.mindconverter.common.exceptions import ScriptGenerationError, ReportGenerationError
  21. from mindinsight.mindconverter.graph_based_converter.constant import SEPARATOR_IN_ONNX_OP
  22. def is_converted(operation: str):
  23. """
  24. Whether convert successful.
  25. Args:
  26. operation (str): Operation name.
  27. Returns:
  28. bool, true or false.
  29. """
  30. return operation and SEPARATOR_IN_ONNX_OP not in operation
  31. def _add_outputs_of_onnx_model(model, output_nodes: List[str]):
  32. """
  33. Add output nodes of onnx model.
  34. Args:
  35. model (ModelProto): ONNX model.
  36. output_nodes (list[str]): Output nodes list.
  37. Returns:
  38. ModelProto, edited ONNX model.
  39. """
  40. onnx = import_module("onnx")
  41. for opt_name in output_nodes:
  42. intermediate_layer_value_info = onnx.helper.ValueInfoProto()
  43. intermediate_layer_value_info.name = opt_name
  44. model.graph.output.append(intermediate_layer_value_info)
  45. return model
  46. def fetch_output_from_onnx_model(model, feed_dict: dict, output_nodes: List[str]):
  47. """
  48. Fetch specific nodes output from onnx model.
  49. Notes:
  50. Only support to get output without batch dimension.
  51. Args:
  52. model (ModelProto): ONNX model.
  53. feed_dict (dict): Feed forward inputs.
  54. output_nodes (list[str]): Output nodes list.
  55. Returns:
  56. dict, nodes' output value.
  57. """
  58. if not isinstance(feed_dict, dict) or not isinstance(output_nodes, list):
  59. raise TypeError("`feed_dict` should be type of dict, and `output_nodes` "
  60. "should be type of List[str].")
  61. edit_model = _add_outputs_of_onnx_model(model, output_nodes)
  62. ort = import_module("onnxruntime")
  63. sess = ort.InferenceSession(path_or_bytes=bytes(edit_model.SerializeToString()))
  64. fetched_res = sess.run(output_names=output_nodes, input_feed=feed_dict)
  65. run_result = dict()
  66. for idx, opt in enumerate(output_nodes):
  67. run_result[opt] = fetched_res[idx]
  68. return run_result
  69. def save_code_file_and_report(model_name: str, code_lines: Mapping[str, Tuple],
  70. out_folder: str, report_folder: str):
  71. """
  72. Save code file and report.
  73. Args:
  74. model_name (str): Model name.
  75. code_lines (dict): Code lines.
  76. out_folder (str): Output folder.
  77. report_folder (str): Report output folder.
  78. """
  79. flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
  80. modes = stat.S_IRUSR | stat.S_IWUSR
  81. modes_usr = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
  82. out_folder = os.path.realpath(out_folder)
  83. if not report_folder:
  84. report_folder = out_folder
  85. else:
  86. report_folder = os.path.realpath(report_folder)
  87. if not os.path.exists(out_folder):
  88. os.makedirs(out_folder, modes_usr)
  89. if not os.path.exists(report_folder):
  90. os.makedirs(report_folder, modes_usr)
  91. for file_name in code_lines:
  92. code, report = code_lines[file_name]
  93. code_file_path = os.path.realpath(os.path.join(out_folder, f"{model_name}.py"))
  94. report_file_path = os.path.realpath(os.path.join(report_folder, f"report_of_{model_name}.txt"))
  95. try:
  96. if os.path.exists(code_file_path):
  97. raise ScriptGenerationError("Code file with the same name already exists.")
  98. with os.fdopen(os.open(code_file_path, flags, modes), 'w') as file:
  99. file.write(code)
  100. except (IOError, FileExistsError) as error:
  101. raise ScriptGenerationError(str(error))
  102. try:
  103. if os.path.exists(report_file_path):
  104. raise ReportGenerationError("Report file with the same name already exists.")
  105. with os.fdopen(os.open(report_file_path, flags, stat.S_IRUSR), "w") as rpt_f:
  106. rpt_f.write(report)
  107. except (IOError, FileExistsError) as error:
  108. raise ReportGenerationError(str(error))
  109. def lib_version_satisfied(current_ver: str, mini_ver_limited: str,
  110. newest_ver_limited: str = ""):
  111. """
  112. Check python lib version whether is satisfied.
  113. Notes:
  114. Version number must be format of x.x.x, e.g. 1.1.0.
  115. Args:
  116. current_ver (str): Current lib version.
  117. mini_ver_limited (str): Mini lib version.
  118. newest_ver_limited (str): Newest lib version.
  119. Returns:
  120. bool, true or false.
  121. """
  122. required_version_number_len = 3
  123. if len(list(current_ver.split("."))) != required_version_number_len or \
  124. len(list(mini_ver_limited.split("."))) != required_version_number_len or \
  125. (newest_ver_limited and len(newest_ver_limited.split(".")) != required_version_number_len):
  126. raise ValueError("Version number must be format of x.x.x.")
  127. if current_ver < mini_ver_limited or (newest_ver_limited and current_ver > newest_ver_limited):
  128. return False
  129. return True
  130. def get_dict_key_by_value(val, dic):
  131. """
  132. Return the first appeared key of a dictionary by given value.
  133. Args:
  134. val (Any): Value of the key.
  135. dic (dict): Dictionary to be checked.
  136. Returns:
  137. Any, key of the given value.
  138. """
  139. for d_key, d_val in dic.items():
  140. if d_val == val:
  141. return d_key
  142. return None