broadcast_tensors_op.cc 7.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 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. */

15 16
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/fluid/framework/op_registry.h"
17
#include "paddle/fluid/framework/var_type_inference.h"
18 19
#include "paddle/phi/core/infermeta_utils.h"
#include "paddle/phi/infermeta/multiary.h"
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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

namespace paddle {
namespace operators {
using framework::Tensor;
using framework::DDim;

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

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    // Broadcast semantics enforces all input variables having the same
    // DataType/VarType
    // This condition is also checked during VarType Inference
    // Here we simply copy input type to output
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
  }
};

class BroadcastTensorsOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "A Varaible list. The shape and data type of the list elements"
             "should be consistent. Variable can be multi-dimensional Tensor"
             "or LoDTensor, and data types can be: bool, float16, float32, "
             "float64, int32, "
             "int64.")
        .AsDuplicable();
    AddOutput("Out",
              "the sum of input :code:`x`. its shape and data types are "
              "consistent with :code:`x`.")
        .AsDuplicable();
    AddComment(
        R"DOC(This OP is used to broadcast a vector of inputs 
                     with Tensor or LoDTensor type, following broadcast semantics.)DOC");
  }
};

class BroadcastTensorsOpVarTypeInference : public framework::VarTypeInference {
 public:
  void operator()(framework::InferVarTypeContext* ctx) const override {
    // We need at least two tensors to satisfy broadcast semantics
    size_t input_size = ctx->InputSize("X");
    PADDLE_ENFORCE_GT(
        input_size, 0,
        platform::errors::InvalidArgument(
            "BroadcastTensorsOp should have at least one input variables,"
            "but only received %d ",
            input_size));

    // BroadcastTensorsOp takes a vector of variables named "X"
    // Here we loop through input variables,
    // and check if their DataType/VarType are the same
    auto var_type = ctx->GetInputType("X", 0);
    auto data_type = ctx->GetInputDataType("X", 0);
    for (size_t ind = 1; ind < input_size; ind++) {
      auto cur_var_type = ctx->GetInputType("X", ind);
      PADDLE_ENFORCE_EQ(
          var_type, cur_var_type,
          platform::errors::InvalidArgument(
              "inputs to BroadcastTensorsOp should have the same variable type,"
              "but detected %d v.s %d ",
              framework::ToTypeName(var_type),
              framework::ToTypeName(cur_var_type)));

      auto cur_data_type = ctx->GetInputDataType("X", ind);
      PADDLE_ENFORCE_EQ(
          data_type, cur_data_type,
          platform::errors::InvalidArgument(
              "inputs to BroadcastTensorsOp should have the same data type,"
              "but detected %d v.s %d ",
              framework::ToTypeName(var_type),
              framework::ToTypeName(cur_var_type)));
    }

    // Outputs having the same DataType/VarType as inputs
    ctx->SetOutputType("Out", var_type, framework::ALL_ELEMENTS);
    ctx->SetOutputDataType("Out", data_type, framework::ALL_ELEMENTS);
  }
};

/* ------ BroadcastTensorsGradOp ------ */
class BroadcastTensorsGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasOutputs(framework::GradVarName("X")), "Output",
                   "X@grad", "broadcast_tensors");
    OP_INOUT_CHECK(ctx->HasInputs("X"), "Input", "X", "broadcast_tensors");
    OP_INOUT_CHECK(ctx->HasInputs(framework::GradVarName("Out")), "Input",
                   "Out@grad", "broadcast_tensors");

    const auto& forward_input_dims = ctx->GetInputsDim("X");
    ctx->SetOutputsDim(framework::GradVarName("X"), forward_input_dims);
    ctx->ShareAllLoD("X", /*->*/ framework::GradVarName("X"));
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
  }
};

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

  void Apply(GradOpPtr<T> grad_op) const override {
    grad_op->SetType("broadcast_tensors_grad");
    // We need "X" only for backward shape inference
    grad_op->SetInput("X", this->Input("X"));
    grad_op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    grad_op->SetOutput(framework::GradVarName("X"),
                       this->InputGrad("X", /* drop_empty_grad */ false));
    grad_op->SetAttrMap(this->Attrs());
  }
};

class BroadcastTensorsGradOpVarTypeInference
    : public framework::VarTypeInference {
 public:
  void operator()(framework::InferVarTypeContext* ctx) const override {
    auto var_type = ctx->GetInputType("X", 0);
    auto data_type = ctx->GetInputDataType("X", 0);

    ctx->SetOutputType(framework::GradVarName("X"), var_type,
                       framework::ALL_ELEMENTS);
    ctx->SetOutputDataType(framework::GradVarName("X"), data_type,
                           framework::ALL_ELEMENTS);
  }
};

DECLARE_NO_NEED_BUFFER_VARS_INFERER(BroadcastTensorsGradNoNeedBufVarsInferer,
                                    "X");

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

170
DECLARE_INFER_SHAPE_FUNCTOR(broadcast_tensors,
171
                            BroadcastTensorsInferShapeFunctor,
172
                            PD_INFER_META(phi::BroadcastTensorsInferMeta));
173

174 175 176 177
REGISTER_OPERATOR(broadcast_tensors, ops::BroadcastTensorsOp,
                  ops::BroadcastTensorsOpMaker,
                  ops::BroadcastTensorsGradOpMaker<paddle::framework::OpDesc>,
                  ops::BroadcastTensorsGradOpMaker<paddle::imperative::OpBase>,
178 179
                  ops::BroadcastTensorsOpVarTypeInference,
                  BroadcastTensorsInferShapeFunctor);
180 181 182 183

REGISTER_OPERATOR(broadcast_tensors_grad, ops::BroadcastTensorsGradOp,
                  ops::BroadcastTensorsGradOpVarTypeInference,
                  ops::BroadcastTensorsGradNoNeedBufVarsInferer);