nan_inf_utils_detail.cc 21.5 KB
Newer Older
W
WangXi 已提交
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/framework/details/nan_inf_utils_detail.h"
16 17

#include "paddle/fluid/framework/details/nan_inf_utils.h"
W
WangXi 已提交
18
#include "paddle/fluid/framework/op_proto_maker.h"
19
#include "paddle/fluid/framework/scope.h"
20 21

#ifdef PADDLE_WITH_ASCEND_CL
22
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
23
#endif
24
#include "paddle/fluid/framework/convert_utils.h"
Z
zyfncg 已提交
25
#include "paddle/phi/kernels/funcs/eigen/extensions.h"
26

W
WangXi 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
namespace paddle {
namespace framework {
namespace details {

static std::once_flag white_list_init_flag;

static int op_role_nan_inf_white_list = 0;

static constexpr int FORWARD = 0x10000;

// lazy init
static const std::unordered_map<std::string, int>& role_str2int() {
  /* In op_proto_maker.h
   * framework::OpRole::kForward      = 0x0000,
   * framework::OpRole::kBackward     = 0x0001,
   * framework::OpRole::kOptimize     = 0x0002,
   * framework::OpRole::kRPC          = 0x0004,
   * framework::OpRole::kDist         = 0x0008,
   * framework::OpRole::kLRSched      = 0x0010,
   * framework::OpRole::kLoss         = 0x0100,
   * framework::OpRole::kNotSpecified = 0x1000,
   */
  static const std::unordered_map<std::string, int> _role_str2int = {
      {"forward", FORWARD}, /* kForward=0, can't filter */
      {"backward", static_cast<int>(framework::OpRole::kBackward)},
      {"optimize", static_cast<int>(framework::OpRole::kOptimize)},
      {"rpc", static_cast<int>(framework::OpRole::kRPC)},
      {"dist", static_cast<int>(framework::OpRole::kDist)},
      {"lrsched", static_cast<int>(framework::OpRole::kLRSched)},
      {"loss", static_cast<int>(framework::OpRole::kLoss)},
      {"default", static_cast<int>(framework::OpRole::kNotSpecified)},
  };
  return _role_str2int;
}

static std::unordered_set<std::string>& op_type_nan_inf_white_list() {
  static std::unordered_set<std::string> _op_type_nan_inf_white_list = {
      "coalesce_tensor", /* This Op will alloc tensor, and may not init space */
  };
  return _op_type_nan_inf_white_list;
}

static std::unordered_map<std::string, std::vector<std::string>>&
op_var_nan_inf_white_list() {
  static std::unordered_map<std::string, std::vector<std::string>>
      _op_var_nan_inf_white_list = {
          /* encoded & gather var consist of idx&val, can't judge directly */
          {"dgc", {"__dgc_encoded__", "__dgc_gather__"}},
      };
  return _op_var_nan_inf_white_list;
}

static void InitWhiteListFormEnv() {
  // op_type_skip and op_var_skip may be NULL.
  // So need init static value in there, prevent thread competition.
  // NOTE. role_str2int needn't do this for it only used in this func.
  op_type_nan_inf_white_list();
  op_var_nan_inf_white_list();

  // export PADDLE_INF_NAN_SKIP_OP="op0,op1,op2"
  // export PADDLE_INF_NAN_SKIP_ROLE="role1,role2,role3"
  // export PADDLE_INF_NAN_SKIP_VAR="op0:var0,op0:var1,op1:var0"
  const char* op_type_skip = std::getenv("PADDLE_INF_NAN_SKIP_OP");
  const char* op_role_skip = std::getenv("PADDLE_INF_NAN_SKIP_ROLE");
  const char* op_var_skip = std::getenv("PADDLE_INF_NAN_SKIP_VAR");

  if (op_type_skip != NULL) {
    std::stringstream ss(op_type_skip);
    std::string op_type;
    while (std::getline(ss, op_type, ',')) {
      op_type_nan_inf_white_list().emplace(op_type);
    }
  }

  if (op_role_skip != NULL) {
    std::stringstream ss(op_role_skip);
    std::string op_role;
    while (std::getline(ss, op_role, ',')) {
      PADDLE_ENFORCE_EQ(role_str2int().find(op_role) != role_str2int().end(),
                        true,
                        platform::errors::InvalidArgument(
                            "Skip role must be one of "
                            "{forward,backward,optimize,rpc,dist,lrsched,loss,"
                            "default}, instead of %s",
                            op_role));
      op_role_nan_inf_white_list |= role_str2int().at(op_role);
    }
  }

  if (op_var_skip != NULL) {
    std::stringstream ss(op_var_skip);
    std::string op_var;
    while (std::getline(ss, op_var, ',')) {
      auto pos = op_var.find(":");
      PADDLE_ENFORCE_EQ(
122 123
          pos != std::string::npos,
          true,
W
WangXi 已提交
124 125 126 127 128 129 130 131 132 133 134
          platform::errors::InvalidArgument(
              "Skip var format must be op:var, instead of %s", op_var));
      std::string op = op_var.substr(0, pos);
      std::string var = op_var.substr(pos + 1);

      op_var_nan_inf_white_list()[op].emplace_back(var);
    }
  }
}

template <typename T>
135 136 137 138 139
static void PrintNanInf(const T* value,
                        const size_t numel,
                        int print_num,
                        const std::string& op_type,
                        const std::string& var_name,
140 141 142
                        bool abort = true) {
  T min_value = std::numeric_limits<T>::max();
  T max_value = std::numeric_limits<T>::min();
W
WangXi 已提交
143 144 145 146 147 148 149 150 151 152 153 154
  size_t nan_count, inf_count, num_count;
  nan_count = inf_count = num_count = 0;

  // CPU print num value
  for (size_t i = 0; i < numel; ++i) {
    size_t count = 0;
    if (std::isnan(value[i])) {
      count = nan_count++;
    } else if (std::isinf(value[i])) {
      count = inf_count++;
    } else {
      count = num_count++;
155 156
      min_value = std::min(min_value, value[i]);
      max_value = std::max(max_value, value[i]);
W
WangXi 已提交
157 158 159
    }

    if (count < static_cast<size_t>(print_num)) {
160 161 162
      printf("numel:%zu index:%zu value:%f\n",
             numel,
             i,
163
             static_cast<float>(value[i]));
W
WangXi 已提交
164 165
    }
  }
166
  printf(
167
      "In cpu, there has %zu,%zu,%zu nan,inf,num. "
168
      "And in num, min_value is %f, max_value is %f\n",
169 170 171
      nan_count,
      inf_count,
      num_count,
172
      static_cast<double>(min_value),
173 174 175
      static_cast<double>(max_value));
  if (abort) {
    PADDLE_THROW(platform::errors::PreconditionNotMet(
176 177
        "There are `nan` or `inf` in tensor (%s) of operator (%s).",
        var_name,
178 179
        op_type));
  }
W
WangXi 已提交
180 181 182 183 184 185 186
}

// openmp 4.0, reduction with fp16
#if defined _OPENMP && _OPENMP >= 201307
// more detail see: 180 page of
// https://www.openmp.org/wp-content/uploads/OpenMP4.0.0.pdf
#pragma omp declare reduction(+ : paddle::platform::float16 : omp_out += omp_in)
187 188
#pragma omp declare reduction(+ : paddle::platform::bfloat16 : omp_out += \
                              omp_in)
189 190 191 192 193
#pragma omp declare reduction(+ : paddle::platform::complex < \
                                  float > : omp_out += omp_in)
#pragma omp declare reduction(+ : paddle::platform::complex < \
                                  double > : omp_out += omp_in)

W
WangXi 已提交
194 195 196
#endif

template <typename T>
197 198 199
static void CheckNanInf(const T* value,
                        const size_t numel,
                        int print_num,
W
WangXi 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
                        const std::string& op_type,
                        const std::string& var_name) {
  T sum = static_cast<T>(0.0);
#if defined _OPENMP && _OPENMP >= 201307
#pragma omp parallel for simd reduction(+ : sum)
#elif defined _OPENMP
#pragma omp parallel for reduction(+ : sum)
#endif
  for (size_t i = 0; i < numel; ++i) {
    sum += (value[i] - value[i]);
  }

  if (std::isnan(sum) || std::isinf(sum)) {
    PrintNanInf(value, numel, print_num, op_type, var_name);
  }
}

#if defined _OPENMP && _OPENMP >= 201307
// openmp4.0 not need to specialization fp16
#elif defined _OPENMP
template <>
void CheckNanInf<paddle::platform::float16>(
222 223 224 225 226
    const paddle::platform::float16* value,
    const size_t numel,
    int print_num,
    const std::string& op_type,
    const std::string& var_name) {
W
WangXi 已提交
227
  float sum = 0.0f;
228 229 230 231 232 233 234 235 236 237 238 239
#pragma omp parallel for reduction(+ : sum)
  for (size_t i = 0; i < numel; ++i) {
    sum += static_cast<float>(value[i] - value[i]);
  }

  if (std::isnan(sum) || std::isinf(sum)) {
    PrintNanInf(value, numel, print_num, op_type, var_name);
  }
}

template <>
void CheckNanInf<paddle::platform::bfloat16>(
240 241 242 243 244
    const paddle::platform::bfloat16* value,
    const size_t numel,
    int print_num,
    const std::string& op_type,
    const std::string& var_name) {
245
  float sum = 0.0f;
W
WangXi 已提交
246 247 248 249 250 251 252 253 254
#pragma omp parallel for reduction(+ : sum)
  for (size_t i = 0; i < numel; ++i) {
    sum += static_cast<float>(value[i] - value[i]);
  }

  if (std::isnan(sum) || std::isinf(sum)) {
    PrintNanInf(value, numel, print_num, op_type, var_name);
  }
}
255

256 257
template <>
void CheckNanInf<paddle::platform::complex<float>>(
258 259 260 261 262
    const paddle::platform::complex<float>* value,
    const size_t numel,
    int print_num,
    const std::string& op_type,
    const std::string& var_name) {
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  float real_sum = 0.0f;
#pragma omp parallel for reduction(+ : real_sum)
  for (size_t i = 0; i < numel; ++i) {
    real_sum += (value[i].real - value[i].real);
  }

  float imag_sum = 0.0f;
#pragma omp parallel for reduction(+ : imag_sum)
  for (size_t i = 0; i < numel; ++i) {
    imag_sum += (value[i].imag - value[i].imag);
  }

  if (std::isnan(real_sum) || std::isinf(real_sum) || std::isnan(imag_sum) ||
      std::isinf(imag_sum)) {
    // hot fix for compile failed in gcc4.8
    // here also need print detail info of nan or inf later
    PADDLE_THROW(platform::errors::PreconditionNotMet(
280 281
        "There are `nan` or `inf` in tensor (%s) of operator (%s).",
        var_name,
282 283 284 285 286
        op_type));
  }
}

template <>
287
    void CheckNanInf < paddle::platform::complex < double >>>
288 289 290 291 292
    (const paddle::platform::complex<double>* value,
     const size_t numel,
     int print_num,
     const std::string& op_type,
     const std::string& var_name) {
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
  double real_sum = 0.0;
#pragma omp parallel for reduction(+ : real_sum)
  for (size_t i = 0; i < numel; ++i) {
    real_sum += (value[i].real - value[i].real);
  }

  double imag_sum = 0.0;
#pragma omp parallel for reduction(+ : imag_sum)
  for (size_t i = 0; i < numel; ++i) {
    imag_sum += (value[i].imag - value[i].imag);
  }

  if (std::isnan(real_sum) || std::isinf(real_sum) || std::isnan(imag_sum) ||
      std::isinf(imag_sum)) {
    // hot fix for compile failed in gcc4.8
    // here also need print detail info of nan or inf later
    PADDLE_THROW(platform::errors::PreconditionNotMet(
310 311
        "There are `nan` or `inf` in tensor (%s) of operator (%s).",
        var_name,
312 313 314 315
        op_type));
  }
}

W
WangXi 已提交
316 317 318 319
#endif

template <>
template <typename T>
L
Leo Chen 已提交
320
void TensorCheckerVisitor<phi::CPUContext>::apply(
321 322 323 324 325
    typename std::enable_if<
        std::is_floating_point<T>::value ||
        std::is_same<T, ::paddle::platform::complex<float>>::value ||
        std::is_same<T, ::paddle::platform::complex<double>>::value>::type*)
    const {
W
WangXi 已提交
326 327
  // use env strategy control in future, -1=print_all.
  int print_num = 3;
328 329
  CheckNanInf(
      tensor_.data<T>(), tensor_.numel(), print_num, op_type_, var_name_);
W
WangXi 已提交
330 331 332
}

template <>
L
Leo Chen 已提交
333 334
void tensor_check<phi::CPUContext>(const std::string& op_type,
                                   const std::string& var_name,
335
                                   const phi::DenseTensor& tensor,
L
Leo Chen 已提交
336 337
                                   const platform::Place& place) {
  TensorCheckerVisitor<phi::CPUContext> vistor(
338
      op_type, var_name, tensor, place);
339
  VisitDataType(framework::TransToProtoVarType(tensor.dtype()), vistor);
W
WangXi 已提交
340 341 342 343
}

void CheckVarHasNanOrInf(const std::string& op_type,
                         const std::string& var_name,
344
                         const framework::Variable* var,
W
WangXi 已提交
345 346
                         const platform::Place& place) {
  PADDLE_ENFORCE_NOT_NULL(
347 348 349
      var,
      platform::errors::NotFound(
          "Cannot find var: `%s` in op `%s`.", var_name, op_type));
W
WangXi 已提交
350

351
  const phi::DenseTensor* tensor{nullptr};
352 353
  if (var->IsType<phi::DenseTensor>()) {
    tensor = &var->Get<phi::DenseTensor>();
354 355
  } else if (var->IsType<phi::SelectedRows>()) {
    tensor = &var->Get<phi::SelectedRows>().value();
W
WangXi 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369
  } else {
    VLOG(10) << var_name << " var_name need not to check";
    return;
  }

  if (tensor->memory_size() == 0) {
    VLOG(10) << var_name << " var_name need not to check, size == 0";
    return;
  }

  VLOG(10) << "begin check " << op_type << " var_name:" << var_name
           << ", place:" << tensor->place() << ", numel:" << tensor->numel();

  if (platform::is_gpu_place(tensor->place())) {
370
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
L
Leo Chen 已提交
371
    tensor_check<phi::GPUContext>(op_type, var_name, *tensor, place);
W
WangXi 已提交
372 373
#else
    PADDLE_THROW(platform::errors::PreconditionNotMet(
374 375
        "phi::DenseTensor[%s] use gpu place. PaddlePaddle must compile with "
        "GPU.",
W
WangXi 已提交
376
        var_name));
377 378 379 380
#endif
    return;
  } else if (platform::is_xpu_place(tensor->place())) {
#ifdef PADDLE_WITH_XPU
381 382
    if (framework::TransToProtoVarType(tensor->dtype()) !=
        proto::VarType::FP32) {
383 384 385 386
      return;
    }

    float* cpu_data = new float[tensor->numel()];
387 388
    memory::Copy(platform::CPUPlace(),
                 static_cast<void*>(cpu_data),
389
                 tensor->place(),
T
taixiurong 已提交
390 391
                 static_cast<const void*>(tensor->data<float>()),
                 tensor->numel() * sizeof(float));
392 393 394 395 396 397 398 399 400
    bool flag = false;
    for (int i = 0; i < tensor->numel(); i++) {
      if (isnan(cpu_data[i]) || isinf(cpu_data[i])) {
        flag = true;
        break;
      }
    }
    delete[] cpu_data;
    PADDLE_ENFORCE_NE(
401 402 403
        flag,
        true,
        platform::errors::Fatal(
404 405 406
            "Operator %s output phi::DenseTensor %s contains Inf.",
            op_type,
            var_name));
407 408
#else
    PADDLE_THROW(platform::errors::PreconditionNotMet(
409 410
        "phi::DenseTensor[%s] use xpu place. PaddlePaddle must compile with "
        "XPU.",
411
        var_name));
W
WangXi 已提交
412 413
#endif
    return;
414 415
  } else if (platform::is_npu_place(tensor->place())) {
#ifdef PADDLE_WITH_ASCEND_CL
416 417
    if (framework::TransToProtoVarType(tensor->dtype()) !=
        proto::VarType::FP32) {
418 419 420
      return;
    }

421
    phi::DenseTensor cpu_tensor;
422 423
    cpu_tensor.Resize(tensor->dims());
    float* cpu_data = static_cast<float*>(
424
        cpu_tensor.mutable_data(platform::CPUPlace(), tensor->dtype()));
W
WangXi 已提交
425

426 427 428 429 430 431 432 433 434
    framework::TensorCopySync(*tensor, platform::CPUPlace(), &cpu_tensor);
    bool flag = false;
    for (int i = 0; i < cpu_tensor.numel(); i++) {
      if (isnan(cpu_data[i]) || isinf(cpu_data[i])) {
        flag = true;
        break;
      }
    }
    PADDLE_ENFORCE_NE(
435 436 437
        flag,
        true,
        platform::errors::Fatal(
438 439 440
            "Operator %s output phi::DenseTensor %s contains Inf.",
            op_type,
            var_name));
441 442
#else
    PADDLE_THROW(platform::errors::PreconditionNotMet(
443 444
        "phi::DenseTensor[%s] use npu place. PaddlePaddle must compile with "
        "NPU.",
445 446 447 448
        var_name));
#endif
    return;
  }
L
Leo Chen 已提交
449
  tensor_check<phi::CPUContext>(op_type, var_name, *tensor, place);
W
WangXi 已提交
450 451
}

452
void CheckVarHasNanOrInf(const std::string& op_type,
453
                         const framework::Scope& scope,
454 455 456 457 458 459
                         const std::string& var_name,
                         const platform::Place& place) {
  auto* var = scope.FindVar(var_name);
  CheckVarHasNanOrInf(op_type, var_name, var, place);
}

W
WangXi 已提交
460 461 462
bool IsSkipOp(const framework::OperatorBase& op) {
  if (op_type_nan_inf_white_list().count(op.Type()) != 0) return true;

463 464 465 466 467
  int op_role = 0;
  if (op.HasAttr(framework::OpProtoAndCheckerMaker::OpRoleAttrName())) {
    op_role = op.template Attr<int>(
        framework::OpProtoAndCheckerMaker::OpRoleAttrName());
  }
W
WangXi 已提交
468 469 470 471 472 473 474 475 476 477

  // kForward=0, can't filter
  if (op_role == static_cast<int>(framework::OpRole::kForward)) {
    op_role = FORWARD;
  }
  if (op_role_nan_inf_white_list & op_role) return true;

  return false;
}

478 479 480 481 482
#ifdef PADDLE_WITH_ASCEND_CL
using NpuOpRunner = paddle::operators::NpuOpRunner;

constexpr int FLOAT_STATUS_SIZE = 8;

483 484
static phi::DenseTensor& npu_float_status() {
  static phi::DenseTensor float_status;
485 486 487 488
  return float_status;
}

void NPUAllocAndClearFloatStatus(const framework::OperatorBase& op,
489
                                 const framework::Scope& scope,
490 491 492 493 494 495 496 497 498 499 500 501 502 503
                                 const platform::Place& place) {
  if (!platform::is_npu_place(place)) return;

  std::call_once(white_list_init_flag, InitWhiteListFormEnv);
  if (IsSkipOp(op)) return;

  auto* dev_ctx = reinterpret_cast<platform::NPUDeviceContext*>(
      platform::DeviceContextPool::Instance().Get(place));
  auto stream = dev_ctx->stream();

  auto& flag = npu_float_status();
  flag.mutable_data<float>({FLOAT_STATUS_SIZE}, place);
  NpuOpRunner("NPUAllocFloatStatus", {}, {flag}).Run(stream);

504
  phi::DenseTensor tmp;
505 506 507 508
  tmp.mutable_data<float>({FLOAT_STATUS_SIZE}, place);
  NpuOpRunner("NPUClearFloatStatus", {tmp}, {flag}).Run(stream);
}

509 510
void PrintNpuVarInfo(const std::string& op_type,
                     const std::string& var_name,
511 512
                     const framework::Variable* var,
                     const platform::Place& place) {
513
  const phi::DenseTensor* tensor{nullptr};
514 515
  if (var->IsType<phi::DenseTensor>()) {
    tensor = &var->Get<phi::DenseTensor>();
516 517
  } else if (var->IsType<phi::SelectedRows>()) {
    tensor = &var->Get<phi::SelectedRows>().value();
518 519 520 521 522
  } else {
    VLOG(10) << var_name << " var_name need not to check";
    return;
  }

523 524 525 526
  if ((framework::TransToProtoVarType(tensor->dtype()) !=
       proto::VarType::FP32) &&
      (framework::TransToProtoVarType(tensor->dtype()) !=
       proto::VarType::FP16)) {
527 528 529 530 531 532 533 534 535 536 537
    return;
  }

  if (tensor->memory_size() == 0) {
    VLOG(10) << var_name << " var_name need not to check, size == 0";
    return;
  }

  VLOG(10) << "begin check " << op_type << " var_name:" << var_name
           << ", place:" << tensor->place() << ", numel:" << tensor->numel();

538
  phi::DenseTensor cpu_tensor;
539
  cpu_tensor.Resize(tensor->dims());
540
  cpu_tensor.mutable_data(platform::CPUPlace(), tensor->dtype());
541 542 543 544 545
  framework::TensorCopySync(*tensor, platform::CPUPlace(), &cpu_tensor);

  LOG(WARNING) << "print [" << var_name << "] tensor info:";
  // use env strategy control in future, -1=print_all.
  int print_num = 3;
546
  if (framework::TransToProtoVarType(tensor->dtype()) == proto::VarType::FP32) {
547 548
    const float* value = cpu_tensor.data<float>();
    PrintNanInf(value, tensor->numel(), print_num, op_type, var_name, false);
549 550
  } else if (framework::TransToProtoVarType(tensor->dtype()) ==
             proto::VarType::FP16) {
551 552 553 554 555 556 557
    const paddle::platform::float16* value =
        cpu_tensor.data<paddle::platform::float16>();
    PrintNanInf(value, tensor->numel(), print_num, op_type, var_name, false);
  }
}

void PrintNPUOpValueInfo(const framework::OperatorBase& op,
558
                         const framework::Scope& scope,
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
                         const platform::Place& place) {
  LOG(WARNING) << "There are `nan` or `inf` in operator (" << op.Type()
               << "), here we print some tensor value info of this op.";
  for (auto& vname : op.InputVars()) {
    auto* var = scope.FindVar(vname);
    if (var == nullptr) continue;
    PrintNpuVarInfo(op.Type(), vname, var, place);
  }

  for (auto& vname : op.OutputVars(true)) {
    auto* var = scope.FindVar(vname);
    if (var == nullptr) continue;
    PrintNpuVarInfo(op.Type(), vname, var, place);
  }
}

static void NPUCheckOpHasNanOrInf(const framework::OperatorBase& op,
576
                                  const framework::Scope& scope,
577 578 579 580 581 582 583 584
                                  const platform::Place& place) {
  if (!platform::is_npu_place(place)) return;

  auto* dev_ctx = reinterpret_cast<platform::NPUDeviceContext*>(
      platform::DeviceContextPool::Instance().Get(place));
  auto stream = dev_ctx->stream();

  auto& flag = npu_float_status();
585
  phi::DenseTensor tmp;
586 587 588 589 590
  tmp.mutable_data<float>({FLOAT_STATUS_SIZE}, place);
  // NPUGetFloatStatus updates data on input in-place.
  // tmp is only placeholder.
  NpuOpRunner("NPUGetFloatStatus", {flag}, {tmp}).Run(stream);

591
  phi::DenseTensor cpu_tensor;
592 593 594 595 596 597 598 599 600 601 602 603
  auto cpu_place = platform::CPUPlace();
  float* cpu_data = static_cast<float*>(
      cpu_tensor.mutable_data<float>({FLOAT_STATUS_SIZE}, cpu_place));

  framework::TensorCopySync(flag, cpu_place, &cpu_tensor);
  float sum = 0.0;
  for (int i = 0; i < FLOAT_STATUS_SIZE; ++i) {
    sum += cpu_data[i];
  }

  if (sum >= 1.0) PrintNPUOpValueInfo(op, scope, place);

604 605
  PADDLE_ENFORCE_LT(sum,
                    1.0,
606 607
                    platform::errors::PreconditionNotMet(
                        "Operator %s contains Nan/Inf.", op.Type()));
608 609 610
}
#endif

W
WangXi 已提交
611
void CheckOpHasNanOrInf(const framework::OperatorBase& op,
612
                        const framework::Scope& exec_scope,
W
WangXi 已提交
613 614 615 616 617
                        const platform::Place& place) {
  std::call_once(white_list_init_flag, InitWhiteListFormEnv);

  if (IsSkipOp(op)) return;

618 619 620 621 622 623 624
#ifdef PADDLE_WITH_ASCEND_CL
  if (platform::is_npu_place(place)) {
    NPUCheckOpHasNanOrInf(op, exec_scope, place);
    return;
  }
#endif

W
WangXi 已提交
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
  if (op_var_nan_inf_white_list().count(op.Type()) == 0) {
    // NOTE. vname may destruct in the end of this func.
    for (auto& vname : op.OutputVars(true)) {
      auto* var = exec_scope.FindVar(vname);
      if (var == nullptr) continue;
      CheckVarHasNanOrInf(op.Type(), exec_scope, vname, place);
    }
  } else {
    for (auto& vname : op.OutputVars(true)) {
      bool need_check = true;
      for (auto& white_vname : op_var_nan_inf_white_list().at(op.Type())) {
        if (vname.find(white_vname) != std::string::npos) {
          need_check = false;
          break;
        }
      }
      if (!need_check) continue;
      auto* var = exec_scope.FindVar(vname);
      if (var == nullptr) continue;
      CheckVarHasNanOrInf(op.Type(), exec_scope, vname, place);
    }
  }
}

}  // namespace details
}  // namespace framework
}  // namespace paddle