phi_utils.cc 12.8 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/phi_utils.h"

17 18
#include <sstream>

19
#include "paddle/fluid/framework/convert_utils.h"
20
#include "paddle/fluid/framework/lod_tensor.h"
Z
Zeng Jinle 已提交
21
#include "paddle/fluid/framework/op_info.h"
22
#include "paddle/fluid/framework/selected_rows_utils.h"
23
#include "paddle/fluid/string/string_helper.h"
24 25 26
#include "paddle/phi/core/compat/convert_utils.h"
#include "paddle/phi/core/compat/op_utils.h"
#include "paddle/phi/core/kernel_factory.h"
27
#include "paddle/phi/core/tensor_utils.h"
28
#include "paddle/phi/core/type_defs.h"
29 30 31 32

namespace paddle {
namespace framework {

Z
Zeng Jinle 已提交
33 34 35 36 37
class KernelArgsNameMakerByOpProto : public KernelArgsNameMaker {
 public:
  explicit KernelArgsNameMakerByOpProto(
      const framework::proto::OpProto* op_proto)
      : op_proto_(op_proto) {
38 39 40
    PADDLE_ENFORCE_NOT_NULL(
        op_proto_,
        platform::errors::InvalidArgument("Op proto cannot be nullptr."));
Z
Zeng Jinle 已提交
41 42 43 44
  }

  ~KernelArgsNameMakerByOpProto() {}

C
Chen Weihang 已提交
45 46 47
  const paddle::small_vector<const char*>& GetInputArgsNames() override;
  const paddle::small_vector<const char*>& GetOutputArgsNames() override;
  const paddle::small_vector<const char*>& GetAttrsArgsNames() override;
Z
Zeng Jinle 已提交
48

49
  phi::KernelSignature GetKernelSignature();
Z
Zeng Jinle 已提交
50 51 52 53 54 55 56

 private:
  DISABLE_COPY_AND_ASSIGN(KernelArgsNameMakerByOpProto);

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

C
Chen Weihang 已提交
57 58 59
  paddle::small_vector<const char*> input_names_;
  paddle::small_vector<const char*> output_names_;
  paddle::small_vector<const char*> attr_names_;
Z
Zeng Jinle 已提交
60 61
};

62
OpKernelType TransPhiKernelKeyToOpKernelType(const phi::KernelKey& kernel_key) {
63
  proto::VarType::Type data_type =
64
      paddle::framework::TransToProtoVarType(kernel_key.dtype());
65
  // no need to set current device id here
66
  platform::Place place = phi::TransToPhiPlace(kernel_key.backend(), false);
67
  DataLayout data_layout = kernel_key.layout();
68
  LibraryType library_type = LibraryType::kPlain;
69
  if (kernel_key.backend() == phi::Backend::ONEDNN) {
70
    library_type = LibraryType::kMKLDNN;
71
  } else if (kernel_key.backend() == phi::Backend::GPUDNN) {
72
    library_type = LibraryType::kCUDNN;
73 74
  } else if (kernel_key.backend() == phi::Backend::KPS) {
    library_type = LibraryType::kKP;
75 76 77 78 79 80 81
  } else {
    // do nothing
  }
  // TODO(chenweihang): the customized_type_value is lost
  return OpKernelType(data_type, place, data_layout, library_type);
}

82
phi::KernelKey TransOpKernelTypeToPhiKernelKey(
83
    const OpKernelType& kernel_type) {
84
  phi::Backend backend = phi::TransToPhiBackend(kernel_type.place_);
85 86 87 88 89
  switch (kernel_type.library_type_) {
    case LibraryType::kCUDNN:
      backend = phi::Backend::GPUDNN;
      break;
    case LibraryType::kMKLDNN:
90
      backend = phi::Backend::ONEDNN;
91 92 93 94 95 96
      break;
    case LibraryType::kKP:
      backend = phi::Backend::KPS;
      break;
    default:
      break;
97
  }
98 99
  return phi::KernelKey(backend,
                        kernel_type.data_layout_,
100
                        framework::TransToPhiDataType(kernel_type.data_type_));
101 102
}

H
HongyuJia 已提交
103
phi::KernelKey FallBackToCpu(const phi::KernelKey& kernel_key,
104
                             const framework::OperatorBase& op) {
105
#ifdef PADDLE_WITH_XPU
H
HongyuJia 已提交
106
  if (kernel_key.backend() == phi::Backend::XPU ||
107
      paddle::platform::is_in_xpu_black_list(op.Type())) {
108
    VLOG(3) << "phi missing XPU kernel: " << op.Type()
H
HongyuJia 已提交
109 110
            << ", expected_kernel_key:" << kernel_key
            << ", fallback to CPU one!";
111 112
    return phi::KernelKey(
        phi::Backend::CPU, kernel_key.layout(), kernel_key.dtype());
113 114 115
  }
#endif
#ifdef PADDLE_WITH_IPU
H
HongyuJia 已提交
116
  if (kernel_key.backend() == phi::Backend::IPU) {
117
    VLOG(3) << "phi missing IPU kernel: " << op.Type()
H
HongyuJia 已提交
118 119
            << ", expected_kernel_key:" << kernel_key
            << ", fallback to CPU one!";
120 121
    return phi::KernelKey(
        phi::Backend::CPU, kernel_key.layout(), kernel_key.dtype());
122 123 124
  }
#endif
#ifdef PADDLE_WITH_CUSTOM_DEVICE
H
HongyuJia 已提交
125
  auto place = phi::TransToPhiPlace(kernel_key.backend());
126 127 128 129 130
  bool is_custom_place = platform::is_custom_place(place);
  if (is_custom_place ||
      phi::backends::custom_device::is_in_custom_black_list(op.Type())) {
    std::string info = is_custom_place ? "phi missing " : "phi in black list ";
    VLOG(3) << info << place.GetDeviceType() << " kernel: " << op.Type()
H
HongyuJia 已提交
131 132
            << ", expected_kernel_key:" << kernel_key
            << ", fallback to CPU one!";
133 134
    return phi::KernelKey(
        phi::Backend::CPU, kernel_key.layout(), kernel_key.dtype());
135 136
  }
#endif
137
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
H
HongyuJia 已提交
138 139
  if (kernel_key.backend() == phi::Backend::GPU ||
      kernel_key.backend() == phi::Backend::GPUDNN) {
140 141 142 143 144
    PADDLE_THROW(
        phi::errors::NotFound("The kernel (%s) with key %s is not found and "
                              "GPU kernel cannot fallback to CPU one.",
                              op.Type(),
                              kernel_key));
145 146 147
  }
#endif

148
  return phi::KernelKey();
149 150
}

C
Chen Weihang 已提交
151
const paddle::small_vector<const char*>&
152 153 154 155 156 157 158 159
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())) {
      continue;
    }
    // If contains dispensable input, we should override the
160
    // OpArgumentMapping method self in phi/ops/compat dir
161 162 163
    if (in.has_dispensable() && in.dispensable()) {
      continue;
    }
164 165 166 167 168
    input_names_.emplace_back(in_name.c_str());
  }
  if (VLOG_IS_ON(10)) {
    std::ostringstream sout;
    sout << "PhiKernel inputs: ";
169 170
    std::copy(input_names_.begin(),
              input_names_.end(),
171 172
              std::ostream_iterator<const char*>(sout, ", "));
    VLOG(10) << sout.str();
173 174 175 176
  }
  return input_names_;
}

C
Chen Weihang 已提交
177
const paddle::small_vector<const char*>&
178 179 180 181
KernelArgsNameMakerByOpProto::GetOutputArgsNames() {
  for (int i = 0; i < op_proto_->outputs_size(); ++i) {
    auto& out = op_proto_->outputs()[i];
    auto& out_name = out.name();
182 183 184
    if ((out.has_extra() && out.extra()) || (out.has_quant() && out.quant())) {
      continue;
    }
185 186 187 188 189
    output_names_.emplace_back(out_name.c_str());
  }
  if (VLOG_IS_ON(10)) {
    std::ostringstream sout;
    sout << "PhiKernel outputs: ";
190 191
    std::copy(output_names_.begin(),
              output_names_.end(),
192 193
              std::ostream_iterator<const char*>(sout, ", "));
    VLOG(10) << sout.str();
194 195 196 197
  }
  return output_names_;
}

C
Chen Weihang 已提交
198
const paddle::small_vector<const char*>&
199 200 201 202
KernelArgsNameMakerByOpProto::GetAttrsArgsNames() {
  for (int i = 0; i < op_proto_->attrs_size(); ++i) {
    auto& attr = op_proto_->attrs()[i];
    auto& attr_name = attr.name();
203 204 205 206
    if (attr_name == "use_mkldnn" || attr_name == "use_cudnn" ||
        attr_name == "op_role" || attr_name == "op_role_var" ||
        attr_name == "op_namescope" || attr_name == "op_callstack" ||
        attr_name == "op_device") {
207 208 209 210 211 212
      continue;
    }
    if ((attr.has_extra() && attr.extra()) ||
        (attr.has_quant() && attr.quant())) {
      continue;
    }
213 214 215 216 217
    attr_names_.emplace_back(attr_name.c_str());
  }
  if (VLOG_IS_ON(10)) {
    std::ostringstream sout;
    sout << "PhiKernel attributes: ";
218 219
    std::copy(attr_names_.begin(),
              attr_names_.end(),
220 221
              std::ostream_iterator<const char*>(sout, ", "));
    VLOG(10) << sout.str();
222 223 224 225
  }
  return attr_names_;
}

226 227
phi::KernelSignature KernelArgsNameMakerByOpProto::GetKernelSignature() {
  return phi::KernelSignature(
228 229 230 231
      phi::TransToPhiKernelName(op_proto_->type()).c_str(),
      GetInputArgsNames(),
      GetAttrsArgsNames(),
      GetOutputArgsNames());
232 233
}

234 235 236 237 238 239 240
std::once_flag kernel_sig_map_init_flag;

void InitDefaultKernelSignatureMap() {
  std::call_once(kernel_sig_map_init_flag, [] {
    for (const auto& pair : paddle::framework::OpInfoMap::Instance().map()) {
      const auto& op_type = pair.first;
      const auto* op_proto = pair.second.proto_;
241
      if (phi::KernelFactory::Instance().HasCompatiblePhiKernel(op_type) &&
242 243
          op_proto) {
        paddle::framework::KernelArgsNameMakerByOpProto maker(op_proto);
244
        VLOG(10) << "Register `" << op_type << "` kernel signature:";
245
        phi::DefaultKernelSignatureMap::Instance().Insert(
246 247 248 249 250 251
            op_type, std::move(maker.GetKernelSignature()));
      }
    }
  });
}

252
static void SetAllocationForUninitializedDenseTensor(
253
    phi::DenseTensor* dense_tensor, const platform::Place& place) {
254 255
  int dtype_size = dense_tensor->dtype() == DataType::UNDEFINED
                       ? 0
256
                       : phi::SizeOf(dense_tensor->dtype());
257 258 259 260 261 262
  int64_t numels = product(dense_tensor->dims());
  numels = numels < 0 ? 0 : numels;
  auto tmp_allocation_ptr = memory::Alloc(place, numels * dtype_size);
  auto& deleter = tmp_allocation_ptr.get_deleter();
  auto* allocation_ptr = tmp_allocation_ptr.release();
  auto shared_allocation =
263
      std::shared_ptr<phi::Allocation>(allocation_ptr, deleter);
264 265 266 267

  dense_tensor->ResetHolder(shared_allocation);
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
phi::Scalar MakePhiScalarFromVar(const framework::Variable& variable) {
  auto expected_place = phi::TransToPhiPlace(phi::Backend::CPU);
  if (variable.IsType<phi::DenseTensor>()) {
    const auto& tensor = variable.Get<phi::DenseTensor>();
    PADDLE_ENFORCE_EQ(
        tensor.numel(),
        1UL,
        platform::errors::InvalidArgument("The DenseTensor used to construct "
                                          "the Scalar contains more than 1 "
                                          "value, it contains `%d` values.",
                                          tensor.numel()));
    if (!platform::is_same_place(tensor.place(), expected_place)) {
      phi::DenseTensor tmp_tensor;
      framework::TensorCopySync(tensor, expected_place, &tmp_tensor);
      return {tmp_tensor};
    } else {
      return {tensor};
    }
  } else {
    PADDLE_THROW(platform::errors::Unimplemented(
        "Unsupport casting input `%s` type to Scalar when call pt "
        "kernel.",
        framework::ToTypeName(variable.Type())));
  }
}

phi::IntArray MakePhiIntArrayFromVar(const framework::Variable& variable) {
  if (variable.IsType<phi::DenseTensor>()) {
    const auto& tensor = variable.Get<phi::DenseTensor>();
H
Huang Jiyi 已提交
297
    return phi::IntArray(tensor);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  } else {
    PADDLE_THROW(platform::errors::Unimplemented(
        "Unsupport casting input `%s` type to IntArray when call pt "
        "kernel.",
        framework::ToTypeName(variable.Type())));
  }
}

// TODO(chentianyu03): Inplace with IntArray constructor
phi::IntArray MakePhiIntArrayFromVarList(
    const std::vector<framework::Variable*>& variable_list) {
  if (variable_list.size() == 0) {
    return phi::IntArray();
  }
  auto expected_place = phi::TransToPhiPlace(phi::Backend::CPU);

  std::vector<int64_t> vector_data;
  vector_data.reserve(variable_list.size());

  for (auto* var : variable_list) {
318
    phi::DataType data_type;
319 320 321
    if (var->IsType<phi::DenseTensor>()) {
      const auto& tensor = var->Get<phi::DenseTensor>();
      data_type = tensor.dtype();
322
      if (data_type == phi::DataType::INT64) {
323 324 325 326 327 328 329 330 331
        const auto& tensor = var->Get<phi::DenseTensor>();
        if (tensor.IsInitialized() &&
            !platform::is_same_place(tensor.place(), expected_place)) {
          phi::DenseTensor tmp_tensor;
          framework::TensorCopySync(tensor, expected_place, &tmp_tensor);
          vector_data.push_back(*tmp_tensor.data<int64_t>());
        } else {
          vector_data.push_back(*tensor.data<int64_t>());
        }
332
      } else if (data_type == phi::DataType::INT32) {
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        const auto& tensor = var->Get<phi::DenseTensor>();
        if (tensor.IsInitialized() &&
            !platform::is_same_place(tensor.place(), expected_place)) {
          phi::DenseTensor tmp_tensor;
          framework::TensorCopySync(tensor, expected_place, &tmp_tensor);
          vector_data.push_back(*tmp_tensor.data<int32_t>());
        } else {
          vector_data.push_back(*tensor.data<int32_t>());
        }
      } else {
        PADDLE_THROW(phi::errors::InvalidArgument(
            "Data type error. When cast a LoDTensor to VectorTensor, "
            "the data type of LoDTensor must be int32 or int64, "
            "but now data type is %s.",
            data_type));
      }
    } else {
      PADDLE_THROW(phi::errors::Unimplemented(
          "Unsupport casting input `%s` type to VectorTensor when call pt "
          "kernel.",
          framework::ToTypeName(var->Type())));
    }
  }

  phi::IntArray result{vector_data};
  result.SetFromTensor(true);

  return result;
}

363 364
}  // namespace framework
}  // namespace paddle