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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. # Copyright 2020-2021 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 abc
  17. import sys
  18. from enum import unique, Enum
  19. from importlib import import_module
  20. from lib2to3.pgen2 import parse
  21. from treelib.exceptions import DuplicatedNodeIdError, MultipleRootError, NodeIDAbsentError
  22. from mindinsight.mindconverter.common.log import logger as log, logger_console as log_console
  23. from mindinsight.utils.constant import ScriptConverterErrors
  24. from mindinsight.utils.exceptions import MindInsightException
  25. @unique
  26. class ConverterErrors(ScriptConverterErrors):
  27. """Converter error codes."""
  28. SCRIPT_NOT_SUPPORT = 1
  29. NODE_TYPE_NOT_SUPPORT = 2
  30. CODE_SYNTAX_ERROR = 3
  31. BASE_CONVERTER_FAIL = 000
  32. GRAPH_INIT_FAIL = 100
  33. TREE_CREATE_FAIL = 200
  34. SOURCE_FILES_SAVE_FAIL = 300
  35. GENERATOR_FAIL = 400
  36. SUB_GRAPH_SEARCHING_FAIL = 500
  37. class ScriptNotSupport(MindInsightException):
  38. """The script can not support to process."""
  39. def __init__(self, msg):
  40. super(ScriptNotSupport, self).__init__(ConverterErrors.SCRIPT_NOT_SUPPORT,
  41. msg,
  42. http_code=400)
  43. class NodeTypeNotSupport(MindInsightException):
  44. """The astNode can not support to process."""
  45. def __init__(self, msg):
  46. super(NodeTypeNotSupport, self).__init__(ConverterErrors.NODE_TYPE_NOT_SUPPORT,
  47. msg,
  48. http_code=400)
  49. class CodeSyntaxError(MindInsightException):
  50. """The CodeSyntaxError class definition."""
  51. def __init__(self, msg):
  52. super(CodeSyntaxError, self).__init__(ConverterErrors.CODE_SYNTAX_ERROR,
  53. msg,
  54. http_code=400)
  55. class MindConverterException(Exception):
  56. """MindConverter exception."""
  57. BASE_ERROR_CODE = None # ConverterErrors.BASE_CONVERTER_FAIL.value
  58. # ERROR_CODE should be declared in child exception.
  59. ERROR_CODE = None
  60. def __init__(self, **kwargs):
  61. """Initialization of MindInsightException."""
  62. user_msg = kwargs.get('user_msg', '')
  63. if isinstance(user_msg, str):
  64. user_msg = ' '.join(user_msg.split())
  65. super(MindConverterException, self).__init__()
  66. self.user_msg = user_msg
  67. self.root_exception_error_code = None
  68. def __str__(self):
  69. return '[{}] code: {}, msg: {}'.format(self.__class__.__name__, self.error_code(), self.user_msg)
  70. def __repr__(self):
  71. return self.__str__()
  72. def error_code(self):
  73. """"
  74. Calculate error code.
  75. code compose(2bytes)
  76. error: 16bits.
  77. num = 0xFFFF & error
  78. error_cods
  79. Returns:
  80. str, Hex string representing the composed MindConverter error code.
  81. """
  82. if self.root_exception_error_code:
  83. return self.root_exception_error_code
  84. if self.BASE_ERROR_CODE is None or self.ERROR_CODE is None:
  85. raise ValueError("MindConverterException has not been initialized.")
  86. num = 0xFFFF & self.ERROR_CODE # 0xFFFF & self.error.value
  87. error_code = f"{str(self.BASE_ERROR_CODE).zfill(3)}{hex(num)[2:].zfill(4).upper()}"
  88. return error_code
  89. @classmethod
  90. @abc.abstractmethod
  91. def raise_from(cls):
  92. """Raise from below exceptions."""
  93. @classmethod
  94. def normalize_error_msg(cls, error_msg):
  95. """Normalize error msg for common python exception."""
  96. if cls.BASE_ERROR_CODE is None or cls.ERROR_CODE is None:
  97. raise ValueError("MindConverterException has not been initialized.")
  98. num = 0xFFFF & cls.ERROR_CODE # 0xFFFF & self.error.value
  99. error_code = f"{str(cls.BASE_ERROR_CODE).zfill(3)}{hex(num)[2:].zfill(4).upper()}"
  100. return f"[{cls.__name__}] code: {error_code}, msg: {error_msg}"
  101. @classmethod
  102. def uniform_catcher(cls, msg: str = ""):
  103. """Uniform exception catcher."""
  104. def decorator(func):
  105. def _f(*args, **kwargs):
  106. try:
  107. res = func(*args, **kwargs)
  108. except cls.raise_from() as e:
  109. error = cls() if not msg else cls(msg=msg)
  110. detail_info = str(e)
  111. if not isinstance(e, MindConverterException):
  112. detail_info = cls.normalize_error_msg(str(e))
  113. log.error(error)
  114. log_console.error(detail_info)
  115. log.exception(e)
  116. sys.exit(0)
  117. except ModuleNotFoundError as e:
  118. detail_info = "Error detail: Required package not found, please check the runtime environment."
  119. log_console.error(f"{str(e)}\n{detail_info}")
  120. log.exception(e)
  121. sys.exit(0)
  122. return res
  123. return _f
  124. return decorator
  125. @classmethod
  126. def check_except(cls, msg):
  127. """Check except."""
  128. def decorator(func):
  129. def _f(*args, **kwargs):
  130. try:
  131. output = func(*args, **kwargs)
  132. except cls.raise_from() as e:
  133. error = cls(msg=msg)
  134. error_code = e.error_code() if isinstance(e, MindConverterException) else None
  135. error.root_exception_error_code = error_code
  136. log.error(msg)
  137. log.exception(e)
  138. raise error
  139. except Exception as e:
  140. log.error(msg)
  141. log.exception(e)
  142. raise e
  143. return output
  144. return _f
  145. return decorator
  146. class BaseConverterError(MindConverterException):
  147. """Base converter failed."""
  148. @unique
  149. class ErrCode(Enum):
  150. """Define error code of BaseConverterError."""
  151. UNKNOWN_ERROR = 0
  152. UNKNOWN_MODEL = 1
  153. PARAM_MISSING = 2
  154. BAD_PARAM = 3
  155. BASE_ERROR_CODE = ConverterErrors.BASE_CONVERTER_FAIL.value
  156. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  157. DEFAULT_MSG = "Failed to start base converter."
  158. def __init__(self, msg=DEFAULT_MSG):
  159. super(BaseConverterError, self).__init__(user_msg=msg)
  160. @classmethod
  161. def raise_from(cls):
  162. """Raise from exceptions below."""
  163. except_source = Exception, UnknownModelError, ParamMissingError, cls
  164. return except_source
  165. class UnknownModelError(BaseConverterError):
  166. """The unknown model error."""
  167. ERROR_CODE = BaseConverterError.ErrCode.UNKNOWN_MODEL.value
  168. def __init__(self, msg):
  169. super(UnknownModelError, self).__init__(msg=msg)
  170. @classmethod
  171. def raise_from(cls):
  172. return cls
  173. class ParamMissingError(BaseConverterError):
  174. """Define cli params missing error."""
  175. ERROR_CODE = BaseConverterError.ErrCode.PARAM_MISSING.value
  176. def __init__(self, msg):
  177. super(ParamMissingError, self).__init__(msg=msg)
  178. @classmethod
  179. def raise_from(cls):
  180. return cls
  181. class BadParamError(BaseConverterError):
  182. """Define cli bad params error."""
  183. ERROR_CODE = BaseConverterError.ErrCode.BAD_PARAM.value
  184. def __init__(self, msg):
  185. super(BadParamError, self).__init__(msg=msg)
  186. @classmethod
  187. def raise_from(cls):
  188. return cls
  189. class GraphInitError(MindConverterException):
  190. """The graph init fail error."""
  191. @unique
  192. class ErrCode(Enum):
  193. """Define error code of GraphInitError."""
  194. UNKNOWN_ERROR = 0
  195. MODEL_LOADING_ERROR = 1
  196. TF_RUNTIME_ERROR = 2
  197. MI_RUNTIME_ERROR = 3
  198. BASE_ERROR_CODE = ConverterErrors.GRAPH_INIT_FAIL.value
  199. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  200. DEFAULT_MSG = "Error occurred when init graph object."
  201. def __init__(self, msg=DEFAULT_MSG):
  202. super(GraphInitError, self).__init__(user_msg=msg)
  203. @classmethod
  204. def raise_from(cls):
  205. """Raise from exceptions below."""
  206. except_source = (FileNotFoundError,
  207. ModuleNotFoundError,
  208. ModelLoadingError,
  209. RuntimeIntegrityError,
  210. TypeError,
  211. ZeroDivisionError,
  212. RuntimeError,
  213. cls)
  214. return except_source
  215. class TreeCreationError(MindConverterException):
  216. """The tree create fail."""
  217. @unique
  218. class ErrCode(Enum):
  219. """Define error code of TreeCreationError."""
  220. UNKNOWN_ERROR = 0
  221. NODE_INPUT_MISSING = 1
  222. TREE_NODE_INSERT_FAIL = 2
  223. BASE_ERROR_CODE = ConverterErrors.TREE_CREATE_FAIL.value
  224. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  225. DEFAULT_MSG = "Error occurred when create hierarchical tree."
  226. def __init__(self, msg=DEFAULT_MSG):
  227. super(TreeCreationError, self).__init__(user_msg=msg)
  228. @classmethod
  229. def raise_from(cls):
  230. """Raise from exceptions below."""
  231. except_source = NodeInputMissingError, TreeNodeInsertError, cls
  232. return except_source
  233. class SourceFilesSaveError(MindConverterException):
  234. """The source files save fail error."""
  235. @unique
  236. class ErrCode(Enum):
  237. """Define error code of SourceFilesSaveError."""
  238. UNKNOWN_ERROR = 0
  239. NODE_INPUT_TYPE_NOT_SUPPORT = 1
  240. SCRIPT_GENERATE_FAIL = 2
  241. REPORT_GENERATE_FAIL = 3
  242. CKPT_GENERATE_FAIL = 4
  243. MAP_GENERATE_FAIL = 5
  244. BASE_ERROR_CODE = ConverterErrors.SOURCE_FILES_SAVE_FAIL.value
  245. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  246. DEFAULT_MSG = "Error occurred when save source files."
  247. def __init__(self, msg=DEFAULT_MSG):
  248. super(SourceFilesSaveError, self).__init__(user_msg=msg)
  249. @classmethod
  250. def raise_from(cls):
  251. """Raise from exceptions below."""
  252. except_source = (NodeInputTypeNotSupportError,
  253. ScriptGenerationError,
  254. ReportGenerationError,
  255. CheckPointGenerationError,
  256. WeightMapGenerationError,
  257. IOError, cls)
  258. return except_source
  259. class ModelLoadingError(GraphInitError):
  260. """The model not support error."""
  261. ERROR_CODE = GraphInitError.ErrCode.MODEL_LOADING_ERROR.value
  262. def __init__(self, msg):
  263. super(ModelLoadingError, self).__init__(msg=msg)
  264. @classmethod
  265. def raise_from(cls):
  266. """Raise from exceptions below."""
  267. onnxruntime_error = getattr(import_module('onnxruntime.capi'), 'onnxruntime_pybind11_state')
  268. except_source = (RuntimeError,
  269. ModuleNotFoundError,
  270. ValueError,
  271. AssertionError,
  272. TypeError,
  273. OSError,
  274. ZeroDivisionError,
  275. onnxruntime_error.Fail,
  276. onnxruntime_error.InvalidArgument,
  277. onnxruntime_error.NoSuchFile,
  278. onnxruntime_error.NoModel,
  279. onnxruntime_error.EngineError,
  280. onnxruntime_error.RuntimeException,
  281. onnxruntime_error.InvalidProtobuf,
  282. onnxruntime_error.ModelLoaded,
  283. onnxruntime_error.NotImplemented,
  284. onnxruntime_error.InvalidGraph,
  285. onnxruntime_error.EPFail,
  286. cls)
  287. return except_source
  288. class TfRuntimeError(GraphInitError):
  289. """Catch tf runtime error."""
  290. ERROR_CODE = GraphInitError.ErrCode.TF_RUNTIME_ERROR.value
  291. DEFAULT_MSG = "Error occurred when init graph, TensorFlow runtime error."
  292. def __init__(self, msg=DEFAULT_MSG):
  293. super(TfRuntimeError, self).__init__(msg=msg)
  294. @classmethod
  295. def raise_from(cls):
  296. tf_error_module = import_module('tensorflow.python.framework.errors_impl')
  297. tf_error = getattr(tf_error_module, 'OpError')
  298. return tf_error, ValueError, RuntimeError, cls
  299. class RuntimeIntegrityError(GraphInitError):
  300. """Catch runtime error."""
  301. ERROR_CODE = GraphInitError.ErrCode.MI_RUNTIME_ERROR.value
  302. def __init__(self, msg):
  303. super(RuntimeIntegrityError, self).__init__(msg=msg)
  304. @classmethod
  305. def raise_from(cls):
  306. return RuntimeError, AttributeError, ImportError, ModuleNotFoundError, cls
  307. class NodeInputMissingError(TreeCreationError):
  308. """The node input missing error."""
  309. ERROR_CODE = TreeCreationError.ErrCode.NODE_INPUT_MISSING.value
  310. def __init__(self, msg):
  311. super(NodeInputMissingError, self).__init__(msg=msg)
  312. @classmethod
  313. def raise_from(cls):
  314. return ValueError, IndexError, KeyError, AttributeError, cls
  315. class TreeNodeInsertError(TreeCreationError):
  316. """The tree node create fail error."""
  317. ERROR_CODE = TreeCreationError.ErrCode.TREE_NODE_INSERT_FAIL.value
  318. def __init__(self, msg):
  319. super(TreeNodeInsertError, self).__init__(msg=msg)
  320. @classmethod
  321. def raise_from(cls):
  322. """Raise from exceptions below."""
  323. except_source = (OSError,
  324. DuplicatedNodeIdError,
  325. MultipleRootError,
  326. NodeIDAbsentError, cls)
  327. return except_source
  328. class NodeInputTypeNotSupportError(SourceFilesSaveError):
  329. """The node input type NOT support error."""
  330. ERROR_CODE = SourceFilesSaveError.ErrCode.NODE_INPUT_TYPE_NOT_SUPPORT.value
  331. def __init__(self, msg):
  332. super(NodeInputTypeNotSupportError, self).__init__(msg=msg)
  333. @classmethod
  334. def raise_from(cls):
  335. return ValueError, TypeError, IndexError, cls
  336. class ScriptGenerationError(SourceFilesSaveError):
  337. """The script generate fail error."""
  338. ERROR_CODE = SourceFilesSaveError.ErrCode.SCRIPT_GENERATE_FAIL.value
  339. def __init__(self, msg):
  340. super(ScriptGenerationError, self).__init__(msg=msg)
  341. @classmethod
  342. def raise_from(cls):
  343. """Raise from exceptions below."""
  344. except_source = (RuntimeError,
  345. parse.ParseError,
  346. AttributeError, cls)
  347. return except_source
  348. class ReportGenerationError(SourceFilesSaveError):
  349. """The report generate fail error."""
  350. ERROR_CODE = SourceFilesSaveError.ErrCode.REPORT_GENERATE_FAIL.value
  351. def __init__(self, msg):
  352. super(ReportGenerationError, self).__init__(msg=msg)
  353. @classmethod
  354. def raise_from(cls):
  355. """Raise from exceptions below."""
  356. return ZeroDivisionError, cls
  357. class CheckPointGenerationError(SourceFilesSaveError):
  358. """The checkpoint generate fail error."""
  359. ERROR_CODE = SourceFilesSaveError.ErrCode.CKPT_GENERATE_FAIL.value
  360. def __init__(self, msg):
  361. super(CheckPointGenerationError, self).__init__(msg=msg)
  362. @classmethod
  363. def raise_from(cls):
  364. """Raise from exceptions below."""
  365. return cls
  366. class WeightMapGenerationError(SourceFilesSaveError):
  367. """The weight names map generate fail error."""
  368. ERROR_CODE = SourceFilesSaveError.ErrCode.MAP_GENERATE_FAIL.value
  369. def __init__(self, msg):
  370. super(WeightMapGenerationError, self).__init__(msg=msg)
  371. @classmethod
  372. def raise_from(cls):
  373. """Raise from exception below."""
  374. return cls
  375. class SubGraphSearchingError(MindConverterException):
  376. """Sub-graph searching exception."""
  377. @unique
  378. class ErrCode(Enum):
  379. """Define error code of SourceFilesSaveError."""
  380. BASE_ERROR = 0
  381. CANNOT_FIND_VALID_PATTERN = 1
  382. MODEL_NOT_SUPPORT = 2
  383. BASE_ERROR_CODE = ConverterErrors.SUB_GRAPH_SEARCHING_FAIL.value
  384. ERROR_CODE = ErrCode.BASE_ERROR.value
  385. DEFAULT_MSG = "Sub-Graph pattern searching fail."
  386. def __init__(self, msg=DEFAULT_MSG):
  387. super(SubGraphSearchingError, self).__init__(user_msg=msg)
  388. @classmethod
  389. def raise_from(cls):
  390. """Define exception in sub-graph searching module."""
  391. return IndexError, KeyError, ValueError, AttributeError, ZeroDivisionError, cls
  392. class GeneratorError(MindConverterException):
  393. """The Generator fail error."""
  394. @unique
  395. class ErrCode(Enum):
  396. """Define error code of SourceFilesSaveError."""
  397. BASE_ERROR = 0
  398. STATEMENT_GENERATION_ERROR = 1
  399. CONVERTED_OPERATOR_LOADING_ERROR = 2
  400. BASE_ERROR_CODE = ConverterErrors.GENERATOR_FAIL.value
  401. ERROR_CODE = ErrCode.BASE_ERROR.value
  402. DEFAULT_MSG = "Error occurred when generate code."
  403. def __init__(self, msg=DEFAULT_MSG):
  404. super(GeneratorError, self).__init__(user_msg=msg)
  405. @classmethod
  406. def raise_from(cls):
  407. """Raise from exceptions below."""
  408. except_source = (ValueError, TypeError, SyntaxError, cls)
  409. return except_source