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

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