prepared_operator.cc 17.1 KB
Newer Older
J
Jiabin Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 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 "paddle/fluid/imperative/prepared_operator.h"
16

17
#include "paddle/fluid/framework/data_type_transform.h"
18
#include "paddle/fluid/framework/details/nan_inf_utils.h"
19
#include "paddle/fluid/imperative/infer_shape_context.h"
20
#include "paddle/fluid/imperative/tracer.h"
21
#include "paddle/pten/common/scalar.h"
22
#include "paddle/pten/common/scalar_array.h"
23
#include "paddle/utils/small_vector.h"
Q
QingshuChen 已提交
24
#ifdef PADDLE_WITH_XPU
25
#include "paddle/fluid/platform/device/xpu/xpu_op_list.h"
Q
QingshuChen 已提交
26
#endif
L
Liu-xiandong 已提交
27
#include "paddle/fluid/framework/library_type.h"
28
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
29
#include "paddle/fluid/platform/profiler.h"
30

31
DECLARE_bool(check_nan_inf);
32
DECLARE_bool(benchmark);
F
Feng Xing 已提交
33
DECLARE_bool(run_kp_kernel);
34

J
Jiabin Yang 已提交
35 36 37
namespace paddle {
namespace imperative {

38 39 40 41 42 43 44 45 46 47
const std::shared_ptr<VariableWrapper>& GetVariableWrapper(
    const std::shared_ptr<paddle::imperative::VarBase>& var) {
  return var->SharedVar();
}

const std::shared_ptr<VariableWrapper>& GetVariableWrapper(
    const std::shared_ptr<VariableWrapper>& var) {
  return var;
}

J
Jiabin Yang 已提交
48 49 50
const framework::Tensor* GetTensorFromVar(const framework::Variable& var) {
  if (var.IsType<framework::LoDTensor>()) {
    return &(var.Get<framework::LoDTensor>());
51 52
  } else if (var.IsType<pten::SelectedRows>()) {
    return &(var.Get<pten::SelectedRows>().value());
J
Jiabin Yang 已提交
53 54 55 56 57
  } else {
    return nullptr;
  }
}

58
template <typename VarType>
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
static void HandleComplexGradToRealGrad(const NameVarMap<VarType>& outs) {
  for (auto& pair : outs) {
    for (auto& var : pair.second) {
      if (var == nullptr) {
        continue;
      }
      if (var->ForwardDataType() ==
          static_cast<framework::proto::VarType::Type>(-1)) {
        VLOG(6) << "Var (" << var->Name()
                << ")'s forward data type is not set.";
        continue;
      }
      if (!framework::IsComplexType(var->DataType()) ||
          framework::IsComplexType(var->ForwardDataType())) {
        continue;
      }
      const auto* tensor = GetTensorFromVar(var->Var());
J
Jiabin Yang 已提交
76
      if (tensor && tensor->IsInitialized()) {
77 78 79 80 81 82 83 84
        VLOG(6) << "Transform " << framework::DataTypeToString(var->DataType())
                << " var `" << var->Name() << "` to "
                << framework::DataTypeToString(var->ForwardDataType())
                << " real var in dynamic graph.";
        framework::Tensor out;
        framework::TransComplexToReal(var->ForwardDataType(), var->DataType(),
                                      *tensor, &out);
        SetTensorToVariable(var->Var(), out, var->MutableVar());
J
Jiabin Yang 已提交
85 86 87 88 89 90 91
      }
    }
  }
}

PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
92
                       const framework::OpKernelType& kernel_type,
93
                       const framework::OperatorWithKernel::OpKernelFunc& func,
94
                       platform::DeviceContext* dev_ctx)
95 96 97 98 99 100
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(func),
      dev_ctx_(dev_ctx) {}

101 102 103 104 105 106 107 108 109 110 111 112 113
PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
                       const framework::OpKernelType& kernel_type,
                       const framework::KernelSignature& kernel_signature,
                       const pten::Kernel& pt_kernel,
                       platform::DeviceContext* dev_ctx)
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(nullptr),
      dev_ctx_(dev_ctx),
      run_pten_kernel_(true),
      pt_kernel_signature_(kernel_signature),
114
      pt_kernel_(pt_kernel) {}
115

116 117 118 119 120
template <typename VarType>
PreparedOp PrepareImpl(const NameVarMap<VarType>& ins,
                       const NameVarMap<VarType>& outs,
                       const framework::OperatorWithKernel& op,
                       const platform::Place& place,
121
                       const framework::AttributeMap& attrs,
122
                       const framework::AttributeMap& default_attrs) {
123
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
124
  auto* dev_ctx = pool.Get(place);
125

126 127 128 129 130 131 132 133
  framework::RuntimeContext ctx({}, {});

#ifdef PADDLE_WITH_MKLDNN
  // MKLDNN variant of code reads attributes in some of GetKernelTypeForVar and
  // GetKernelType functions, so we need to copy the attributes there.
  // Const qualifier of Attrs had to be discarded to overwrite it.
  if (FLAGS_use_mkldnn) {
    auto& mutable_op_attrs = const_cast<framework::AttributeMap&>(op.Attrs());
134 135 136 137
    mutable_op_attrs = default_attrs;
    for (auto& attr : attrs) {
      mutable_op_attrs[attr.first] = attr.second;
    }
138 139
  }
#endif
140 141 142
  // NOTE(zhiqiu): for kernels on given device, for example NPU, the order to
  // choose is:
  // pten npu kernel > fluid npu kernel > pten cpu kernel > fluid cpu kernel
J
Jiabin Yang 已提交
143

144
  // 1. get expected kernel key
145 146 147
  auto dygraph_exe_ctx = DygraphExecutionContext<VarType>(
      op, framework::Scope(), *dev_ctx, ctx, ins, outs, attrs, default_attrs);
  auto expected_kernel_key = op.GetExpectedKernelType(dygraph_exe_ctx);
148

149 150 151 152 153
  framework::KernelSignature pt_kernel_signature;
  pten::KernelKey pt_kernel_key;
  std::string pt_kernel_name;
  if (pten::KernelFactory::Instance().HasCompatiblePtenKernel(op.Type())) {
    pt_kernel_signature = op.GetExpectedPtenKernelArgs(dygraph_exe_ctx);
154
    VLOG(6) << pt_kernel_signature;
155

156 157
    pt_kernel_name = pt_kernel_signature.name;
    pt_kernel_key = TransOpKernelTypeToPtenKernelKey(expected_kernel_key);
158 159 160 161
    auto pt_kernel = pten::KernelFactory::Instance().SelectKernel(
        pt_kernel_name, pt_kernel_key);

    if (pt_kernel.IsValid()) {
C
Chen Weihang 已提交
162
      VLOG(6) << "Dynamic mode PrepareImpl - kernel name: " << pt_kernel_name
163 164 165
              << " | kernel key: " << pt_kernel_key
              << " | kernel: " << pt_kernel;

W
Wilber 已提交
166 167 168 169 170
      if (platform::is_cpu_place(expected_kernel_key.place_)) {
        auto* cpu_ctx = pool.Get(paddle::platform::CPUPlace());
        return PreparedOp(op, ctx, expected_kernel_key, pt_kernel_signature,
                          pt_kernel, cpu_ctx);
      }
171 172
      // TODO(chenweihang): using CPUKernel when miss device kernel case
      return PreparedOp(op, ctx, expected_kernel_key, pt_kernel_signature,
173
                        pt_kernel, dev_ctx);
174
    } else {
C
Chen Weihang 已提交
175
      VLOG(6) << "Dynamic mode ChoosePtenKernel - kernel `" << pt_kernel_name
176 177 178 179
              << "` not found.";
    }
  }

180
  // 2. check if op[type] has kernel registered.
J
Jiabin Yang 已提交
181 182
  auto& all_op_kernels = op.AllOpKernels();
  auto kernels_iter = all_op_kernels.find(op.Type());
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

  if ((kernels_iter == all_op_kernels.end() ||
       kernels_iter->second.find(expected_kernel_key) ==
           kernels_iter->second.end())
#ifdef PADDLE_WITH_XPU
      ||
      paddle::platform::is_xpu_place(expected_kernel_key.place_) &&
          !paddle::platform::is_xpu_support_op(op.Type(),
                                               expected_kernel_key) ||
      paddle::platform::is_in_xpu_black_list(op.Type())
#endif
          ) {
    if (pten::KernelFactory::Instance().HasCompatiblePtenKernel(op.Type())) {
      auto pt_cpu_kernel_key =
          FallBackToCpu(expected_kernel_key, pt_kernel_key, op);
      auto pt_cpu_kernel = pten::KernelFactory::Instance().SelectKernel(
          pt_kernel_name, pt_cpu_kernel_key);
      if (pt_cpu_kernel.IsValid()) {
        VLOG(6) << "Dynamic mode PrepareImpl - kernel name: " << pt_kernel_name
                << " | kernel key: " << pt_cpu_kernel_key
                << " | kernel: " << pt_cpu_kernel;
        auto* cpu_ctx = pool.Get(paddle::platform::CPUPlace());
        return PreparedOp(op, ctx, expected_kernel_key, pt_kernel_signature,
                          pt_cpu_kernel, cpu_ctx);
      }
    }
  }

211 212 213 214 215
  PADDLE_ENFORCE_NE(
      kernels_iter, all_op_kernels.end(),
      platform::errors::NotFound(
          "There are no kernels which are registered in the %s operator.",
          op.Type()));
J
Jiabin Yang 已提交
216 217
  auto& kernels = kernels_iter->second;
  auto kernel_iter = kernels.find(expected_kernel_key);
218

219
#ifdef PADDLE_WITH_XPU
220
  if (paddle::platform::is_xpu_place(expected_kernel_key.place_) &&
Q
QingshuChen 已提交
221 222 223
      (kernel_iter == kernels.end() ||
       !paddle::platform::is_xpu_support_op(op.Type(), expected_kernel_key) ||
       paddle::platform::is_in_xpu_black_list(op.Type()))) {
224 225 226
    VLOG(3) << "missing XPU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
227 228 229
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
L
Liu-xiandong 已提交
230

231
#endif
L
Liu-xiandong 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

#ifdef PADDLE_WITH_XPU_KP
  bool use_xpu_kp_kernel_rt =
      FLAGS_run_kp_kernel &&
      paddle::platform::is_xpu_kp_support_op(op.Type(), expected_kernel_key);
  bool use_xpu_kp_kernel_debug =
      paddle::platform::is_in_xpu_kpwhite_list(op.Type());
  if (use_xpu_kp_kernel_rt) {
    VLOG(3) << "xpu_kp using rt mode ";
  }
  if (use_xpu_kp_kernel_debug) {
    VLOG(3) << "xpu_kp using debug mode ";
  }
  if (paddle::platform::is_xpu_place(expected_kernel_key.place_) &&
      (use_xpu_kp_kernel_rt || use_xpu_kp_kernel_debug)) {
    expected_kernel_key.place_ = platform::XPUPlace();
    expected_kernel_key.library_type_ = paddle::framework::LibraryType::kKP;
    kernel_iter = kernels.find(expected_kernel_key);
    VLOG(3) << "using XPU KP kernel: " << op.Type()
            << ", using_kernel_key:" << expected_kernel_key;
  }
#endif

255 256
#ifdef PADDLE_WITH_ASCEND_CL
  if (kernel_iter == kernels.end() &&
257
      paddle::platform::is_npu_place(expected_kernel_key.place_)) {
258 259 260
    VLOG(3) << "missing NPU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
261 262 263
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
264 265 266
#endif
#ifdef PADDLE_WITH_MLU
  if (kernel_iter == kernels.end() &&
267
      paddle::platform::is_mlu_place(expected_kernel_key.place_)) {
268 269 270 271 272 273
    VLOG(3) << "missing MLU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
274
#endif
275 276
  // TODO(jiabin): Add operator.cc's line 1000 part back when we need that
  // case
277 278 279 280
  PADDLE_ENFORCE_NE(kernel_iter, kernels.end(),
                    platform::errors::NotFound(
                        "Operator %s does not have kernel for %s.", op.Type(),
                        KernelTypeToString(expected_kernel_key)));
281

282 283 284 285
  if (!(expected_kernel_key.place_ == place)) {
    dev_ctx = pool.Get(expected_kernel_key.place_);
  }

286
  return PreparedOp(op, ctx, expected_kernel_key, kernel_iter->second, dev_ctx);
287 288
}

289 290 291 292
PreparedOp PreparedOp::Prepare(const NameVarMap<VarBase>& ins,
                               const NameVarMap<VarBase>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
293
                               const framework::AttributeMap& attrs,
294 295
                               const framework::AttributeMap& default_attrs) {
  return PrepareImpl<VarBase>(ins, outs, op, place, attrs, default_attrs);
296 297 298 299 300 301
}

PreparedOp PreparedOp::Prepare(const NameVarMap<VariableWrapper>& ins,
                               const NameVarMap<VariableWrapper>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
302
                               const framework::AttributeMap& attrs,
303
                               const framework::AttributeMap& default_attrs) {
304
  return PrepareImpl<VariableWrapper>(ins, outs, op, place, attrs,
305
                                      default_attrs);
306 307
}

308 309 310
template <typename VarType>
static void PreparedOpRunImpl(
    const framework::OperatorBase& op, const framework::RuntimeContext& ctx,
311
    const framework::OpKernelType& kernel_type,
312
    const framework::OperatorWithKernel::OpKernelFunc& func,
313
    platform::DeviceContext* dev_ctx, const NameVarMap<VarType>& ins,
314 315
    const NameVarMap<VarType>& outs, const framework::AttributeMap& attrs,
    const framework::AttributeMap& default_attrs) {
J
Jiabin Yang 已提交
316 317
  // TODO(zjl): remove scope in dygraph
  framework::Scope scope;
H
hong 已提交
318

319 320 321 322 323 324 325 326 327 328 329
  {
    platform::RecordEvent record_event(op.Type() + " infer_shape",
                                       platform::EventRole::kInnerOp);
    DygraphInferShapeContext<VarType> infer_shape_ctx(
        &ins, &outs, &attrs, &default_attrs, op.Type(), &kernel_type);
    op.Info().infer_shape_(&infer_shape_ctx);
  }

  {
    platform::RecordEvent record_event(op.Type() + " compute",
                                       platform::EventRole::kInnerOp);
H
hong 已提交
330

331 332 333
    func(DygraphExecutionContext<VarType>(op, scope, *dev_ctx, ctx, ins, outs,
                                          attrs, default_attrs));
  }
334

335 336 337 338 339
  if (FLAGS_check_nan_inf) {
    framework::details::CheckOpHasNanOrInfInDygraph<VarType>(
        op.Type(), outs, dev_ctx->GetPlace());
  }

L
Leo Chen 已提交
340 341 342 343 344 345 346 347
  if (FLAGS_benchmark) {
    dev_ctx->Wait();
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    PADDLE_ENFORCE_GPU_SUCCESS(platform::GpuGetLastError());
    VLOG(4) << "Operator(" << op.Type() << "): context wait and get last error";
#endif
  }

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
  /**
   * [ Why need handle complex gradient to real gradient? ]
   *
   * After the introduction of complex number calculations, Ops that support
   * complex number calculations generally support type promotion, such as
   * x(float32) + y(complex64) = out(complex64), then the type of the grad
   * tensor should be dout(complex64), dx(float32), dy (complex64).
   *
   * But because the dout is complex64, the dx is also complex64 after
   * grad op kernel executed, we need to recognize this situation and
   * convert dx to float32 type. HandleComplexGradToRealGrad does this thing.
   */
  if (framework::IsComplexType(kernel_type.data_type_)) {
    HandleComplexGradToRealGrad<VarType>(outs);
  }
363
}
H
hong 已提交
364

365 366 367
template <typename VarType>
static void PreparedOpRunPtImpl(
    const framework::OperatorBase& op,
368
    const framework::OpKernelType& kernel_type,
369
    const framework::KernelSignature& pt_kernel_signature,
370 371 372
    const pten::Kernel& pt_kernel, platform::DeviceContext* dev_ctx,
    const NameVarMap<VarType>& ins, const NameVarMap<VarType>& outs,
    const framework::AttributeMap& attrs,
373
    const framework::AttributeMap& default_attrs) {
374 375 376 377 378 379 380 381 382 383 384
  {
    platform::RecordEvent record_event(op.Type() + " infer_shape",
                                       platform::EventRole::kInnerOp);
    DygraphInferShapeContext<VarType> infer_shape_ctx(
        &ins, &outs, &attrs, &default_attrs, op.Type(), &kernel_type);
    op.Info().infer_shape_(&infer_shape_ctx);
  }

  {
    platform::RecordEvent record_event(op.Type() + " compute",
                                       platform::EventRole::kInnerOp);
385

386
    PreparePtenData<VarType>(pt_kernel, pt_kernel_signature, ins);
387

388 389 390 391
    pten::KernelContext pt_kernel_context;
    BuildDygraphPtenKernelContext<VarType>(pt_kernel_signature, pt_kernel, ins,
                                           outs, attrs, default_attrs, dev_ctx,
                                           &pt_kernel_context);
392

393 394
    pt_kernel(&pt_kernel_context);
  }
395

396 397
  if (FLAGS_benchmark) {
    dev_ctx->Wait();
398 399
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    PADDLE_ENFORCE_GPU_SUCCESS(platform::GpuGetLastError());
400 401 402 403
    VLOG(4) << "Operator(" << op.Type() << "): context wait and get last error";
#endif
  }

404
  // TODO(chenweihang): add debug flags later
405 406 407
  if (framework::IsComplexType(kernel_type.data_type_)) {
    HandleComplexGradToRealGrad<VarType>(outs);
  }
408 409
}

410 411
void PreparedOp::Run(const NameVarMap<VarBase>& ins,
                     const NameVarMap<VarBase>& outs,
412 413
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
414
  if (run_pten_kernel_) {
415
    PreparedOpRunPtImpl<VarBase>(op_, kernel_type_, pt_kernel_signature_,
416 417
                                 pt_kernel_, dev_ctx_, ins, outs, attrs,
                                 default_attrs);
418 419 420 421
  } else {
    PreparedOpRunImpl<VarBase>(op_, ctx_, kernel_type_, func_, dev_ctx_, ins,
                               outs, attrs, default_attrs);
  }
422
}
H
hong 已提交
423

424 425
void PreparedOp::Run(const NameVarMap<VariableWrapper>& ins,
                     const NameVarMap<VariableWrapper>& outs,
426 427
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
428
  if (run_pten_kernel_) {
429
    PreparedOpRunPtImpl<VariableWrapper>(
430 431
        op_, kernel_type_, pt_kernel_signature_, pt_kernel_, dev_ctx_, ins,
        outs, attrs, default_attrs);
432 433 434 435
  } else {
    PreparedOpRunImpl<VariableWrapper>(op_, ctx_, kernel_type_, func_, dev_ctx_,
                                       ins, outs, attrs, default_attrs);
  }
J
Jiabin Yang 已提交
436 437 438 439
}

}  // namespace imperative
}  // namespace paddle