pytorch/caffe2/operators/assert_op.h
Richard Barnes 1433160a36 use irange for loops 6 (#66742)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/66742

Modified loops in files under fbsource/fbcode/caffe2/ from the format

`for(TYPE var=x0;var<x_max;x++)`

to the format

`for(const auto var: irange(xmax))`

This was achieved by running r-barnes's loop upgrader script (D28874212) with some modification to exclude all files under /torch/jit and a number of reversions or unused variable suppression warnings added by hand.

Test Plan: Sandcastle

Reviewed By: malfet

Differential Revision: D31705366

fbshipit-source-id: be58222426c192406a7f93c21582c3f6f2082401
2021-12-07 16:07:50 -08:00

53 lines
1.3 KiB
C++

#ifndef CAFFE2_OPERATORS_ASSERT_OP_H_
#define CAFFE2_OPERATORS_ASSERT_OP_H_
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
#include <c10/util/irange.h>
namespace caffe2 {
template <class Context>
class AssertOp final : public Operator<Context> {
public:
template <class... Args>
explicit AssertOp(Args&&... args)
: Operator<Context>(std::forward<Args>(args)...),
error_msg_(
this->template GetSingleArgument<std::string>("error_msg", "")) {}
USE_OPERATOR_CONTEXT_FUNCTIONS;
template <typename T>
bool DoRunWithType() {
// Copy into CPU context for comparison
cmp_tensor_.CopyFrom(Input(0));
auto *const cmp_data = cmp_tensor_.template data<T>();
for (const auto i : c10::irange(cmp_tensor_.numel())) {
CAFFE_ENFORCE((bool)cmp_data[i], [&]() {
std::stringstream ss;
ss << "Assert failed for element " << i
<< " in tensor, value: " << cmp_data[i] << "\n";
if (!error_msg_.empty()) {
ss << "Error message: " << error_msg_;
}
return ss.str();
}());
}
return true;
}
bool RunOnDevice() override {
return DispatchHelper<TensorTypes<long, int, bool>>::call(this, Input(0));
}
private:
Tensor cmp_tensor_{CPU};
std::string error_msg_;
};
} // namespace caffe2
#endif /* CAFFE2_OPERATORS_ASSERT_OP_H_ */