op_meta_info.cc 8.4 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
#include "paddle/phi/api/ext/op_meta_info.h"
16 17 18 19 20 21

#include <string>
#include <unordered_map>
#include <vector>

#include "paddle/fluid/framework/custom_operator.h"
22 23
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/enforce.h"
24 25 26

namespace paddle {

27 28 29
PADDLE_API void AssignTensorImpl(const Tensor& src, Tensor* dst) {
  PADDLE_ENFORCE_EQ(src.is_dense_tensor() && dst->is_dense_tensor(),
                    true,
30
                    phi::errors::Unavailable(
31 32 33 34
                        "Now only supported DenseTensor in Custom Operator."));
  PADDLE_ENFORCE_EQ(
      src.initialized(),
      true,
35
      phi::errors::Unavailable(
36 37 38
          "The Custom OpKernel calculate output is not initialized."));
  PADDLE_ENFORCE_EQ(dst->defined(),
                    true,
39
                    phi::errors::Unavailable(
40
                        "The Custom OpKernel origin output is not defined."));
41 42
  auto& dense_src = static_cast<const phi::DenseTensor&>(*src.impl());
  auto* dense_dst = static_cast<phi::DenseTensor*>(dst->impl().get());
43 44 45 46 47 48 49 50 51 52 53
  *dense_dst = dense_src;
}

////////////////////// Kernel Context //////////////////////

void CustomOpKernelContext::EmplaceBackInput(Tensor&& input) {
  size_t index = inputs_.size();
  inputs_.emplace_back(input);
  input_range_.emplace_back(std::make_pair(index, index + 1));
}

54 55
void CustomOpKernelContext::EmplaceBackInputs(
    const std::vector<Tensor>& inputs) {
56 57 58 59 60 61 62 63 64 65 66 67 68
  size_t index = inputs_.size();
  input_range_.emplace_back(std::make_pair(index, index + inputs.size()));
  inputs_.insert(inputs_.end(),
                 std::make_move_iterator(inputs.begin()),
                 std::make_move_iterator(inputs.end()));
}

void CustomOpKernelContext::EmplaceBackOutput(Tensor&& output) {
  size_t index = outputs_.size();
  outputs_.emplace_back(output);
  output_range_.emplace_back(std::make_pair(index, index + 1));
}

69 70
void CustomOpKernelContext::EmplaceBackOutputs(
    const std::vector<Tensor>& outputs) {
71 72 73 74 75 76 77 78 79
  size_t index = outputs_.size();
  output_range_.emplace_back(std::make_pair(index, index + outputs.size()));
  outputs_.insert(outputs_.end(),
                  std::make_move_iterator(outputs.begin()),
                  std::make_move_iterator(outputs.end()));
}

void CustomOpKernelContext::EmplaceBackAttr(paddle::any attr) {
  attrs_.emplace_back(std::move(attr));
80 81
  VLOG(7) << "attrs_ No." << attrs_.size() - 1
          << " has value of type: " << attrs_[attrs_.size() - 1].type().name();
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
}

const Tensor& CustomOpKernelContext::InputAt(size_t idx) const {
  return inputs_.at(idx);
}

std::vector<Tensor> CustomOpKernelContext::InputsBetween(size_t start,
                                                         size_t end) const {
  std::vector<Tensor> rlt;
  for (size_t i = start; i < end; ++i) {
    rlt.emplace_back(inputs_.at(i));
  }
  return rlt;
}

Tensor* CustomOpKernelContext::MutableOutputAt(size_t idx) {
  return &(outputs_.at(idx));
}
std::vector<Tensor*> CustomOpKernelContext::MutableOutputBetweeen(size_t start,
                                                                  size_t end) {
  std::vector<Tensor*> rlt;
  for (size_t i = start; i < end; ++i) {
    rlt.emplace_back(&(outputs_.at(i)));
  }
  return rlt;
}

109 110 111 112 113 114 115 116 117
std::vector<Tensor> CustomOpKernelContext::OutputsBetweeen(size_t start,
                                                           size_t end) {
  std::vector<Tensor> rlt;
  for (size_t i = start; i < end; ++i) {
    rlt.emplace_back(outputs_.at(i));
  }
  return rlt;
}

118 119 120 121 122 123 124 125 126 127 128 129 130
std::vector<Tensor>* CustomOpKernelContext::AllMutableOutput() {
  return &outputs_;
}

const std::pair<size_t, size_t>& CustomOpKernelContext::InputRangeAt(
    size_t idx) const {
  return input_range_.at(idx);
}
const std::pair<size_t, size_t>& CustomOpKernelContext::OutputRangeAt(
    size_t idx) const {
  return output_range_.at(idx);
}

131 132 133 134 135 136 137 138 139 140
////////////////////// Op Meta Info //////////////////////

OpMetaInfo& OpMetaInfo::Inputs(std::vector<std::string>&& inputs) {
  inputs_ = std::forward<std::vector<std::string>>(inputs);
  return *this;
}
OpMetaInfo& OpMetaInfo::Outputs(std::vector<std::string>&& outputs) {
  outputs_ = std::forward<std::vector<std::string>>(outputs);
  return *this;
}
141 142 143 144
OpMetaInfo& OpMetaInfo::Attrs(std::vector<std::string>&& attrs) {
  attrs_ = std::forward<std::vector<std::string>>(attrs);
  return *this;
}
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 170
OpMetaInfo& OpMetaInfo::SetKernelFn(KernelFunc&& func) {
  kernel_fn_ = std::forward<KernelFunc>(func);
  return *this;
}
OpMetaInfo& OpMetaInfo::SetInferShapeFn(InferShapeFunc&& func) {
  infer_shape_fn_ = std::forward<InferShapeFunc>(func);
  return *this;
}
OpMetaInfo& OpMetaInfo::SetInferDtypeFn(InferDtypeFunc&& func) {
  infer_dtype_fn_ = std::forward<InferDtypeFunc>(func);
  return *this;
}

//////////////// Op Meta Info Map /////////////////

std::vector<OpMetaInfo>& OpMetaInfoMap::operator[](const std::string& name) {
  return map_[name];
}

const std::unordered_map<std::string, std::vector<OpMetaInfo>>&
OpMetaInfoMap::GetMap() const {
  return map_;
}

//////////////// Op Meta Info Builder /////////////////

171 172
OpMetaInfoBuilder::OpMetaInfoBuilder(std::string&& name, size_t index) {
  // 1. member assign
173
  name_ = std::forward<std::string>(name);
174 175 176
  index_ = index;

  // 2. check and meta info build
177
  auto& info_vector = OpMetaInfoMap::Instance()[name_];
178 179
  // index check
  PADDLE_ENFORCE_EQ(
180 181
      info_vector.size(),
      index_,
182
      phi::errors::PreconditionNotMet(
183 184 185 186 187 188 189 190 191 192 193 194 195
          "The operator %s's meta info register failed. "
          "Please make sure you call marcos as order `PD_BUILD_OP`, "
          "`PD_BUILD_GRAD_OP`, `PD_BUILD_DOUBLE_GRAD_OP`.",
          name_));
  switch (index_) {
    case 0:
      break;
    case 1:
      name_ = name_ + "_grad";
      break;
    case 2:
      name_ = name_ + "_grad_grad";
    default:
196
      PADDLE_THROW(phi::errors::InvalidArgument(
197 198 199 200
          "Not support index `%d` when construct OpMetaInfoBuilder, "
          "now only support `0, 1, 2`.",
          index_));
  }
201 202
  auto op_meta = OpMetaInfo(name_);
  info_vector.emplace_back(std::move(op_meta));
203
  // 3. get current info ptr
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  info_ptr_ = &(info_vector.back());
}

OpMetaInfoBuilder& OpMetaInfoBuilder::Inputs(
    std::vector<std::string>&& inputs) {
  info_ptr_->Inputs(std::forward<std::vector<std::string>>(inputs));
  return *this;
}

OpMetaInfoBuilder& OpMetaInfoBuilder::Outputs(
    std::vector<std::string>&& outputs) {
  info_ptr_->Outputs(std::forward<std::vector<std::string>>(outputs));
  return *this;
}

219 220 221 222 223
OpMetaInfoBuilder& OpMetaInfoBuilder::Attrs(std::vector<std::string>&& attrs) {
  info_ptr_->Attrs(std::forward<std::vector<std::string>>(attrs));
  return *this;
}

224
OpMetaInfoBuilder& OpMetaInfoBuilder::SetKernelFn(KernelFunc func) {
225 226 227 228
  info_ptr_->SetKernelFn(std::forward<KernelFunc>(func));
  return *this;
}

229
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInferShapeFn(InferShapeFunc func) {
230 231 232 233
  info_ptr_->SetInferShapeFn(std::forward<InferShapeFunc>(func));
  return *this;
}

234
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInferDtypeFn(InferDtypeFunc func) {
235
  PADDLE_ENFORCE_EQ(
236 237
      index_,
      0UL,
238
      phi::errors::Unimplemented(
239 240 241
          "Currently, the InferDtypeFn setting of Grad Op is not supported, "
          "And backward Tensor `X@GRAD` will use the dtype of forward Tensor "
          "`X` by default."));
242 243 244 245 246 247 248 249 250 251 252
  info_ptr_->SetInferDtypeFn(std::forward<InferDtypeFunc>(func));
  return *this;
}

/////////////////////// Op register API /////////////////////////

void RegisterAllCustomOperator() {
  auto& op_meta_info_map = OpMetaInfoMap::Instance();
  framework::RegisterOperatorWithMetaInfoMap(op_meta_info_map);
}

253 254 255
void LoadCustomOperatorLib(const std::string& dso_name) {
  paddle::framework::LoadOpMetaInfoAndRegisterOp(dso_name);
}
256 257
}  // namespace paddle

258
#ifdef __cplusplus
259
extern "C" {
260
#endif
261

262 263
#ifndef _WIN32
// C-API to get global OpMetaInfoMap.
264 265 266
paddle::OpMetaInfoMap& PD_GetOpMetaInfoMap() {
  return paddle::OpMetaInfoMap::Instance();
}
267
#endif
268

269
#ifdef __cplusplus
270
}  // end extern "C"
271
#endif