pten_utils.cc 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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. */

#include <sstream>

#include "paddle/fluid/framework/pten_utils.h"
Z
Zeng Jinle 已提交
18
#include "paddle/pten/core/kernel_factory.h"
19 20

#include "paddle/fluid/framework/lod_tensor.h"
Z
Zeng Jinle 已提交
21
#include "paddle/fluid/framework/op_info.h"
22 23 24 25 26 27 28
#include "paddle/fluid/framework/selected_rows.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/string/string_helper.h"

namespace paddle {
namespace framework {

Z
Zeng Jinle 已提交
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
class KernelArgsNameMakerByOpProto : public KernelArgsNameMaker {
 public:
  explicit KernelArgsNameMakerByOpProto(
      const framework::proto::OpProto* op_proto)
      : op_proto_(op_proto) {
    PADDLE_ENFORCE_NOT_NULL(op_proto_, platform::errors::InvalidArgument(
                                           "Op proto cannot be nullptr."));
  }

  ~KernelArgsNameMakerByOpProto() {}

  const paddle::SmallVector<std::string>& GetInputArgsNames() override;
  const paddle::SmallVector<std::string>& GetOutputArgsNames() override;
  const paddle::SmallVector<std::string>& GetAttrsArgsNames() override;

  KernelSignature GetKernelSignature();

 private:
  DISABLE_COPY_AND_ASSIGN(KernelArgsNameMakerByOpProto);

 private:
  const framework::proto::OpProto* op_proto_;

  paddle::SmallVector<std::string> input_names_;
  paddle::SmallVector<std::string> output_names_;
  paddle::SmallVector<std::string> attr_names_;
};

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
OpKernelType TransPtenKernelKeyToOpKernelType(
    const pten::KernelKey& kernel_key) {
  proto::VarType::Type data_type =
      pten::TransToProtoVarType(kernel_key.dtype());
  platform::Place place = pten::TransToFluidPlace(kernel_key.backend());
  DataLayout data_layout = pten::TransToFluidDataLayout(kernel_key.layout());
  LibraryType library_type = LibraryType::kPlain;
  if (kernel_key.backend() == pten::Backend::MKLDNN) {
    library_type = LibraryType::kMKLDNN;
  } else if (kernel_key.backend() == pten::Backend::CUDNN) {
    library_type = LibraryType::kCUDNN;
  } else {
    // do nothing
  }
  // TODO(chenweihang): the customized_type_value is lost
  return OpKernelType(data_type, place, data_layout, library_type);
}

pten::KernelKey TransOpKernelTypeToPtenKernelKey(
    const OpKernelType& kernel_type) {
  pten::Backend backend = pten::TransToPtenBackend(kernel_type.place_);
  if (kernel_type.library_type_ == LibraryType::kMKLDNN) {
    backend = pten::Backend::MKLDNN;
  } else if (kernel_type.library_type_ == LibraryType::kCUDNN) {
    backend = pten::Backend::CUDNN;
  } else {
    // do
  }
  paddle::experimental::DataLayout layout =
      pten::TransToPtenDataLayout(kernel_type.data_layout_);
  paddle::experimental::DataType dtype =
      pten::TransToPtenDataType(kernel_type.data_type_);
  return pten::KernelKey(backend, layout, dtype);
}

92
KernelSignatureMap* KernelSignatureMap::kernel_signature_map_ = nullptr;
Z
Zeng Jinle 已提交
93
std::once_flag KernelSignatureMap::init_flag_;
94 95

KernelSignatureMap& KernelSignatureMap::Instance() {
Z
Zeng Jinle 已提交
96 97 98 99 100 101 102 103
  std::call_once(init_flag_, [] {
    kernel_signature_map_ = new KernelSignatureMap();
    for (const auto& pair : OpInfoMap::Instance().map()) {
      const auto& op_type = pair.first;
      const auto* op_proto = pair.second.proto_;
      if (pten::KernelFactory::Instance().HasCompatiblePtenKernel(op_type)) {
        KernelArgsNameMakerByOpProto maker(op_proto);
        VLOG(10) << "Register kernel signature for " << op_type;
Y
YuanRisheng 已提交
104 105 106 107
        auto success = kernel_signature_map_->map_
                           .emplace(pten::TransToPtenKernelName(op_type),
                                    std::move(maker.GetKernelSignature()))
                           .second;
Z
Zeng Jinle 已提交
108 109 110 111 112 113
        PADDLE_ENFORCE_EQ(
            success, true,
            platform::errors::PermissionDenied(
                "Kernel signature of the operator %s has been registered.",
                op_type));
      }
114
    }
Z
Zeng Jinle 已提交
115
  });
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
  return *kernel_signature_map_;
}

bool KernelSignatureMap::Has(const std::string& op_type) const {
  return map_.find(op_type) != map_.end();
}

const KernelSignature& KernelSignatureMap::Get(
    const std::string& op_type) const {
  auto it = map_.find(op_type);
  PADDLE_ENFORCE_NE(
      it, map_.end(),
      platform::errors::NotFound(
          "Operator `%s`'s kernel signature is not registered.", op_type));
  return it->second;
}

133 134 135 136 137 138
const paddle::SmallVector<std::string>&
KernelArgsNameMakerByOpProto::GetInputArgsNames() {
  for (int i = 0; i < op_proto_->inputs_size(); ++i) {
    auto& in = op_proto_->inputs()[i];
    auto& in_name = in.name();
    if ((in.has_extra() && in.extra()) || (in.has_quant() && in.quant())) {
139
      VLOG(3) << "Parse PtenKernel input: skip extra & quant input - "
140 141 142 143 144 145
              << in_name;
      continue;
    }
    // If contains dispensable input, we should override the
    // GetExpectedPtenKernelArgs method self
    if (in.has_dispensable() && in.dispensable()) {
146
      VLOG(3) << "Parse PtenKernel input: skip dispensable input - " << in_name;
147 148
      continue;
    }
149
    VLOG(3) << "Parse PtenKernel input: " << in_name;
150 151 152 153 154 155 156 157 158 159 160
    input_names_.emplace_back(in_name);
  }
  return input_names_;
}

const paddle::SmallVector<std::string>&
KernelArgsNameMakerByOpProto::GetOutputArgsNames() {
  for (int i = 0; i < op_proto_->outputs_size(); ++i) {
    auto& out = op_proto_->outputs()[i];
    auto& out_name = out.name();
    // TODO(chenweihang): outputs also need skip some cases
161
    VLOG(3) << "Parse PtenKernel output: " << out_name;
162 163 164 165 166 167 168 169 170 171 172 173 174
    output_names_.emplace_back(out_name);
  }
  return output_names_;
}

const paddle::SmallVector<std::string>&
KernelArgsNameMakerByOpProto::GetAttrsArgsNames() {
  for (int i = 0; i < op_proto_->attrs_size(); ++i) {
    auto& attr = op_proto_->attrs()[i];
    auto& attr_name = attr.name();
    if (attr_name == "use_mkldnn" || attr_name == "op_role" ||
        attr_name == "op_role_var" || attr_name == "op_namescope" ||
        attr_name == "op_callstack" || attr_name == "op_device") {
175
      VLOG(3) << "Parse PtenKernel attribute: skip needless attr - "
176 177 178 179 180
              << attr_name;
      continue;
    }
    if ((attr.has_extra() && attr.extra()) ||
        (attr.has_quant() && attr.quant())) {
181
      VLOG(3) << "Parse PtenKernel attribute: skip extra & quant attr - "
182 183 184
              << attr_name;
      continue;
    }
185
    VLOG(3) << "Parse PtenKernel attribute: " << attr_name;
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    attr_names_.emplace_back(attr_name);
  }

  return attr_names_;
}

KernelSignature KernelArgsNameMakerByOpProto::GetKernelSignature() {
  return KernelSignature(op_proto_->type(), GetInputArgsNames(),
                         GetAttrsArgsNames(), GetOutputArgsNames());
}

std::string KernelSignatureToString(const KernelSignature& signature) {
  std::stringstream os;
  os << "Kernel Signature - name: " << signature.name
     << "; inputs: " << string::join_strings(std::get<0>(signature.args), ", ")
     << "; attributes: "
     << string::join_strings(std::get<1>(signature.args), ", ") << "; outputs: "
     << string::join_strings(std::get<2>(signature.args), ", ");
  return os.str();
}

}  // namespace framework
}  // namespace paddle