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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 multiprocessing as mp
  17. import os
  18. import re
  19. import sys
  20. from importlib import import_module
  21. from importlib.util import find_spec
  22. from functools import partial
  23. from mindinsight.mindconverter.graph_based_converter.common.global_context import GlobalContext
  24. from mindinsight.mindconverter.graph_based_converter.common.utils import lib_version_satisfied, onnx_satisfied, \
  25. save_code_file_and_report, get_framework_type, check_dependency_integrity, get_third_part_lib_validation_error_info
  26. from mindinsight.mindconverter.graph_based_converter.constant import FrameworkType, \
  27. ONNX_MIN_VER, TF2ONNX_MIN_VER, ONNXRUNTIME_MIN_VER, ONNXOPTIMIZER_MIN_VER, ONNXOPTIMIZER_MAX_VER, TORCH_MIN_VER
  28. from mindinsight.mindconverter.graph_based_converter.generator import batch_add_nodes
  29. from mindinsight.mindconverter.graph_based_converter.mapper import ONNXToMindSporeMapper
  30. from mindinsight.mindconverter.common.log import logger as log, logger_console as log_console
  31. from mindinsight.mindconverter.common.exceptions import GraphInitError, TreeCreationError, SourceFilesSaveError, \
  32. BaseConverterError, UnknownModelError, GeneratorError, TfRuntimeError, RuntimeIntegrityError, ParamMissingError
  33. from mindinsight.mindconverter.graph_based_converter.third_party_graph import GraphFactory
  34. check_common_dependency_integrity = partial(check_dependency_integrity,
  35. "onnx", "onnxruntime", "onnxoptimizer")
  36. def onnx_lib_version_satisfied():
  37. """Check onnx libs version whether is satisfied."""
  38. onnx = import_module("onnx")
  39. ort = import_module("onnxruntime")
  40. optimizer = import_module("onnxoptimizer.version")
  41. if not lib_version_satisfied(getattr(ort, "__version__"), ONNXRUNTIME_MIN_VER):
  42. log_console.warning("onnxruntime's version should be greater than %s, however current version is %s.",
  43. ONNXRUNTIME_MIN_VER, ort.__version__)
  44. if not lib_version_satisfied(getattr(onnx, "__version__"), ONNX_MIN_VER) \
  45. or not lib_version_satisfied(getattr(optimizer, "version"), ONNXOPTIMIZER_MIN_VER, ONNXOPTIMIZER_MAX_VER):
  46. return False
  47. return True
  48. def _print_error(err):
  49. """Print error to stdout and record it."""
  50. log.error(err)
  51. log_console.error("\n")
  52. log_console.error(str(err))
  53. log_console.error("\n")
  54. def torch_version_satisfied(output_queue):
  55. """Check Torch version whether is satisfied."""
  56. satisfied = False
  57. pattern = r"\d+\.\d+\.\d+"
  58. torch_version = re.findall(pattern, getattr(import_module('torch'), "__version__"))
  59. if torch_version:
  60. satisfied = lib_version_satisfied(torch_version[0], TORCH_MIN_VER)
  61. output_queue.put(satisfied)
  62. def torch_installation_validation(func):
  63. """
  64. Validate args of func.
  65. Args:
  66. func (type): Function.
  67. Returns:
  68. type, inner function.
  69. """
  70. def _f(graph_path: str, sample_shape: tuple, input_nodes: str, output_nodes: str,
  71. output_folder: str, report_folder: str = None):
  72. # Check whether pytorch is installed.
  73. error_info = None
  74. torch_version_validation = False
  75. if graph_path.endswith('.onnx'):
  76. if not onnx_satisfied() or not check_common_dependency_integrity():
  77. error_info = f"{get_third_part_lib_validation_error_info(['onnx', 'onnxruntime', 'onnxoptimizer'])} " \
  78. f"are required when using graph based scripts converter."
  79. else:
  80. if not find_spec("torch") or not onnx_satisfied() or not check_common_dependency_integrity():
  81. error_info = \
  82. f"{get_third_part_lib_validation_error_info(['torch', 'onnx', 'onnxruntime', 'onnxoptimizer'])} " \
  83. f"are required when using graph based scripts converter, and PyTorch version must " \
  84. f"be consisted with model generation runtime."
  85. output_queue = mp.Queue()
  86. process = mp.Process(target=torch_version_satisfied, args=(output_queue,))
  87. process.start()
  88. torch_version_validation = output_queue.get()
  89. process.join()
  90. if error_info:
  91. _print_error(RuntimeIntegrityError(error_info))
  92. sys.exit(0)
  93. if (not torch_version_validation and not graph_path.endswith('.onnx')) or not onnx_lib_version_satisfied():
  94. lib_check_list = ['onnx', 'onnxruntime', 'onnxoptimizer']
  95. if not graph_path.endswith('.onnx'):
  96. lib_check_list.insert(0, 'torch')
  97. error = RuntimeIntegrityError(
  98. f"{get_third_part_lib_validation_error_info(lib_check_list)} "
  99. f"are required when using graph based scripts converter."
  100. )
  101. _print_error(error)
  102. sys.exit(0)
  103. func(graph_path=graph_path, sample_shape=sample_shape,
  104. input_nodes=input_nodes, output_nodes=output_nodes,
  105. output_folder=output_folder, report_folder=report_folder)
  106. return _f
  107. def _check_tf_installation():
  108. """
  109. Check whether TensorFlow was installed.
  110. Returns:
  111. bool, true or false.
  112. """
  113. return find_spec("tensorflow") or find_spec("tensorflow-gpu")
  114. def tf_installation_validation(func):
  115. """
  116. Validate args of func.
  117. Args:
  118. func(type): Function.
  119. Returns:
  120. type, inner function.
  121. """
  122. def _f(graph_path: str, sample_shape: tuple, output_folder: str, report_folder: str = None,
  123. input_nodes: str = None, output_nodes: str = None):
  124. not_integral_error = RuntimeIntegrityError(
  125. f"TensorFlow, "
  126. f"{get_third_part_lib_validation_error_info(['tf2onnx', 'onnx', 'onnxruntime', 'onnxoptimizer'])} "
  127. f"are required when using graph based scripts converter for TensorFlow conversion."
  128. )
  129. # Check whether tensorflow is installed.
  130. if not _check_tf_installation() or not onnx_satisfied():
  131. _print_error(not_integral_error)
  132. sys.exit(0)
  133. if not any([check_common_dependency_integrity("tensorflow"),
  134. check_common_dependency_integrity("tensorflow-gpu")]):
  135. _print_error(not_integral_error)
  136. sys.exit(0)
  137. tf2onnx = import_module("tf2onnx")
  138. if not lib_version_satisfied(getattr(tf2onnx, "__version__"), TF2ONNX_MIN_VER) \
  139. or not onnx_lib_version_satisfied():
  140. _print_error(not_integral_error)
  141. sys.exit(0)
  142. func(graph_path=graph_path, sample_shape=sample_shape,
  143. output_folder=output_folder, report_folder=report_folder,
  144. input_nodes=input_nodes, output_nodes=output_nodes)
  145. return _f
  146. def _extract_model_name(model_path):
  147. """
  148. Extract model name from model path.
  149. Args:
  150. model_path (str): Path of Converted model.
  151. Returns:
  152. str, name of Converted model.
  153. """
  154. base_path = os.path.basename(model_path)
  155. model_name = '.'.join(base_path.split('.')[:-1])
  156. return model_name
  157. @torch_installation_validation
  158. @GraphInitError.uniform_catcher()
  159. @TreeCreationError.uniform_catcher()
  160. @SourceFilesSaveError.uniform_catcher()
  161. @GeneratorError.uniform_catcher()
  162. def graph_based_converter_pytorch_to_ms(graph_path: str, sample_shape: tuple,
  163. input_nodes: str, output_nodes: str,
  164. output_folder: str, report_folder: str = None):
  165. """
  166. PyTorch to MindSpore based on Graph.
  167. Args:
  168. graph_path (str): Graph file path.
  169. sample_shape (tuple): Input shape of the model.
  170. input_nodes (str): Input node(s) of the model.
  171. output_nodes (str): Output node(s) of the model.
  172. output_folder (str): Output folder.
  173. report_folder (str): Report output folder path.
  174. """
  175. graph_obj = GraphFactory.init(graph_path, sample_shape=sample_shape,
  176. input_nodes=input_nodes, output_nodes=output_nodes)
  177. generator_inst = batch_add_nodes(graph_obj, ONNXToMindSporeMapper)
  178. model_name = _extract_model_name(graph_path)
  179. code_fragments = generator_inst.generate()
  180. save_code_file_and_report(model_name, code_fragments, output_folder, report_folder)
  181. # Release global context.
  182. GlobalContext.release()
  183. @tf_installation_validation
  184. @GraphInitError.uniform_catcher()
  185. @TfRuntimeError.uniform_catcher()
  186. @TreeCreationError.uniform_catcher()
  187. @SourceFilesSaveError.uniform_catcher()
  188. @GeneratorError.uniform_catcher()
  189. def graph_based_converter_tf_to_ms(graph_path: str, sample_shape: tuple,
  190. input_nodes: str, output_nodes: str,
  191. output_folder: str, report_folder: str = None):
  192. """
  193. Tensorflow to MindSpore based on Graph.
  194. Args:
  195. graph_path(str): Graph file path.
  196. sample_shape(tuple): Input shape of the model.
  197. input_nodes(str): Input node(s) of the model.
  198. output_nodes(str): Output node(s) of the model.
  199. output_folder(str): Output folder.
  200. report_folder(str): Report output folder path.
  201. """
  202. # Close unnecessary log.
  203. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  204. graph_obj = GraphFactory.init(graph_path, sample_shape=sample_shape,
  205. input_nodes=input_nodes, output_nodes=output_nodes)
  206. generator_inst = batch_add_nodes(graph_obj, ONNXToMindSporeMapper)
  207. model_name = _extract_model_name(graph_path)
  208. code_fragments = generator_inst.generate()
  209. save_code_file_and_report(model_name, code_fragments, output_folder, report_folder)
  210. # Release global context.
  211. GlobalContext.release()
  212. @BaseConverterError.uniform_catcher()
  213. def main_graph_base_converter(file_config):
  214. """
  215. The entrance for converter, script files will be converted.
  216. Args:
  217. file_config (dict): The config of file which to convert.
  218. """
  219. graph_path = file_config['model_file']
  220. frame_type = get_framework_type(graph_path)
  221. if not file_config.get("shape"):
  222. raise ParamMissingError("Param missing, `--shape` is required when using graph mode.")
  223. if frame_type == FrameworkType.PYTORCH.value:
  224. if graph_path.endswith('.onnx'):
  225. check_params = ['input_nodes', 'output_nodes']
  226. check_params_exist(check_params, file_config)
  227. graph_based_converter_pytorch_to_ms(graph_path=graph_path,
  228. sample_shape=file_config['shape'],
  229. input_nodes=file_config['input_nodes'],
  230. output_nodes=file_config['output_nodes'],
  231. output_folder=file_config['outfile_dir'],
  232. report_folder=file_config['report_dir'])
  233. else:
  234. graph_based_converter_pytorch_to_ms(graph_path=graph_path,
  235. sample_shape=file_config['shape'],
  236. input_nodes='input.1',
  237. output_nodes='',
  238. output_folder=file_config['outfile_dir'],
  239. report_folder=file_config['report_dir'])
  240. elif frame_type == FrameworkType.TENSORFLOW.value:
  241. check_params = ['input_nodes', 'output_nodes']
  242. check_params_exist(check_params, file_config)
  243. graph_based_converter_tf_to_ms(graph_path=graph_path,
  244. sample_shape=file_config['shape'],
  245. input_nodes=file_config['input_nodes'],
  246. output_nodes=file_config['output_nodes'],
  247. output_folder=file_config['outfile_dir'],
  248. report_folder=file_config['report_dir'])
  249. else:
  250. error_msg = "Get UNSUPPORTED model."
  251. error = UnknownModelError(error_msg)
  252. raise error
  253. def check_params_exist(params: list, config):
  254. """Check params exist."""
  255. miss_param_list = ''
  256. for param in params:
  257. if not config.get(param) or not config[param]:
  258. miss_param_list = ', '.join((miss_param_list, param)) if miss_param_list else param
  259. if miss_param_list:
  260. raise ParamMissingError(f"Param(s) missing, {miss_param_list} is(are) required when using graph mode.")