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

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