flip_op.cc 7.0 KB
Newer Older
W
Wilber 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/operators/flip_op.h"
#include <string>
#include <unordered_map>
#include <vector>
19
#include "paddle/fluid/framework/op_version_registry.h"
20
#include "paddle/fluid/platform/complex.h"
W
Wilber 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

namespace paddle {
namespace operators {

using framework::OpKernelType;
using framework::Tensor;

class FlipOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE_EQ(
        ctx->HasInput("X"), true,
        platform::errors::NotFound("Input(X) of FlipOp should not be null."));
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
                      platform::errors::NotFound(
                          "Output(Out) of FlipOp should not be null."));
    auto x_dims = ctx->GetInputDim("X");
Y
yaoxuefeng 已提交
40
    auto flip_dims = ctx->Attrs().Get<std::vector<int>>("axis");
W
Wilber 已提交
41 42
    size_t flip_dims_size = flip_dims.size();

Y
yaoxuefeng 已提交
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
    if (flip_dims_size > 0) {
      // check if dims axis within range
      auto min_max_d = std::minmax_element(flip_dims.begin(), flip_dims.end());
      PADDLE_ENFORCE_LT(
          *min_max_d.first, x_dims.size(),
          platform::errors::InvalidArgument(
              "min(axes) should be less than the input tensor X's "
              "axes of FlipOp. But received min(axes) = %d,  "
              "X's axes = %d, X's shape = [%s]",
              *min_max_d.first, x_dims.size(), x_dims));
      PADDLE_ENFORCE_GE(*min_max_d.first, x_dims.size() * -1,
                        platform::errors::InvalidArgument(
                            "min(axes) should be greater than or equal to the "
                            "input tensor X's "
                            "axes of FlipOp times -1. But received "
                            "min(axes) = %d,  X's "
                            "axes = %d, X's shape = [%s]",
                            *min_max_d.first, x_dims.size() * -1, x_dims));
      PADDLE_ENFORCE_LT(
          *min_max_d.second, x_dims.size(),
          platform::errors::InvalidArgument(
              "max(axes) should be less than the input tensor X's "
              "axes of FlipOp. But received max(axes) = %d,  "
              "X's axes = %d, X's shape = [%s]",
              *min_max_d.second, x_dims.size(), x_dims));
      PADDLE_ENFORCE_GE(*min_max_d.second, x_dims.size() * -1,
                        platform::errors::InvalidArgument(
                            "max(axes) should be greater than or equal to the "
                            "input tensor X's "
                            "axes of FlipOp times -1. But received "
                            "max(axes) = %d,  X's "
                            "axes = %d, X's shape = [%s]",
                            *min_max_d.second, x_dims.size() * -1, x_dims));

      // check duplicates in dims
      flip_dims.erase(std::unique(flip_dims.begin(), flip_dims.end()),
                      flip_dims.end());
      PADDLE_ENFORCE_EQ(flip_dims.size(), flip_dims_size,
                        platform::errors::InvalidArgument(
                            "axes has duplicates, original flip axes size=%d, "
                            "but unique flip axes size=%d.)",
                            flip_dims_size, flip_dims.size()));
    }
W
Wilber 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

    VLOG(3) << "flip operator x.shape=" << x_dims;

    std::vector<int64_t> output_dims(x_dims.size());
    for (int i = 0; i < x_dims.size(); ++i) {
      output_dims[i] = x_dims[i];
    }
    ctx->SetOutputDim("Out", framework::make_ddim(output_dims));
    ctx->ShareLoD("X", "Out");
  }

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const {
    framework::LibraryType library = framework::LibraryType::kPlain;
    framework::DataLayout layout = framework::DataLayout::kAnyLayout;
    int customized_type_value =
        framework::OpKernelType::kDefaultCustomizedTypeValue;
    auto input_data_type = OperatorWithKernel::IndicateVarDataType(ctx, "X");
    return framework::OpKernelType(input_data_type, ctx.GetPlace(), layout,
                                   library, customized_type_value);
  }
};

class FlipOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor), The input tensor of flip op.");
    AddOutput("Out", "(Tensor), The output tensor of flip op.");
Y
yaoxuefeng 已提交
114
    AddAttr<std::vector<int>>("axis", "The axes to flip on.");
W
Wilber 已提交
115 116
    AddComment(R"DOC(
          Flip Operator.
Y
yaoxuefeng 已提交
117
          Reverse the order of a n-D tensor along given axis in axes.
W
Wilber 已提交
118 119 120 121 122 123
      )DOC");
  }
};

class FlipOpInferVarType : public framework::PassInDtypeAndVarTypeToOutput {
 protected:
124
  std::unordered_map<std::string, std::string>& GetInputOutputWithSameType()
W
Wilber 已提交
125
      const override {
126 127
    static std::unordered_map<std::string, std::string> m{{"X", /*->*/ "Out"}};
    return m;
W
Wilber 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  }
};

template <typename T>
class FlipOpGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> retv) const override {
    retv->SetType("flip");
    retv->SetInput("X", this->OutputGrad("Out"));
    retv->SetOutput("Out", this->InputGrad("X"));
    retv->SetAttrMap(this->Attrs());
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
149
namespace plat = paddle::platform;
W
Wilber 已提交
150 151 152 153 154 155 156 157
REGISTER_OPERATOR(flip, ops::FlipOp, ops::FlipOpMaker, ops::FlipOpInferVarType,
                  ops::FlipOpGradMaker<paddle::framework::OpDesc>,
                  ops::FlipOpGradMaker<paddle::imperative::OpBase>);
REGISTER_OP_CPU_KERNEL(
    flip, ops::FlipKernel<paddle::platform::CPUDeviceContext, float>,
    ops::FlipKernel<paddle::platform::CPUDeviceContext, double>,
    ops::FlipKernel<paddle::platform::CPUDeviceContext, int32_t>,
    ops::FlipKernel<paddle::platform::CPUDeviceContext, int64_t>,
158 159 160
    ops::FlipKernel<paddle::platform::CPUDeviceContext, bool>,
    ops::FlipKernel<paddle::platform::CPUDeviceContext, plat::complex<float>>,
    ops::FlipKernel<paddle::platform::CPUDeviceContext, plat::complex<double>>);
161 162 163 164 165 166 167

/* ==========================  register checkpoint ===========================*/
REGISTER_OP_VERSION(flip)
    .AddCheckpoint(
        R"ROC(Upgrade flip, add new attr [axis] and delete attr [dims].)ROC",
        paddle::framework::compatible::OpVersionDesc()
            .NewAttr("axis", "The added attr 'axis' doesn't set default value.",
168
                     paddle::none)
169
            .DeleteAttr("dims", "The attr 'dims' is deleted."));