meshgrid_op.cc 4.5 KB
Newer Older
S
suytingwan 已提交
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 <memory>
#include <string>
#include <vector>

19
#include "paddle/fluid/framework/infershape_utils.h"
H
hong 已提交
20 21
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
H
hong 已提交
22 23 24
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/multiary.h"

S
suytingwan 已提交
25 26 27 28 29 30 31 32
namespace paddle {
namespace operators {

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

 protected:
33
  phi::KernelKey GetExpectedKernelType(
S
suytingwan 已提交
34
      const framework::ExecutionContext& ctx) const override {
35
    auto inputs = ctx.MultiInput<phi::DenseTensor>("X");
S
suytingwan 已提交
36 37 38 39
    auto input_data_type = framework::proto::VarType::Type(0);
    bool flag = 0;
    for (auto* input : inputs) {
      if (input->IsInitialized() && input->numel() > 0) {
40
        input_data_type = framework::TransToProtoVarType(input->dtype());
S
suytingwan 已提交
41 42 43 44 45 46 47 48 49
        flag = 1;
        break;
      }
    }
    if (flag == 0) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "All Inputs of Meshgrid OP are Empty!"));
    }

50
    return phi::KernelKey(input_data_type, ctx.GetPlace());
S
suytingwan 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  }
};

class MeshgridOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "(Tensor, default Tensor<float>).").AsDuplicable();
    AddOutput("Out", "(Tensor, default Tensor<float>.)").AsDuplicable();

    AddComment(R"DOC(
Meshgrid Operator.
Take: N tensors, each of which can be either scalr or 1-dimensional vector, and create
N-dimensional grids.

Args:
66
  tensors (list of tensor): if the input k tensors has (N1,), (N2,),..., (Nk,), then
S
suytingwan 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  the output tensors are all of size (N1, N2, ...., Nk).

Example::
>>> x = fluid.data(name='x', shape=[10], dtype='float64')
>>> y = fluid.data(name='y', shape=[20], dtype='float64')
>>> grid_x, grid_y = fluid.layers.meshgrid([x, y])
>>> grid_x.shape
(10,20)
>>> grid_y.shape
(10,20)
)DOC");
  }
};

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

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
87 88
    PADDLE_ENFORCE_GT(ctx->Inputs(framework::GradVarName("Out")).size(),
                      1,
S
suytingwan 已提交
89
                      platform::errors::InvalidArgument(
K
Kqnonrime 已提交
90 91 92
                          "Number of Inputs(Out@Grad) should be larger than 1."
                          "But received Inputs(Out@Grad)' size = %d .",
                          ctx->Inputs(framework::GradVarName("Out")).size()));
S
suytingwan 已提交
93 94 95 96
    ctx->SetOutputsDim(framework::GradVarName("X"), ctx->GetInputsDim("X"));
  }

 protected:
97
  phi::KernelKey GetExpectedKernelType(
S
suytingwan 已提交
98
      const framework::ExecutionContext& ctx) const override {
99 100 101
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(
                              ctx, framework::GradVarName("Out")),
                          ctx.device_context().GetPlace());
S
suytingwan 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  }
};

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

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("meshgrid_grad");
    op->SetInput("X", this->Input("X"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X", false));
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
123 124
DECLARE_INFER_SHAPE_FUNCTOR(meshgrid,
                            MeshgridInferShapeFunctor,
H
hong 已提交
125
                            PD_INFER_META(phi::MeshgridInferMeta));
126 127 128
REGISTER_OPERATOR(meshgrid,
                  ops::MeshgridOp,
                  ops::MeshgridOpMaker,
S
suytingwan 已提交
129
                  ops::MeshgridGradOpMaker<paddle::framework::OpDesc>,
H
hong 已提交
130 131
                  ops::MeshgridGradOpMaker<paddle::imperative::OpBase>,
                  MeshgridInferShapeFunctor);
S
suytingwan 已提交
132
REGISTER_OPERATOR(meshgrid_grad, ops::MeshgridGradOp);