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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # Copyright 2020-2021 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 argparse
  18. import sys
  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, get_framework_type
  24. from mindinsight.mindconverter.graph_based_converter.constant import FrameworkType, \
  25. ONNX_MIN_VER, TF2ONNX_MIN_VER, ONNXRUNTIME_MIN_VER
  26. from mindinsight.mindconverter.graph_based_converter.generator import batch_add_nodes
  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. from mindinsight.mindconverter.graph_based_converter.third_party_graph import GraphFactory
  32. permissions = os.R_OK | os.W_OK | os.X_OK
  33. os.umask(permissions << 3 | permissions)
  34. parser = argparse.ArgumentParser(
  35. prog="MindConverter",
  36. description="Graph based MindConverter CLI entry point (version: {})".format(
  37. mindinsight.__version__)
  38. )
  39. parser.add_argument("--graph", type=str, required=True,
  40. help="Third party framework's graph path.")
  41. parser.add_argument("--sample_shape", nargs='+', type=int, required=True,
  42. help="Input shape of the model.")
  43. parser.add_argument("--ckpt", type=str, required=False,
  44. help="Third party framework's checkpoint path.")
  45. parser.add_argument("--output", type=str, required=True,
  46. help="Generated scripts output folder path.")
  47. parser.add_argument("--report", type=str, required=False,
  48. help="Generated reports output folder path.")
  49. def torch_installation_validation(func):
  50. """
  51. Validate args of func.
  52. Args:
  53. func (type): Function.
  54. Returns:
  55. type, inner function.
  56. """
  57. def _f(graph_path: str, sample_shape: tuple,
  58. input_nodes: str, output_nodes: str,
  59. output_folder: str, report_folder: str = None):
  60. # Check whether pytorch is installed.
  61. if not find_spec("torch") or not find_spec("onnx") or not find_spec("onnxruntime"):
  62. error = RuntimeIntegrityError(f"PyTorch, onnx(>={ONNX_MIN_VER}) and "
  63. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) "
  64. f"are required when using graph based "
  65. f"scripts converter, and PyTorch version must "
  66. f"be consisted with model generation runtime.")
  67. log.error(error)
  68. log_console.error("\n")
  69. log_console.error(str(error))
  70. log_console.error("\n")
  71. sys.exit(0)
  72. onnx = import_module("onnx")
  73. ort = import_module("onnxruntime")
  74. if not lib_version_satisfied(getattr(onnx, "__version__"), ONNX_MIN_VER) \
  75. or not lib_version_satisfied(getattr(ort, "__version__"), ONNXRUNTIME_MIN_VER):
  76. error = RuntimeIntegrityError(
  77. f"onnx(>={ONNX_MIN_VER}) and "
  78. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) are required when using graph "
  79. f"based scripts converter for Pytorch conversion."
  80. )
  81. log.error(error)
  82. log_console.error("\n")
  83. log_console.error(str(error))
  84. log_console.error("\n")
  85. sys.exit(0)
  86. func(graph_path=graph_path, sample_shape=sample_shape,
  87. input_nodes=input_nodes, output_nodes=output_nodes,
  88. output_folder=output_folder, report_folder=report_folder)
  89. return _f
  90. def _check_tf_installation():
  91. """
  92. Check whether TensorFlow was installed.
  93. Returns:
  94. bool, true or false.
  95. """
  96. return find_spec("tensorflow") or find_spec("tensorflow-gpu")
  97. def tf_installation_validation(func):
  98. """
  99. Validate args of func.
  100. Args:
  101. func(type): Function.
  102. Returns:
  103. type, inner function.
  104. """
  105. def _f(graph_path: str, sample_shape: tuple,
  106. output_folder: str, report_folder: str = None,
  107. input_nodes: str = None, output_nodes: str = None):
  108. # Check whether tensorflow is installed.
  109. if not _check_tf_installation() or not find_spec("tf2onnx") \
  110. or not find_spec("onnx") or not find_spec("onnxruntime"):
  111. error = RuntimeIntegrityError(
  112. f"TensorFlow, tf2onnx(>={TF2ONNX_MIN_VER}), onnx(>={ONNX_MIN_VER}) and "
  113. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) are required when using graph "
  114. f"based scripts converter for TensorFlow conversion."
  115. )
  116. log.error(error)
  117. log_console.error("\n")
  118. log_console.error(str(error))
  119. log_console.error("\n")
  120. sys.exit(0)
  121. onnx, tf2onnx = import_module("onnx"), import_module("tf2onnx")
  122. ort = import_module("onnxruntime")
  123. if not lib_version_satisfied(getattr(onnx, "__version__"), ONNX_MIN_VER) \
  124. or not lib_version_satisfied(getattr(ort, "__version__"), ONNXRUNTIME_MIN_VER) \
  125. or not lib_version_satisfied(getattr(tf2onnx, "__version__"), TF2ONNX_MIN_VER):
  126. error = RuntimeIntegrityError(
  127. f"TensorFlow, tf2onnx(>={TF2ONNX_MIN_VER}), onnx(>={ONNX_MIN_VER}) and "
  128. f"onnxruntime(>={ONNXRUNTIME_MIN_VER}) are required when using graph "
  129. f"based scripts converter for TensorFlow conversion."
  130. )
  131. log.error(error)
  132. log_console.error("\n")
  133. log_console.error(str(error))
  134. log_console.error("\n")
  135. sys.exit(0)
  136. func(graph_path=graph_path, sample_shape=sample_shape,
  137. output_folder=output_folder, report_folder=report_folder,
  138. input_nodes=input_nodes, output_nodes=output_nodes)
  139. return _f
  140. def _extract_model_name(model_path):
  141. """
  142. Extract model name from model path.
  143. Args:
  144. model_path(str): Path of Converted model.
  145. Returns:
  146. str: Name of Converted model.
  147. """
  148. base_path = os.path.basename(model_path)
  149. model_name = '.'.join(base_path.split('.')[:-1])
  150. return model_name
  151. @torch_installation_validation
  152. @GraphInitError.uniform_catcher()
  153. @TreeCreationError.uniform_catcher()
  154. @SourceFilesSaveError.uniform_catcher()
  155. @GeneratorError.uniform_catcher()
  156. def graph_based_converter_pytorch_to_ms(graph_path: str, sample_shape: tuple,
  157. input_nodes: str, output_nodes: str,
  158. output_folder: str, report_folder: str = None):
  159. """
  160. PyTorch to MindSpore based on Graph.
  161. Args:
  162. graph_path (str): Graph file path.
  163. sample_shape (tuple): Input shape of the model.
  164. input_nodes (str): Input node(s) of the model.
  165. output_nodes (str): Output node(s) of the model.
  166. output_folder (str): Output folder.
  167. report_folder (str): Report output folder path.
  168. """
  169. graph_obj = GraphFactory.init(graph_path, sample_shape=sample_shape,
  170. input_nodes=input_nodes, output_nodes=output_nodes)
  171. generator_inst = batch_add_nodes(graph_obj, ONNXToMindSporeMapper)
  172. model_name = _extract_model_name(graph_path)
  173. code_fragments = generator_inst.generate()
  174. save_code_file_and_report(model_name, code_fragments, output_folder, report_folder)
  175. @tf_installation_validation
  176. @GraphInitError.uniform_catcher()
  177. @TfRuntimeError.uniform_catcher()
  178. @TreeCreationError.uniform_catcher()
  179. @SourceFilesSaveError.uniform_catcher()
  180. @GeneratorError.uniform_catcher()
  181. def graph_based_converter_tf_to_ms(graph_path: str, sample_shape: tuple,
  182. input_nodes: str, output_nodes: str,
  183. output_folder: str, report_folder: str = None):
  184. """
  185. Tensorflow to MindSpore based on Graph.
  186. Args:
  187. graph_path(str): Graph file path.
  188. sample_shape(tuple): Input shape of the model.
  189. input_nodes(str): Input node(s) of the model.
  190. output_nodes(str): Output node(s) of the model.
  191. output_folder(str): Output folder.
  192. report_folder(str): Report output folder path.
  193. """
  194. # Close unnecessary log.
  195. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  196. graph_obj = GraphFactory.init(graph_path, sample_shape=sample_shape,
  197. input_nodes=input_nodes, output_nodes=output_nodes)
  198. generator_inst = batch_add_nodes(graph_obj, ONNXToMindSporeMapper)
  199. model_name = _extract_model_name(graph_path)
  200. code_fragments = generator_inst.generate()
  201. save_code_file_and_report(model_name, code_fragments, output_folder, report_folder)
  202. @BaseConverterError.uniform_catcher()
  203. def main_graph_base_converter(file_config):
  204. """
  205. The entrance for converter, script files will be converted.
  206. Args:
  207. file_config (dict): The config of file which to convert.
  208. """
  209. graph_path = file_config['model_file']
  210. frame_type = get_framework_type(graph_path)
  211. if not file_config.get("shape"):
  212. raise ParamMissingError("Param missing, `--shape` is required when using graph mode.")
  213. if frame_type == FrameworkType.PYTORCH.value:
  214. check_params = ['input_nodes', 'output_nodes']
  215. check_params_exist(check_params, file_config)
  216. graph_based_converter_pytorch_to_ms(graph_path=graph_path,
  217. sample_shape=file_config['shape'],
  218. input_nodes=file_config['input_nodes'],
  219. output_nodes=file_config['output_nodes'],
  220. output_folder=file_config['outfile_dir'],
  221. report_folder=file_config['report_dir'])
  222. elif frame_type == FrameworkType.TENSORFLOW.value:
  223. check_params = ['input_nodes', 'output_nodes']
  224. check_params_exist(check_params, file_config)
  225. graph_based_converter_tf_to_ms(graph_path=graph_path,
  226. sample_shape=file_config['shape'],
  227. input_nodes=file_config['input_nodes'],
  228. output_nodes=file_config['output_nodes'],
  229. output_folder=file_config['outfile_dir'],
  230. report_folder=file_config['report_dir'])
  231. else:
  232. error_msg = "Get UNSUPPORTED model."
  233. error = UnknownModelError(error_msg)
  234. raise error
  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.")