[caffe2] Don't evaluate message in CAFFE_ENFORCE_THAT unless the check fails (#106145)

D26829714 improved CAFFE_ENFORCE_THAT, but made us eagerly evaluate the message, which has costs.

Differential Revision: [D47809432](https://our.internmc.facebook.com/intern/diff/D47809432/)
Pull Request resolved: https://github.com/pytorch/pytorch/pull/106145
Approved by: https://github.com/davidberard98
This commit is contained in:
Scott Wolchok
2023-07-28 11:51:04 -07:00
committed by PyTorch MergeBot
parent 26d29d9639
commit 505dd319ef

View File

@ -196,6 +196,11 @@ std::string enforceFailMsgImpl(const T1& x, const T2& y, const Args&... args) {
return c10::str(x, " vs ", y, ". ", args...);
}
// GCC7 is getting an internal compiler error on the new
// implementation, so keep the old one (which evaluates the error
// message eagerly and therefore is undesirable for general use
// compared to the new one) around for it.
#if defined(__GNUG__) && __GNUC__ <= 7 && !defined(__clang__)
template <typename Pred, typename T1, typename T2, typename... Args>
void enforceThatImpl(
Pred p,
@ -215,6 +220,7 @@ void enforceThatImpl(
caller);
}
}
#define CAFFE_ENFORCE_THAT_IMPL(op, lhs, rhs, expr, ...) \
::c10::enforce_detail::enforceThatImpl( \
op, lhs, rhs, __FILE__, __LINE__, expr, nullptr, ##__VA_ARGS__)
@ -223,6 +229,51 @@ void enforceThatImpl(
::c10::enforce_detail::enforceThatImpl( \
op, (lhs), (rhs), __FILE__, __LINE__, expr, this, ##__VA_ARGS__)
#else
template <typename Pred, typename T1, typename T2, typename GetFailMsgFunc>
void enforceThatImpl(
Pred p,
const T1& lhs,
const T2& rhs,
const char* file,
int line,
const char* expr,
const void* caller,
GetFailMsgFunc getFailMsg) {
if (C10_UNLIKELY(!(p(lhs, rhs)))) {
::c10::ThrowEnforceNotMet(file, line, expr, getFailMsg(lhs, rhs), caller);
}
}
#define CAFFE_ENFORCE_THAT_IMPL(op, lhs, rhs, expr, ...) \
::c10::enforce_detail::enforceThatImpl( \
op, \
(lhs), \
(rhs), \
__FILE__, \
__LINE__, \
expr, \
nullptr, \
[&](const auto& arg1, const auto& arg2) { \
return ::c10::enforce_detail::enforceFailMsgImpl( \
arg1, arg2, ##__VA_ARGS__); \
})
#define CAFFE_ENFORCE_THAT_IMPL_WITH_CALLER(op, lhs, rhs, expr, ...) \
::c10::enforce_detail::enforceThatImpl( \
op, \
(lhs), \
(rhs), \
__FILE__, \
__LINE__, \
expr, \
this, \
[&](const auto& arg1, const auto& arg2) { \
return ::c10::enforce_detail::enforceFailMsgImpl( \
arg1, arg2, ##__VA_ARGS__); \
})
#endif
} // namespace enforce_detail
#define CAFFE_ENFORCE_THAT(cmp, op, lhs, rhs, ...) \