Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/tensorboard/compat/tensorflow_stub/errors.py: 53%

136 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-03 07:57 +0000

1# Copyright 2015 The TensorFlow Authors. 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"""Exception types for TensorFlow errors.""" 

16 

17 

18import traceback 

19import warnings 

20 

21from . import error_codes 

22 

23 

24# @tf_export("OpError", "errors.OpError") 

25class OpError(Exception): 

26 """A generic error that is raised when TensorFlow execution fails. 

27 

28 Whenever possible, the session will raise a more specific subclass 

29 of `OpError` from the `tf.errors` module. 

30 """ 

31 

32 def __init__(self, node_def, op, message, error_code): 

33 """Creates a new `OpError` indicating that a particular op failed. 

34 

35 Args: 

36 node_def: The `node_def_pb2.NodeDef` proto representing the op that 

37 failed, if known; otherwise None. 

38 op: The `ops.Operation` that failed, if known; otherwise None. 

39 message: The message string describing the failure. 

40 error_code: The `error_codes.Code` describing the error. 

41 """ 

42 super().__init__() 

43 self._message = message 

44 self._node_def = node_def 

45 self._op = op 

46 self._error_code = error_code 

47 

48 @property 

49 def message(self): 

50 """The error message that describes the error.""" 

51 return self._message 

52 

53 @property 

54 def op(self): 

55 """The operation that failed, if known. 

56 

57 *N.B.* If the failed op was synthesized at runtime, e.g. a `Send` 

58 or `Recv` op, there will be no corresponding 

59 @{tf.Operation} 

60 object. In that case, this will return `None`, and you should 

61 instead use the @{tf.OpError.node_def} to 

62 discover information about the op. 

63 

64 Returns: 

65 The `Operation` that failed, or None. 

66 """ 

67 return self._op 

68 

69 @property 

70 def error_code(self): 

71 """The integer error code that describes the error.""" 

72 return self._error_code 

73 

74 @property 

75 def node_def(self): 

76 """The `NodeDef` proto representing the op that failed.""" 

77 return self._node_def 

78 

79 def __str__(self): 

80 if self._op is not None: 

81 output = [ 

82 "%s\n\nCaused by op %r, defined at:\n" 

83 % (self.message, self._op.name) 

84 ] 

85 curr_traceback_list = traceback.format_list(self._op.traceback) 

86 output.extend(curr_traceback_list) 

87 # pylint: disable=protected-access 

88 original_op = self._op._original_op 

89 # pylint: enable=protected-access 

90 while original_op is not None: 

91 output.append( 

92 "\n...which was originally created as op %r, defined at:\n" 

93 % (original_op.name,) 

94 ) 

95 prev_traceback_list = curr_traceback_list 

96 curr_traceback_list = traceback.format_list( 

97 original_op.traceback 

98 ) 

99 

100 # Attempt to elide large common subsequences of the subsequent 

101 # stack traces. 

102 # 

103 # TODO(mrry): Consider computing the actual longest common subsequence. 

104 is_eliding = False 

105 elide_count = 0 

106 last_elided_line = None 

107 for line, line_in_prev in zip( 

108 curr_traceback_list, prev_traceback_list 

109 ): 

110 if line == line_in_prev: 

111 if is_eliding: 

112 elide_count += 1 

113 last_elided_line = line 

114 else: 

115 output.append(line) 

116 is_eliding = True 

117 elide_count = 0 

118 else: 

119 if is_eliding: 

120 if elide_count > 0: 

121 output.extend( 

122 [ 

123 "[elided %d identical lines from previous traceback]\n" 

124 % (elide_count - 1,), 

125 last_elided_line, 

126 ] 

127 ) 

128 is_eliding = False 

129 output.extend(line) 

130 

131 # pylint: disable=protected-access 

132 original_op = original_op._original_op 

133 # pylint: enable=protected-access 

134 output.append( 

135 "\n%s (see above for traceback): %s\n" 

136 % (type(self).__name__, self.message) 

137 ) 

138 return "".join(output) 

139 else: 

140 return self.message 

141 

142 

143OK = error_codes.OK 

144# tf_export("errors.OK").export_constant(__name__, "OK") 

145CANCELLED = error_codes.CANCELLED 

146# tf_export("errors.CANCELLED").export_constant(__name__, "CANCELLED") 

147UNKNOWN = error_codes.UNKNOWN 

148# tf_export("errors.UNKNOWN").export_constant(__name__, "UNKNOWN") 

149INVALID_ARGUMENT = error_codes.INVALID_ARGUMENT 

150# tf_export("errors.INVALID_ARGUMENT").export_constant(__name__, 

151# "INVALID_ARGUMENT") 

152DEADLINE_EXCEEDED = error_codes.DEADLINE_EXCEEDED 

153# tf_export("errors.DEADLINE_EXCEEDED").export_constant(__name__, 

154# "DEADLINE_EXCEEDED") 

155NOT_FOUND = error_codes.NOT_FOUND 

156# tf_export("errors.NOT_FOUND").export_constant(__name__, "NOT_FOUND") 

157ALREADY_EXISTS = error_codes.ALREADY_EXISTS 

158# tf_export("errors.ALREADY_EXISTS").export_constant(__name__, "ALREADY_EXISTS") 

159PERMISSION_DENIED = error_codes.PERMISSION_DENIED 

160# tf_export("errors.PERMISSION_DENIED").export_constant(__name__, 

161# "PERMISSION_DENIED") 

162UNAUTHENTICATED = error_codes.UNAUTHENTICATED 

163# tf_export("errors.UNAUTHENTICATED").export_constant(__name__, "UNAUTHENTICATED") 

164RESOURCE_EXHAUSTED = error_codes.RESOURCE_EXHAUSTED 

165# tf_export("errors.RESOURCE_EXHAUSTED").export_constant(__name__, 

166# "RESOURCE_EXHAUSTED") 

167FAILED_PRECONDITION = error_codes.FAILED_PRECONDITION 

168# tf_export("errors.FAILED_PRECONDITION").export_constant(__name__, 

169# "FAILED_PRECONDITION") 

170ABORTED = error_codes.ABORTED 

171# tf_export("errors.ABORTED").export_constant(__name__, "ABORTED") 

172OUT_OF_RANGE = error_codes.OUT_OF_RANGE 

173# tf_export("errors.OUT_OF_RANGE").export_constant(__name__, "OUT_OF_RANGE") 

174UNIMPLEMENTED = error_codes.UNIMPLEMENTED 

175# tf_export("errors.UNIMPLEMENTED").export_constant(__name__, "UNIMPLEMENTED") 

176INTERNAL = error_codes.INTERNAL 

177# tf_export("errors.INTERNAL").export_constant(__name__, "INTERNAL") 

178UNAVAILABLE = error_codes.UNAVAILABLE 

179# tf_export("errors.UNAVAILABLE").export_constant(__name__, "UNAVAILABLE") 

180DATA_LOSS = error_codes.DATA_LOSS 

181# tf_export("errors.DATA_LOSS").export_constant(__name__, "DATA_LOSS") 

182 

183 

184# @tf_export("errors.CancelledError") 

185class CancelledError(OpError): 

186 """Raised when an operation or step is cancelled. 

187 

188 For example, a long-running operation (e.g. 

189 @{tf.QueueBase.enqueue} may be 

190 cancelled by running another operation (e.g. 

191 @{tf.QueueBase.close}, 

192 or by @{tf.Session.close}. 

193 A step that is running such a long-running operation will fail by raising 

194 `CancelledError`. 

195 

196 @@__init__ 

197 """ 

198 

199 def __init__(self, node_def, op, message): 

200 """Creates a `CancelledError`.""" 

201 super().__init__(node_def, op, message, CANCELLED) 

202 

203 

204# @tf_export("errors.UnknownError") 

205class UnknownError(OpError): 

206 """Unknown error. 

207 

208 An example of where this error may be returned is if a Status value 

209 received from another address space belongs to an error-space that 

210 is not known to this address space. Also errors raised by APIs that 

211 do not return enough error information may be converted to this 

212 error. 

213 

214 @@__init__ 

215 """ 

216 

217 def __init__(self, node_def, op, message, error_code=UNKNOWN): 

218 """Creates an `UnknownError`.""" 

219 super().__init__(node_def, op, message, error_code) 

220 

221 

222# @tf_export("errors.InvalidArgumentError") 

223class InvalidArgumentError(OpError): 

224 """Raised when an operation receives an invalid argument. 

225 

226 This may occur, for example, if an operation is receives an input 

227 tensor that has an invalid value or shape. For example, the 

228 @{tf.matmul} op will raise this 

229 error if it receives an input that is not a matrix, and the 

230 @{tf.reshape} op will raise 

231 this error if the new shape does not match the number of elements in the input 

232 tensor. 

233 

234 @@__init__ 

235 """ 

236 

237 def __init__(self, node_def, op, message): 

238 """Creates an `InvalidArgumentError`.""" 

239 super().__init__(node_def, op, message, INVALID_ARGUMENT) 

240 

241 

242# @tf_export("errors.DeadlineExceededError") 

243class DeadlineExceededError(OpError): 

244 """Raised when a deadline expires before an operation could complete. 

245 

246 This exception is not currently used. 

247 

248 @@__init__ 

249 """ 

250 

251 def __init__(self, node_def, op, message): 

252 """Creates a `DeadlineExceededError`.""" 

253 super().__init__(node_def, op, message, DEADLINE_EXCEEDED) 

254 

255 

256# @tf_export("errors.NotFoundError") 

257class NotFoundError(OpError): 

258 """Raised when a requested entity (e.g., a file or directory) was not 

259 found. 

260 

261 For example, running the 

262 @{tf.WholeFileReader.read} 

263 operation could raise `NotFoundError` if it receives the name of a file that 

264 does not exist. 

265 

266 @@__init__ 

267 """ 

268 

269 def __init__(self, node_def, op, message): 

270 """Creates a `NotFoundError`.""" 

271 super().__init__(node_def, op, message, NOT_FOUND) 

272 

273 

274# @tf_export("errors.AlreadyExistsError") 

275class AlreadyExistsError(OpError): 

276 """Raised when an entity that we attempted to create already exists. 

277 

278 For example, running an operation that saves a file 

279 (e.g. @{tf.train.Saver.save}) 

280 could potentially raise this exception if an explicit filename for an 

281 existing file was passed. 

282 

283 @@__init__ 

284 """ 

285 

286 def __init__(self, node_def, op, message): 

287 """Creates an `AlreadyExistsError`.""" 

288 super().__init__(node_def, op, message, ALREADY_EXISTS) 

289 

290 

291# @tf_export("errors.PermissionDeniedError") 

292class PermissionDeniedError(OpError): 

293 """Raised when the caller does not have permission to run an operation. 

294 

295 For example, running the 

296 @{tf.WholeFileReader.read} 

297 operation could raise `PermissionDeniedError` if it receives the name of a 

298 file for which the user does not have the read file permission. 

299 

300 @@__init__ 

301 """ 

302 

303 def __init__(self, node_def, op, message): 

304 """Creates a `PermissionDeniedError`.""" 

305 super().__init__(node_def, op, message, PERMISSION_DENIED) 

306 

307 

308# @tf_export("errors.UnauthenticatedError") 

309class UnauthenticatedError(OpError): 

310 """The request does not have valid authentication credentials. 

311 

312 This exception is not currently used. 

313 

314 @@__init__ 

315 """ 

316 

317 def __init__(self, node_def, op, message): 

318 """Creates an `UnauthenticatedError`.""" 

319 super().__init__(node_def, op, message, UNAUTHENTICATED) 

320 

321 

322# @tf_export("errors.ResourceExhaustedError") 

323class ResourceExhaustedError(OpError): 

324 """Some resource has been exhausted. 

325 

326 For example, this error might be raised if a per-user quota is 

327 exhausted, or perhaps the entire file system is out of space. 

328 

329 @@__init__ 

330 """ 

331 

332 def __init__(self, node_def, op, message): 

333 """Creates a `ResourceExhaustedError`.""" 

334 super().__init__(node_def, op, message, RESOURCE_EXHAUSTED) 

335 

336 

337# @tf_export("errors.FailedPreconditionError") 

338class FailedPreconditionError(OpError): 

339 """Operation was rejected because the system is not in a state to execute 

340 it. 

341 

342 This exception is most commonly raised when running an operation 

343 that reads a @{tf.Variable} 

344 before it has been initialized. 

345 

346 @@__init__ 

347 """ 

348 

349 def __init__(self, node_def, op, message): 

350 """Creates a `FailedPreconditionError`.""" 

351 super().__init__(node_def, op, message, FAILED_PRECONDITION) 

352 

353 

354# @tf_export("errors.AbortedError") 

355class AbortedError(OpError): 

356 """The operation was aborted, typically due to a concurrent action. 

357 

358 For example, running a 

359 @{tf.QueueBase.enqueue} 

360 operation may raise `AbortedError` if a 

361 @{tf.QueueBase.close} operation 

362 previously ran. 

363 

364 @@__init__ 

365 """ 

366 

367 def __init__(self, node_def, op, message): 

368 """Creates an `AbortedError`.""" 

369 super().__init__(node_def, op, message, ABORTED) 

370 

371 

372# @tf_export("errors.OutOfRangeError") 

373class OutOfRangeError(OpError): 

374 """Raised when an operation iterates past the valid input range. 

375 

376 This exception is raised in "end-of-file" conditions, such as when a 

377 @{tf.QueueBase.dequeue} 

378 operation is blocked on an empty queue, and a 

379 @{tf.QueueBase.close} 

380 operation executes. 

381 

382 @@__init__ 

383 """ 

384 

385 def __init__(self, node_def, op, message): 

386 """Creates an `OutOfRangeError`.""" 

387 super().__init__(node_def, op, message, OUT_OF_RANGE) 

388 

389 

390# @tf_export("errors.UnimplementedError") 

391class UnimplementedError(OpError): 

392 """Raised when an operation has not been implemented. 

393 

394 Some operations may raise this error when passed otherwise-valid 

395 arguments that it does not currently support. For example, running 

396 the @{tf.nn.max_pool} operation 

397 would raise this error if pooling was requested on the batch dimension, 

398 because this is not yet supported. 

399 

400 @@__init__ 

401 """ 

402 

403 def __init__(self, node_def, op, message): 

404 """Creates an `UnimplementedError`.""" 

405 super().__init__(node_def, op, message, UNIMPLEMENTED) 

406 

407 

408# @tf_export("errors.InternalError") 

409class InternalError(OpError): 

410 """Raised when the system experiences an internal error. 

411 

412 This exception is raised when some invariant expected by the runtime 

413 has been broken. Catching this exception is not recommended. 

414 

415 @@__init__ 

416 """ 

417 

418 def __init__(self, node_def, op, message): 

419 """Creates an `InternalError`.""" 

420 super().__init__(node_def, op, message, INTERNAL) 

421 

422 

423# @tf_export("errors.UnavailableError") 

424class UnavailableError(OpError): 

425 """Raised when the runtime is currently unavailable. 

426 

427 This exception is not currently used. 

428 

429 @@__init__ 

430 """ 

431 

432 def __init__(self, node_def, op, message): 

433 """Creates an `UnavailableError`.""" 

434 super().__init__(node_def, op, message, UNAVAILABLE) 

435 

436 

437# @tf_export("errors.DataLossError") 

438class DataLossError(OpError): 

439 """Raised when unrecoverable data loss or corruption is encountered. 

440 

441 For example, this may be raised by running a 

442 @{tf.WholeFileReader.read} 

443 operation, if the file is truncated while it is being read. 

444 

445 @@__init__ 

446 """ 

447 

448 def __init__(self, node_def, op, message): 

449 """Creates a `DataLossError`.""" 

450 super().__init__(node_def, op, message, DATA_LOSS) 

451 

452 

453_CODE_TO_EXCEPTION_CLASS = { 

454 CANCELLED: CancelledError, 

455 UNKNOWN: UnknownError, 

456 INVALID_ARGUMENT: InvalidArgumentError, 

457 DEADLINE_EXCEEDED: DeadlineExceededError, 

458 NOT_FOUND: NotFoundError, 

459 ALREADY_EXISTS: AlreadyExistsError, 

460 PERMISSION_DENIED: PermissionDeniedError, 

461 UNAUTHENTICATED: UnauthenticatedError, 

462 RESOURCE_EXHAUSTED: ResourceExhaustedError, 

463 FAILED_PRECONDITION: FailedPreconditionError, 

464 ABORTED: AbortedError, 

465 OUT_OF_RANGE: OutOfRangeError, 

466 UNIMPLEMENTED: UnimplementedError, 

467 INTERNAL: InternalError, 

468 UNAVAILABLE: UnavailableError, 

469 DATA_LOSS: DataLossError, 

470} 

471 

472_EXCEPTION_CLASS_TO_CODE = dict( 

473 ((class_, code) for (code, class_) in _CODE_TO_EXCEPTION_CLASS.items()) 

474) 

475 

476 

477# @tf_export("errors.exception_type_from_error_code") 

478def exception_type_from_error_code(error_code): 

479 return _CODE_TO_EXCEPTION_CLASS[error_code] 

480 

481 

482# @tf_export("errors.error_code_from_exception_type") 

483def error_code_from_exception_type(cls): 

484 return _EXCEPTION_CLASS_TO_CODE[cls] 

485 

486 

487def _make_specific_exception(node_def, op, message, error_code): 

488 try: 

489 exc_type = exception_type_from_error_code(error_code) 

490 return exc_type(node_def, op, message) 

491 except KeyError: 

492 warnings.warn("Unknown error code: %d" % error_code) 

493 return UnknownError(node_def, op, message, error_code) 

494 

495 

496# Named like a function for backwards compatibility with the 

497# @tf_contextlib.contextmanager version, which was switched to a class to avoid 

498# some object creation overhead. 

499# TODO(b/77295559): expand use of TF_Status* SWIG typemap and deprecate this. 

500# @tf_export("errors.raise_exception_on_not_ok_status") # pylint: disable=invalid-name 

501class raise_exception_on_not_ok_status: 

502 """Context manager to check for C API status.""" 

503 

504 def __enter__(self): 

505 return "Status not OK" 

506 

507 def __exit__(self, type_arg, value_arg, traceback_arg): 

508 return False # False values do not suppress exceptions