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 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. # Copyright 2020-2021 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 json
  17. import os
  18. import stat
  19. from importlib import import_module
  20. from importlib.util import find_spec
  21. from typing import List, Tuple, Mapping
  22. from mindinsight.mindconverter.common.exceptions import ScriptGenerationError, ReportGenerationError, \
  23. UnknownModelError, CheckPointGenerationError, WeightMapGenerationError
  24. from mindinsight.mindconverter.common.log import logger as log
  25. from mindinsight.mindconverter.graph_based_converter.constant import SEPARATOR_IN_ONNX_OP, BINARY_HEADER_PYTORCH_BITS, \
  26. FrameworkType, BINARY_HEADER_PYTORCH_FILE, TENSORFLOW_MODEL_SUFFIX, THIRD_PART_VERSION
  27. from mindspore.train.serialization import save_checkpoint
  28. def is_converted(operation: str):
  29. """
  30. Whether convert successful.
  31. Args:
  32. operation (str): Operation name.
  33. Returns:
  34. bool, true or false.
  35. """
  36. return operation and SEPARATOR_IN_ONNX_OP not in operation
  37. def _add_outputs_of_onnx_model(model, output_nodes: List[str]):
  38. """
  39. Add output nodes of onnx model.
  40. Args:
  41. model (ModelProto): ONNX model.
  42. output_nodes (list[str]): Output nodes list.
  43. Returns:
  44. ModelProto, edited ONNX model.
  45. """
  46. onnx = import_module("onnx")
  47. for opt_name in output_nodes:
  48. intermediate_layer_value_info = onnx.helper.ValueInfoProto()
  49. intermediate_layer_value_info.name = opt_name
  50. model.graph.output.append(intermediate_layer_value_info)
  51. return model
  52. def check_dependency_integrity(*packages):
  53. """Check dependency package integrity."""
  54. try:
  55. for pkg in packages:
  56. import_module(pkg)
  57. return True
  58. except ImportError:
  59. return False
  60. def fetch_output_from_onnx_model(model, feed_dict: dict, output_nodes: List[str]):
  61. """
  62. Fetch specific nodes output from onnx model.
  63. Notes:
  64. Only support to get output without batch dimension.
  65. Args:
  66. model (ModelProto): ONNX model.
  67. feed_dict (dict): Feed forward inputs.
  68. output_nodes (list[str]): Output nodes list.
  69. Returns:
  70. dict, nodes' output value.
  71. """
  72. if not isinstance(feed_dict, dict) or not isinstance(output_nodes, list):
  73. raise TypeError("`feed_dict` should be type of dict, and `output_nodes` "
  74. "should be type of List[str].")
  75. edit_model = _add_outputs_of_onnx_model(model, output_nodes)
  76. ort = import_module("onnxruntime")
  77. sess = ort.InferenceSession(path_or_bytes=bytes(edit_model.SerializeToString()))
  78. fetched_res = sess.run(output_names=output_nodes, input_feed=feed_dict)
  79. run_result = dict()
  80. for idx, opt in enumerate(output_nodes):
  81. run_result[opt] = fetched_res[idx]
  82. return run_result
  83. def save_code_file_and_report(model_name: str, code_lines: Mapping[str, Tuple],
  84. out_folder: str, report_folder: str):
  85. """
  86. Save code file and report.
  87. Args:
  88. model_name (str): Model name.
  89. code_lines (dict): Code lines.
  90. out_folder (str): Output folder.
  91. report_folder (str): Report output folder.
  92. """
  93. flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
  94. modes = stat.S_IRUSR | stat.S_IWUSR
  95. modes_usr = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
  96. out_folder = os.path.realpath(out_folder)
  97. if not report_folder:
  98. report_folder = out_folder
  99. else:
  100. report_folder = os.path.realpath(report_folder)
  101. if not os.path.exists(out_folder):
  102. os.makedirs(out_folder, modes_usr)
  103. if not os.path.exists(report_folder):
  104. os.makedirs(report_folder, modes_usr)
  105. for file_name in code_lines:
  106. code, report, trainable_weights, weight_map = code_lines[file_name]
  107. code_file_path = os.path.realpath(os.path.join(out_folder, f"{model_name}.py"))
  108. report_file_path = os.path.realpath(os.path.join(report_folder, f"report_of_{model_name}.txt"))
  109. try:
  110. if os.path.exists(code_file_path):
  111. raise ScriptGenerationError("Code file with the same name already exists.")
  112. with os.fdopen(os.open(code_file_path, flags, modes), 'w') as file:
  113. file.write(code)
  114. except (IOError, FileExistsError) as error:
  115. raise ScriptGenerationError(str(error))
  116. try:
  117. if os.path.exists(report_file_path):
  118. raise ReportGenerationError("Report file with the same name already exists.")
  119. with os.fdopen(os.open(report_file_path, flags, stat.S_IRUSR), "w") as rpt_f:
  120. rpt_f.write(report)
  121. except (IOError, FileExistsError) as error:
  122. raise ReportGenerationError(str(error))
  123. ckpt_file_path = os.path.realpath(os.path.join(out_folder, f"{model_name}.ckpt"))
  124. try:
  125. if os.path.exists(ckpt_file_path):
  126. raise CheckPointGenerationError("Checkpoint file with the same name already exists.")
  127. save_checkpoint(trainable_weights, ckpt_file_path)
  128. except TypeError as error:
  129. raise CheckPointGenerationError(str(error))
  130. weight_map_path = os.path.realpath(os.path.join(out_folder, f"weight_map_of_{model_name}.json"))
  131. try:
  132. if os.path.exists(weight_map_path):
  133. raise WeightMapGenerationError("Weight map file with the same name already exists.")
  134. with os.fdopen(os.open(weight_map_path, flags, stat.S_IRUSR), 'w') as map_f:
  135. weight_map_json = {f"{model_name}": weight_map}
  136. json.dump(weight_map_json, map_f)
  137. except (IOError, FileExistsError) as error:
  138. raise WeightMapGenerationError(str(error))
  139. def onnx_satisfied():
  140. """Validate ONNX , ONNXRUNTIME, ONNXOPTIMIZER installation."""
  141. if not find_spec("onnx") or not find_spec("onnxruntime") or not find_spec("onnxoptimizer"):
  142. return False
  143. return True
  144. def lib_version_satisfied(current_ver: str, mini_ver_limited: str,
  145. newest_ver_limited: str = ""):
  146. """
  147. Check python lib version whether is satisfied.
  148. Notes:
  149. Version number must be format of x.x.x, e.g. 1.1.0.
  150. Args:
  151. current_ver (str): Current lib version.
  152. mini_ver_limited (str): Mini lib version.
  153. newest_ver_limited (str): Newest lib version.
  154. Returns:
  155. bool, true or false.
  156. """
  157. required_version_number_len = 3
  158. if len(list(current_ver.split("."))) != required_version_number_len or \
  159. len(list(mini_ver_limited.split("."))) != required_version_number_len or \
  160. (newest_ver_limited and len(newest_ver_limited.split(".")) != required_version_number_len):
  161. raise ValueError("Version number must be format of x.x.x.")
  162. if current_ver < mini_ver_limited or (newest_ver_limited and current_ver > newest_ver_limited):
  163. return False
  164. return True
  165. def get_dict_key_by_value(val, dic):
  166. """
  167. Return the first appeared key of a dictionary by given value.
  168. Args:
  169. val (Any): Value of the key.
  170. dic (dict): Dictionary to be checked.
  171. Returns:
  172. Any, key of the given value.
  173. """
  174. for d_key, d_val in dic.items():
  175. if d_val == val:
  176. return d_key
  177. return None
  178. def convert_bytes_string_to_string(bytes_str):
  179. """
  180. Convert a byte string to string by utf-8.
  181. Args:
  182. bytes_str (bytes): A bytes string.
  183. Returns:
  184. str, a str with utf-8 encoding.
  185. """
  186. if isinstance(bytes_str, bytes):
  187. return bytes_str.decode('utf-8')
  188. return bytes_str
  189. def get_framework_type(model_path):
  190. """Get framework type."""
  191. if model_path.endswith('.onnx'):
  192. return FrameworkType.PYTORCH.value
  193. try:
  194. with open(model_path, 'rb') as f:
  195. if f.read(BINARY_HEADER_PYTORCH_BITS) == BINARY_HEADER_PYTORCH_FILE:
  196. framework_type = FrameworkType.PYTORCH.value
  197. elif os.path.basename(model_path).split(".")[-1].lower() == TENSORFLOW_MODEL_SUFFIX:
  198. framework_type = FrameworkType.TENSORFLOW.value
  199. else:
  200. framework_type = FrameworkType.UNKNOWN.value
  201. except IOError:
  202. error_msg = "Get UNSUPPORTED model."
  203. error = UnknownModelError(error_msg)
  204. log.error(str(error))
  205. raise error
  206. return framework_type
  207. def reset_init_or_construct(template, variable_slot, new_data, scope):
  208. """Reset init statement."""
  209. template[variable_slot][scope].clear()
  210. template[variable_slot][scope] += new_data
  211. return template
  212. def replace_string_in_list(str_list: list, original_str: str, target_str: str):
  213. """
  214. Replace a string in a list by provided string.
  215. Args:
  216. str_list (list): A list contains the string to be replaced.
  217. original_str (str): The string to be replaced.
  218. target_str (str): The replacement of string.
  219. Returns,
  220. list, the original list with replaced string.
  221. """
  222. return [s.replace(original_str, target_str) for s in str_list]
  223. def get_third_part_lib_validation_error_info(lib_list):
  224. """Get error info when not satisfying third part lib validation."""
  225. error_info = None
  226. link_str = ', '
  227. for idx, lib in enumerate(lib_list):
  228. if idx == len(lib_list) - 1:
  229. link_str = ' and '
  230. lib_version_required = THIRD_PART_VERSION[lib]
  231. if len(lib_version_required) == 2:
  232. lib_version_required_min = lib_version_required[0]
  233. lib_version_required_max = lib_version_required[1]
  234. if lib_version_required_min == lib_version_required_max:
  235. info = f"{lib}(=={lib_version_required_min})"
  236. else:
  237. info = f"{lib}(>={lib_version_required_min} and <{lib_version_required_max})"
  238. else:
  239. info = f"{lib}(>={lib_version_required[0]})"
  240. if not error_info:
  241. error_info = info
  242. else:
  243. error_info = link_str.join((error_info, info))
  244. return error_info