op_meta_info.cc 13.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

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

Z
zyfncg 已提交
21
#include "glog/logging.h"
22 23
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/enforce.h"
24 25 26

namespace paddle {

27
PADDLE_API void AssignTensorImpl(const Tensor& src, Tensor* dst) {
28 29 30 31 32
  if (!src.initialized() || !dst->defined()) {
    VLOG(3) << "Custom operator assigns non-initialized tensor, this only "
               "happens when handling inplace optional inputs & outputs.";
    return;
  }
33 34
  PADDLE_ENFORCE_EQ(src.is_dense_tensor() && dst->is_dense_tensor(),
                    true,
35
                    phi::errors::Unavailable(
36 37 38 39
                        "Now only supported DenseTensor in Custom Operator."));
  PADDLE_ENFORCE_EQ(
      src.initialized(),
      true,
40
      phi::errors::Unavailable(
41 42 43
          "The Custom OpKernel calculate output is not initialized."));
  PADDLE_ENFORCE_EQ(dst->defined(),
                    true,
44
                    phi::errors::Unavailable(
45
                        "The Custom OpKernel origin output is not defined."));
46 47
  auto& dense_src = static_cast<const phi::DenseTensor&>(*src.impl());
  auto* dense_dst = static_cast<phi::DenseTensor*>(dst->impl().get());
48 49 50 51 52 53 54 55 56 57 58
  *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));
}

59 60
void CustomOpKernelContext::EmplaceBackInputs(
    const std::vector<Tensor>& inputs) {
61 62 63 64 65 66 67 68 69 70 71 72 73
  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));
}

74 75
void CustomOpKernelContext::EmplaceBackOutputs(
    const std::vector<Tensor>& outputs) {
76 77 78 79 80 81 82 83 84
  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));
85 86
  VLOG(7) << "attrs_ No." << attrs_.size() - 1
          << " has value of type: " << attrs_[attrs_.size() - 1].type().name();
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
}

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;
}

102 103 104 105
Tensor& CustomOpKernelContext::MutableInputAt(size_t idx) {
  return inputs_.at(idx);
}

106 107 108 109 110 111 112
paddle::optional<Tensor> CustomOpKernelContext::OptionalInputAt(size_t idx) {
  if (!inputs_.at(idx).is_initialized()) {
    return paddle::none;
  }
  return paddle::make_optional<paddle::Tensor>(inputs_.at(idx));
}

113 114 115 116 117 118 119 120 121 122 123 124
paddle::optional<std::vector<Tensor>>
CustomOpKernelContext::OptionalInputsBetween(size_t start, size_t end) {
  std::vector<Tensor> rlt;
  for (size_t i = start; i < end; ++i) {
    if (!inputs_.at(i).is_initialized()) {
      return paddle::none;
    }
    rlt.emplace_back(inputs_.at(i));
  }
  return paddle::make_optional<std::vector<Tensor>>(rlt);
}

125 126 127 128 129 130 131 132 133 134 135 136
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;
}

137 138 139 140 141 142 143 144 145
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;
}

146 147 148 149 150 151 152 153 154 155 156 157 158
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);
}

159 160
// handle inplace mechanism
// Find out non-inplace output tensors.
161
// TODO(HongyuJia): Add cache for inplace_tensor_map_ to optimize performance
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
void CustomOpKernelContext::MapPlainOutputs(
    const std::vector<std::string>& inputs,
    const std::vector<std::string>& outputs,
    const std::unordered_map<std::string, std::string>& inplace_map) {
  for (size_t in_idx = 0; in_idx < inputs.size(); ++in_idx) {
    auto& input = inputs[in_idx];
    if (inplace_map.find(input) == inplace_map.end()) {
      continue;
    }
    auto out_iter = find(outputs.begin(), outputs.end(), inplace_map.at(input));
    PADDLE_ENFORCE(
        out_iter != outputs.end(),
        phi::errors::NotFound("Can't find the mapped value of %s, please check "
                              "the input of `Inplace` again and make "
                              "sure you registered your op accurately. ",
                              input));
    inplace_tensor_map_[in_idx] = distance(outputs.begin(), out_iter);
  }
  for (size_t i = 0; i < outputs.size(); ++i) {
    if (std::any_of(
            inplace_tensor_map_.begin(),
            inplace_tensor_map_.end(),
            [i](std::unordered_map<size_t, size_t>::const_reference pair) {
              return pair.second == i;
            })) {
      continue;
    }
    size_t output_start_idx = output_range_[i].first;
    size_t output_end_idx = output_range_[i].second;
    for (size_t idx = output_start_idx; idx < output_end_idx; ++idx) {
      plain_outputs_.push_back(&outputs_[idx]);
    }
  }
  VLOG(4) << "Custom opertor update inplace input-output map successfully.";
}
// Assign input tensor to inplace output tensors.
void CustomOpKernelContext::AssignInplaceOutputs() {
  for (auto pair : inplace_tensor_map_) {
    size_t in_start_idx = input_range_[pair.first].first;
    size_t in_end_idx = input_range_[pair.first].second;
    size_t out_start_idx = output_range_[pair.second].first;
    size_t out_end_idx = output_range_[pair.second].second;
    size_t assign_tensor_size = in_end_idx - in_start_idx;
    PADDLE_ENFORCE(
        assign_tensor_size == out_end_idx - out_start_idx,
        phi::errors::OutOfRange("When assigning inplaced tensor, Input vector "
                                "size %d mismatch output vector size %d",
                                in_end_idx - in_start_idx,
                                out_end_idx - out_start_idx));
    for (size_t i = 0; i < assign_tensor_size; ++i) {
      AssignTensorImpl(inputs_[in_start_idx + i], &outputs_[out_start_idx + i]);
    }
214 215 216
    VLOG(4) << "Custom opertor update inplace input-output tensor "
               "successfully. Update map size = "
            << inplace_tensor_map_.size();
217 218 219 220 221 222 223 224 225
  }
}
std::vector<Tensor*>* CustomOpKernelContext::AllMutablePlainOutput() {
  return &plain_outputs_;
}
std::unordered_map<size_t, size_t>
CustomOpKernelContext::GetInplaceTensorMap() {
  return inplace_tensor_map_;
}
226 227 228 229 230 231 232 233 234 235
////////////////////// 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;
}
236 237 238 239
OpMetaInfo& OpMetaInfo::Attrs(std::vector<std::string>&& attrs) {
  attrs_ = std::forward<std::vector<std::string>>(attrs);
  return *this;
}
240
OpMetaInfo& OpMetaInfo::SetInplaceMap(
241 242 243
    std::unordered_map<std::string, std::string>&& inplace_map) {
  inplace_map_ =
      std::forward<std::unordered_map<std::string, std::string>>(inplace_map);
244 245 246
  for (const auto& pair : inplace_map_) {
    inplace_reverse_map_[pair.second] = pair.first;
  }
247 248
  return *this;
}
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
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 /////////////////

275 276
OpMetaInfoBuilder::OpMetaInfoBuilder(std::string&& name, size_t index) {
  // 1. member assign
277
  name_ = std::forward<std::string>(name);
278 279 280
  index_ = index;

  // 2. check and meta info build
281
  auto& info_vector = OpMetaInfoMap::Instance()[name_];
282 283
  // index check
  PADDLE_ENFORCE_EQ(
284 285
      info_vector.size(),
      index_,
286
      phi::errors::PreconditionNotMet(
287 288 289 290 291 292 293 294 295 296 297 298
          "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";
299
      break;
300
    default:
301
      PADDLE_THROW(phi::errors::InvalidArgument(
302 303 304 305
          "Not support index `%d` when construct OpMetaInfoBuilder, "
          "now only support `0, 1, 2`.",
          index_));
  }
306 307
  auto op_meta = OpMetaInfo(name_);
  info_vector.emplace_back(std::move(op_meta));
308
  // 3. get current info ptr
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
  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;
}

324 325
OpMetaInfoBuilder& OpMetaInfoBuilder::Attrs(std::vector<std::string>&& attrs) {
  info_ptr_->Attrs(std::forward<std::vector<std::string>>(attrs));
326 327 328
  return *this;
}

329
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInplaceMap(
330
    std::unordered_map<std::string, std::string>&& inplace_map) {
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
  const std::vector<std::string>& inputs =
      OpMetaInfoHelper::GetInputs(*info_ptr_);
  const std::vector<std::string>& outputs =
      OpMetaInfoHelper::GetOutputs(*info_ptr_);
  for (const auto& pair : inplace_map) {
    PADDLE_ENFORCE(
        std::find(inputs.begin(), inputs.end(), pair.first) != inputs.cend(),
        phi::errors::PreconditionNotMet(
            "The register of operator %s's `SetInplaceMap` failed. "
            "Please make sure: 1. Call `Inputs` and `Outputs` before "
            "`SetInplaceMap`; 2. The keys of inplace_map are inside `Inputs`",
            name_));
    PADDLE_ENFORCE(std::find(outputs.begin(), outputs.end(), pair.second) !=
                       outputs.cend(),
                   phi::errors::PreconditionNotMet(
                       "The register of operator %s's `SetInplaceMap` failed. "
                       "Please make sure: 1. Call `Inputs` and `Outputs` "
                       "before `SetInplaceMap`; 2. The values of inplace_map "
                       "are inside `Outputs`",
                       name_));
  }
352
  info_ptr_->SetInplaceMap(
353
      std::forward<std::unordered_map<std::string, std::string>>(inplace_map));
354 355 356
  return *this;
}

357
OpMetaInfoBuilder& OpMetaInfoBuilder::SetKernelFn(KernelFunc func) {
358 359 360 361
  info_ptr_->SetKernelFn(std::forward<KernelFunc>(func));
  return *this;
}

362
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInferShapeFn(InferShapeFunc func) {
363 364 365 366
  info_ptr_->SetInferShapeFn(std::forward<InferShapeFunc>(func));
  return *this;
}

367
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInferDtypeFn(InferDtypeFunc func) {
368
  PADDLE_ENFORCE_EQ(
369 370
      index_,
      0UL,
371
      phi::errors::Unimplemented(
372 373 374
          "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."));
375 376 377 378 379
  info_ptr_->SetInferDtypeFn(std::forward<InferDtypeFunc>(func));
  return *this;
}
}  // namespace paddle

380
#ifdef __cplusplus
381
extern "C" {
382
#endif
383

384 385
#ifndef _WIN32
// C-API to get global OpMetaInfoMap.
386 387 388
paddle::OpMetaInfoMap& PD_GetOpMetaInfoMap() {
  return paddle::OpMetaInfoMap::Instance();
}
389
#endif
390

391
#ifdef __cplusplus
392
}  // end extern "C"
393
#endif