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.

exceptions.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  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. """Define custom exception."""
  16. import sys
  17. from enum import unique
  18. from importlib import import_module
  19. from lib2to3.pgen2 import parse
  20. from treelib.exceptions import DuplicatedNodeIdError, MultipleRootError, NodeIDAbsentError
  21. from mindinsight.mindconverter.common.log import logger as log, logger_console as log_console
  22. from mindinsight.utils.constant import ScriptConverterErrors
  23. from mindinsight.utils.exceptions import MindInsightException, ParamMissError
  24. @unique
  25. class ConverterErrors(ScriptConverterErrors):
  26. """Converter error codes."""
  27. SCRIPT_NOT_SUPPORT = 1
  28. NODE_TYPE_NOT_SUPPORT = 2
  29. CODE_SYNTAX_ERROR = 3
  30. NODE_INPUT_TYPE_NOT_SUPPORT = 4
  31. NODE_INPUT_MISSING = 5
  32. TREE_NODE_INSERT_FAIL = 6
  33. UNKNOWN_MODEL = 7
  34. MODEL_NOT_SUPPORT = 8
  35. SCRIPT_GENERATE_FAIL = 9
  36. REPORT_GENERATE_FAIL = 10
  37. BASE_CONVERTER_FAIL = 000
  38. GRAPH_INIT_FAIL = 100
  39. TREE_CREATE_FAIL = 200
  40. SOURCE_FILES_SAVE_FAIL = 300
  41. class ScriptNotSupport(MindInsightException):
  42. """The script can not support to process."""
  43. def __init__(self, msg):
  44. super(ScriptNotSupport, self).__init__(ConverterErrors.SCRIPT_NOT_SUPPORT,
  45. msg,
  46. http_code=400)
  47. class NodeTypeNotSupport(MindInsightException):
  48. """The astNode can not support to process."""
  49. def __init__(self, msg):
  50. super(NodeTypeNotSupport, self).__init__(ConverterErrors.NODE_TYPE_NOT_SUPPORT,
  51. msg,
  52. http_code=400)
  53. class CodeSyntaxError(MindInsightException):
  54. """The CodeSyntaxError class definition."""
  55. def __init__(self, msg):
  56. super(CodeSyntaxError, self).__init__(ConverterErrors.CODE_SYNTAX_ERROR,
  57. msg,
  58. http_code=400)
  59. class MindConverterException(Exception):
  60. """MindConverter exception."""
  61. def __init__(self, **kwargs):
  62. """Initialization of MindInsightException."""
  63. error = kwargs.get('error', None)
  64. user_msg = kwargs.get('user_msg', '')
  65. debug_msg = kwargs.get('debug_msg', '')
  66. cls_code = kwargs.get('cls_code', 0)
  67. if isinstance(user_msg, str):
  68. user_msg = ' '.join(user_msg.split())
  69. super(MindConverterException, self).__init__()
  70. self.error = error
  71. self.user_msg = user_msg
  72. self.debug_msg = debug_msg
  73. self.cls_code = cls_code
  74. def __str__(self):
  75. return '[{}] code: {}, msg: {}'.format(self.__class__.__name__, self.error_code(), self.user_msg)
  76. def error_code(self):
  77. """"
  78. Calculate error code.
  79. code compose(2bytes)
  80. error: 16bits.
  81. num = 0xFFFF & error
  82. error_cods
  83. Returns:
  84. str, Hex string representing the composed MindConverter error code.
  85. """
  86. num = 0xFFFF & self.error.value
  87. error_code = ''.join((f'{self.cls_code}'.zfill(3), hex(num)[2:].zfill(4).upper()))
  88. return error_code
  89. @staticmethod
  90. def raise_from():
  91. """Raise from below exceptions."""
  92. return None
  93. @classmethod
  94. def check_except_with_print_pytorch(cls, msg):
  95. """Check except in pytorch."""
  96. def decorator(func):
  97. def _f(graph_path, sample_shape, output_folder, report_folder):
  98. try:
  99. func(graph_path=graph_path, sample_shape=sample_shape,
  100. output_folder=output_folder, report_folder=report_folder)
  101. except cls.raise_from() as e:
  102. error = cls(msg=msg)
  103. detail_info = f"Error detail: {str(e)}"
  104. log_console.error(str(error))
  105. log_console.error(detail_info)
  106. log.exception(e)
  107. sys.exit(-1)
  108. return _f
  109. return decorator
  110. @classmethod
  111. def check_except_with_print_tf(cls, msg):
  112. """Check except in tf."""
  113. def decorator(func):
  114. def _f(graph_path, sample_shape,
  115. input_nodes, output_nodes,
  116. output_folder, report_folder):
  117. try:
  118. func(graph_path=graph_path, sample_shape=sample_shape,
  119. input_nodes=input_nodes, output_nodes=output_nodes,
  120. output_folder=output_folder, report_folder=report_folder)
  121. except cls.raise_from() as e:
  122. error = cls(msg=msg)
  123. detail_info = f"Error detail: {str(e)}"
  124. log_console.error(str(error))
  125. log_console.error(detail_info)
  126. log.exception(e)
  127. sys.exit(-1)
  128. return _f
  129. return decorator
  130. class BaseConverterFail(MindConverterException):
  131. """Base converter failed."""
  132. def __init__(self, msg):
  133. super(BaseConverterFail, self).__init__(error=ConverterErrors.BASE_CONVERTER_FAIL,
  134. user_msg=msg)
  135. @staticmethod
  136. def raise_from():
  137. """Raise from exceptions below."""
  138. except_source = (UnknownModel,
  139. ParamMissError)
  140. return except_source
  141. @classmethod
  142. def check_except(cls, msg):
  143. """Check except."""
  144. def decorator(func):
  145. def _f(file_config):
  146. try:
  147. func(file_config=file_config)
  148. except cls.raise_from() as e:
  149. error = cls(msg=msg)
  150. detail_info = f"Error detail: {str(e)}"
  151. log_console.error(str(error))
  152. log_console.error(detail_info)
  153. log.exception(e)
  154. sys.exit(-1)
  155. return _f
  156. return decorator
  157. class UnknownModel(MindConverterException):
  158. """The unknown model error."""
  159. def __init__(self, msg):
  160. super(UnknownModel, self).__init__(error=ConverterErrors.UNKNOWN_MODEL,
  161. user_msg=msg)
  162. class GraphInitFail(MindConverterException):
  163. """The graph init fail error."""
  164. def __init__(self, **kwargs):
  165. super(GraphInitFail, self).__init__(error=ConverterErrors.GRAPH_INIT_FAIL,
  166. user_msg=kwargs.get('msg', ''))
  167. @staticmethod
  168. def raise_from():
  169. """Raise from exceptions below."""
  170. except_source = (FileNotFoundError,
  171. ModuleNotFoundError,
  172. ModelNotSupport,
  173. TypeError,
  174. ZeroDivisionError,
  175. RuntimeError)
  176. return except_source
  177. @classmethod
  178. def check_except_pytorch(cls, msg):
  179. """Check except for pytorch."""
  180. return super().check_except_with_print_pytorch(msg)
  181. @classmethod
  182. def check_except_tf(cls, msg):
  183. """Check except for tf."""
  184. return super().check_except_with_print_tf(msg)
  185. class TreeCreateFail(MindConverterException):
  186. """The tree create fail."""
  187. def __init__(self, msg):
  188. super(TreeCreateFail, self).__init__(error=ConverterErrors.TREE_CREATE_FAIL,
  189. user_msg=msg)
  190. @staticmethod
  191. def raise_from():
  192. """Raise from exceptions below."""
  193. except_source = (NodeInputMissing,
  194. TreeNodeInsertFail)
  195. return except_source
  196. @classmethod
  197. def check_except_pytorch(cls, msg):
  198. """Check except."""
  199. return super().check_except_with_print_pytorch(msg)
  200. @classmethod
  201. def check_except_tf(cls, msg):
  202. """Check except for tf."""
  203. return super().check_except_with_print_tf(msg)
  204. class SourceFilesSaveFail(MindConverterException):
  205. """The source files save fail error."""
  206. def __init__(self, msg):
  207. super(SourceFilesSaveFail, self).__init__(error=ConverterErrors.SOURCE_FILES_SAVE_FAIL,
  208. user_msg=msg)
  209. @staticmethod
  210. def raise_from():
  211. """Raise from exceptions below."""
  212. except_source = (NodeInputTypeNotSupport,
  213. ScriptGenerateFail,
  214. ReportGenerateFail,
  215. IOError)
  216. return except_source
  217. @classmethod
  218. def check_except_pytorch(cls, msg):
  219. """Check except."""
  220. return super().check_except_with_print_pytorch(msg)
  221. @classmethod
  222. def check_except_tf(cls, msg):
  223. """Check except for tf."""
  224. return super().check_except_with_print_tf(msg)
  225. class ModelNotSupport(MindConverterException):
  226. """The model not support error."""
  227. def __init__(self, msg):
  228. super(ModelNotSupport, self).__init__(error=ConverterErrors.MODEL_NOT_SUPPORT,
  229. user_msg=msg,
  230. cls_code=ConverterErrors.GRAPH_INIT_FAIL.value)
  231. @staticmethod
  232. def raise_from():
  233. """Raise from exceptions below."""
  234. except_source = (RuntimeError,
  235. ValueError,
  236. TypeError,
  237. OSError,
  238. ZeroDivisionError)
  239. return except_source
  240. @classmethod
  241. def check_except_pytorch(cls, msg):
  242. """Check except."""
  243. def decorator(func):
  244. def _f(arch, model_path, **kwargs):
  245. try:
  246. output = func(arch, model_path=model_path, **kwargs)
  247. except cls.raise_from() as e:
  248. error = cls(msg=msg)
  249. log.error(msg)
  250. log.exception(e)
  251. raise error from e
  252. return output
  253. return _f
  254. return decorator
  255. @classmethod
  256. def check_except_tf(cls, msg):
  257. """Check except."""
  258. tf_error_module = import_module('tensorflow.python.framework.errors_impl')
  259. tf_error = getattr(tf_error_module, 'OpError')
  260. cls._error = cls.raise_from() + (tf_error,)
  261. def decorator(func):
  262. def _f(arch, model_path, **kwargs):
  263. try:
  264. output = func(arch, model_path=model_path, **kwargs)
  265. except cls._error as e:
  266. error = cls(msg=msg)
  267. log.error(msg)
  268. log.exception(e)
  269. raise error from e
  270. return output
  271. return _f
  272. return decorator
  273. class NodeInputMissing(MindConverterException):
  274. """The node input missing error."""
  275. def __init__(self, msg):
  276. super(NodeInputMissing, self).__init__(error=ConverterErrors.NODE_INPUT_MISSING,
  277. user_msg=msg,
  278. cls_code=ConverterErrors.TREE_CREATE_FAIL.value)
  279. class TreeNodeInsertFail(MindConverterException):
  280. """The tree node create fail error."""
  281. def __init__(self, msg):
  282. super(TreeNodeInsertFail, self).__init__(error=ConverterErrors.TREE_NODE_INSERT_FAIL,
  283. user_msg=msg,
  284. cls_code=ConverterErrors.TREE_CREATE_FAIL.value)
  285. @staticmethod
  286. def raise_from():
  287. """Raise from exceptions below."""
  288. except_source = (OSError,
  289. DuplicatedNodeIdError,
  290. MultipleRootError,
  291. NodeIDAbsentError)
  292. return except_source
  293. @classmethod
  294. def check_except(cls, msg):
  295. """Check except."""
  296. def decorator(func):
  297. def _f(arch, graph):
  298. try:
  299. output = func(arch, graph=graph)
  300. except cls.raise_from() as e:
  301. error = cls(msg=msg)
  302. log.error(msg)
  303. log.exception(e)
  304. raise error from e
  305. return output
  306. return _f
  307. return decorator
  308. class NodeInputTypeNotSupport(MindConverterException):
  309. """The node input type NOT support error."""
  310. def __init__(self, msg):
  311. super(NodeInputTypeNotSupport, self).__init__(error=ConverterErrors.NODE_INPUT_TYPE_NOT_SUPPORT,
  312. user_msg=msg,
  313. cls_code=ConverterErrors.SOURCE_FILES_SAVE_FAIL.value)
  314. class ScriptGenerateFail(MindConverterException):
  315. """The script generate fail error."""
  316. def __init__(self, msg):
  317. super(ScriptGenerateFail, self).__init__(error=ConverterErrors.SCRIPT_GENERATE_FAIL,
  318. user_msg=msg,
  319. cls_code=ConverterErrors.SOURCE_FILES_SAVE_FAIL.value)
  320. @staticmethod
  321. def raise_from():
  322. """Raise from exceptions below."""
  323. except_source = (RuntimeError,
  324. parse.ParseError,
  325. AttributeError)
  326. return except_source
  327. @classmethod
  328. def check_except(cls, msg):
  329. """Check except."""
  330. def decorator(func):
  331. def _f(arch, mapper):
  332. try:
  333. output = func(arch, mapper=mapper)
  334. except cls.raise_from() as e:
  335. error = cls(msg=msg)
  336. log.error(msg)
  337. log.exception(e)
  338. raise error from e
  339. return output
  340. return _f
  341. return decorator
  342. class ReportGenerateFail(MindConverterException):
  343. """The report generate fail error."""
  344. def __init__(self, msg):
  345. super(ReportGenerateFail, self).__init__(error=ConverterErrors.REPORT_GENERATE_FAIL,
  346. user_msg=msg,
  347. cls_code=ConverterErrors.SOURCE_FILES_SAVE_FAIL.value)
  348. @staticmethod
  349. def raise_from():
  350. """Raise from exceptions below."""
  351. except_source = ZeroDivisionError
  352. return except_source
  353. @classmethod
  354. def check_except(cls, msg):
  355. """Check except."""
  356. def decorator(func):
  357. def _f(arch, mapper):
  358. try:
  359. output = func(arch, mapper=mapper)
  360. except cls.raise_from() as e:
  361. error = cls(msg=msg)
  362. log.error(msg)
  363. log.exception(e)
  364. raise error from e
  365. return output
  366. return _f
  367. return decorator