prepared_operator.cc 22.6 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
static const phi::Kernel empty_kernel;
40 41
static const framework::RuntimeContext empty_ctx({}, {});
static const framework::Scope empty_scope;
42

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

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

J
Jiabin Yang 已提交
95
template <>
96 97
void HandleComplexGradToRealGrad<egr::EagerVariable>(
    const NameVarMap<egr::EagerVariable>& outs) {
J
Jiabin Yang 已提交
98 99 100
  // TODO(jiabin): Support Complex here.
}

101 102 103 104 105
void TestHandleComplexGradToRealGradEager(
    const NameVarMap<egr::EagerVariable>& outs) {
  HandleComplexGradToRealGrad<egr::EagerVariable>(outs);
}

J
Jiabin Yang 已提交
106 107
PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
108
                       const framework::OpKernelType& kernel_type,
109
                       const framework::OperatorWithKernel::OpKernelFunc& func,
110
                       platform::DeviceContext* dev_ctx)
111 112 113 114
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(func),
115 116
      dev_ctx_(dev_ctx),
      pt_kernel_(empty_kernel) {}
117

118 119 120
PreparedOp::PreparedOp(const framework::OperatorBase& op,
                       const framework::RuntimeContext& ctx,
                       const framework::OpKernelType& kernel_type,
121
                       framework::KernelSignature&& kernel_signature,
122
                       const phi::Kernel& pt_kernel,
123 124 125 126 127 128
                       platform::DeviceContext* dev_ctx)
    : op_(op),
      ctx_(ctx),
      kernel_type_(kernel_type),
      func_(nullptr),
      dev_ctx_(dev_ctx),
129
      run_phi_kernel_(true),
130
      pt_kernel_signature_(std::move(kernel_signature)),
131
      pt_kernel_(pt_kernel) {}
132

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

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

159
  // 1. get expected kernel key
160
  auto dygraph_exe_ctx = DygraphExecutionContext<VarType>(
161
      op, empty_scope, *dev_ctx, empty_ctx, ins, outs, attrs, default_attrs);
162
  auto expected_kernel_key = op.GetExpectedKernelType(dygraph_exe_ctx);
163

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

174
#endif
175

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  bool has_phi_kernel = false;

  const auto* arg_map_fn =
      phi::OpUtilsMap::Instance().GetArgumentMappingFn(op.Type());
  if (arg_map_fn) {
    has_phi_kernel = true;
    pt_kernel_signature = (*arg_map_fn)(
        framework::ExecutionArgumentMappingContext(dygraph_exe_ctx));
  } else {
    const auto* kernel_sig =
        phi::DefaultKernelSignatureMap::Instance().GetNullable(op.Type());
    if (kernel_sig) {
      has_phi_kernel = true;
      pt_kernel_signature = *kernel_sig;
    }
  }

  if (has_phi_kernel) {
    VLOG(6) << pt_kernel_signature;
195
    pt_kernel_name = pt_kernel_signature.name;
196 197 198
// 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 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
#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) {
215 216
        auto expected_kernel_key_library_type =
            expected_kernel_key.library_type_;
L
Liu-xiandong 已提交
217
        expected_kernel_key.library_type_ = paddle::framework::LibraryType::kKP;
218
        VLOG(3) << "modifing XPU KP kernel: " << op.Type()
L
Liu-xiandong 已提交
219
                << ", using_kernel_key:" << expected_kernel_key;
220 221
        phi::KernelKey try_pt_kernel_key =
            TransOpKernelTypeToPhiKernelKey(expected_kernel_key);
222 223
        if (!phi::KernelFactory::Instance().HasKernel(pt_kernel_name,
                                                      try_pt_kernel_key)) {
224 225 226 227
          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 已提交
228 229 230
      }
    }
#endif
231

232
    pt_kernel_key = TransOpKernelTypeToPhiKernelKey(expected_kernel_key);
233 234
    auto& pt_kernel = phi::KernelFactory::Instance().SelectKernel(
        pt_kernel_name, pt_kernel_key);
235

236
    if (pt_kernel.IsValid()
L
Liu-xiandong 已提交
237
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
238 239 240
        && !is_xpu_unsupport
#endif
        ) {
C
Chen Weihang 已提交
241
      VLOG(6) << "Dynamic mode PrepareImpl - kernel name: " << pt_kernel_name
242 243 244
              << " | kernel key: " << pt_kernel_key
              << " | kernel: " << pt_kernel;

F
From00 已提交
245 246
      if (expected_kernel_key.place_ != place) {
        dev_ctx = pool.Get(expected_kernel_key.place_);
W
Wilber 已提交
247
      }
F
From00 已提交
248

249
      return PreparedOp(op, empty_ctx, expected_kernel_key,
250
                        std::move(pt_kernel_signature), pt_kernel, dev_ctx);
251
    } else {
252
      VLOG(6) << "Dynamic mode ChoosePhiKernel - kernel `" << pt_kernel_name
253 254 255 256
              << "` not found.";
    }
  }

257
  // 2. check if op[type] has kernel registered.
J
Jiabin Yang 已提交
258 259
  auto& all_op_kernels = op.AllOpKernels();
  auto kernels_iter = all_op_kernels.find(op.Type());
260

261 262 263
// 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.
264 265 266 267 268 269 270 271 272 273 274 275 276 277
#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

278 279 280
  if ((kernels_iter == all_op_kernels.end() ||
       kernels_iter->second.find(expected_kernel_key) ==
           kernels_iter->second.end())
L
Liu-xiandong 已提交
281
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
282
      || is_xpu_unsupport
283
#endif
284 285 286 287
#if defined(PADDLE_WITH_XPU_KP)
      || (is_xpu_unsupport && !is_xpu_kp_support)
#endif
          ) {
288
    if (phi::KernelFactory::Instance().HasCompatiblePhiKernel(op.Type())) {
289 290
      auto pt_cpu_kernel_key =
          FallBackToCpu(expected_kernel_key, pt_kernel_key, op);
291
      auto& pt_cpu_kernel = phi::KernelFactory::Instance().SelectKernel(
292 293 294 295 296 297
          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());
298
        return PreparedOp(op, empty_ctx, expected_kernel_key,
299 300
                          std::move(pt_kernel_signature), pt_cpu_kernel,
                          cpu_ctx);
301 302 303 304
      }
    }
  }

305 306 307 308 309
  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()));
310

J
Jiabin Yang 已提交
311 312
  auto& kernels = kernels_iter->second;
  auto kernel_iter = kernels.find(expected_kernel_key);
313

314
#if defined(PADDLE_WITH_XPU) && !defined(PADDLE_WITH_XPU_KP)
315
  if (paddle::platform::is_xpu_place(expected_kernel_key.place_) &&
316
      (kernel_iter == kernels.end() || is_xpu_unsupport)) {
317 318 319
    VLOG(3) << "missing XPU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
320 321 322
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
323
#endif
L
Liu-xiandong 已提交
324 325

#ifdef PADDLE_WITH_XPU_KP
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  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 已提交
347 348 349
  }
#endif

350 351
#ifdef PADDLE_WITH_ASCEND_CL
  if (kernel_iter == kernels.end() &&
352
      paddle::platform::is_npu_place(expected_kernel_key.place_)) {
353 354 355
    VLOG(3) << "missing NPU kernel: " << op.Type()
            << ", expected_kernel_key:" << expected_kernel_key
            << ", fallbacking to CPU one!";
356 357 358
    expected_kernel_key.place_ = platform::CPUPlace();
    kernel_iter = kernels.find(expected_kernel_key);
  }
359 360 361
#endif
#ifdef PADDLE_WITH_MLU
  if (kernel_iter == kernels.end() &&
362
      paddle::platform::is_mlu_place(expected_kernel_key.place_)) {
363 364 365 366 367 368
    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);
  }
369 370 371 372 373 374 375 376 377 378
#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);
  }
379
#endif
380 381
  // TODO(jiabin): Add operator.cc's line 1000 part back when we need that
  // case
382 383 384 385
  PADDLE_ENFORCE_NE(kernel_iter, kernels.end(),
                    platform::errors::NotFound(
                        "Operator %s does not have kernel for %s.", op.Type(),
                        KernelTypeToString(expected_kernel_key)));
386

387 388 389 390
  if (!(expected_kernel_key.place_ == place)) {
    dev_ctx = pool.Get(expected_kernel_key.place_);
  }

391 392
  return PreparedOp(op, empty_ctx, expected_kernel_key, kernel_iter->second,
                    dev_ctx);
393 394
}

395 396 397 398
PreparedOp PreparedOp::Prepare(const NameVarMap<VarBase>& ins,
                               const NameVarMap<VarBase>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
399
                               const framework::AttributeMap& attrs,
400 401
                               const framework::AttributeMap& default_attrs) {
  return PrepareImpl<VarBase>(ins, outs, op, place, attrs, default_attrs);
402 403 404 405 406 407
}

PreparedOp PreparedOp::Prepare(const NameVarMap<VariableWrapper>& ins,
                               const NameVarMap<VariableWrapper>& outs,
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
408
                               const framework::AttributeMap& attrs,
409
                               const framework::AttributeMap& default_attrs) {
410
  return PrepareImpl<VariableWrapper>(ins, outs, op, place, attrs,
411
                                      default_attrs);
412 413
}

414 415
PreparedOp PreparedOp::Prepare(const NameVarMap<egr::EagerVariable>& ins,
                               const NameVarMap<egr::EagerVariable>& outs,
J
Jiabin Yang 已提交
416 417 418 419
                               const framework::OperatorWithKernel& op,
                               const platform::Place& place,
                               const framework::AttributeMap& attrs,
                               const framework::AttributeMap& default_attrs) {
420 421
  return PrepareImpl<egr::EagerVariable>(ins, outs, op, place, attrs,
                                         default_attrs);
J
Jiabin Yang 已提交
422
}
423 424 425
template <typename VarType>
static void PreparedOpRunImpl(
    const framework::OperatorBase& op, const framework::RuntimeContext& ctx,
426
    const framework::OpKernelType& kernel_type,
427
    const framework::OperatorWithKernel::OpKernelFunc& func,
428
    platform::DeviceContext* dev_ctx, const NameVarMap<VarType>& ins,
429 430
    const NameVarMap<VarType>& outs, const framework::AttributeMap& attrs,
    const framework::AttributeMap& default_attrs) {
J
Jiabin Yang 已提交
431 432
  // TODO(zjl): remove scope in dygraph
  framework::Scope scope;
H
hong 已提交
433

434
  {
C
chenjian 已提交
435 436 437
    platform::RecordEvent record_event(op.Type() + "::infer_shape",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
438 439 440 441 442 443
    DygraphInferShapeContext<VarType> infer_shape_ctx(
        &ins, &outs, &attrs, &default_attrs, op.Type(), &kernel_type);
    op.Info().infer_shape_(&infer_shape_ctx);
  }

  {
C
chenjian 已提交
444 445 446
    platform::RecordEvent record_event(op.Type() + "::compute",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
H
hong 已提交
447

448 449 450
    func(DygraphExecutionContext<VarType>(op, scope, *dev_ctx, ctx, ins, outs,
                                          attrs, default_attrs));
  }
451

452 453 454 455 456
  if (FLAGS_check_nan_inf) {
    framework::details::CheckOpHasNanOrInfInDygraph<VarType>(
        op.Type(), outs, dev_ctx->GetPlace());
  }

L
Leo Chen 已提交
457 458 459 460 461 462 463 464
  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
  }

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  /**
   * [ 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);
  }
480
}
H
hong 已提交
481

482 483 484
template <typename VarType>
static void PreparedOpRunPtImpl(
    const framework::OperatorBase& op,
485
    const framework::OpKernelType& kernel_type,
486
    const framework::KernelSignature& pt_kernel_signature,
487
    const phi::Kernel& pt_kernel, platform::DeviceContext* dev_ctx,
488 489
    const NameVarMap<VarType>& ins, const NameVarMap<VarType>& outs,
    const framework::AttributeMap& attrs,
490
    const framework::AttributeMap& default_attrs) {
491
  {
C
chenjian 已提交
492 493 494
    platform::RecordEvent record_event(op.Type() + "::infer_shape",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
495 496 497 498 499 500
    DygraphInferShapeContext<VarType> infer_shape_ctx(
        &ins, &outs, &attrs, &default_attrs, op.Type(), &kernel_type);
    op.Info().infer_shape_(&infer_shape_ctx);
  }

  {
C
chenjian 已提交
501 502 503
    platform::RecordEvent record_event(op.Type() + "::compute",
                                       platform::TracerEventType::OperatorInner,
                                       1, platform::EventRole::kInnerOp);
504

505
    PreparePhiData<VarType>(pt_kernel, pt_kernel_signature, ins);
506

507
    phi::KernelContext pt_kernel_context;
508 509 510
    BuildDygraphPhiKernelContext<VarType>(pt_kernel_signature, pt_kernel, ins,
                                          outs, attrs, default_attrs, dev_ctx,
                                          &pt_kernel_context);
511

512 513
    pt_kernel(&pt_kernel_context);
  }
514

515 516 517 518 519
  if (FLAGS_check_nan_inf) {
    framework::details::CheckOpHasNanOrInfInDygraph<VarType>(
        op.Type(), outs, dev_ctx->GetPlace());
  }

520 521
  if (FLAGS_benchmark) {
    dev_ctx->Wait();
522 523
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    PADDLE_ENFORCE_GPU_SUCCESS(platform::GpuGetLastError());
524 525 526 527
    VLOG(4) << "Operator(" << op.Type() << "): context wait and get last error";
#endif
  }

528 529 530
  if (framework::IsComplexType(kernel_type.data_type_)) {
    HandleComplexGradToRealGrad<VarType>(outs);
  }
531 532
}

533 534
void PreparedOp::Run(const NameVarMap<VarBase>& ins,
                     const NameVarMap<VarBase>& outs,
535 536
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
537
  if (run_phi_kernel_) {
538
    PreparedOpRunPtImpl<VarBase>(op_, kernel_type_, pt_kernel_signature_,
539 540
                                 pt_kernel_, dev_ctx_, ins, outs, attrs,
                                 default_attrs);
541 542 543 544
  } else {
    PreparedOpRunImpl<VarBase>(op_, ctx_, kernel_type_, func_, dev_ctx_, ins,
                               outs, attrs, default_attrs);
  }
545
}
H
hong 已提交
546

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

561 562
void PreparedOp::Run(const NameVarMap<egr::EagerVariable>& ins,
                     const NameVarMap<egr::EagerVariable>& outs,
J
Jiabin Yang 已提交
563 564
                     const framework::AttributeMap& attrs,
                     const framework::AttributeMap& default_attrs) {
565
  if (run_phi_kernel_) {
566
    PreparedOpRunPtImpl<egr::EagerVariable>(
J
Jiabin Yang 已提交
567 568 569
        op_, kernel_type_, pt_kernel_signature_, pt_kernel_, dev_ctx_, ins,
        outs, attrs, default_attrs);
  } else {
570 571 572
    PreparedOpRunImpl<egr::EagerVariable>(op_, ctx_, kernel_type_, func_,
                                          dev_ctx_, ins, outs, attrs,
                                          default_attrs);
J
Jiabin Yang 已提交
573 574 575
  }
}

J
Jiabin Yang 已提交
576 577
}  // namespace imperative
}  // namespace paddle