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

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