Exception.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. #ifndef C10_UTIL_EXCEPTION_H_
  2. #define C10_UTIL_EXCEPTION_H_
  3. #include <c10/macros/Export.h>
  4. #include <c10/macros/Macros.h>
  5. #include <c10/util/Backtrace.h>
  6. #include <c10/util/Lazy.h>
  7. #include <c10/util/StringUtil.h>
  8. #include <cstdint>
  9. #include <exception>
  10. #include <memory>
  11. #include <string>
  12. #include <variant>
  13. #include <vector>
  14. #if defined(_MSC_VER) && _MSC_VER <= 1900
  15. #define __func__ __FUNCTION__
  16. #endif
  17. namespace c10 {
  18. /// The primary ATen error class.
  19. /// Provides a complete error message with source location information via
  20. /// `what()`, and a more concise message via `what_without_backtrace()`.
  21. /// Don't throw this directly; use TORCH_CHECK/TORCH_INTERNAL_ASSERT instead.
  22. ///
  23. /// NB: c10::Error is handled specially by the default torch to suppress the
  24. /// backtrace, see torch/csrc/Exceptions.h
  25. class C10_API Error : public std::exception {
  26. private:
  27. // The actual error message.
  28. std::string msg_;
  29. // Context for the message (in order of decreasing specificity). Context will
  30. // be automatically formatted appropriately, so it is not necessary to add
  31. // extra leading/trailing newlines to strings inside this vector
  32. std::vector<std::string> context_;
  33. // The C++ backtrace at the point when this exception was raised. This
  34. // may be empty if there is no valid backtrace. (We don't use optional
  35. // here to reduce the dependencies this file has.)
  36. Backtrace backtrace_;
  37. // These two are derived fields from msg_stack_ and backtrace_, but we need
  38. // fields for the strings so that we can return a const char* (as the
  39. // signature of std::exception requires). Currently, the invariant
  40. // is that these fields are ALWAYS populated consistently with respect
  41. // to msg_stack_ and backtrace_.
  42. mutable OptimisticLazy<std::string> what_;
  43. std::string what_without_backtrace_;
  44. // This is a little debugging trick: you can stash a relevant pointer
  45. // in caller, and then when you catch the exception, you can compare
  46. // against pointers you have on hand to get more information about
  47. // where the exception came from. In Caffe2, this is used to figure
  48. // out which operator raised an exception.
  49. const void* caller_;
  50. public:
  51. // PyTorch-style Error constructor. NB: the implementation of this
  52. // is actually in Logging.cpp
  53. Error(SourceLocation source_location, std::string msg);
  54. // Caffe2-style error message
  55. Error(
  56. const char* file,
  57. const uint32_t line,
  58. const char* condition,
  59. const std::string& msg,
  60. Backtrace backtrace,
  61. const void* caller = nullptr);
  62. // Base constructor
  63. Error(
  64. std::string msg,
  65. Backtrace backtrace = nullptr,
  66. const void* caller = nullptr);
  67. // Add some new context to the message stack. The last added context
  68. // will be formatted at the end of the context list upon printing.
  69. // WARNING: This method is O(n) in the size of the stack, so don't go
  70. // wild adding a ridiculous amount of context to error messages.
  71. void add_context(std::string msg);
  72. const std::string& msg() const {
  73. return msg_;
  74. }
  75. const std::vector<std::string>& context() const {
  76. return context_;
  77. }
  78. const Backtrace& backtrace() const;
  79. /// Returns the complete error message, including the source location.
  80. /// The returned pointer is invalidated if you call add_context() on
  81. /// this object.
  82. const char* what() const noexcept override;
  83. const void* caller() const noexcept {
  84. return caller_;
  85. }
  86. /// Returns only the error message string, without source location.
  87. /// The returned pointer is invalidated if you call add_context() on
  88. /// this object.
  89. virtual const char* what_without_backtrace() const noexcept {
  90. return what_without_backtrace_.c_str();
  91. }
  92. private:
  93. void refresh_what();
  94. std::string compute_what(bool include_backtrace) const;
  95. };
  96. class C10_API Warning {
  97. public:
  98. class C10_API UserWarning {};
  99. class C10_API DeprecationWarning {};
  100. using warning_variant_t = std::variant<UserWarning, DeprecationWarning>;
  101. Warning(
  102. warning_variant_t type,
  103. const SourceLocation& source_location,
  104. std::string msg,
  105. bool verbatim);
  106. Warning(
  107. warning_variant_t type,
  108. SourceLocation source_location,
  109. const char* msg,
  110. bool verbatim);
  111. Warning(
  112. warning_variant_t type,
  113. SourceLocation source_location,
  114. ::c10::detail::CompileTimeEmptyString msg,
  115. bool verbatim);
  116. // Getters for members
  117. warning_variant_t type() const;
  118. const SourceLocation& source_location() const;
  119. const std::string& msg() const;
  120. bool verbatim() const;
  121. private:
  122. // The type of warning
  123. warning_variant_t type_;
  124. // Where the warning happened.
  125. SourceLocation source_location_;
  126. // The actual warning message.
  127. std::string msg_;
  128. // See note: [Verbatim Warnings]
  129. bool verbatim_;
  130. };
  131. using UserWarning = Warning::UserWarning;
  132. using DeprecationWarning = Warning::DeprecationWarning;
  133. // Issue a warning with a given message. Dispatched to the current
  134. // warning handler.
  135. void C10_API warn(const Warning& warning);
  136. class C10_API WarningHandler {
  137. public:
  138. virtual ~WarningHandler() = default;
  139. /// The default warning handler. Prints the message to stderr.
  140. virtual void process(const Warning& warning);
  141. };
  142. namespace WarningUtils {
  143. // Note: [Verbatim Warnings]
  144. // Warnings originating in C++ code can appear out-of-place to Python users:
  145. // a user runs a line in Python, but the warning references a line in C++.
  146. // Some parts of PyTorch, like the JIT, are cognizant of this mismatch
  147. // and take care to map warnings back to the user's program, but most
  148. // of PyTorch simply throws a context-free warning. To allow warning
  149. // handlers to add context where appropriate, warn takes the
  150. // "verbatim" flag. When this is false a warning handler might append
  151. // the C++ warning to a Python warning message that relates the warning
  152. // back to the user's program. Callers who have already accounted for
  153. // context in their warnings should set verbatim to true so their warnings
  154. // appear without modification.
  155. /// Sets the global warning handler. This is not thread-safe, so it should
  156. /// generally be called once during initialization or while holding the GIL
  157. /// for programs that use python.
  158. /// User is responsible for keeping the WarningHandler alive until
  159. /// it is not needed.
  160. C10_API void set_warning_handler(WarningHandler* handler) noexcept(true);
  161. /// Gets the global warning handler.
  162. C10_API WarningHandler* get_warning_handler() noexcept(true);
  163. class C10_API WarningHandlerGuard {
  164. WarningHandler* prev_handler_;
  165. public:
  166. WarningHandlerGuard(WarningHandler* new_handler)
  167. : prev_handler_(c10::WarningUtils::get_warning_handler()) {
  168. c10::WarningUtils::set_warning_handler(new_handler);
  169. }
  170. ~WarningHandlerGuard() {
  171. c10::WarningUtils::set_warning_handler(prev_handler_);
  172. }
  173. };
  174. /// The TORCH_WARN_ONCE macro is difficult to test for. Use
  175. /// setWarnAlways(true) to turn it into TORCH_WARN, which can be
  176. /// tested for more easily.
  177. C10_API void set_warnAlways(bool) noexcept(true);
  178. C10_API bool get_warnAlways() noexcept(true);
  179. // A RAII guard that sets warn_always (not thread-local) on
  180. // construction, and sets it back to the original value upon destruction.
  181. struct C10_API WarnAlways {
  182. public:
  183. explicit WarnAlways(bool setting = true);
  184. ~WarnAlways();
  185. private:
  186. bool prev_setting;
  187. };
  188. } // namespace WarningUtils
  189. // Like Error, but we always report the C++ backtrace, instead of only
  190. // reporting when TORCH_SHOW_CPP_STACKTRACES
  191. class C10_API ErrorAlwaysShowCppStacktrace : public Error {
  192. using Error::Error;
  193. const char* what_without_backtrace() const noexcept override {
  194. return what();
  195. }
  196. };
  197. // Used in ATen for out-of-bound indices that can reasonably only be detected
  198. // lazily inside a kernel (See: advanced indexing). These turn into
  199. // IndexError when they cross to Python.
  200. class C10_API IndexError : public Error {
  201. using Error::Error;
  202. };
  203. // Used in ATen for invalid values. These turn into
  204. // ValueError when they cross to Python.
  205. class C10_API ValueError : public Error {
  206. using Error::Error;
  207. };
  208. // Used in ATen for invalid types. These turn into
  209. // TypeError when they cross to Python.
  210. class C10_API TypeError : public Error {
  211. using Error::Error;
  212. };
  213. // Used in ATen for functionality that is not implemented. These turn into
  214. // NotImplementedError when they cross to Python.
  215. class C10_API NotImplementedError : public Error {
  216. using Error::Error;
  217. };
  218. // Used in ATen for non finite indices. These turn into
  219. // ExitException when they cross to Python.
  220. class C10_API EnforceFiniteError : public Error {
  221. using Error::Error;
  222. };
  223. // Used in Onnxifi backend lowering. These turn into
  224. // ExitException when they cross to Python.
  225. class C10_API OnnxfiBackendSystemError : public Error {
  226. using Error::Error;
  227. };
  228. // Used for numerical errors from the linalg module. These
  229. // turn into LinAlgError when they cross into Python.
  230. class C10_API LinAlgError : public Error {
  231. using Error::Error;
  232. };
  233. class C10_API OutOfMemoryError : public Error {
  234. using Error::Error;
  235. };
  236. // Base error type for all distributed errors.
  237. // These turn into DistError when they cross into Python.
  238. class C10_API DistError : public Error {
  239. using Error::Error;
  240. };
  241. // Used for collective communication library errors from the distributed module.
  242. // These turn into DistBackendError when they cross into Python.
  243. class C10_API DistBackendError : public DistError {
  244. using DistError::DistError;
  245. };
  246. // Used for errors originating from the store.
  247. // These turn into DistStoreError when they cross into Python.
  248. class C10_API DistStoreError : public DistError {
  249. using DistError::DistError;
  250. };
  251. // Used for errors originating from the TCP/IP stack and not from collective
  252. // libraries. These turn into DistNetworkError when they cross into Python.
  253. class C10_API DistNetworkError : public DistError {
  254. using DistError::DistError;
  255. };
  256. // A utility function to return an exception std::string by prepending its
  257. // exception type before its what() content
  258. C10_API std::string GetExceptionString(const std::exception& e);
  259. } // namespace c10
  260. // Private helper macro for implementing TORCH_INTERNAL_ASSERT and TORCH_CHECK
  261. //
  262. // Note: In the debug build With MSVC, __LINE__ might be of long type (a.k.a
  263. // int32_t), which is different from the definition of `SourceLocation` that
  264. // requires unsigned int (a.k.a uint32_t) and may cause a compile error with the
  265. // message: error C2397: conversion from 'long' to 'uint32_t' requires a
  266. // narrowing conversion Here the static cast is used to pass the build. if this
  267. // is used inside a lambda the __func__ macro expands to operator(), which isn't
  268. // very useful, but hard to fix in a macro so suppressing the warning.
  269. #define C10_THROW_ERROR(err_type, msg) \
  270. throw ::c10::err_type( \
  271. {__func__, __FILE__, static_cast<uint32_t>(__LINE__)}, msg)
  272. #define C10_BUILD_ERROR(err_type, msg) \
  273. ::c10::err_type({__func__, __FILE__, static_cast<uint32_t>(__LINE__)}, msg)
  274. // Private helper macro for workaround MSVC misexpansion of nested macro
  275. // invocations involving __VA_ARGS__. See
  276. // https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly
  277. #define C10_EXPAND_MSVC_WORKAROUND(x) x
  278. // On nvcc, C10_UNLIKELY thwarts missing return statement analysis. In cases
  279. // where the unlikely expression may be a constant, use this macro to ensure
  280. // return statement analysis keeps working (at the cost of not getting the
  281. // likely/unlikely annotation on nvcc).
  282. // https://github.com/pytorch/pytorch/issues/21418
  283. //
  284. // Currently, this is only used in the error reporting macros below. If you
  285. // want to use it more generally, move me to Macros.h
  286. //
  287. // TODO: Brian Vaughan observed that we might be able to get this to work on
  288. // nvcc by writing some sort of C++ overload that distinguishes constexpr inputs
  289. // from non-constexpr. Since there isn't any evidence that losing C10_UNLIKELY
  290. // in nvcc is causing us perf problems, this is not yet implemented, but this
  291. // might be an interesting piece of C++ code for an intrepid bootcamper to
  292. // write.
  293. #if defined(__CUDACC__)
  294. #define C10_UNLIKELY_OR_CONST(e) e
  295. #else
  296. #define C10_UNLIKELY_OR_CONST(e) C10_UNLIKELY(e)
  297. #endif
  298. // ----------------------------------------------------------------------------
  299. // Error reporting macros
  300. // ----------------------------------------------------------------------------
  301. #ifdef STRIP_ERROR_MESSAGES
  302. #define TORCH_RETHROW(e, ...) throw
  303. #else
  304. #define TORCH_RETHROW(e, ...) \
  305. do { \
  306. e.add_context(::c10::str(__VA_ARGS__)); \
  307. throw; \
  308. } while (false)
  309. #endif
  310. // A utility macro to provide assert()-like functionality; that is, enforcement
  311. // of internal invariants in code. It supports an arbitrary number of extra
  312. // arguments (evaluated only on failure), which will be printed in the assert
  313. // failure message using operator<< (this is useful to print some variables
  314. // which may be useful for debugging.)
  315. //
  316. // Usage:
  317. // TORCH_INTERNAL_ASSERT(should_be_true);
  318. // TORCH_INTERNAL_ASSERT(x == 0, "x = ", x);
  319. //
  320. // Assuming no bugs in PyTorch, the conditions tested by this macro should
  321. // always be true; e.g., it should be possible to disable all of these
  322. // conditions without changing observable user behavior. If you would like to
  323. // do error reporting for user input, please use TORCH_CHECK instead.
  324. //
  325. // NOTE: It is SAFE to use this macro in production code; on failure, this
  326. // simply raises an exception, it does NOT unceremoniously quit the process
  327. // (unlike assert()).
  328. //
  329. #ifdef STRIP_ERROR_MESSAGES
  330. #define TORCH_INTERNAL_ASSERT(cond, ...) \
  331. if (C10_UNLIKELY_OR_CONST(!(cond))) { \
  332. ::c10::detail::torchCheckFail( \
  333. __func__, \
  334. __FILE__, \
  335. static_cast<uint32_t>(__LINE__), \
  336. #cond " INTERNAL ASSERT FAILED at " C10_STRINGIZE(__FILE__)); \
  337. }
  338. #else
  339. // It would be nice if we could build a combined string literal out of
  340. // the TORCH_INTERNAL_ASSERT prefix and a user-provided string literal
  341. // as the first argument, but there doesn't seem to be any good way to
  342. // do that while still supporting having a first argument that isn't a
  343. // string literal.
  344. #define TORCH_INTERNAL_ASSERT(cond, ...) \
  345. if (C10_UNLIKELY_OR_CONST(!(cond))) { \
  346. ::c10::detail::torchInternalAssertFail( \
  347. __func__, \
  348. __FILE__, \
  349. static_cast<uint32_t>(__LINE__), \
  350. #cond \
  351. " INTERNAL ASSERT FAILED at " C10_STRINGIZE(__FILE__) ":" C10_STRINGIZE( \
  352. __LINE__) ", please report a bug to PyTorch. ", \
  353. c10::str(__VA_ARGS__)); \
  354. }
  355. #endif
  356. // A utility macro to make it easier to test for error conditions from user
  357. // input. Like TORCH_INTERNAL_ASSERT, it supports an arbitrary number of extra
  358. // arguments (evaluated only on failure), which will be printed in the error
  359. // message using operator<< (e.g., you can pass any object which has
  360. // operator<< defined. Most objects in PyTorch have these definitions!)
  361. //
  362. // Usage:
  363. // TORCH_CHECK(should_be_true); // A default error message will be provided
  364. // // in this case; but we recommend writing an
  365. // // explicit error message, as it is more
  366. // // user friendly.
  367. // TORCH_CHECK(x == 0, "Expected x to be 0, but got ", x);
  368. //
  369. // On failure, this macro will raise an exception. If this exception propagates
  370. // to Python, it will convert into a Python RuntimeError.
  371. //
  372. // NOTE: It is SAFE to use this macro in production code; on failure, this
  373. // simply raises an exception, it does NOT unceremoniously quit the process
  374. // (unlike CHECK() from glog.)
  375. //
  376. #define TORCH_CHECK_WITH(error_t, cond, ...) \
  377. TORCH_CHECK_WITH_MSG(error_t, cond, "", __VA_ARGS__)
  378. #ifdef STRIP_ERROR_MESSAGES
  379. #define TORCH_CHECK_MSG(cond, type, ...) \
  380. (#cond #type " CHECK FAILED at " C10_STRINGIZE(__FILE__))
  381. #define TORCH_CHECK_WITH_MSG(error_t, cond, type, ...) \
  382. if (C10_UNLIKELY_OR_CONST(!(cond))) { \
  383. C10_THROW_ERROR(Error, TORCH_CHECK_MSG(cond, type, __VA_ARGS__)); \
  384. }
  385. #else
  386. namespace c10::detail {
  387. template <typename... Args>
  388. decltype(auto) torchCheckMsgImpl(const char* /*msg*/, const Args&... args) {
  389. return ::c10::str(args...);
  390. }
  391. inline C10_API const char* torchCheckMsgImpl(const char* msg) {
  392. return msg;
  393. }
  394. // If there is just 1 user-provided C-string argument, use it.
  395. inline C10_API const char* torchCheckMsgImpl(
  396. const char* /*msg*/,
  397. const char* args) {
  398. return args;
  399. }
  400. } // namespace c10::detail
  401. #define TORCH_CHECK_MSG(cond, type, ...) \
  402. (::c10::detail::torchCheckMsgImpl( \
  403. "Expected " #cond \
  404. " to be true, but got false. " \
  405. "(Could this error message be improved? If so, " \
  406. "please report an enhancement request to PyTorch.)", \
  407. ##__VA_ARGS__))
  408. #define TORCH_CHECK_WITH_MSG(error_t, cond, type, ...) \
  409. if (C10_UNLIKELY_OR_CONST(!(cond))) { \
  410. C10_THROW_ERROR(error_t, TORCH_CHECK_MSG(cond, type, __VA_ARGS__)); \
  411. }
  412. #endif
  413. namespace c10::detail {
  414. [[noreturn]] C10_API void torchCheckFail(
  415. const char* func,
  416. const char* file,
  417. uint32_t line,
  418. const std::string& msg);
  419. [[noreturn]] C10_API void torchCheckFail(
  420. const char* func,
  421. const char* file,
  422. uint32_t line,
  423. const char* msg);
  424. // The c10::str() call that creates userMsg can have 1 of 3 return
  425. // types depending on the number and types of arguments passed to
  426. // TORCH_INTERNAL_ASSERT. 0 arguments will get a
  427. // CompileTimeEmptyString, 1 const char * will be passed straight
  428. // through, and anything else will get converted to std::string.
  429. [[noreturn]] C10_API void torchInternalAssertFail(
  430. const char* func,
  431. const char* file,
  432. uint32_t line,
  433. const char* condMsg,
  434. const char* userMsg);
  435. [[noreturn]] inline C10_API void torchInternalAssertFail(
  436. const char* func,
  437. const char* file,
  438. uint32_t line,
  439. const char* condMsg,
  440. ::c10::detail::CompileTimeEmptyString /*userMsg*/) {
  441. torchCheckFail(func, file, line, condMsg);
  442. }
  443. [[noreturn]] C10_API void torchInternalAssertFail(
  444. const char* func,
  445. const char* file,
  446. uint32_t line,
  447. const char* condMsg,
  448. const std::string& userMsg);
  449. } // namespace c10::detail
  450. #ifdef STRIP_ERROR_MESSAGES
  451. #define TORCH_CHECK(cond, ...) \
  452. if (C10_UNLIKELY_OR_CONST(!(cond))) { \
  453. ::c10::detail::torchCheckFail( \
  454. __func__, \
  455. __FILE__, \
  456. static_cast<uint32_t>(__LINE__), \
  457. TORCH_CHECK_MSG(cond, "", __VA_ARGS__)); \
  458. }
  459. #else
  460. #define TORCH_CHECK(cond, ...) \
  461. if (C10_UNLIKELY_OR_CONST(!(cond))) { \
  462. ::c10::detail::torchCheckFail( \
  463. __func__, \
  464. __FILE__, \
  465. static_cast<uint32_t>(__LINE__), \
  466. TORCH_CHECK_MSG(cond, "", ##__VA_ARGS__)); \
  467. }
  468. #endif
  469. // An utility macro that does what `TORCH_CHECK` does if compiled in the host
  470. // code, otherwise does nothing. Supposed to be used in the code shared between
  471. // host and device code as an alternative for `TORCH_CHECK`.
  472. #if defined(__CUDACC__) || defined(__HIPCC__)
  473. #define TORCH_CHECK_IF_NOT_ON_CUDA(cond, ...)
  474. #else
  475. #define TORCH_CHECK_IF_NOT_ON_CUDA(cond, ...) TORCH_CHECK(cond, ##__VA_ARGS__)
  476. #endif
  477. // Debug only version of TORCH_INTERNAL_ASSERT. This macro only checks in debug
  478. // build, and does nothing in release build. It is appropriate to use
  479. // in situations where you want to add an assert to a hotpath, but it is
  480. // too expensive to run this assert on production builds.
  481. #ifdef NDEBUG
  482. // Optimized version - generates no code.
  483. #define TORCH_INTERNAL_ASSERT_DEBUG_ONLY(...) \
  484. while (false) \
  485. C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(__VA_ARGS__))
  486. #else
  487. #define TORCH_INTERNAL_ASSERT_DEBUG_ONLY(...) \
  488. C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(__VA_ARGS__))
  489. #endif
  490. // TODO: We're going to get a lot of similar looking string literals
  491. // this way; check if this actually affects binary size.
  492. // Like TORCH_CHECK, but raises LinAlgError instead of Error.
  493. #define TORCH_CHECK_LINALG(cond, ...) \
  494. TORCH_CHECK_WITH_MSG(LinAlgError, cond, "LINALG", __VA_ARGS__)
  495. // Like TORCH_CHECK, but raises IndexErrors instead of Errors.
  496. #define TORCH_CHECK_INDEX(cond, ...) \
  497. TORCH_CHECK_WITH_MSG(IndexError, cond, "INDEX", __VA_ARGS__)
  498. // Like TORCH_CHECK, but raises ValueErrors instead of Errors.
  499. #define TORCH_CHECK_VALUE(cond, ...) \
  500. TORCH_CHECK_WITH_MSG(ValueError, cond, "VALUE", __VA_ARGS__)
  501. // Like TORCH_CHECK, but raises TypeErrors instead of Errors.
  502. #define TORCH_CHECK_TYPE(cond, ...) \
  503. TORCH_CHECK_WITH_MSG(TypeError, cond, "TYPE", __VA_ARGS__)
  504. // Like TORCH_CHECK, but raises NotImplementedErrors instead of Errors.
  505. #define TORCH_CHECK_NOT_IMPLEMENTED(cond, ...) \
  506. TORCH_CHECK_WITH_MSG(NotImplementedError, cond, "TYPE", __VA_ARGS__)
  507. #define TORCH_CHECK_ALWAYS_SHOW_CPP_STACKTRACE(cond, ...) \
  508. TORCH_CHECK_WITH_MSG( \
  509. ErrorAlwaysShowCppStacktrace, cond, "TYPE", ##__VA_ARGS__)
  510. #ifdef STRIP_ERROR_MESSAGES
  511. #define WARNING_MESSAGE_STRING(...) \
  512. ::c10::detail::CompileTimeEmptyString {}
  513. #else
  514. #define WARNING_MESSAGE_STRING(...) ::c10::str(__VA_ARGS__)
  515. #endif
  516. // Report a warning to the user. Accepts an arbitrary number of extra
  517. // arguments which are concatenated into the warning message using operator<<
  518. //
  519. #ifdef DISABLE_WARN
  520. #define _TORCH_WARN_WITH(...) ((void)0);
  521. #else
  522. #define _TORCH_WARN_WITH(warning_t, ...) \
  523. ::c10::warn(::c10::Warning( \
  524. warning_t(), \
  525. {__func__, __FILE__, static_cast<uint32_t>(__LINE__)}, \
  526. WARNING_MESSAGE_STRING(__VA_ARGS__), \
  527. false));
  528. #endif
  529. #define TORCH_WARN(...) _TORCH_WARN_WITH(::c10::UserWarning, __VA_ARGS__);
  530. #define TORCH_WARN_DEPRECATION(...) \
  531. _TORCH_WARN_WITH(::c10::DeprecationWarning, __VA_ARGS__);
  532. // Report a warning to the user only once. Accepts an arbitrary number of extra
  533. // arguments which are concatenated into the warning message using operator<<
  534. //
  535. #define _TORCH_WARN_ONCE(...) \
  536. C10_UNUSED static const auto C10_ANONYMOUS_VARIABLE(torch_warn_once_) = \
  537. [&] { \
  538. TORCH_WARN(__VA_ARGS__); \
  539. return true; \
  540. }()
  541. #ifdef DISABLE_WARN
  542. #define TORCH_WARN_ONCE(...) ((void)0);
  543. #else
  544. #define TORCH_WARN_ONCE(...) \
  545. if (::c10::WarningUtils::get_warnAlways()) { \
  546. TORCH_WARN(__VA_ARGS__); \
  547. } else { \
  548. _TORCH_WARN_ONCE(__VA_ARGS__); \
  549. }
  550. #endif
  551. // Report an error with a specific argument
  552. // NOTE: using the argument name in TORCH_CHECK's message is preferred
  553. #define TORCH_CHECK_ARG(cond, argN, ...) \
  554. TORCH_CHECK(cond, "invalid argument ", argN, ": ", __VA_ARGS__)
  555. // ----------------------------------------------------------------------------
  556. // Deprecated macros
  557. // ----------------------------------------------------------------------------
  558. namespace c10::detail {
  559. /*
  560. // Deprecation disabled until we fix sites in our codebase
  561. C10_DEPRECATED_MESSAGE("AT_ERROR(msg) is deprecated, use TORCH_CHECK(false, msg)
  562. instead.")
  563. */
  564. inline void deprecated_AT_ERROR() {}
  565. /*
  566. // Deprecation disabled until we fix sites in our codebase
  567. C10_DEPRECATED_MESSAGE("AT_ASSERT is deprecated, if you mean to indicate an
  568. internal invariant failure, use " \
  569. "TORCH_INTERNAL_ASSERT instead; if you mean to do user
  570. error checking, use " \ "TORCH_CHECK. See
  571. https://github.com/pytorch/pytorch/issues/20287 for more details.")
  572. */
  573. inline void deprecated_AT_ASSERT() {}
  574. /*
  575. // Deprecation disabled until we fix sites in our codebase
  576. C10_DEPRECATED_MESSAGE("AT_ASSERTM is deprecated, if you mean to indicate an
  577. internal invariant failure, use " \
  578. "TORCH_INTERNAL_ASSERT instead; if you mean to do user
  579. error checking, use " \ "TORCH_CHECK. See
  580. https://github.com/pytorch/pytorch/issues/20287 for more details.")
  581. */
  582. inline void deprecated_AT_ASSERTM() {}
  583. } // namespace c10::detail
  584. // Deprecated alias; this alias was deprecated because people kept mistakenly
  585. // using it for user error checking. Use TORCH_INTERNAL_ASSERT or TORCH_CHECK
  586. // instead. See https://github.com/pytorch/pytorch/issues/20287 for more
  587. // details.
  588. #define AT_ASSERT(...) \
  589. do { \
  590. ::c10::detail::deprecated_AT_ASSERT(); \
  591. C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(__VA_ARGS__)); \
  592. } while (false)
  593. // Deprecated alias, like AT_ASSERT. The new TORCH_INTERNAL_ASSERT macro
  594. // supports both 0-ary and variadic calls, so having a separate
  595. // message-accepting macro is not necessary.
  596. //
  597. // NB: we MUST include cond explicitly here, as MSVC will miscompile the macro
  598. // expansion, shunting all of __VA_ARGS__ to cond. An alternate workaround
  599. // can be seen at
  600. // https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly
  601. #define AT_ASSERTM(cond, ...) \
  602. do { \
  603. ::c10::detail::deprecated_AT_ASSERTM(); \
  604. C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(cond, __VA_ARGS__)); \
  605. } while (false)
  606. // Deprecated alias; this alias was deprecated because it represents extra API
  607. // surface that makes it hard for people to understand what macro to use.
  608. // Use TORCH_CHECK(false, ...) or TORCH_INTERNAL_ASSERT(false, ...) to
  609. // unconditionally fail at a line of code.
  610. #define AT_ERROR(...) \
  611. do { \
  612. ::c10::detail::deprecated_AT_ERROR(); \
  613. C10_EXPAND_MSVC_WORKAROUND(TORCH_CHECK(false, ::c10::str(__VA_ARGS__))); \
  614. } while (false)
  615. #endif // C10_UTIL_EXCEPTION_H_