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

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