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

#include <string>
#include <unordered_map>
19
#include <unordered_set>
20 21
#include <vector>

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

namespace paddle {

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
// remove leading and tailing spaces
std::string trim_spaces(const std::string& str) {
  const char* p = str.c_str();
  while (*p != 0 && isspace(*p)) {
    p++;
  }
  size_t len = strlen(p);
  while (len > 0 && isspace(p[len - 1])) {
    len--;
  }
  return std::string(p, len);
}

std::vector<std::string> ParseAttrStr(const std::string& attr) {
  auto split_pos = attr.find_first_of(":");
  PADDLE_ENFORCE_NE(split_pos,
                    std::string::npos,
                    phi::errors::InvalidArgument(
                        "Invalid attribute string format. Attribute string "
                        "format is `<name>:<type>`."));

  std::vector<std::string> rlt;
  // 1. name
  rlt.emplace_back(trim_spaces(attr.substr(0, split_pos)));
  // 2. type
  rlt.emplace_back(trim_spaces(attr.substr(split_pos + 1)));

  VLOG(3) << "attr name: " << rlt[0] << ", attr type str: " << rlt[1];

  return rlt;
}

60
PADDLE_API void AssignTensorImpl(const Tensor& src, Tensor* dst) {
61 62 63 64 65
  if (!src.initialized() || !dst->defined()) {
    VLOG(3) << "Custom operator assigns non-initialized tensor, this only "
               "happens when handling inplace optional inputs & outputs.";
    return;
  }
66 67
  PADDLE_ENFORCE_EQ(src.is_dense_tensor() && dst->is_dense_tensor(),
                    true,
68
                    phi::errors::Unavailable(
69 70 71 72
                        "Now only supported DenseTensor in Custom Operator."));
  PADDLE_ENFORCE_EQ(
      src.initialized(),
      true,
73
      phi::errors::Unavailable(
74 75 76
          "The Custom OpKernel calculate output is not initialized."));
  PADDLE_ENFORCE_EQ(dst->defined(),
                    true,
77
                    phi::errors::Unavailable(
78
                        "The Custom OpKernel origin output is not defined."));
79 80
  auto& dense_src = static_cast<const phi::DenseTensor&>(*src.impl());
  auto* dense_dst = static_cast<phi::DenseTensor*>(dst->impl().get());
81 82 83 84 85 86 87 88
  *dense_dst = dense_src;
}

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

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

92 93
void CustomOpKernelContext::EmplaceBackInputs(
    const std::vector<Tensor>& inputs) {
94
  size_t index = inputs_.size();
95
  input_range_.emplace_back(index, index + inputs.size());
96 97 98 99 100 101 102 103
  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);
104
  output_range_.emplace_back(index, index + 1);
105 106
}

107 108
void CustomOpKernelContext::EmplaceBackOutputs(
    const std::vector<Tensor>& outputs) {
109
  size_t index = outputs_.size();
110
  output_range_.emplace_back(index, index + outputs.size());
111 112 113 114 115 116 117
  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));
118 119
  VLOG(7) << "attrs_ No." << attrs_.size() - 1
          << " has value of type: " << attrs_[attrs_.size() - 1].type().name();
120 121
}

122 123 124 125 126
void CustomOpKernelContext::EmplaceBackAttrs(
    const std::vector<paddle::any>& attrs) {
  attrs_ = std::move(attrs);
}

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

140 141 142 143
const std::vector<paddle::any>& CustomOpKernelContext::Attrs() const {
  return attrs_;
}

144 145 146 147
Tensor& CustomOpKernelContext::MutableInputAt(size_t idx) {
  return inputs_.at(idx);
}

148 149 150 151
std::vector<Tensor>* CustomOpKernelContext::AllMutableInput() {
  return &inputs_;
}

152 153 154 155 156 157 158
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));
}

159 160 161 162 163 164 165 166 167 168 169 170
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);
}

171 172 173
Tensor* CustomOpKernelContext::MutableOutputAt(size_t idx) {
  return &(outputs_.at(idx));
}
C
co63oc 已提交
174 175
std::vector<Tensor*> CustomOpKernelContext::MutableOutputBetween(size_t start,
                                                                 size_t end) {
176 177 178 179 180 181 182
  std::vector<Tensor*> rlt;
  for (size_t i = start; i < end; ++i) {
    rlt.emplace_back(&(outputs_.at(i)));
  }
  return rlt;
}

C
co63oc 已提交
183 184
std::vector<Tensor> CustomOpKernelContext::OutputsBetween(size_t start,
                                                          size_t end) {
185 186 187 188 189 190 191
  std::vector<Tensor> rlt;
  for (size_t i = start; i < end; ++i) {
    rlt.emplace_back(outputs_.at(i));
  }
  return rlt;
}

192 193 194 195 196 197 198 199 200 201 202 203 204
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);
}

205 206 207 208 209 210 211 212 213 214
const std::vector<std::pair<size_t, size_t>>&
CustomOpKernelContext::InputRange() {
  return input_range_;
}

const std::vector<std::pair<size_t, size_t>>&
CustomOpKernelContext::OutputRange() {
  return output_range_;
}

215
void CustomOpKernelContext::ConstructInplaceIndex(
216 217 218
    const std::vector<std::string>& inputs,
    const std::vector<std::string>& outputs,
    const std::unordered_map<std::string, std::string>& inplace_map) {
219 220 221 222 223
  // Cache inplace indices.
  if (inplace_map.empty() || !inplace_idx_map_.empty()) {
    VLOG(4) << "Custom opertor ConstructInplaceIndex no need to recompute.";
    return;
  }
224 225 226 227 228 229
  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));
230 231 232
    PADDLE_ENFORCE_NE(
        out_iter,
        outputs.end(),
233 234 235 236
        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));
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    size_t out_idx = distance(outputs.begin(), out_iter);
    inplace_idx_map_[in_idx] = out_idx;
    inplace_reverse_idx_map_[out_idx] = in_idx;
  }
  VLOG(4) << "Custom opertor update inplace input-output map successfully.";
}

// Find out non-inplace output tensors.
void CustomOpKernelContext::UpdatePlainOutputs(
    const std::vector<std::string>& inputs,
    const std::vector<std::string>& outputs,
    const std::unordered_map<std::string, std::string>& inplace_map) {
  // Cache plain outputs vector.
  if (!plain_outputs_.empty()) {
    VLOG(4) << "Custom opertor UpdatePlainOutputs no need to recompute.";
    return;
253
  }
254
  ConstructInplaceIndex(inputs, outputs, inplace_map);
255
  for (size_t i = 0; i < outputs.size(); ++i) {
256
    if (inplace_reverse_idx_map_.find(i) != inplace_reverse_idx_map_.end()) {
257 258 259 260 261 262 263 264
      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]);
    }
  }
265
  VLOG(4) << "Custom opertor update plain outputs map successfully.";
266
}
267

268 269
// Assign input tensor to inplace output tensors.
void CustomOpKernelContext::AssignInplaceOutputs() {
270
  for (auto pair : inplace_idx_map_) {
271 272 273 274 275
    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;
276 277 278
    PADDLE_ENFORCE_EQ(
        assign_tensor_size,
        out_end_idx - out_start_idx,
279 280 281 282 283 284 285
        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]);
    }
286 287
    VLOG(4) << "Custom opertor update inplace input-output tensor "
               "successfully. Update map size = "
288
            << inplace_idx_map_.size();
289 290
  }
}
291

292 293 294
std::vector<Tensor*>* CustomOpKernelContext::AllMutablePlainOutput() {
  return &plain_outputs_;
}
295 296 297 298 299

std::unordered_map<size_t, size_t> CustomOpKernelContext::GetInplaceIndexMap() {
  return inplace_idx_map_;
}

300
std::unordered_map<size_t, size_t>
301 302
CustomOpKernelContext::GetInplaceReverseIndexMap() {
  return inplace_reverse_idx_map_;
303
}
304 305 306 307 308 309 310 311 312 313
////////////////////// 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;
}
314 315 316 317
OpMetaInfo& OpMetaInfo::Attrs(std::vector<std::string>&& attrs) {
  attrs_ = std::forward<std::vector<std::string>>(attrs);
  return *this;
}
318
OpMetaInfo& OpMetaInfo::SetInplaceMap(
319 320 321
    std::unordered_map<std::string, std::string>&& inplace_map) {
  inplace_map_ =
      std::forward<std::unordered_map<std::string, std::string>>(inplace_map);
322 323 324
  for (const auto& pair : inplace_map_) {
    inplace_reverse_map_[pair.second] = pair.first;
  }
325 326
  return *this;
}
327 328 329 330 331 332 333 334 335 336 337 338 339
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;
}

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
//////////////// Op Meta Info Helper /////////////////
const std::string& OpMetaInfoHelper::GetOpName(const paddle::OpMetaInfo& info) {
  return info.name_;
}
const std::vector<std::string>& OpMetaInfoHelper::GetInputs(
    const paddle::OpMetaInfo& info) {
  return info.inputs_;
}
const std::vector<std::string>& OpMetaInfoHelper::GetOutputs(
    const paddle::OpMetaInfo& info) {
  return info.outputs_;
}
const std::vector<std::string>& OpMetaInfoHelper::GetAttrs(
    const paddle::OpMetaInfo& info) {
  return info.attrs_;
}
const std::unordered_map<std::string, std::string>&
OpMetaInfoHelper::GetInplaceMap(const paddle::OpMetaInfo& info) {
  return info.inplace_map_;
}
const std::unordered_map<std::string, std::string>&
OpMetaInfoHelper::GetInplaceReverseMap(const paddle::OpMetaInfo& info) {
  return info.inplace_reverse_map_;
}
const KernelFunc& OpMetaInfoHelper::GetKernelFn(
    const paddle::OpMetaInfo& info) {
  return info.kernel_fn_;
}
const InferShapeFunc& OpMetaInfoHelper::GetInferShapeFn(
    const paddle::OpMetaInfo& info) {
  return info.infer_shape_fn_;
}
const InferDtypeFunc& OpMetaInfoHelper::GetInferDtypeFn(
    const paddle::OpMetaInfo& info) {
  return info.infer_dtype_fn_;
}

377 378 379 380 381 382 383 384 385 386 387 388 389
//////////////// 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 /////////////////

390 391
OpMetaInfoBuilder::OpMetaInfoBuilder(std::string&& name, size_t index) {
  // 1. member assign
392
  name_ = std::forward<std::string>(name);
393 394 395
  index_ = index;

  // 2. check and meta info build
396
  auto& info_vector = OpMetaInfoMap::Instance()[name_];
397 398
  // index check
  PADDLE_ENFORCE_EQ(
399 400
      info_vector.size(),
      index_,
401
      phi::errors::PreconditionNotMet(
402 403 404 405 406 407 408 409 410 411 412 413
          "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";
414
      break;
415
    default:
416
      PADDLE_THROW(phi::errors::InvalidArgument(
417 418 419 420
          "Not support index `%d` when construct OpMetaInfoBuilder, "
          "now only support `0, 1, 2`.",
          index_));
  }
421 422
  auto op_meta = OpMetaInfo(name_);
  info_vector.emplace_back(std::move(op_meta));
423
  // 3. get current info ptr
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  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;
}

439
OpMetaInfoBuilder& OpMetaInfoBuilder::Attrs(std::vector<std::string>&& attrs) {
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  const std::unordered_set<std::string> custom_attrs_type(
      {"bool",
       "int",
       "float",
       "int64_t",
       "std::string",
       "std::vector<int>",
       "std::vector<float>",
       "std::vector<int64_t>",
       "std::vector<std::string>"});
  for (const auto& attr : attrs) {
    auto attr_type_str = ParseAttrStr(attr)[1];
    if (custom_attrs_type.find(attr_type_str) == custom_attrs_type.end()) {
      PADDLE_THROW(phi::errors::Unimplemented(
          "Unsupported `%s` type value as custom attribute now. "
          "Supported data types include `bool`, `int`, `float`, "
          "`int64_t`, `std::string`, `std::vector<int>`, "
          "`std::vector<float>`, `std::vector<int64_t>`, "
          "`std::vector<std::string>`, "
          "Please check whether the attribute data type and "
          "data type string are matched.",
          attr_type_str));
    }
  }
464
  info_ptr_->Attrs(std::forward<std::vector<std::string>>(attrs));
465 466 467
  return *this;
}

468
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInplaceMap(
469
    std::unordered_map<std::string, std::string>&& inplace_map) {
470 471 472 473 474
  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) {
475 476 477
    PADDLE_ENFORCE_NE(
        std::find(inputs.begin(), inputs.end(), pair.first),
        inputs.cend(),
478 479 480 481 482
        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_));
483 484 485 486 487 488 489 490 491
    PADDLE_ENFORCE_NE(
        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_));
492
  }
493
  info_ptr_->SetInplaceMap(
494
      std::forward<std::unordered_map<std::string, std::string>>(inplace_map));
495 496 497
  return *this;
}

498
OpMetaInfoBuilder& OpMetaInfoBuilder::SetKernelFn(KernelFunc func) {
499 500 501 502
  info_ptr_->SetKernelFn(std::forward<KernelFunc>(func));
  return *this;
}

503
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInferShapeFn(InferShapeFunc func) {
504 505 506 507
  info_ptr_->SetInferShapeFn(std::forward<InferShapeFunc>(func));
  return *this;
}

508
OpMetaInfoBuilder& OpMetaInfoBuilder::SetInferDtypeFn(InferDtypeFunc func) {
509 510 511 512 513
  info_ptr_->SetInferDtypeFn(std::forward<InferDtypeFunc>(func));
  return *this;
}
}  // namespace paddle

514
#ifdef __cplusplus
515
extern "C" {
516
#endif
517

518 519
#ifndef _WIN32
// C-API to get global OpMetaInfoMap.
520 521 522
paddle::OpMetaInfoMap& PD_GetOpMetaInfoMap() {
  return paddle::OpMetaInfoMap::Instance();
}
523
#endif
524

525
#ifdef __cplusplus
526
}  // end extern "C"
527
#endif