prepared_operator.cc 22.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

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

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

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

39 40 41 42 43 44 45 46 47 48
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 已提交
49 50 51
const framework::Tensor* GetTensorFromVar(const framework::Variable& var) {
  if (var.IsType<framework::LoDTensor>()) {
    return &(var.Get<framework::LoDTensor>());
52 53
  } else if (var.IsType<phi::SelectedRows>()) {
    return &(var.Get<phi::SelectedRows>().value());
J
Jiabin Yang 已提交
54 55 56 57 58
  } else {
    return nullptr;
  }
}

59
template <typename VarType>
J
Jiabin Yang 已提交
60
void HandleComplexGradToRealGrad(const NameVarMap<VarType>& outs) {
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  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 已提交
77
      if (tensor && tensor->IsInitialized()) {
78 79 80 81 82 83 84 85
        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 已提交
86 87 88 89 90
      }
    }
  }
}

J
Jiabin Yang 已提交
91
template <>
92 93
void HandleComplexGradToRealGrad<egr::EagerVariable>(
    const NameVarMap<egr::EagerVariable>& outs) {
J
Jiabin Yang 已提交
94 95 96
  // TODO(jiabin): Support Complex here.
}

97 98 99 100 101
void TestHandleComplexGradToRealGradEager(
    const NameVarMap<egr::EagerVariable>& outs) {
  HandleComplexGradToRealGrad<egr::EagerVariable>(outs);
}

J
Jiabin Yang 已提交
102 103
PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
104
                       const framework::OpKernelType& kernel_type,
105
                       const framework::OperatorWithKernel::OpKernelFunc& func,
106
                       platform::DeviceContext* dev_ctx)
107 108 109 110 111 112
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(func),
      dev_ctx_(dev_ctx) {}

113 114 115 116
PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
                       const framework::OpKernelType& kernel_type,
                       const framework::KernelSignature& kernel_signature,
117
                       const phi::Kernel& pt_kernel,
118 119 120 121 122 123
                       platform::DeviceContext* dev_ctx)
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(nullptr),
      dev_ctx_(dev_ctx),
124
      run_phi_kernel_(true),
125
      pt_kernel_signature_(kernel_signature),
126
      pt_kernel_(pt_kernel) {}
127

128 129 130 131 132
template <typename VarType>
PreparedOp PrepareImpl(const NameVarMap<VarType>& ins,
                       const NameVarMap<VarType>& outs,
                       const framework::OperatorWithKernel& op,
                       const platform::Place& place,
133
                       const framework::AttributeMap& attrs,
134
                       const framework::AttributeMap& default_attrs) {
135
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
136
  auto* dev_ctx = pool.Get(place);
137

138 139 140 141 142 143 144 145
  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());
146 147 148 149
    mutable_op_attrs = default_attrs;
    for (auto& attr : attrs) {
      mutable_op_attrs[attr.first] = attr.second;
    }
150 151
  }
#endif
152 153
  // NOTE(zhiqiu): for kernels on given device, for example NPU, the order to
  // choose is:
154
  // phi npu kernel > fluid npu kernel > phi cpu kernel > fluid cpu kernel
J
Jiabin Yang 已提交
155

156
  // 1. get expected kernel key
157 158 159
  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);
160

161
  framework::KernelSignature pt_kernel_signature;
162
  phi::KernelKey pt_kernel_key;
163
  std::string pt_kernel_name;
L
Liu-xiandong 已提交
164
#if defined(PADDLE_WITH_XPU)
165 166 167 168 169
  bool is_xpu_unsupport =
      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());
L
Liu-xiandong 已提交
170

171
#endif
172 173
  if (phi::KernelFactory::Instance().HasCompatiblePhiKernel(op.Type())) {
    pt_kernel_signature = op.GetExpectedPhiKernelArgs(dygraph_exe_ctx);
174
    VLOG(6) << pt_kernel_signature;
175

176
    pt_kernel_name = pt_kernel_signature.name;
177 178 179
// NOTE(Liu-xiandong): The register kernel used KP have library_type[KP],
// But the default library_type is Plain, so we need to modify the
// library_type here, otherwise it can't work.
L
Liu-xiandong 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
#ifdef PADDLE_WITH_XPU_KP
    if (paddle::platform::is_xpu_place(expected_kernel_key.place_)) {
      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) << "phi xpu_kp using rt mode ";
      }
      if (use_xpu_kp_kernel_debug) {
        VLOG(3) << "phi xpu_kp using debug mode ";
      }
      bool is_xpu_kp_support =
          (use_xpu_kp_kernel_rt || use_xpu_kp_kernel_debug);
      if (is_xpu_kp_support) {
196 197
        auto expected_kernel_key_library_type =
            expected_kernel_key.library_type_;
L
Liu-xiandong 已提交
198
        expected_kernel_key.library_type_ = paddle::framework::LibraryType::kKP;
199
        VLOG(3) << "modifing XPU KP kernel: " << op.Type()
L
Liu-xiandong 已提交
200
                << ", using_kernel_key:" << expected_kernel_key;
201 202 203 204 205 206 207 208
        phi::KernelKey try_pt_kernel_key =
            TransOpKernelTypeToPhiKernelKey(expected_kernel_key);
        if (!phi::KernelFactory::Instance().IsSelectKernelValid(
                pt_kernel_name, try_pt_kernel_key)) {
          expected_kernel_key.library_type_ = expected_kernel_key_library_type;
          VLOG(3) << "modify XPU KP kernel: " << op.Type() << " is failed "
                  << expected_kernel_key;
        }
L
Liu-xiandong 已提交
209 210 211
      }
    }
#endif
212

213
    pt_kernel_key = TransOpKernelTypeToPhiKernelKey(expected_kernel_key);
214 215
    auto pt_kernel = phi::KernelFactory::Instance().SelectKernel(pt_kernel_name,
                                                                 pt_kernel_key);
216

217
    if (pt_kernel.IsValid()
L
Liu-xiandong 已提交
218
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
219 220 221
        && !is_xpu_unsupport
#endif
        ) {
C
Chen Weihang 已提交
222
      VLOG(6) << "Dynamic mode PrepareImpl - kernel name: " << pt_kernel_name
223 224 225
              << " | kernel key: " << pt_kernel_key
              << " | kernel: " << pt_kernel;

F
From00 已提交
226 227
      if (expected_kernel_key.place_ != place) {
        dev_ctx = pool.Get(expected_kernel_key.place_);
W
Wilber 已提交
228
      }
F
From00 已提交
229

230 231
      // TODO(chenweihang): using CPUKernel when miss device kernel case
      return PreparedOp(op, ctx, expected_kernel_key, pt_kernel_signature,
232
                        pt_kernel, dev_ctx);
233
    } else {
234
      VLOG(6) << "Dynamic mode ChoosePhiKernel - kernel `" << pt_kernel_name
235 236 237 238
              << "` not found.";
    }
  }

239
  // 2. check if op[type] has kernel registered.
J
Jiabin Yang 已提交
240 241
  auto& all_op_kernels = op.AllOpKernels();
  auto kernels_iter = all_op_kernels.find(op.Type());
242

243 244 245
// NOTE(Liu-xiandong): If we can't find heterogeneous kernel in phi,
// we need to select the heterogeneous kernel in fluid, but the kernel
// registered in KP use library_type[KP], we need to modify it.
246 247 248 249 250 251 252 253 254 255 256 257 258 259
#ifdef PADDLE_WITH_XPU_KP
  bool use_xpu_kp_kernel_rt =
      paddle::platform::is_xpu_place(expected_kernel_key.place_) &&
      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_xpu_place(expected_kernel_key.place_) &&
      paddle::platform::is_in_xpu_kpwhite_list(op.Type());
  bool is_xpu_kp_support = (use_xpu_kp_kernel_rt || use_xpu_kp_kernel_debug);
  if (is_xpu_kp_support) {
    expected_kernel_key.library_type_ = paddle::framework::LibraryType::kKP;
  }
#endif

260 261 262
  if ((kernels_iter == all_op_kernels.end() ||
       kernels_iter->second.find(expected_kernel_key) ==
           kernels_iter->second.end())
L
Liu-xiandong 已提交
263
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
264
      || is_xpu_unsupport
265
#endif
266 267 268 269
#if defined(PADDLE_WITH_XPU_KP)
      || (is_xpu_unsupport && !is_xpu_kp_support)
#endif
          ) {
270
    if (phi::KernelFactory::Instance().HasCompatiblePhiKernel(op.Type())) {
271 272
      auto pt_cpu_kernel_key =
          FallBackToCpu(expected_kernel_key, pt_kernel_key, op);
273
      auto pt_cpu_kernel = phi::KernelFactory::Instance().SelectKernel(
274 275 276 277 278 279 280 281 282 283 284 285
          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);
      }
    }
  }

286 287 288 289 290
  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()));
291

J
Jiabin Yang 已提交
292 293
  auto& kernels = kernels_iter->second;
  auto kernel_iter = kernels.find(expected_kernel_key);
294

295
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
296
  if (paddle::platform::is_xpu_place(expected_kernel_key.place_) &&
297
      (kernel_iter == kernels.end() || is_xpu_unsupport)) {
298 299 300
    VLOG(3) << "missing XPU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
301 302 303
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
304
#endif
L
Liu-xiandong 已提交
305 306

#ifdef PADDLE_WITH_XPU_KP
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  if (paddle::platform::is_xpu_place(expected_kernel_key.place_)) {
    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 (is_xpu_kp_support) {
      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;
    }
    if (!is_xpu_kp_support &&
        (kernel_iter == kernels.end() || is_xpu_unsupport)) {
      VLOG(3) << "missing XPU 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);
    }
L
Liu-xiandong 已提交
328 329 330
  }
#endif

331 332
#ifdef PADDLE_WITH_ASCEND_CL
  if (kernel_iter == kernels.end() &&
333
      paddle::platform::is_npu_place(expected_kernel_key.place_)) {
334 335 336
    VLOG(3) << "missing NPU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
337 338 339
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
340 341 342
#endif
#ifdef PADDLE_WITH_MLU
  if (kernel_iter == kernels.end() &&
343
      paddle::platform::is_mlu_place(expected_kernel_key.place_)) {
344 345 346 347 348 349
    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);
  }
350 351 352 353 354 355 356 357 358 359
#endif
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  if (kernel_iter == kernels.end() &&
      paddle::platform::is_custom_place(expected_kernel_key.place_)) {
    VLOG(3) << "missing " << place.GetDeviceType() << " 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);
  }
360
#endif
361 362
  // TODO(jiabin): Add operator.cc's line 1000 part back when we need that
  // case
363 364 365 366
  PADDLE_ENFORCE_NE(kernel_iter, kernels.end(),
                    platform::errors::NotFound(
                        "Operator %s does not have kernel for %s.", op.Type(),
                        KernelTypeToString(expected_kernel_key)));
367

368 369 370 371
  if (!(expected_kernel_key.place_ == place)) {
    dev_ctx = pool.Get(expected_kernel_key.place_);
  }

372
  return PreparedOp(op, ctx, expected_kernel_key, kernel_iter->second, dev_ctx);
373 374
}

375 376 377 378
PreparedOp PreparedOp::Prepare(const NameVarMap<VarBase>& ins,
                               const NameVarMap<VarBase>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
379
                               const framework::AttributeMap& attrs,
380 381
                               const framework::AttributeMap& default_attrs) {
  return PrepareImpl<VarBase>(ins, outs, op, place, attrs, default_attrs);
382 383 384 385 386 387
}

PreparedOp PreparedOp::Prepare(const NameVarMap<VariableWrapper>& ins,
                               const NameVarMap<VariableWrapper>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
388
                               const framework::AttributeMap& attrs,
389
                               const framework::AttributeMap& default_attrs) {
390
  return PrepareImpl<VariableWrapper>(ins, outs, op, place, attrs,
391
                                      default_attrs);
392 393
}

394 395
PreparedOp PreparedOp::Prepare(const NameVarMap<egr::EagerVariable>& ins,
                               const NameVarMap<egr::EagerVariable>& outs,
J
Jiabin Yang 已提交
396 397 398 399
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
                               const framework::AttributeMap& attrs,
                               const framework::AttributeMap& default_attrs) {
400 401
  return PrepareImpl<egr::EagerVariable>(ins, outs, op, place, attrs,
                                         default_attrs);
J
Jiabin Yang 已提交
402
}
403 404 405
template <typename VarType>
static void PreparedOpRunImpl(
    const framework::OperatorBase& op, const framework::RuntimeContext& ctx,
406
    const framework::OpKernelType& kernel_type,
407
    const framework::OperatorWithKernel::OpKernelFunc& func,
408
    platform::DeviceContext* dev_ctx, const NameVarMap<VarType>& ins,
409 410
    const NameVarMap<VarType>& outs, const framework::AttributeMap& attrs,
    const framework::AttributeMap& default_attrs) {
J
Jiabin Yang 已提交
411 412
  // TODO(zjl): remove scope in dygraph
  framework::Scope scope;
H
hong 已提交
413

414
  {
C
chenjian 已提交
415 416 417
    platform::RecordEvent record_event(op.Type() + "::infer_shape",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
418 419 420 421 422 423
    DygraphInferShapeContext<VarType> infer_shape_ctx(
        &ins, &outs, &attrs, &default_attrs, op.Type(), &kernel_type);
    op.Info().infer_shape_(&infer_shape_ctx);
  }

  {
C
chenjian 已提交
424 425 426
    platform::RecordEvent record_event(op.Type() + "::compute",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
H
hong 已提交
427

428 429 430
    func(DygraphExecutionContext<VarType>(op, scope, *dev_ctx, ctx, ins, outs,
                                          attrs, default_attrs));
  }
431

432 433 434 435 436
  if (FLAGS_check_nan_inf) {
    framework::details::CheckOpHasNanOrInfInDygraph<VarType>(
        op.Type(), outs, dev_ctx->GetPlace());
  }

L
Leo Chen 已提交
437 438 439 440 441 442 443 444
  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
  }

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
  /**
   * [ 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);
  }
460
}
H
hong 已提交
461

462 463 464
template <typename VarType>
static void PreparedOpRunPtImpl(
    const framework::OperatorBase& op,
465
    const framework::OpKernelType& kernel_type,
466
    const framework::KernelSignature& pt_kernel_signature,
467
    const phi::Kernel& pt_kernel, platform::DeviceContext* dev_ctx,
468 469
    const NameVarMap<VarType>& ins, const NameVarMap<VarType>& outs,
    const framework::AttributeMap& attrs,
470
    const framework::AttributeMap& default_attrs) {
471
  {
C
chenjian 已提交
472 473 474
    platform::RecordEvent record_event(op.Type() + "::infer_shape",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
475 476 477 478 479 480
    DygraphInferShapeContext<VarType> infer_shape_ctx(
        &ins, &outs, &attrs, &default_attrs, op.Type(), &kernel_type);
    op.Info().infer_shape_(&infer_shape_ctx);
  }

  {
C
chenjian 已提交
481 482 483
    platform::RecordEvent record_event(op.Type() + "::compute",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
484

485
    PreparePhiData<VarType>(pt_kernel, pt_kernel_signature, ins);
486

487
    phi::KernelContext pt_kernel_context;
488 489 490
    BuildDygraphPhiKernelContext<VarType>(pt_kernel_signature, pt_kernel, ins,
                                          outs, attrs, default_attrs, dev_ctx,
                                          &pt_kernel_context);
491

492 493
    pt_kernel(&pt_kernel_context);
  }
494

495 496 497 498 499
  if (FLAGS_check_nan_inf) {
    framework::details::CheckOpHasNanOrInfInDygraph<VarType>(
        op.Type(), outs, dev_ctx->GetPlace());
  }

500 501
  if (FLAGS_benchmark) {
    dev_ctx->Wait();
502 503
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    PADDLE_ENFORCE_GPU_SUCCESS(platform::GpuGetLastError());
504 505 506 507
    VLOG(4) << "Operator(" << op.Type() << "): context wait and get last error";
#endif
  }

508
  // TODO(chenweihang): add debug flags later
509 510 511
  if (framework::IsComplexType(kernel_type.data_type_)) {
    HandleComplexGradToRealGrad<VarType>(outs);
  }
512 513
}

514 515
void PreparedOp::Run(const NameVarMap<VarBase>& ins,
                     const NameVarMap<VarBase>& outs,
516 517
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
518
  if (run_phi_kernel_) {
519
    PreparedOpRunPtImpl<VarBase>(op_, kernel_type_, pt_kernel_signature_,
520 521
                                 pt_kernel_, dev_ctx_, ins, outs, attrs,
                                 default_attrs);
522 523 524 525
  } else {
    PreparedOpRunImpl<VarBase>(op_, ctx_, kernel_type_, func_, dev_ctx_, ins,
                               outs, attrs, default_attrs);
  }
526
}
H
hong 已提交
527

528 529
void PreparedOp::Run(const NameVarMap<VariableWrapper>& ins,
                     const NameVarMap<VariableWrapper>& outs,
530 531
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
532
  if (run_phi_kernel_) {
533
    PreparedOpRunPtImpl<VariableWrapper>(
534 535
        op_, kernel_type_, pt_kernel_signature_, pt_kernel_, dev_ctx_, ins,
        outs, attrs, default_attrs);
536 537 538 539
  } else {
    PreparedOpRunImpl<VariableWrapper>(op_, ctx_, kernel_type_, func_, dev_ctx_,
                                       ins, outs, attrs, default_attrs);
  }
J
Jiabin Yang 已提交
540 541
}

542 543
void PreparedOp::Run(const NameVarMap<egr::EagerVariable>& ins,
                     const NameVarMap<egr::EagerVariable>& outs,
J
Jiabin Yang 已提交
544 545
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
546
  if (run_phi_kernel_) {
547
    PreparedOpRunPtImpl<egr::EagerVariable>(
J
Jiabin Yang 已提交
548 549 550
        op_, kernel_type_, pt_kernel_signature_, pt_kernel_, dev_ctx_, ins,
        outs, attrs, default_attrs);
  } else {
551 552 553
    PreparedOpRunImpl<egr::EagerVariable>(op_, ctx_, kernel_type_, func_,
                                          dev_ctx_, ins, outs, attrs,
                                          default_attrs);
J
Jiabin Yang 已提交
554 555 556
  }
}

J
Jiabin Yang 已提交
557 558
}  // namespace imperative
}  // namespace paddle