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.

framework.py 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. # Copyright 2020 Huawei Technologies Co., Ltd.All Rights Reserved.
  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. """Graph based scripts converter workflow."""
  16. import os
  17. import re
  18. import argparse
  19. from importlib import import_module
  20. from importlib.util import find_spec
  21. import mindinsight
  22. from mindinsight.mindconverter.graph_based_converter.common.utils import lib_version_satisfied
  23. from mindinsight.mindconverter.graph_based_converter.constant import BINARY_HEADER_PYTORCH_FILE, FrameworkType, \
  24. BINARY_HEADER_PYTORCH_BITS, ONNX_MIN_VER, TF2ONNX_MIN_VER, ONNXRUNTIME_MIN_VER
  25. from mindinsight.mindconverter.graph_based_converter.mapper import ONNXToMindSporeMapper
  26. from mindinsight.mindconverter.common.log import logger as log
  27. from mindinsight.mindconverter.common.exceptions import GraphInitFail, TreeCreateFail, SourceFilesSaveFail, \
  28. BaseConverterFail, UnknownModel
  29. from mindinsight.utils.exceptions import ParamMissError
  30. permissions = os.R_OK | os.W_OK | os.X_OK
  31. os.umask(permissions << 3 | permissions)
  32. parser = argparse.ArgumentParser(
  33. prog="MindConverter",
  34. description="Graph based MindConverter CLI entry point (version: {})".format(
  35. mindinsight.__version__)
  36. )
  37. parser.add_argument("--graph", type=str, required=True,
  38. help="Third party framework's graph path.")
  39. parser.add_argument("--sample_shape", nargs='+', type=int, required=True,
  40. help="Input shape of the model.")
  41. parser.add_argument("--ckpt", type=str, required=False,
  42. help="Third party framework's checkpoint path.")
  43. parser.add_argument("--output", type=str, required=True,
  44. help="Generated scripts output folder path.")
  45. parser.add_argument("--report", type=str, required=False,
  46. help="Generated reports output folder path.")
  47. def torch_installation_validation(func):
  48. """
  49. Validate args of func.
  50. Args:
  51. func (type): Function.
  52. Returns:
  53. type, inner function.
  54. """
  55. def _f(graph_path: str, sample_shape: tuple,
  56. output_folder: str, report_folder: str = None):
  57. # Check whether pytorch is installed.
  58. if not find_spec("torch"):
  59. error = ModuleNotFoundError("PyTorch is required when using graph based "
  60. "scripts converter, and PyTorch vision must "
  61. "be consisted with model generation runtime.")
  62. log.error(str(error))
  63. log.exception(error)
  64. raise error
  65. func(graph_path=graph_path, sample_shape=sample_shape,
  66. output_folder=output_folder, report_folder=report_folder)
  67. return _f
  68. def tf_installation_validation(func):
  69. """
  70. Validate args of func.
  71. Args:
  72. func(type): Function.
  73. Returns:
  74. type, inner function.
  75. """
  76. def _f(graph_path: str, sample_shape: tuple,
  77. output_folder: str, report_folder: str = None,
  78. input_nodes: str = None, output_nodes: str = None):
  79. # Check whether tensorflow is installed.
  80. if not find_spec("tensorflow") or not find_spec("tf2onnx") or not find_spec("onnx") \
  81. or not find_spec("onnxruntime"):
  82. error = ModuleNotFoundError(
  83. f"TensorFlow, tf2onnx(>={TF2ONNX_MIN_VER}), onnx(>={ONNX_MIN_VER}) and "
  84. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) are required when using graph "
  85. f"based scripts converter for TensorFlow conversion."
  86. )
  87. log.error(str(error))
  88. raise error
  89. onnx, tf2onnx = import_module("onnx"), import_module("tf2onnx")
  90. ort = import_module("onnxruntime")
  91. if not lib_version_satisfied(getattr(onnx, "__version__"), ONNX_MIN_VER) \
  92. or not lib_version_satisfied(getattr(ort, "__version__"), ONNXRUNTIME_MIN_VER) \
  93. or not lib_version_satisfied(getattr(tf2onnx, "__version__"), TF2ONNX_MIN_VER):
  94. error = ModuleNotFoundError(
  95. f"TensorFlow, tf2onnx(>={TF2ONNX_MIN_VER}), onnx(>={ONNX_MIN_VER}) and "
  96. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) are required when using graph "
  97. f"based scripts converter for TensorFlow conversion."
  98. )
  99. log.error(str(error))
  100. raise error
  101. func(graph_path=graph_path, sample_shape=sample_shape,
  102. output_folder=output_folder, report_folder=report_folder,
  103. input_nodes=input_nodes, output_nodes=output_nodes)
  104. return _f
  105. def _extract_model_name(model_path):
  106. """
  107. Extract model name from model path.
  108. Args:
  109. model_path(str): Path of Converted model.
  110. Returns:
  111. str: Name of Converted model.
  112. """
  113. model_name = re.findall(r".*[/](.*)(?:\.pth|\.pb)", model_path)[-1]
  114. return model_name
  115. @torch_installation_validation
  116. @GraphInitFail.check_except_pytorch("Error occurred when init graph object.")
  117. @TreeCreateFail.check_except_pytorch("Error occurred when create hierarchical tree.")
  118. @SourceFilesSaveFail.check_except_pytorch("Error occurred when save source files.")
  119. def graph_based_converter_pytorch_to_ms(graph_path: str, sample_shape: tuple,
  120. output_folder: str, report_folder: str = None):
  121. """
  122. Pytoch to MindSpore based on Graph.
  123. Args:
  124. graph_path (str): Graph file path.
  125. sample_shape (tuple): Input shape of the model.
  126. output_folder (str): Output folder.
  127. report_folder (str): Report output folder path.
  128. """
  129. third_party_graph_module = import_module(
  130. 'mindinsight.mindconverter.graph_based_converter.third_party_graph')
  131. hierarchical_tree_module = import_module(
  132. 'mindinsight.mindconverter.graph_based_converter.hierarchical_tree')
  133. cls_graph_factory = getattr(third_party_graph_module, 'GraphFactory')
  134. cls_hierarchical_tree_factory = getattr(hierarchical_tree_module, 'HierarchicalTreeFactory')
  135. graph_obj = cls_graph_factory.init(graph_path, sample_shape=sample_shape)
  136. hierarchical_tree = cls_hierarchical_tree_factory.create(graph_obj)
  137. model_name = _extract_model_name(graph_path)
  138. hierarchical_tree.save_source_files(output_folder, mapper=ONNXToMindSporeMapper,
  139. model_name=model_name,
  140. report_folder=report_folder)
  141. @tf_installation_validation
  142. @GraphInitFail.check_except_tf("Error occurred when init graph object.")
  143. @TreeCreateFail.check_except_tf("Error occurred when create hierarchical tree.")
  144. @SourceFilesSaveFail.check_except_tf("Error occurred when save source files.")
  145. def graph_based_converter_tf_to_ms(graph_path: str, sample_shape: tuple,
  146. input_nodes: str, output_nodes: str,
  147. output_folder: str, report_folder: str = None):
  148. """
  149. Tensorflow to MindSpore based on Graph.
  150. Args:
  151. graph_path(str): Graph file path.
  152. sample_shape(tuple): Input shape of the model.
  153. input_nodes(str): Input node(s) of the model.
  154. output_nodes(str): Output node(s) of the model.
  155. output_folder(str): Output folder.
  156. report_folder(str): Report output folder path.
  157. """
  158. third_party_graph_module = import_module(
  159. 'mindinsight.mindconverter.graph_based_converter.third_party_graph')
  160. hierarchical_tree_module = import_module(
  161. 'mindinsight.mindconverter.graph_based_converter.hierarchical_tree')
  162. cls_graph_factory = getattr(third_party_graph_module, 'GraphFactory')
  163. cls_hierarchical_tree_factory = getattr(hierarchical_tree_module, 'HierarchicalTreeFactory')
  164. # Close unnecessary log.
  165. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  166. graph_obj = cls_graph_factory.init(graph_path, sample_shape=sample_shape,
  167. input_nodes=input_nodes, output_nodes=output_nodes)
  168. hierarchical_tree, scope_name_map = cls_hierarchical_tree_factory.create(graph_obj)
  169. model_name = _extract_model_name(graph_path)
  170. hierarchical_tree.save_source_files(output_folder, mapper=ONNXToMindSporeMapper,
  171. model_name=model_name,
  172. report_folder=report_folder,
  173. scope_name_map=scope_name_map)
  174. @BaseConverterFail.check_except("Failed to start base converter.")
  175. def main_graph_base_converter(file_config):
  176. """
  177. The entrance for converter, script files will be converted.
  178. Args:
  179. file_config (dict): The config of file which to convert.
  180. """
  181. graph_path = file_config['model_file']
  182. frame_type = get_framework_type(graph_path)
  183. if frame_type == FrameworkType.PYTORCH.value:
  184. graph_based_converter_pytorch_to_ms(graph_path=graph_path,
  185. sample_shape=file_config['shape'],
  186. output_folder=file_config['outfile_dir'],
  187. report_folder=file_config['report_dir'])
  188. elif frame_type == FrameworkType.TENSORFLOW.value:
  189. check_params = ['input_nodes', 'output_nodes']
  190. check_params_exist(check_params, file_config)
  191. graph_based_converter_tf_to_ms(graph_path=graph_path,
  192. sample_shape=file_config['shape'],
  193. input_nodes=file_config['input_nodes'],
  194. output_nodes=file_config['output_nodes'],
  195. output_folder=file_config['outfile_dir'],
  196. report_folder=file_config['report_dir'])
  197. else:
  198. error_msg = "Get UNSUPPORTED model."
  199. error = UnknownModel(error_msg)
  200. log.error(str(error))
  201. raise error
  202. def get_framework_type(model_path):
  203. """Get framework type."""
  204. try:
  205. with open(model_path, 'rb') as f:
  206. if f.read(BINARY_HEADER_PYTORCH_BITS) == BINARY_HEADER_PYTORCH_FILE:
  207. framework_type = FrameworkType.PYTORCH.value
  208. else:
  209. framework_type = FrameworkType.TENSORFLOW.value
  210. except IOError:
  211. error_msg = "Get UNSUPPORTED model."
  212. error = UnknownModel(error_msg)
  213. log.error(str(error))
  214. raise error
  215. return framework_type
  216. def check_params_exist(params: list, config):
  217. """Check params exist."""
  218. miss_param_list = ''
  219. for param in params:
  220. if not config.get(param) or not config[param]:
  221. miss_param_list = ', '.join((miss_param_list, param)) if miss_param_list else param
  222. if miss_param_list:
  223. error = ParamMissError(miss_param_list)
  224. log.error(str(error))
  225. raise error