prepared_operator.cc 28.7 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"
C
chenjian 已提交
31
#include "paddle/fluid/platform/profiler/supplement_tracing.h"
32

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

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

40
static const phi::Kernel empty_kernel;
41 42
static const framework::RuntimeContext empty_ctx({}, {});
static const framework::Scope empty_scope;
43

44 45 46 47 48 49 50
const phi::KernelFactory& PreparedOp::phi_kernel_factory =
    phi::KernelFactory::Instance();
const phi::OpUtilsMap& PreparedOp::phi_op_utils_map =
    phi::OpUtilsMap::Instance();
const phi::DefaultKernelSignatureMap& PreparedOp::default_phi_kernel_sig_map =
    phi::DefaultKernelSignatureMap::Instance();

51 52 53 54 55 56 57 58 59 60
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 已提交
61 62 63
const framework::Tensor* GetTensorFromVar(const framework::Variable& var) {
  if (var.IsType<framework::LoDTensor>()) {
    return &(var.Get<framework::LoDTensor>());
64 65
  } else if (var.IsType<phi::SelectedRows>()) {
    return &(var.Get<phi::SelectedRows>().value());
J
Jiabin Yang 已提交
66 67 68 69 70
  } else {
    return nullptr;
  }
}

71
template <typename VarType>
J
Jiabin Yang 已提交
72
void HandleComplexGradToRealGrad(const NameVarMap<VarType>& outs) {
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  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 已提交
89
      if (tensor && tensor->IsInitialized()) {
90 91 92 93 94
        VLOG(6) << "Transform " << framework::DataTypeToString(var->DataType())
                << " var `" << var->Name() << "` to "
                << framework::DataTypeToString(var->ForwardDataType())
                << " real var in dynamic graph.";
        framework::Tensor out;
95 96
        framework::TransComplexToReal(
            var->ForwardDataType(), var->DataType(), *tensor, &out);
97
        SetTensorToVariable(var->Var(), out, var->MutableVar());
J
Jiabin Yang 已提交
98 99 100 101 102
      }
    }
  }
}

J
Jiabin Yang 已提交
103
template <>
104 105
void HandleComplexGradToRealGrad<egr::EagerVariable>(
    const NameVarMap<egr::EagerVariable>& outs) {
J
Jiabin Yang 已提交
106 107 108
  // TODO(jiabin): Support Complex here.
}

109 110 111 112 113
void TestHandleComplexGradToRealGradEager(
    const NameVarMap<egr::EagerVariable>& outs) {
  HandleComplexGradToRealGrad<egr::EagerVariable>(outs);
}

J
Jiabin Yang 已提交
114 115
PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
116
                       const framework::OpKernelType& kernel_type,
117
                       const framework::OperatorWithKernel::OpKernelFunc& func,
118 119
                       const phi::ArgumentMappingFn* arg_map_fn,
                       const phi::KernelSignature* default_kernel_signature,
120
                       platform::DeviceContext* dev_ctx)
121 122 123 124
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(func),
125
      dev_ctx_(dev_ctx),
126 127 128
      arg_map_fn_(arg_map_fn),
      default_kernel_signature_(default_kernel_signature),
      phi_kernel_(empty_kernel) {}
129

130 131 132
PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
                       const framework::OpKernelType& kernel_type,
133 134 135 136
                       const phi::ArgumentMappingFn* arg_map_fn,
                       const phi::KernelSignature* default_kernel_signature,
                       phi::KernelSignature&& kernel_signature,
                       const phi::Kernel& phi_kernel,
137 138 139 140 141 142
                       platform::DeviceContext* dev_ctx)
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(nullptr),
      dev_ctx_(dev_ctx),
143
      run_phi_kernel_(true),
144 145 146 147
      arg_map_fn_(arg_map_fn),
      default_kernel_signature_(default_kernel_signature),
      kernel_signature_(std::move(kernel_signature)),
      phi_kernel_(phi_kernel) {}
148

149
template <typename VarType>
150
PreparedOp PrepareImpl(
151 152 153 154
    const NameVarMap<VarType>& ins,
    const NameVarMap<VarType>& outs,
    const framework::OperatorWithKernel& op,
    const platform::Place& place,
155 156 157 158 159
    const framework::AttributeMap& attrs,
    const framework::AttributeMap& default_attrs,
    const phi::KernelFactory& phi_kernel_factory,
    const phi::OpUtilsMap& phi_op_utils_map,
    const phi::DefaultKernelSignatureMap& default_phi_kernel_sig_map) {
160
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
161
  auto* dev_ctx = pool.Get(place);
162

163 164 165 166 167 168
#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());
169 170 171 172
    mutable_op_attrs = default_attrs;
    for (auto& attr : attrs) {
      mutable_op_attrs[attr.first] = attr.second;
    }
173 174
  }
#endif
175 176
  // NOTE(zhiqiu): for kernels on given device, for example NPU, the order to
  // choose is:
177
  // phi npu kernel > fluid npu kernel > phi cpu kernel > fluid cpu kernel
J
Jiabin Yang 已提交
178

179
  // 1. get expected kernel key
180
  auto dygraph_exe_ctx = DygraphExecutionContext<VarType>(
181
      op, empty_scope, *dev_ctx, empty_ctx, ins, outs, attrs, default_attrs);
182
  auto expected_kernel_key = op.GetExpectedKernelType(dygraph_exe_ctx);
183

184 185
  const phi::KernelSignature* default_kernel_signature = nullptr;
  phi::KernelSignature kernel_signature;
186
  phi::KernelKey pt_kernel_key;
187
  std::string pt_kernel_name;
L
Liu-xiandong 已提交
188
#if defined(PADDLE_WITH_XPU)
189 190 191 192 193
  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 已提交
194

195
#endif
196

197 198
  bool has_phi_kernel = false;

199 200
  const auto* arg_map_fn = phi_op_utils_map.GetArgumentMappingFn(op.Type());

201 202
  if (arg_map_fn) {
    has_phi_kernel = true;
203
    kernel_signature = (*arg_map_fn)(
204 205
        framework::ExecutionArgumentMappingContext(dygraph_exe_ctx));
  } else {
206
    default_kernel_signature =
207
        default_phi_kernel_sig_map.GetNullable(op.Type());
208
    if (default_kernel_signature) {
209
      has_phi_kernel = true;
210
      kernel_signature = *default_kernel_signature;
211 212 213 214
    }
  }

  if (has_phi_kernel) {
215 216
    VLOG(6) << kernel_signature;
    pt_kernel_name = kernel_signature.name;
217 218 219
// 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 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
#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) {
236 237
        auto expected_kernel_key_library_type =
            expected_kernel_key.library_type_;
L
Liu-xiandong 已提交
238
        expected_kernel_key.library_type_ = paddle::framework::LibraryType::kKP;
239
        VLOG(3) << "modifing XPU KP kernel: " << pt_kernel_name
L
Liu-xiandong 已提交
240
                << ", using_kernel_key:" << expected_kernel_key;
241

242 243
        phi::KernelKey try_pt_kernel_key =
            TransOpKernelTypeToPhiKernelKey(expected_kernel_key);
244
        if (!phi_kernel_factory.HasKernel(pt_kernel_name, try_pt_kernel_key)) {
245
          expected_kernel_key.library_type_ = expected_kernel_key_library_type;
246 247 248 249 250
          VLOG(3) << "modify XPU KP kernel: " << pt_kernel_name
                  << " in dynamic graph is failed " << expected_kernel_key;
        } else {
          VLOG(3) << "modify XPU KP kernel: " << pt_kernel_name
                  << " in dynamic graph is succeed " << expected_kernel_key;
251
        }
L
Liu-xiandong 已提交
252 253 254
      }
    }
#endif
255

256
    pt_kernel_key = TransOpKernelTypeToPhiKernelKey(expected_kernel_key);
257 258
    auto& phi_kernel =
        phi_kernel_factory.SelectKernel(pt_kernel_name, pt_kernel_key);
259

260
    if (phi_kernel.IsValid()
L
Liu-xiandong 已提交
261
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
262 263
        && !is_xpu_unsupport
#endif
264
    ) {
C
Chen Weihang 已提交
265
      VLOG(6) << "Dynamic mode PrepareImpl - kernel name: " << pt_kernel_name
266
              << " | kernel key: " << pt_kernel_key
267
              << " | kernel: " << phi_kernel;
268

F
From00 已提交
269 270
      if (expected_kernel_key.place_ != place) {
        dev_ctx = pool.Get(expected_kernel_key.place_);
W
Wilber 已提交
271
      }
F
From00 已提交
272

273 274 275 276 277 278 279 280
      return PreparedOp(op,
                        empty_ctx,
                        expected_kernel_key,
                        arg_map_fn,
                        default_kernel_signature,
                        std::move(kernel_signature),
                        phi_kernel,
                        dev_ctx);
281
    } else {
282
      VLOG(6) << "Dynamic mode ChoosePhiKernel - kernel `" << pt_kernel_name
283 284 285 286
              << "` not found.";
    }
  }

287
  // 2. check if op[type] has kernel registered.
J
Jiabin Yang 已提交
288 289
  auto& all_op_kernels = op.AllOpKernels();
  auto kernels_iter = all_op_kernels.find(op.Type());
290

291 292 293
// 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.
294 295 296 297 298 299 300 301 302 303 304 305 306 307
#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

308 309 310
  if ((kernels_iter == all_op_kernels.end() ||
       kernels_iter->second.find(expected_kernel_key) ==
           kernels_iter->second.end())
L
Liu-xiandong 已提交
311
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
312
      || is_xpu_unsupport
313
#endif
314 315 316
#if defined(PADDLE_WITH_XPU_KP)
      || (is_xpu_unsupport && !is_xpu_kp_support)
#endif
317
  ) {
318
    if (has_phi_kernel) {
319 320
      auto pt_cpu_kernel_key =
          FallBackToCpu(expected_kernel_key, pt_kernel_key, op);
321 322
      auto& pt_cpu_kernel =
          phi_kernel_factory.SelectKernel(pt_kernel_name, pt_cpu_kernel_key);
323 324 325 326 327
      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());
328
        return PreparedOp(
329 330
            op,
            empty_ctx,
331
            framework::TransPhiKernelKeyToOpKernelType(pt_cpu_kernel_key),
332 333 334 335 336
            arg_map_fn,
            default_kernel_signature,
            std::move(kernel_signature),
            pt_cpu_kernel,
            cpu_ctx);
337 338 339 340
      }
    }
  }

341
  PADDLE_ENFORCE_NE(
342 343
      kernels_iter,
      all_op_kernels.end(),
344 345 346
      platform::errors::NotFound(
          "There are no kernels which are registered in the %s operator.",
          op.Type()));
347

J
Jiabin Yang 已提交
348 349
  auto& kernels = kernels_iter->second;
  auto kernel_iter = kernels.find(expected_kernel_key);
350

351
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
352
  if (paddle::platform::is_xpu_place(expected_kernel_key.place_) &&
353
      (kernel_iter == kernels.end() || is_xpu_unsupport)) {
354
    VLOG(3) << "fluid missing XPU kernel: " << op.Type()
355 356
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
357 358 359
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
360
#endif
L
Liu-xiandong 已提交
361 362

#ifdef PADDLE_WITH_XPU_KP
363 364
  if (paddle::platform::is_xpu_place(expected_kernel_key.place_)) {
    if (use_xpu_kp_kernel_rt) {
365
      VLOG(3) << "fluid xpu_kp using rt mode ";
366 367
    }
    if (use_xpu_kp_kernel_debug) {
368
      VLOG(3) << "fluid xpu_kp using debug mode ";
369 370 371 372
    }
    if (is_xpu_kp_support) {
      expected_kernel_key.library_type_ = paddle::framework::LibraryType::kKP;
      kernel_iter = kernels.find(expected_kernel_key);
373
      VLOG(3) << "using fluid XPU KP kernel: " << op.Type()
374 375 376 377
              << ", using_kernel_key:" << expected_kernel_key;
    }
    if (!is_xpu_kp_support &&
        (kernel_iter == kernels.end() || is_xpu_unsupport)) {
378
      VLOG(3) << "fluid missing XPU kernel: " << op.Type()
379 380 381 382 383
              << ", 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 已提交
384 385 386
  }
#endif

387 388
#ifdef PADDLE_WITH_ASCEND_CL
  if (kernel_iter == kernels.end() &&
389
      paddle::platform::is_npu_place(expected_kernel_key.place_)) {
390 391 392
    VLOG(3) << "missing NPU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
393 394 395
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
396 397 398
#endif
#ifdef PADDLE_WITH_MLU
  if (kernel_iter == kernels.end() &&
399
      paddle::platform::is_mlu_place(expected_kernel_key.place_)) {
400 401 402 403 404 405
    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);
  }
406 407 408 409 410 411 412 413 414 415
#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);
  }
416
#endif
417 418
  // TODO(jiabin): Add operator.cc's line 1000 part back when we need that
  // case
419 420 421 422 423 424
  PADDLE_ENFORCE_NE(
      kernel_iter,
      kernels.end(),
      platform::errors::NotFound("Operator %s does not have kernel for %s.",
                                 op.Type(),
                                 KernelTypeToString(expected_kernel_key)));
425

426 427 428 429
  if (!(expected_kernel_key.place_ == place)) {
    dev_ctx = pool.Get(expected_kernel_key.place_);
  }

430 431 432 433 434 435 436
  return PreparedOp(op,
                    empty_ctx,
                    expected_kernel_key,
                    kernel_iter->second,
                    arg_map_fn,
                    default_kernel_signature,
                    dev_ctx);
437 438
}

439 440 441 442
PreparedOp PreparedOp::Prepare(const NameVarMap<VarBase>& ins,
                               const NameVarMap<VarBase>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
443
                               const framework::AttributeMap& attrs,
444
                               const framework::AttributeMap& default_attrs) {
445 446 447 448 449 450 451 452
  return PrepareImpl<VarBase>(ins,
                              outs,
                              op,
                              place,
                              attrs,
                              default_attrs,
                              phi_kernel_factory,
                              phi_op_utils_map,
453
                              default_phi_kernel_sig_map);
454 455 456 457 458 459
}

PreparedOp PreparedOp::Prepare(const NameVarMap<VariableWrapper>& ins,
                               const NameVarMap<VariableWrapper>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
460
                               const framework::AttributeMap& attrs,
461
                               const framework::AttributeMap& default_attrs) {
462 463 464 465 466 467 468 469 470
  return PrepareImpl<VariableWrapper>(ins,
                                      outs,
                                      op,
                                      place,
                                      attrs,
                                      default_attrs,
                                      phi_kernel_factory,
                                      phi_op_utils_map,
                                      default_phi_kernel_sig_map);
471 472
}

473 474
PreparedOp PreparedOp::Prepare(const NameVarMap<egr::EagerVariable>& ins,
                               const NameVarMap<egr::EagerVariable>& outs,
J
Jiabin Yang 已提交
475 476 477 478
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
                               const framework::AttributeMap& attrs,
                               const framework::AttributeMap& default_attrs) {
479 480 481 482 483 484 485 486 487
  return PrepareImpl<egr::EagerVariable>(ins,
                                         outs,
                                         op,
                                         place,
                                         attrs,
                                         default_attrs,
                                         phi_kernel_factory,
                                         phi_op_utils_map,
                                         default_phi_kernel_sig_map);
J
Jiabin Yang 已提交
488
}
489 490
template <typename VarType>
static void PreparedOpRunImpl(
491 492
    const framework::OperatorBase& op,
    const framework::RuntimeContext& ctx,
493
    const framework::OpKernelType& kernel_type,
494
    const framework::OperatorWithKernel::OpKernelFunc& func,
495 496
    const phi::ArgumentMappingFn* arg_map_fn,
    const phi::KernelSignature* default_kernel_signature,
497 498 499 500
    platform::DeviceContext* dev_ctx,
    const NameVarMap<VarType>& ins,
    const NameVarMap<VarType>& outs,
    const framework::AttributeMap& attrs,
501
    const framework::AttributeMap& default_attrs) {
J
Jiabin Yang 已提交
502
  // TODO(zjl): remove scope in dygraph
H
hong 已提交
503

504
  {
505
    platform::RecordEvent record_event("infer_shape",
C
chenjian 已提交
506
                                       platform::TracerEventType::OperatorInner,
507 508 509 510 511 512 513 514 515 516
                                       1,
                                       platform::EventRole::kInnerOp);
    DygraphInferShapeContext<VarType> infer_shape_ctx(&ins,
                                                      &outs,
                                                      &attrs,
                                                      &default_attrs,
                                                      op.Type(),
                                                      &kernel_type,
                                                      arg_map_fn,
                                                      default_kernel_signature);
517
    op.Info().infer_shape_(&infer_shape_ctx);
C
chenjian 已提交
518 519 520
    record_event.End();
    platform::RecordOpInfoSupplement(
        op.Type(), op.Attrs(), infer_shape_ctx, ctx);
521 522 523
  }

  {
524
    platform::RecordEvent record_event("compute",
C
chenjian 已提交
525
                                       platform::TracerEventType::OperatorInner,
526 527
                                       1,
                                       platform::EventRole::kInnerOp);
H
hong 已提交
528

529 530
    func(DygraphExecutionContext<VarType>(
        op, empty_scope, *dev_ctx, ctx, ins, outs, attrs, default_attrs));
531
  }
532

533 534 535 536 537
  if (FLAGS_check_nan_inf) {
    framework::details::CheckOpHasNanOrInfInDygraph<VarType>(
        op.Type(), outs, dev_ctx->GetPlace());
  }

L
Leo Chen 已提交
538 539 540 541 542 543 544 545
  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
  }

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
  /**
   * [ 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);
  }
561
}
H
hong 已提交
562

563 564 565
template <typename VarType>
static void PreparedOpRunPtImpl(
    const framework::OperatorBase& op,
566
    const framework::OpKernelType& kernel_type,
567 568
    const phi::ArgumentMappingFn* arg_map_fn,
    const phi::KernelSignature* default_kernel_signature,
569 570 571 572 573 574
    const phi::KernelSignature& kernel_signature,
    const phi::Kernel& phi_kernel,
    platform::DeviceContext* dev_ctx,
    const NameVarMap<VarType>& ins,
    const NameVarMap<VarType>& outs,
    const framework::AttributeMap& attrs,
575
    const framework::AttributeMap& default_attrs) {
576
  {
577
    platform::RecordEvent record_event("infer_shape",
C
chenjian 已提交
578
                                       platform::TracerEventType::OperatorInner,
579 580 581 582 583 584 585 586 587 588
                                       1,
                                       platform::EventRole::kInnerOp);
    DygraphInferShapeContext<VarType> infer_shape_ctx(&ins,
                                                      &outs,
                                                      &attrs,
                                                      &default_attrs,
                                                      op.Type(),
                                                      &kernel_type,
                                                      arg_map_fn,
                                                      default_kernel_signature);
589
    op.Info().infer_shape_(&infer_shape_ctx);
C
chenjian 已提交
590 591 592
    record_event.End();
    platform::RecordOpInfoSupplement(
        op.Type(), op.Attrs(), infer_shape_ctx, kernel_signature);
593 594 595
  }

  {
596
    platform::RecordEvent record_event("compute",
C
chenjian 已提交
597
                                       platform::TracerEventType::OperatorInner,
598 599
                                       1,
                                       platform::EventRole::kInnerOp);
600

601
    PreparePhiData<VarType>(phi_kernel, kernel_signature, ins);
602

603
    phi::KernelContext pt_kernel_context;
604 605 606 607 608 609 610
    BuildDygraphPhiKernelContext<VarType>(kernel_signature,
                                          phi_kernel,
                                          ins,
                                          outs,
                                          attrs,
                                          default_attrs,
                                          dev_ctx,
611
                                          &pt_kernel_context);
612

613
    phi_kernel(&pt_kernel_context);
614
  }
615

616 617 618 619 620
  if (FLAGS_check_nan_inf) {
    framework::details::CheckOpHasNanOrInfInDygraph<VarType>(
        op.Type(), outs, dev_ctx->GetPlace());
  }

621 622
  if (FLAGS_benchmark) {
    dev_ctx->Wait();
623 624
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    PADDLE_ENFORCE_GPU_SUCCESS(platform::GpuGetLastError());
625 626 627 628
    VLOG(4) << "Operator(" << op.Type() << "): context wait and get last error";
#endif
  }

629 630 631
  if (framework::IsComplexType(kernel_type.data_type_)) {
    HandleComplexGradToRealGrad<VarType>(outs);
  }
632 633
}

634 635
void PreparedOp::Run(const NameVarMap<VarBase>& ins,
                     const NameVarMap<VarBase>& outs,
636 637
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
638
  if (run_phi_kernel_) {
639 640 641 642 643 644 645 646 647 648
    PreparedOpRunPtImpl<VarBase>(op_,
                                 kernel_type_,
                                 arg_map_fn_,
                                 default_kernel_signature_,
                                 kernel_signature_,
                                 phi_kernel_,
                                 dev_ctx_,
                                 ins,
                                 outs,
                                 attrs,
649
                                 default_attrs);
650
  } else {
651 652 653 654 655 656 657 658 659 660 661
    PreparedOpRunImpl<VarBase>(op_,
                               ctx_,
                               kernel_type_,
                               func_,
                               arg_map_fn_,
                               default_kernel_signature_,
                               dev_ctx_,
                               ins,
                               outs,
                               attrs,
                               default_attrs);
662
  }
663
}
H
hong 已提交
664

665 666
void PreparedOp::Run(const NameVarMap<VariableWrapper>& ins,
                     const NameVarMap<VariableWrapper>& outs,
667 668
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
669
  if (run_phi_kernel_) {
670 671 672 673 674 675 676 677 678 679 680
    PreparedOpRunPtImpl<VariableWrapper>(op_,
                                         kernel_type_,
                                         arg_map_fn_,
                                         default_kernel_signature_,
                                         kernel_signature_,
                                         phi_kernel_,
                                         dev_ctx_,
                                         ins,
                                         outs,
                                         attrs,
                                         default_attrs);
681
  } else {
682 683 684 685 686 687 688 689 690 691 692
    PreparedOpRunImpl<VariableWrapper>(op_,
                                       ctx_,
                                       kernel_type_,
                                       func_,
                                       arg_map_fn_,
                                       default_kernel_signature_,
                                       dev_ctx_,
                                       ins,
                                       outs,
                                       attrs,
                                       default_attrs);
693
  }
J
Jiabin Yang 已提交
694 695
}

696 697
void PreparedOp::Run(const NameVarMap<egr::EagerVariable>& ins,
                     const NameVarMap<egr::EagerVariable>& outs,
J
Jiabin Yang 已提交
698 699
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
700
  if (run_phi_kernel_) {
701 702 703 704 705 706 707 708 709 710 711
    PreparedOpRunPtImpl<egr::EagerVariable>(op_,
                                            kernel_type_,
                                            arg_map_fn_,
                                            default_kernel_signature_,
                                            kernel_signature_,
                                            phi_kernel_,
                                            dev_ctx_,
                                            ins,
                                            outs,
                                            attrs,
                                            default_attrs);
J
Jiabin Yang 已提交
712
  } else {
713 714 715 716 717 718 719 720 721 722 723
    PreparedOpRunImpl<egr::EagerVariable>(op_,
                                          ctx_,
                                          kernel_type_,
                                          func_,
                                          arg_map_fn_,
                                          default_kernel_signature_,
                                          dev_ctx_,
                                          ins,
                                          outs,
                                          attrs,
                                          default_attrs);
J
Jiabin Yang 已提交
724 725 726
  }
}

J
Jiabin Yang 已提交
727 728
}  // namespace imperative
}  // namespace paddle