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

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. import uuid
  20. from importlib import import_module
  21. from importlib.util import find_spec
  22. from typing import List, Tuple, Mapping
  23. import numpy as np
  24. from mindinsight.mindconverter.common.exceptions import ScriptGenerationError, ReportGenerationError, \
  25. CheckPointGenerationError, WeightMapGenerationError, ModelLoadingError, OnnxModelSaveError
  26. from mindinsight.mindconverter.graph_based_converter.constant import SEPARATOR_IN_ONNX_OP, FrameworkType, \
  27. TENSORFLOW_MODEL_SUFFIX, THIRD_PART_VERSION, ONNX_MODEL_SUFFIX, DTYPE_MAP
  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 build_feed_dict(onnx_model, input_nodes: dict):
  61. """Build feed dict for onnxruntime."""
  62. dtype_mapping = DTYPE_MAP
  63. input_nodes_types = {
  64. node.name: dtype_mapping[node.type.tensor_type.elem_type]
  65. for node in onnx_model.graph.input
  66. }
  67. feed_dict = {
  68. name: np.random.rand(*shape).astype(input_nodes_types[name])
  69. for name, shape in input_nodes.items()
  70. }
  71. return feed_dict
  72. def fetch_output_from_onnx_model(model, model_path: str, feed_dict: dict, output_nodes: List[str]):
  73. """
  74. Fetch specific nodes output from onnx model.
  75. Notes:
  76. Only support to get output without batch dimension.
  77. Args:
  78. model (ModelProto): ONNX model.
  79. model_path (str): ONNX model path.
  80. feed_dict (dict): Feed forward inputs.
  81. output_nodes (list[str]): Output nodes list.
  82. Returns:
  83. dict, nodes' output value.
  84. """
  85. if not isinstance(feed_dict, dict) or not isinstance(output_nodes, list):
  86. raise TypeError("`feed_dict` should be type of dict, and `output_nodes` "
  87. "should be type of List[str].")
  88. edit_model = _add_outputs_of_onnx_model(model, output_nodes)
  89. onnx = import_module("onnx")
  90. ort = import_module("onnxruntime")
  91. try:
  92. dir_path = os.path.dirname(model_path)
  93. stem_name = os.path.splitext(os.path.basename(model_path))[0]
  94. filename = ".~{0}_{1}".format(stem_name, str(uuid.uuid4()))
  95. tmp_file = os.path.join(dir_path, filename)
  96. onnx.save_tensor(edit_model, tmp_file)
  97. except (TypeError, IOError) as error:
  98. if os.path.exists(tmp_file):
  99. os.remove(tmp_file)
  100. raise OnnxModelSaveError("Onnx model save failed, {}".format(str(error)))
  101. try:
  102. sess = ort.InferenceSession(path_or_bytes=tmp_file)
  103. fetched_res = sess.run(output_names=output_nodes, input_feed=feed_dict)
  104. except ModelLoadingError.raise_from() as error:
  105. raise ModelLoadingError("OnnxRuntimeError, {}".format(str(error)))
  106. finally:
  107. if os.path.exists(tmp_file):
  108. os.remove(tmp_file)
  109. run_result = dict()
  110. for idx, opt in enumerate(output_nodes):
  111. run_result[opt] = fetched_res[idx]
  112. return run_result
  113. def save_code_file_and_report(model_name: str, code_lines: Mapping[str, Tuple],
  114. out_folder: str, report_folder: str):
  115. """
  116. Save code file and report.
  117. Args:
  118. model_name (str): Model name.
  119. code_lines (dict): Code lines.
  120. out_folder (str): Output folder.
  121. report_folder (str): Report output folder.
  122. """
  123. flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
  124. modes = stat.S_IRUSR | stat.S_IWUSR
  125. modes_usr = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
  126. out_folder = os.path.realpath(out_folder)
  127. if not report_folder:
  128. report_folder = out_folder
  129. else:
  130. report_folder = os.path.realpath(report_folder)
  131. if not os.path.exists(out_folder):
  132. os.makedirs(out_folder, modes_usr)
  133. if not os.path.exists(report_folder):
  134. os.makedirs(report_folder, modes_usr)
  135. for file_name in code_lines:
  136. code, report, trainable_weights, weight_map = code_lines[file_name]
  137. code_file_path = os.path.realpath(os.path.join(out_folder, f"{model_name}.py"))
  138. report_file_path = os.path.realpath(os.path.join(report_folder, f"report_of_{model_name}.txt"))
  139. try:
  140. if os.path.exists(code_file_path):
  141. raise ScriptGenerationError("Code file with the same name already exists.")
  142. with os.fdopen(os.open(code_file_path, flags, modes), 'w') as file:
  143. file.write(code)
  144. except (IOError, FileExistsError) as error:
  145. raise ScriptGenerationError(str(error))
  146. try:
  147. if os.path.exists(report_file_path):
  148. raise ReportGenerationError("Report file with the same name already exists.")
  149. with os.fdopen(os.open(report_file_path, flags, stat.S_IRUSR), "w") as rpt_f:
  150. rpt_f.write(report)
  151. except (IOError, FileExistsError) as error:
  152. raise ReportGenerationError(str(error))
  153. save_checkpoint = getattr(import_module("mindspore.train.serialization"), "save_checkpoint")
  154. for idx, trainable_weight in enumerate(trainable_weights):
  155. if len(trainable_weights) > 1:
  156. ckpt_file_path = os.path.realpath(os.path.join(out_folder, f"{model_name}_{idx}.ckpt"))
  157. else:
  158. ckpt_file_path = os.path.realpath(os.path.join(out_folder, f"{model_name}.ckpt"))
  159. if os.path.exists(ckpt_file_path):
  160. raise CheckPointGenerationError("Checkpoint file with the same name already exists.")
  161. try:
  162. save_checkpoint(trainable_weight, ckpt_file_path)
  163. except TypeError as error:
  164. raise CheckPointGenerationError(str(error))
  165. weight_map_path = os.path.realpath(os.path.join(report_folder, f"weight_map_of_{model_name}.json"))
  166. try:
  167. if os.path.exists(weight_map_path):
  168. raise WeightMapGenerationError("Weight map file with the same name already exists.")
  169. with os.fdopen(os.open(weight_map_path, flags, stat.S_IRUSR), 'w') as map_f:
  170. weight_map_json = {f"{model_name}": weight_map}
  171. json.dump(weight_map_json, map_f)
  172. except (IOError, FileExistsError) as error:
  173. raise WeightMapGenerationError(str(error))
  174. def onnx_satisfied():
  175. """Validate ONNX , ONNXRUNTIME, ONNXOPTIMIZER installation."""
  176. if not find_spec("onnx") or not find_spec("onnxruntime") or not find_spec("onnxoptimizer"):
  177. return False
  178. return True
  179. def lib_version_satisfied(current_ver: str, mini_ver_limited: str,
  180. newest_ver_limited: str = ""):
  181. """
  182. Check python lib version whether is satisfied.
  183. Notes:
  184. Version number must be format of x.x.x, e.g. 1.1.0.
  185. Args:
  186. current_ver (str): Current lib version.
  187. mini_ver_limited (str): Mini lib version.
  188. newest_ver_limited (str): Newest lib version.
  189. Returns:
  190. bool, true or false.
  191. """
  192. required_version_number_len = 3
  193. if len(list(current_ver.split("."))) != required_version_number_len or \
  194. len(list(mini_ver_limited.split("."))) != required_version_number_len or \
  195. (newest_ver_limited and len(newest_ver_limited.split(".")) != required_version_number_len):
  196. raise ValueError("Version number must be format of x.x.x.")
  197. if current_ver < mini_ver_limited or (newest_ver_limited and current_ver > newest_ver_limited):
  198. return False
  199. return True
  200. def get_dict_key_by_value(val, dic):
  201. """
  202. Return the first appeared key of a dictionary by given value.
  203. Args:
  204. val (Any): Value of the key.
  205. dic (dict): Dictionary to be checked.
  206. Returns:
  207. Any, key of the given value.
  208. """
  209. for d_key, d_val in dic.items():
  210. if d_val == val:
  211. return d_key
  212. return None
  213. def convert_bytes_string_to_string(bytes_str):
  214. """
  215. Convert a byte string to string by utf-8.
  216. Args:
  217. bytes_str (bytes): A bytes string.
  218. Returns:
  219. str, a str with utf-8 encoding.
  220. """
  221. if isinstance(bytes_str, bytes):
  222. return bytes_str.decode('utf-8')
  223. return bytes_str
  224. def get_framework_type(model_path):
  225. """Get framework type."""
  226. model_suffix = os.path.basename(model_path).split(".")[-1].lower()
  227. if model_suffix == ONNX_MODEL_SUFFIX:
  228. framework_type = FrameworkType.ONNX.value
  229. elif model_suffix == TENSORFLOW_MODEL_SUFFIX:
  230. framework_type = FrameworkType.TENSORFLOW.value
  231. else:
  232. framework_type = FrameworkType.UNKNOWN.value
  233. return framework_type
  234. def reset_init_or_construct(template, variable_slot, new_data, scope):
  235. """Reset init statement."""
  236. template[variable_slot][scope].clear()
  237. template[variable_slot][scope] += new_data
  238. return template
  239. def replace_string_in_list(str_list: list, original_str: str, target_str: str):
  240. """
  241. Replace a string in a list by provided string.
  242. Args:
  243. str_list (list): A list contains the string to be replaced.
  244. original_str (str): The string to be replaced.
  245. target_str (str): The replacement of string.
  246. Returns,
  247. list, the original list with replaced string.
  248. """
  249. return [s.replace(original_str, target_str) for s in str_list]
  250. def get_third_part_lib_validation_error_info(lib_list):
  251. """Get error info when not satisfying third part lib validation."""
  252. error_info = None
  253. link_str = ', '
  254. for idx, lib in enumerate(lib_list):
  255. if idx == len(lib_list) - 1:
  256. link_str = ' and '
  257. lib_version_required = THIRD_PART_VERSION[lib]
  258. if len(lib_version_required) == 2:
  259. lib_version_required_min = lib_version_required[0]
  260. lib_version_required_max = lib_version_required[1]
  261. if lib_version_required_min == lib_version_required_max:
  262. info = f"{lib}(=={lib_version_required_min})"
  263. else:
  264. info = f"{lib}(>={lib_version_required_min} and <{lib_version_required_max})"
  265. else:
  266. info = f"{lib}(>={lib_version_required[0]})"
  267. if not error_info:
  268. error_info = info
  269. else:
  270. error_info = link_str.join((error_info, info))
  271. return error_info