1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#ifndef CAFFE2_OPERATORS_ORDER_SWITCH_OPS_H_
#define CAFFE2_OPERATORS_ORDER_SWITCH_OPS_H_
#include "caffe2/core/operator.h"
#include "caffe2/utils/math.h"
#include <c10/util/irange.h>
#include <vector>
namespace caffe2 {
// Note(Yangqing): I think it is possible to do a more general swapaxes operator
// but I am a little afraid of going down that general path. Only implementing
// the two actually needed ones here.
template <typename T, class Context>
class NHWC2NCHWOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
USE_SIMPLE_CTOR_DTOR(NHWC2NCHWOp);
bool RunOnDevice() override {
const auto& X = Input(0);
const int ndim = X.dim();
CAFFE_ENFORCE_GE(ndim, 3);
const int N = X.dim32(0);
const int C = X.dim32(ndim - 1);
std::vector<int64_t> Y_dims(ndim);
Y_dims[0] = N;
Y_dims[1] = C;
int HxW = 1;
for (const auto i : c10::irange(2, ndim)) {
Y_dims[i] = X.dim32(i - 1);
HxW *= Y_dims[i];
}
auto* Y = Output(0, Y_dims, at::dtype<T>());
if (X.numel() <= 0) {
return true;
}
math::NHWC2NCHW<T, Context>(
N,
C,
HxW,
X.template data<T>(),
Y->template mutable_data<T>(),
&context_);
return true;
}
};
template <typename T, class Context>
class NCHW2NHWCOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
USE_SIMPLE_CTOR_DTOR(NCHW2NHWCOp);
bool RunOnDevice() override {
const auto& X = Input(0);
const int ndim = X.dim();
CAFFE_ENFORCE_GE(ndim, 3);
const int N = X.dim32(0);
const int C = X.dim32(1);
std::vector<int64_t> Y_dims(ndim);
Y_dims[0] = N;
Y_dims[ndim - 1] = C;
int HxW = 1;
for (int i = 1; i < ndim - 1; ++i) {
Y_dims[i] = X.dim32(i + 1);
HxW *= Y_dims[i];
}
auto* Y = Output(0, Y_dims, at::dtype<T>());
if (X.numel() <= 0) {
return true;
}
math::NCHW2NHWC<T, Context>(
N,
C,
HxW,
X.template data<T>(),
Y->template mutable_data<T>(),
&context_);
return true;
}
};
} // namespace caffe2
#endif // CAFFE2_OPERATORS_ORDER_SWITCH_OPS_H_
|