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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. import sys
  20. from importlib import import_module
  21. from importlib.util import find_spec
  22. import mindinsight
  23. from mindinsight.mindconverter.graph_based_converter.common.utils import lib_version_satisfied, \
  24. save_code_file_and_report
  25. from mindinsight.mindconverter.graph_based_converter.constant import BINARY_HEADER_PYTORCH_FILE, FrameworkType, \
  26. BINARY_HEADER_PYTORCH_BITS, ONNX_MIN_VER, TF2ONNX_MIN_VER, ONNXRUNTIME_MIN_VER, TENSORFLOW_MODEL_SUFFIX
  27. from mindinsight.mindconverter.graph_based_converter.mapper import ONNXToMindSporeMapper
  28. from mindinsight.mindconverter.common.log import logger as log, logger_console as log_console
  29. from mindinsight.mindconverter.common.exceptions import GraphInitError, TreeCreationError, SourceFilesSaveError, \
  30. BaseConverterError, UnknownModelError, GeneratorError, TfRuntimeError, RuntimeIntegrityError, ParamMissingError
  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 = RuntimeIntegrityError("PyTorch is required when using graph based "
  61. "scripts converter, and PyTorch version must "
  62. "be consisted with model generation runtime.")
  63. log.error(error)
  64. log_console.error("\n")
  65. log_console.error(str(error))
  66. log_console.error("\n")
  67. sys.exit(0)
  68. func(graph_path=graph_path, sample_shape=sample_shape,
  69. output_folder=output_folder, report_folder=report_folder)
  70. return _f
  71. def _check_tf_installation():
  72. """
  73. Check whether TensorFlow was installed.
  74. Returns:
  75. bool, true or false.
  76. """
  77. return find_spec("tensorflow") or find_spec("tensorflow-gpu")
  78. def tf_installation_validation(func):
  79. """
  80. Validate args of func.
  81. Args:
  82. func(type): Function.
  83. Returns:
  84. type, inner function.
  85. """
  86. def _f(graph_path: str, sample_shape: tuple,
  87. output_folder: str, report_folder: str = None,
  88. input_nodes: str = None, output_nodes: str = None):
  89. # Check whether tensorflow is installed.
  90. if not _check_tf_installation() or not find_spec("tf2onnx") \
  91. or not find_spec("onnx") or not find_spec("onnxruntime"):
  92. error = RuntimeIntegrityError(
  93. f"TensorFlow, tf2onnx(>={TF2ONNX_MIN_VER}), onnx(>={ONNX_MIN_VER}) and "
  94. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) are required when using graph "
  95. f"based scripts converter for TensorFlow conversion."
  96. )
  97. log.error(error)
  98. log_console.error("\n")
  99. log_console.error(str(error))
  100. log_console.error("\n")
  101. sys.exit(0)
  102. onnx, tf2onnx = import_module("onnx"), import_module("tf2onnx")
  103. ort = import_module("onnxruntime")
  104. if not lib_version_satisfied(getattr(onnx, "__version__"), ONNX_MIN_VER) \
  105. or not lib_version_satisfied(getattr(ort, "__version__"), ONNXRUNTIME_MIN_VER) \
  106. or not lib_version_satisfied(getattr(tf2onnx, "__version__"), TF2ONNX_MIN_VER):
  107. error = RuntimeIntegrityError(
  108. f"TensorFlow, tf2onnx(>={TF2ONNX_MIN_VER}), onnx(>={ONNX_MIN_VER}) and "
  109. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) are required when using graph "
  110. f"based scripts converter for TensorFlow conversion."
  111. )
  112. log.error(error)
  113. log_console.error("\n")
  114. log_console.error(str(error))
  115. log_console.error("\n")
  116. sys.exit(0)
  117. func(graph_path=graph_path, sample_shape=sample_shape,
  118. output_folder=output_folder, report_folder=report_folder,
  119. input_nodes=input_nodes, output_nodes=output_nodes)
  120. return _f
  121. def _extract_model_name(model_path):
  122. """
  123. Extract model name from model path.
  124. Args:
  125. model_path(str): Path of Converted model.
  126. Returns:
  127. str: Name of Converted model.
  128. """
  129. model_name = re.findall(r".*[/](.*)(?:\.pth|\.pb)", model_path)[-1]
  130. return model_name
  131. @torch_installation_validation
  132. @GraphInitError.uniform_catcher()
  133. @TreeCreationError.uniform_catcher()
  134. @SourceFilesSaveError.uniform_catcher()
  135. @GeneratorError.uniform_catcher()
  136. def graph_based_converter_pytorch_to_ms(graph_path: str, sample_shape: tuple,
  137. output_folder: str, report_folder: str = None):
  138. """
  139. PyTorch to MindSpore based on Graph.
  140. Args:
  141. graph_path (str): Graph file path.
  142. sample_shape (tuple): Input shape of the model.
  143. output_folder (str): Output folder.
  144. report_folder (str): Report output folder path.
  145. """
  146. third_party_graph_module = import_module(
  147. 'mindinsight.mindconverter.graph_based_converter.third_party_graph')
  148. hierarchical_tree_module = import_module(
  149. 'mindinsight.mindconverter.graph_based_converter.hierarchical_tree')
  150. cls_graph_factory = getattr(third_party_graph_module, 'GraphFactory')
  151. cls_hierarchical_tree_factory = getattr(hierarchical_tree_module, 'HierarchicalTreeFactory')
  152. graph_obj = cls_graph_factory.init(graph_path, sample_shape=sample_shape)
  153. hierarchical_tree = cls_hierarchical_tree_factory.create(graph_obj)
  154. model_name = _extract_model_name(graph_path)
  155. hierarchical_tree.save_source_files(output_folder, mapper=ONNXToMindSporeMapper,
  156. model_name=model_name,
  157. report_folder=report_folder)
  158. @tf_installation_validation
  159. @GraphInitError.uniform_catcher()
  160. @TfRuntimeError.uniform_catcher()
  161. @TreeCreationError.uniform_catcher()
  162. @SourceFilesSaveError.uniform_catcher()
  163. @GeneratorError.uniform_catcher()
  164. def graph_based_converter_tf_to_ms(graph_path: str, sample_shape: tuple,
  165. input_nodes: str, output_nodes: str,
  166. output_folder: str, report_folder: str = None):
  167. """
  168. Tensorflow to MindSpore based on Graph.
  169. Args:
  170. graph_path(str): Graph file path.
  171. sample_shape(tuple): Input shape of the model.
  172. input_nodes(str): Input node(s) of the model.
  173. output_nodes(str): Output node(s) of the model.
  174. output_folder(str): Output folder.
  175. report_folder(str): Report output folder path.
  176. """
  177. third_party_graph_module = import_module(
  178. 'mindinsight.mindconverter.graph_based_converter.third_party_graph')
  179. cls_graph_factory = getattr(third_party_graph_module, 'GraphFactory')
  180. batch_add_nodes = getattr(import_module('mindinsight.mindconverter.graph_based_converter.generator'),
  181. "batch_add_nodes")
  182. # Close unnecessary log.
  183. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  184. graph_obj = cls_graph_factory.init(graph_path, sample_shape=sample_shape,
  185. input_nodes=input_nodes, output_nodes=output_nodes)
  186. generator_inst = batch_add_nodes(graph_obj, ONNXToMindSporeMapper)
  187. model_name = _extract_model_name(graph_path)
  188. code_fragments = generator_inst.generate()
  189. save_code_file_and_report(model_name, code_fragments, output_folder, report_folder)
  190. @BaseConverterError.uniform_catcher()
  191. def main_graph_base_converter(file_config):
  192. """
  193. The entrance for converter, script files will be converted.
  194. Args:
  195. file_config (dict): The config of file which to convert.
  196. """
  197. graph_path = file_config['model_file']
  198. frame_type = get_framework_type(graph_path)
  199. if not file_config.get("shape"):
  200. raise ParamMissingError("Param missing, `--shape` is required when using graph mode.")
  201. if frame_type == FrameworkType.PYTORCH.value:
  202. graph_based_converter_pytorch_to_ms(graph_path=graph_path,
  203. sample_shape=file_config['shape'],
  204. output_folder=file_config['outfile_dir'],
  205. report_folder=file_config['report_dir'])
  206. elif frame_type == FrameworkType.TENSORFLOW.value:
  207. check_params = ['input_nodes', 'output_nodes']
  208. check_params_exist(check_params, file_config)
  209. graph_based_converter_tf_to_ms(graph_path=graph_path,
  210. sample_shape=file_config['shape'],
  211. input_nodes=file_config['input_nodes'],
  212. output_nodes=file_config['output_nodes'],
  213. output_folder=file_config['outfile_dir'],
  214. report_folder=file_config['report_dir'])
  215. else:
  216. error_msg = "Get UNSUPPORTED model."
  217. error = UnknownModelError(error_msg)
  218. raise error
  219. def get_framework_type(model_path):
  220. """Get framework type."""
  221. try:
  222. with open(model_path, 'rb') as f:
  223. if f.read(BINARY_HEADER_PYTORCH_BITS) == BINARY_HEADER_PYTORCH_FILE:
  224. framework_type = FrameworkType.PYTORCH.value
  225. elif os.path.basename(model_path).split(".")[-1].lower() == TENSORFLOW_MODEL_SUFFIX:
  226. framework_type = FrameworkType.TENSORFLOW.value
  227. else:
  228. framework_type = FrameworkType.UNKNOWN.value
  229. except IOError:
  230. error_msg = "Get UNSUPPORTED model."
  231. error = UnknownModelError(error_msg)
  232. log.error(str(error))
  233. raise error
  234. return framework_type
  235. def check_params_exist(params: list, config):
  236. """Check params exist."""
  237. miss_param_list = ''
  238. for param in params:
  239. if not config.get(param) or not config[param]:
  240. miss_param_list = ', '.join((miss_param_list, param)) if miss_param_list else param
  241. if miss_param_list:
  242. raise ParamMissingError(f"Param(s) missing, {miss_param_list} is(are) required when using graph mode.")