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

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