tester_helper.h 39.0 KB
Newer Older
L
luotao1 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2018 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.

#pragma once

#include <gtest/gtest.h>
Y
Yan Chunwei 已提交
18

L
luotao1 已提交
19
#include <algorithm>
20
#include <functional>
L
luotao1 已提交
21
#include <memory>
T
Tao Luo 已提交
22
#include <string>
L
luotao1 已提交
23
#include <thread>  // NOLINT
L
luotao1 已提交
24
#include <unordered_map>
25
#include <utility>
L
luotao1 已提交
26
#include <vector>
Y
Yiqun Liu 已提交
27 28 29
#ifdef WITH_GPERFTOOLS
#include <gperftools/profiler.h>
#endif
L
luotao1 已提交
30
#include "paddle/fluid/framework/ir/fuse_pass_base.h"
31
#include "paddle/fluid/framework/scope.h"
L
luotao1 已提交
32 33 34
#include "paddle/fluid/inference/analysis/analyzer.h"
#include "paddle/fluid/inference/analysis/ut_helper.h"
#include "paddle/fluid/inference/api/analysis_predictor.h"
35
#include "paddle/fluid/inference/api/helper.h"
Y
Yan Chunwei 已提交
36
#include "paddle/fluid/inference/api/paddle_inference_pass.h"
37
#include "paddle/fluid/inference/tests/api/config_printer.h"
T
Tao Luo 已提交
38
#include "paddle/fluid/inference/tests/test_helper.h"
N
nhzlx 已提交
39
#include "paddle/fluid/inference/utils/benchmark.h"
L
luotao1 已提交
40 41
#include "paddle/fluid/platform/profiler.h"

N
nhzlx 已提交
42
DEFINE_string(model_name, "", "model name");
L
luotao1 已提交
43
DEFINE_string(infer_model, "", "model path");
44 45
DEFINE_string(fp32_model, "", "FP32 model path");
DEFINE_string(int8_model, "", "INT8 model path");
L
luotao1 已提交
46
DEFINE_string(infer_data, "", "data file");
T
Tao Luo 已提交
47
DEFINE_string(refer_result, "", "reference result for comparison");
48
DEFINE_int32(batch_size, 1, "batch size");
49
DEFINE_bool(ernie_large, false, "Test ernie large");
50 51
DEFINE_bool(with_accuracy_layer, true,
            "Calculate the accuracy while label is in the input");
52
DEFINE_bool(enable_fp32, true, "Enable FP32 type prediction");
53 54
DEFINE_bool(enable_bf16, false, "Enable BF16 type prediction");
DEFINE_bool(enable_int8, false, "Enable INT8 type prediction");
55 56 57
DEFINE_int32(warmup_batch_size, 100, "batch size for quantization warmup");
// setting iterations to 0 means processing the whole dataset
DEFINE_int32(iterations, 0, "number of batches to process");
L
luotao1 已提交
58 59 60
DEFINE_int32(repeat, 1, "Running the inference program repeat times.");
DEFINE_bool(test_all_data, false, "Test the all dataset in data file.");
DEFINE_int32(num_threads, 1, "Running the inference program in multi-threads.");
T
Tao Luo 已提交
61 62
DEFINE_bool(use_analysis, true,
            "Running the inference program in analysis mode.");
N
nhzlx 已提交
63 64
DEFINE_bool(record_benchmark, false,
            "Record benchmark after profiling the model");
L
luotao1 已提交
65
DEFINE_double(accuracy, 1e-3, "Result Accuracy.");
66
DEFINE_double(quantized_accuracy, 1e-2, "Result Quantized Accuracy.");
L
luotao1 已提交
67
DEFINE_bool(zero_copy, false, "Use ZeroCopy to speedup Feed/Fetch.");
68 69 70
DEFINE_bool(warmup, false,
            "Use warmup to calculate elapsed_time more accurately. "
            "To reduce CI time, it sets false in default.");
71
DEFINE_int32(warmup_iters, 1, "Number of batches to process during warmup.");
L
luotao1 已提交
72

73 74
DEFINE_bool(enable_profile, false, "Turn on profiler for fluid");
DEFINE_int32(cpu_num_threads, 1, "Number of threads for each paddle instance.");
75

L
luotao1 已提交
76 77 78
namespace paddle {
namespace inference {

79 80
using paddle::framework::proto::VarType;

81 82 83 84 85 86 87 88 89 90 91 92 93
template <typename T>
constexpr paddle::PaddleDType GetPaddleDType();

template <>
constexpr paddle::PaddleDType GetPaddleDType<int64_t>() {
  return paddle::PaddleDType::INT64;
}

template <>
constexpr paddle::PaddleDType GetPaddleDType<float>() {
  return paddle::PaddleDType::FLOAT32;
}

94
void PrintConfig(const PaddlePredictor::Config *config, bool use_analysis) {
95
  const auto *analysis_config =
96
      reinterpret_cast<const AnalysisConfig *>(config);
97
  if (use_analysis) {
98
    LOG(INFO) << *analysis_config;
99 100
    return;
  }
101
  LOG(INFO) << analysis_config->ToNativeConfig();
102
}
Y
Yan Chunwei 已提交
103

104 105 106 107 108 109 110 111
void CheckError(float data_ref, float data) {
  if (std::abs(data_ref) > 1) {
    CHECK_LE(std::abs((data_ref - data) / data_ref), FLAGS_accuracy);
  } else {
    CHECK_LE(std::abs(data_ref - data), FLAGS_accuracy);
  }
}

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
class Barrier {
 public:
  explicit Barrier(std::size_t count) : _count(count) {}
  void Wait() {
    std::unique_lock<std::mutex> lock(_mutex);
    if (--_count) {
      _cv.wait(lock, [this] { return _count == 0; });
    } else {
      _cv.notify_all();
    }
  }

 private:
  std::mutex _mutex;
  std::condition_variable _cv;
  std::size_t _count;
};

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
template <typename T>
class TensorReader {
 public:
  TensorReader(std::ifstream &file, size_t beginning_offset,
               std::vector<int> shape, std::string name)
      : file_(file), position_(beginning_offset), shape_(shape), name_(name) {
    numel_ = std::accumulate(shape_.begin(), shape_.end(), size_t{1},
                             std::multiplies<size_t>());
  }

  PaddleTensor NextBatch() {
    PaddleTensor tensor;
    tensor.name = name_;
    tensor.shape = shape_;
    tensor.dtype = GetPaddleDType<T>();
    tensor.data.Resize(numel_ * sizeof(T));

    file_.seekg(position_);
    file_.read(static_cast<char *>(tensor.data.data()), numel_ * sizeof(T));
    position_ = file_.tellg();

    if (file_.eof()) LOG(ERROR) << name_ << ": reached end of stream";
    if (file_.fail())
      throw std::runtime_error(name_ + ": failed reading file.");

    return tensor;
  }

 protected:
  std::ifstream &file_;
  size_t position_;
  std::vector<int> shape_;
  std::string name_;
  size_t numel_;
};

std::shared_ptr<std::vector<PaddleTensor>> GetWarmupData(
    const std::vector<std::vector<PaddleTensor>> &test_data,
    int num_images = FLAGS_warmup_batch_size) {
  int test_data_batch_size = test_data[0][0].shape[0];
  auto iterations = test_data.size();
  auto all_test_data_size = iterations * test_data_batch_size;
  PADDLE_ENFORCE_LE(static_cast<size_t>(num_images), all_test_data_size,
                    platform::errors::InvalidArgument(
                        "The requested quantization warmup data size must be "
                        "lower or equal to the test data size. But received"
                        "warmup size is %d and test data size is %d. Please "
                        "use --warmup_batch_size parameter to set smaller "
                        "warmup batch size.",
                        num_images, all_test_data_size));

  PaddleTensor images;
  images.name = "image";
  images.shape = {num_images, 3, 224, 224};
  images.dtype = PaddleDType::FLOAT32;
  images.data.Resize(sizeof(float) * num_images * 3 * 224 * 224);

  PaddleTensor labels;
  labels.name = "label";
  labels.shape = {num_images, 1};
  labels.dtype = PaddleDType::INT64;
  labels.data.Resize(sizeof(int64_t) * num_images);

  for (int i = 0; i < num_images; i++) {
    auto batch = i / test_data_batch_size;
    auto element_in_batch = i % test_data_batch_size;
    std::copy_n(static_cast<float *>(test_data[batch][0].data.data()) +
                    element_in_batch * 3 * 224 * 224,
                3 * 224 * 224,
                static_cast<float *>(images.data.data()) + i * 3 * 224 * 224);

    std::copy_n(static_cast<int64_t *>(test_data[batch][1].data.data()) +
                    element_in_batch,
                1, static_cast<int64_t *>(labels.data.data()) + i);
  }

  auto warmup_data = std::make_shared<std::vector<PaddleTensor>>(2);
  (*warmup_data)[0] = std::move(images);
  (*warmup_data)[1] = std::move(labels);
  return warmup_data;
}

void SetInputs(std::vector<std::vector<PaddleTensor>> *inputs,
               int32_t batch_size = FLAGS_batch_size) {
  std::ifstream file(FLAGS_infer_data, std::ios::binary);
  if (!file) {
    FAIL() << "Couldn't open file: " << FLAGS_infer_data;
  }

  int64_t total_images{0};
  file.read(reinterpret_cast<char *>(&total_images), sizeof(total_images));
  LOG(INFO) << "Total images in file: " << total_images;

  std::vector<int> image_batch_shape{batch_size, 3, 224, 224};
  std::vector<int> label_batch_shape{batch_size, 1};
  auto images_offset_in_file = static_cast<size_t>(file.tellg());
  auto labels_offset_in_file =
      images_offset_in_file + sizeof(float) * total_images * 3 * 224 * 224;

  TensorReader<float> image_reader(file, images_offset_in_file,
                                   image_batch_shape, "image");
  TensorReader<int64_t> label_reader(file, labels_offset_in_file,
                                     label_batch_shape, "label");

  auto iterations_max = total_images / batch_size;
  auto iterations = iterations_max;
  if (FLAGS_iterations > 0 && FLAGS_iterations < iterations_max) {
    iterations = FLAGS_iterations;
  }
  for (auto i = 0; i < iterations; i++) {
    auto images = image_reader.NextBatch();
    auto labels = label_reader.NextBatch();
    inputs->emplace_back(
        std::vector<PaddleTensor>{std::move(images), std::move(labels)});
  }
}

247
// Compare result between two PaddleTensor
L
luotao1 已提交
248
void CompareResult(const std::vector<PaddleTensor> &outputs,
T
tensor-tang 已提交
249
                   const std::vector<PaddleTensor> &ref_outputs) {
T
Tao Luo 已提交
250
  EXPECT_GT(outputs.size(), 0UL);
T
tensor-tang 已提交
251
  EXPECT_EQ(outputs.size(), ref_outputs.size());
L
luotao1 已提交
252 253
  for (size_t i = 0; i < outputs.size(); i++) {
    auto &out = outputs[i];
T
tensor-tang 已提交
254
    auto &ref_out = ref_outputs[i];
255 256
    size_t size = VecReduceToInt(out.shape);
    size_t ref_size = VecReduceToInt(ref_out.shape);
257
    EXPECT_GT(size, 0UL);
T
tensor-tang 已提交
258 259
    EXPECT_EQ(size, ref_size);
    EXPECT_EQ(out.dtype, ref_out.dtype);
260 261 262 263 264 265 266 267 268 269 270

#define COMPARE(paddle_type, type, func)                        \
  case paddle_type: {                                           \
    type *pdata = static_cast<type *>(out.data.data());         \
    type *pdata_ref = static_cast<type *>(ref_out.data.data()); \
    for (size_t j = 0; j < size; ++j) {                         \
      func(pdata_ref[j], pdata[j]);                             \
    }                                                           \
    break;                                                      \
  }

T
tensor-tang 已提交
271
    switch (out.dtype) {
272 273 274 275 276 277 278 279 280
      COMPARE(PaddleDType::INT64, int64_t, EXPECT_EQ);
      COMPARE(PaddleDType::FLOAT32, float, CheckError);
      COMPARE(PaddleDType::INT32, int32_t, EXPECT_EQ);
      COMPARE(PaddleDType::UINT8, uint8_t, EXPECT_EQ);
      COMPARE(PaddleDType::INT8, int8_t, EXPECT_EQ);
      default:
        PADDLE_THROW(platform::errors::InvalidArgument(
            "VarMessageToVarType: Unsupported dtype %d",
            static_cast<int>(out.dtype)));
L
luotao1 已提交
281
    }
282
#undef COMPARE
L
luotao1 已提交
283 284 285
  }
}

286 287 288 289 290 291 292 293 294 295 296 297
// Compare result between a PaddleTensor and a ZeroCopyTensor
void CompareResult(const std::vector<PaddleTensor> &outputs,
                   const std::vector<ZeroCopyTensor> &ref_outputs) {
  EXPECT_GT(outputs.size(), 0UL);
  EXPECT_EQ(outputs.size(), ref_outputs.size());
  for (size_t i = 0; i < outputs.size(); i++) {
    auto &out = outputs[i];
    auto &ref_out = ref_outputs[i];
    size_t size = VecReduceToInt(out.shape);
    EXPECT_GT(size, 0UL);
    int ref_size = 0;  // this is the number of elements not memory size
    PaddlePlace place;
298 299 300 301 302 303 304 305 306 307 308 309

#define COMPARE(paddle_type, type, func)                     \
  case paddle_type: {                                        \
    type *pdata = static_cast<type *>(out.data.data());      \
    type *pdata_ref = ref_out.data<type>(&place, &ref_size); \
    EXPECT_EQ(size, static_cast<size_t>(ref_size));          \
    for (size_t j = 0; j < size; ++j) {                      \
      func(pdata_ref[j], pdata[j]);                          \
    }                                                        \
    break;                                                   \
  }

310
    switch (out.dtype) {
311 312 313 314 315 316 317 318 319
      COMPARE(PaddleDType::INT64, int64_t, EXPECT_EQ);
      COMPARE(PaddleDType::FLOAT32, float, CheckError);
      COMPARE(PaddleDType::INT32, int32_t, EXPECT_EQ);
      COMPARE(PaddleDType::UINT8, uint8_t, EXPECT_EQ);
      COMPARE(PaddleDType::INT8, int8_t, EXPECT_EQ);
      default:
        PADDLE_THROW(platform::errors::InvalidArgument(
            "VarMessageToVarType: Unsupported dtype %d",
            static_cast<int>(out.dtype)));
320
    }
321
#undef COMPARE
322 323 324
  }
}

325
std::unique_ptr<PaddlePredictor> CreateTestPredictor(
326
    const PaddlePredictor::Config *config, bool use_analysis = true) {
327
  const auto *analysis_config =
328
      reinterpret_cast<const AnalysisConfig *>(config);
T
Tao Luo 已提交
329
  if (use_analysis) {
330
    return CreatePaddlePredictor<AnalysisConfig>(*analysis_config);
T
Tao Luo 已提交
331
  }
332 333
  auto native_config = analysis_config->ToNativeConfig();
  return CreatePaddlePredictor<NativeConfig>(native_config);
T
Tao Luo 已提交
334 335
}

336
size_t GetSize(const PaddleTensor &out) { return VecReduceToInt(out.shape); }
T
Tao Luo 已提交
337

338
std::unordered_map<std::string, int> GetFuseStatis(PaddlePredictor *predictor,
T
Tao Luo 已提交
339
                                                   int *num_ops) {
340
  std::unordered_map<std::string, int> res;
341
  auto *analysis_predictor = static_cast<AnalysisPredictor *>(predictor);
342 343 344 345 346 347
  auto *fusion_status =
      analysis_predictor->analysis_argument().fusion_statis_ptr();
  if (!fusion_status) {
    return res;
  }
  for (auto &item : *fusion_status) {
T
Tao Luo 已提交
348 349 350 351
    LOG(INFO) << "fused " << item.first << " " << item.second;
  }
  int num = 0;
  for (auto &node :
352 353
       analysis_predictor->analysis_argument().main_graph().Nodes()) {
    if (node->IsOp()) {
T
Tao Luo 已提交
354 355 356 357
      ++num;
    }
  }
  *num_ops = num;
358
  return *fusion_status;
T
Tao Luo 已提交
359 360
}

T
Tao Luo 已提交
361
void SetFakeImageInput(std::vector<std::vector<PaddleTensor>> *inputs,
362 363
                       const std::string &dirname, bool is_combined = true,
                       std::string model_filename = "model",
T
tensor-tang 已提交
364
                       std::string params_filename = "params",
N
nhzlx 已提交
365 366
                       const std::vector<std::string> *feed_names = nullptr,
                       const int continuous_inuput_index = 0) {
T
Tao Luo 已提交
367
  // Set fake_image_data
368 369 370 371 372
  PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0,
                    platform::errors::InvalidArgument(
                        "In SetFakeImageInput, expected test_all_data = false, "
                        "but now test_all_data=",
                        FLAGS_test_all_data));
373 374 375 376 377 378 379 380 381 382 383
  std::vector<std::vector<int64_t>> feed_target_shapes = GetFeedTargetShapes(
      dirname, is_combined, model_filename, params_filename);
  std::ostringstream os;
  for (size_t i = 0; i < feed_target_shapes.size(); ++i) {
    os << "feed target " << i << ": {" << feed_target_shapes[i][0];
    for (size_t j = 1; j < feed_target_shapes[i].size(); ++j) {
      os << ", " << feed_target_shapes[i][j];
    }
    os << "}\n";
  }
  LOG(INFO) << os.str();
T
tensor-tang 已提交
384
  if (feed_names) {
385 386 387 388 389 390 391
    PADDLE_ENFORCE_EQ(
        feed_names->size(), feed_target_shapes.size(),
        platform::errors::InvalidArgument(
            "The size of feeds_names and size of "
            "feed_target_shapes must be equal, but now feeds_names "
            "size is %d and feed_target_shapes size is %d",
            feed_names->size(), feed_target_shapes.size()));
T
tensor-tang 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404 405
  }
  std::vector<PaddleTensor> input_slots(feed_target_shapes.size());
  for (size_t i = 0; i < feed_target_shapes.size(); ++i) {
    const auto &feed_shape = feed_target_shapes[i];
    auto &input = input_slots[i];
    std::vector<int> shape({FLAGS_batch_size});
    for (size_t s = 1; s < feed_shape.size(); ++s) {
      shape.push_back(static_cast<int>(feed_shape[s]));
    }
    if (feed_names) {
      input.name = (*feed_names)[i];
    }
    input.shape = shape;
    input.dtype = PaddleDType::FLOAT32;
406
    size_t len = std::accumulate(shape.begin(), shape.end(), size_t{1},
T
tensor-tang 已提交
407 408 409 410 411 412
                                 [](int a, int b) { return a * b; });
    input.data.Resize(len * sizeof(float));
    input.lod.assign({{0, static_cast<size_t>(FLAGS_batch_size)}});
    float *input_data = static_cast<float *>(input.data.data());
    // fill input data, for profile easily, do not use random data here.
    for (size_t j = 0; j < len; ++j) {
N
nhzlx 已提交
413 414
      *(input_data + j) =
          static_cast<float>((j + continuous_inuput_index) % len) / len;
T
tensor-tang 已提交
415
    }
T
Tao Luo 已提交
416 417 418 419
  }
  (*inputs).emplace_back(input_slots);
}

420 421 422 423 424 425 426 427 428 429 430 431
void GetInputPerBatch(const std::vector<std::vector<int64_t>> &in,
                      std::vector<std::vector<int64_t>> *out,
                      std::vector<size_t> *lod, size_t batch_iter,
                      size_t batch_end) {
  lod->clear();
  lod->push_back(0);
  for (auto it = in.begin() + batch_iter; it < in.begin() + batch_end; it++) {
    out->push_back(*it);
    lod->push_back(lod->back() + (*it).size());  // calculate lod
  }
}

L
luotao1 已提交
432 433 434 435 436 437 438 439 440 441 442
void ConvertPaddleTensorToZeroCopyTensor(
    PaddlePredictor *predictor, const std::vector<PaddleTensor> &inputs) {
  for (size_t i = 0; i < inputs.size(); i++) {
    auto input = inputs[i];
    auto tensor = predictor->GetInputTensor(input.name);
    tensor->Reshape(input.shape);
    tensor->SetLoD({input.lod});
    if (input.dtype == PaddleDType::INT64) {
      ZeroCopyTensorAssignData<int64_t>(tensor.get(), input.data);
    } else if (input.dtype == PaddleDType::FLOAT32) {
      ZeroCopyTensorAssignData<float>(tensor.get(), input.data);
L
luotao1 已提交
443 444
    } else if (input.dtype == PaddleDType::INT32) {
      ZeroCopyTensorAssignData<int32_t>(tensor.get(), input.data);
445 446
    } else if (input.dtype == PaddleDType::UINT8) {
      ZeroCopyTensorAssignData<uint8_t>(tensor.get(), input.data);
L
luotao1 已提交
447 448 449 450 451
    } else {
      LOG(ERROR) << "unsupported feed type " << input.dtype;
    }
  }
}
452

L
luotao1 已提交
453 454
void PredictionWarmUp(PaddlePredictor *predictor,
                      const std::vector<std::vector<PaddleTensor>> &inputs,
455
                      std::vector<std::vector<PaddleTensor>> *outputs,
456 457
                      int num_threads, int tid,
                      const VarType::Type data_type = VarType::FP32) {
L
luotao1 已提交
458 459 460 461 462
  int batch_size = FLAGS_batch_size;
  LOG(INFO) << "Running thread " << tid << ", warm up run...";
  if (FLAGS_zero_copy) {
    ConvertPaddleTensorToZeroCopyTensor(predictor, inputs[0]);
  }
463 464 465 466
  int iterations = 1;
  if (FLAGS_warmup_iters > 1)
    iterations = std::min(FLAGS_warmup_iters, static_cast<int>(inputs.size()));
  outputs->resize(iterations);
L
luotao1 已提交
467
  Timer warmup_timer;
468
  double elapsed_time = 0;
L
luotao1 已提交
469
  if (!FLAGS_zero_copy) {
470 471 472 473 474
    for (int i = 0; i < iterations; ++i) {
      warmup_timer.tic();
      predictor->Run(inputs[i], &(*outputs)[i], batch_size);
      elapsed_time += warmup_timer.toc();
    }
L
luotao1 已提交
475
  } else {
476 477 478 479 480
    for (int i = 0; i < iterations; ++i) {
      warmup_timer.tic();
      predictor->ZeroCopyRun();
      elapsed_time += warmup_timer.toc();
    }
481
  }
482 483 484
  auto batch_latency = elapsed_time / iterations;
  PrintTime(batch_size, 1, num_threads, tid, batch_latency, iterations,
            data_type);
485
  if (FLAGS_enable_profile) {
L
luotao1 已提交
486 487 488
    paddle::platform::ResetProfiler();
  }
}
489

L
luotao1 已提交
490 491
void PredictionRun(PaddlePredictor *predictor,
                   const std::vector<std::vector<PaddleTensor>> &inputs,
492
                   std::vector<std::vector<PaddleTensor>> *outputs,
493
                   int num_threads, int tid,
494 495
                   const VarType::Type data_type = VarType::FP32,
                   float *sample_latency = nullptr) {
L
luotao1 已提交
496
  int num_times = FLAGS_repeat;
497
  int iterations = inputs.size();  // process the whole dataset ...
498 499
  if (FLAGS_iterations > 0 &&
      FLAGS_iterations < static_cast<int64_t>(inputs.size()))
500 501 502 503 504
    iterations =
        FLAGS_iterations;  // ... unless the number of iterations is set
  outputs->resize(iterations);
  LOG(INFO) << "Thread " << tid << ", number of threads " << num_threads
            << ", run " << num_times << " times...";
L
luotao1 已提交
505 506
  Timer run_timer;
  double elapsed_time = 0;
Y
Yiqun Liu 已提交
507
#ifdef WITH_GPERFTOOLS
L
luotao1 已提交
508
  ProfilerStart("paddle_inference.prof");
Y
Yiqun Liu 已提交
509
#endif
510
  int predicted_num = 0;
L
luotao1 已提交
511
  if (!FLAGS_zero_copy) {
512
    for (int i = 0; i < iterations; i++) {
513
      run_timer.tic();
L
luotao1 已提交
514
      for (int j = 0; j < num_times; j++) {
515
        predictor->Run(inputs[i], &(*outputs)[i], FLAGS_batch_size);
516
      }
517 518 519 520 521 522
      elapsed_time += run_timer.toc();

      predicted_num += FLAGS_batch_size;
      if (predicted_num % 100 == 0) {
        LOG(INFO) << predicted_num << " samples";
      }
L
luotao1 已提交
523
    }
L
luotao1 已提交
524
  } else {
525
    for (int i = 0; i < iterations; i++) {
L
luotao1 已提交
526 527 528 529 530 531
      ConvertPaddleTensorToZeroCopyTensor(predictor, inputs[i]);
      run_timer.tic();
      for (int j = 0; j < num_times; j++) {
        predictor->ZeroCopyRun();
      }
      elapsed_time += run_timer.toc();
532 533 534 535 536

      predicted_num += FLAGS_batch_size;
      if (predicted_num % 100 == 0) {
        LOG(INFO) << predicted_num << " samples";
      }
L
luotao1 已提交
537 538
    }
  }
539

Y
Yiqun Liu 已提交
540
#ifdef WITH_GPERFTOOLS
L
luotao1 已提交
541
  ProfilerStop();
Y
Yiqun Liu 已提交
542
#endif
N
nhzlx 已提交
543

544 545
  auto batch_latency = elapsed_time / (iterations * num_times);
  PrintTime(FLAGS_batch_size, num_times, num_threads, tid, batch_latency,
546
            iterations, data_type);
547 548 549 550

  if (sample_latency != nullptr)
    *sample_latency = batch_latency / FLAGS_batch_size;

L
luotao1 已提交
551 552 553
  if (FLAGS_record_benchmark) {
    Benchmark benchmark;
    benchmark.SetName(FLAGS_model_name);
554 555
    benchmark.SetBatchSize(FLAGS_batch_size);
    benchmark.SetLatency(batch_latency);
L
luotao1 已提交
556
    benchmark.PersistToFile("benchmark_record.txt");
L
luotao1 已提交
557 558 559
  }
}

L
luotao1 已提交
560 561 562
void TestOneThreadPrediction(
    const PaddlePredictor::Config *config,
    const std::vector<std::vector<PaddleTensor>> &inputs,
563
    std::vector<std::vector<PaddleTensor>> *outputs, bool use_analysis = true,
564 565
    const VarType::Type data_type = VarType::FP32,
    float *sample_latency = nullptr) {
L
luotao1 已提交
566
  auto predictor = CreateTestPredictor(config, use_analysis);
567
  if (FLAGS_warmup) {
568
    PredictionWarmUp(predictor.get(), inputs, outputs, 1, 0, data_type);
569
  }
570 571
  PredictionRun(predictor.get(), inputs, outputs, 1, 0, data_type,
                sample_latency);
L
luotao1 已提交
572 573
}

L
luotao1 已提交
574
void TestMultiThreadPrediction(
575
    const PaddlePredictor::Config *config,
576
    const std::vector<std::vector<PaddleTensor>> &inputs,
577
    std::vector<std::vector<PaddleTensor>> *outputs, int num_threads,
T
Tao Luo 已提交
578
    bool use_analysis = true) {
L
luotao1 已提交
579
  std::vector<std::thread> threads;
L
luotao1 已提交
580 581 582 583 584
  std::vector<std::unique_ptr<PaddlePredictor>> predictors;
  predictors.emplace_back(CreateTestPredictor(config, use_analysis));
  for (int tid = 1; tid < num_threads; tid++) {
    predictors.emplace_back(predictors.front()->Clone());
  }
585

L
luotao1 已提交
586 587 588 589
  for (int tid = 0; tid < num_threads; ++tid) {
    threads.emplace_back([&, tid]() {
      // Each thread should have local inputs and outputs.
      // The inputs of each thread are all the same.
590
      std::vector<std::vector<PaddleTensor>> outputs_tid;
L
luotao1 已提交
591
      auto &predictor = predictors[tid];
592 593 594 595
      if (FLAGS_warmup) {
        PredictionWarmUp(predictor.get(), inputs, &outputs_tid, num_threads,
                         tid);
      }
596
      PredictionRun(predictor.get(), inputs, &outputs_tid, num_threads, tid);
L
luotao1 已提交
597 598 599 600 601 602 603
    });
  }
  for (int i = 0; i < num_threads; ++i) {
    threads[i].join();
  }
}

604
void TestPrediction(const PaddlePredictor::Config *config,
605
                    const std::vector<std::vector<PaddleTensor>> &inputs,
606 607
                    std::vector<std::vector<PaddleTensor>> *outputs,
                    int num_threads, bool use_analysis = FLAGS_use_analysis) {
608
  PrintConfig(config, use_analysis);
L
luotao1 已提交
609
  if (num_threads == 1) {
T
Tao Luo 已提交
610
    TestOneThreadPrediction(config, inputs, outputs, use_analysis);
L
luotao1 已提交
611
  } else {
T
Tao Luo 已提交
612 613
    TestMultiThreadPrediction(config, inputs, outputs, num_threads,
                              use_analysis);
L
luotao1 已提交
614 615 616
  }
}

617 618 619
void SummarizeAccuracy(float avg_acc_ref, float avg_acc, int compared_idx) {
  std::string data_type_name = "INT8";
  if (FLAGS_enable_bf16) data_type_name = "BF16";
620 621 622 623 624 625 626 627 628 629 630 631 632 633
  PADDLE_ENFORCE_LE(
      compared_idx, 2,
      platform::errors::InvalidArgument(
          "The compared_idx should be <= 2. But received compared_idx = %d. "
          "For top1 accuracy, set compared_idx = 1; For top5 accuracy or mean "
          "Average Precision (mAP), set compared_idx = 2.",
          compared_idx));
  PADDLE_ENFORCE_GE(
      compared_idx, 1,
      platform::errors::InvalidArgument(
          "The compared_idx should be >= 1. But received compared_idx = %d. "
          "For top1 accuracy, set compared_idx = 1; For top5 accuracy or mean "
          "Average Precision (mAP), set compared_idx = 2.",
          compared_idx));
634
  std::string prefix = (compared_idx == 1) ? "top1_accuracy " : "mAP ";
635
  LOG(INFO) << "--- Accuracy summary --- ";
636 637
  LOG(INFO) << "Accepted " << prefix
            << "drop threshold: " << FLAGS_quantized_accuracy
638 639
            << ". (condition: (FP32_" << prefix << " - " << data_type_name
            << "_" << prefix << ") <= threshold)";
640
  LOG(INFO) << "FP32: avg " << prefix << std::fixed << std::setw(6)
641 642 643
            << std::setprecision(4) << avg_acc_ref;
  LOG(INFO) << data_type_name << ": avg " << prefix << std::fixed
            << std::setw(6) << std::setprecision(4) << avg_acc;
644 645
}

646 647 648 649 650 651 652 653
void SummarizePerformance(const char *title, float sample) {
  CHECK_GT(sample, 0.0);
  auto throughput = 1000.0 / sample;
  LOG(INFO) << title << ": avg fps: " << std::fixed << std::setw(6)
            << std::setprecision(4) << throughput << ", avg latency: " << sample
            << " ms";
}

654 655
void SummarizePerformance(const char *title_fp32, float sample_latency_fp32,
                          const char *title, float sample_latency) {
656 657 658
  if (FLAGS_enable_fp32) SummarizePerformance(title_fp32, sample_latency_fp32);
  if (FLAGS_enable_int8 || FLAGS_enable_bf16)
    SummarizePerformance(title, sample_latency);
659 660
}

661 662
float CompareAccuracyOne(
    const std::vector<std::vector<PaddleTensor>> &output_slots,
663
    int compared_idx) {
664 665 666 667
  PADDLE_ENFORCE_GT(output_slots.size(), 0,
                    platform::errors::InvalidArgument(
                        "The accuracy vector is empty. The accuracy vector "
                        "size should be bigger than 0"));
668

669 670 671 672 673 674 675
  float total_accs{0};

  for (size_t i = 0; i < output_slots.size(); ++i) {
    switch (compared_idx) {
      case 1:
        PADDLE_ENFORCE_GE(
            output_slots[i].size(), 2UL,
676 677 678 679
            platform::errors::InvalidArgument(
                "To achieve top 1 accuracy, output_slots size "
                "must be bigger than or equal to 2, but now the size is %d",
                output_slots[i].size()));
680 681 682
        break;
      case 2:
        PADDLE_ENFORCE_GE(
683 684 685 686 687 688
            output_slots[i].size(), 3UL,
            platform::errors::InvalidArgument(
                "To achieve top 5 accuracy or mean Average "
                "Precision (mAP), output_slots size must be "
                "bigger than or equal to 3, but now the size is %d",
                output_slots[i].size()));
689 690 691 692
        break;
      default:
        throw std::invalid_argument(
            "CompareAccuracy: compared_idx is out of range.");
693 694
    }

695
    if (output_slots[i][compared_idx].lod.size() > 0)
696
      throw std::invalid_argument("CompareAccuracy: output has nonempty LoD.");
697 698

    if (output_slots[i][compared_idx].dtype != paddle::PaddleDType::FLOAT32)
699
      throw std::invalid_argument(
700
          "CompareAccuracy: output is of a wrong type.");
701 702 703

    total_accs +=
        *static_cast<float *>(output_slots[i][compared_idx].data.data());
704
  }
705 706 707 708 709 710 711 712

  return total_accs / output_slots.size();
}

void CompareAccuracy(
    const std::vector<std::vector<PaddleTensor>> &output_slots_quant,
    const std::vector<std::vector<PaddleTensor>> &output_slots_ref,
    int compared_idx) {
713
  if ((FLAGS_enable_fp32 && (FLAGS_enable_int8 || FLAGS_enable_bf16)) &&
714 715 716 717 718 719 720
      (output_slots_quant.size() == 0 || output_slots_ref.size()) == 0)
    throw std::invalid_argument(
        "CompareAccuracy: output_slots vector is empty.");

  float avg_acc_quant = 0.0;
  float avg_acc_ref = 0.0;

721
  if (FLAGS_enable_int8 || FLAGS_enable_bf16)
722 723 724 725
    avg_acc_quant = CompareAccuracyOne(output_slots_quant, compared_idx);

  if (FLAGS_enable_fp32)
    avg_acc_ref = CompareAccuracyOne(output_slots_ref, compared_idx);
726

727
  SummarizeAccuracy(avg_acc_ref, avg_acc_quant, compared_idx);
728 729 730

  if (FLAGS_enable_fp32) CHECK_GT(avg_acc_ref, 0.0);

731
  if (FLAGS_enable_int8 || FLAGS_enable_bf16) CHECK_GT(avg_acc_quant, 0.0);
732

733
  if (FLAGS_enable_fp32 && (FLAGS_enable_int8 || FLAGS_enable_bf16))
734
    CHECK_LE(avg_acc_ref - avg_acc_quant, FLAGS_quantized_accuracy);
735 736
}

L
luotao1 已提交
737 738 739 740 741 742 743 744 745
void CompareDeterministic(
    const PaddlePredictor::Config *config,
    const std::vector<std::vector<PaddleTensor>> &inputs) {
  int batch_size = FLAGS_batch_size;
  int num_times = FLAGS_repeat;
  auto predictor = CreateTestPredictor(config, FLAGS_use_analysis);

  std::vector<PaddleTensor> warmup_outputs, outputs;
  // run num_times to Compare Deterministic Result.
746 747 748 749
  for (size_t j = 0; j < inputs.size(); j++) {
    // warmup run
    predictor->Run(inputs[j], &warmup_outputs, batch_size);
    for (int i = 0; i < num_times; i++) {
L
luotao1 已提交
750 751 752 753 754 755
      predictor->Run(inputs[j], &outputs, batch_size);
      CompareResult(outputs, warmup_outputs);
    }
  }
}

T
Tao Luo 已提交
756
void CompareNativeAndAnalysis(
757
    const PaddlePredictor::Config *config,
758
    const std::vector<std::vector<PaddleTensor>> &inputs) {
759
  PrintConfig(config, true);
760
  std::vector<std::vector<PaddleTensor>> native_outputs, analysis_outputs;
761
  TestOneThreadPrediction(config, inputs, &native_outputs, false);
T
Tao Luo 已提交
762
  TestOneThreadPrediction(config, inputs, &analysis_outputs, true);
763 764 765 766 767 768 769 770
  PADDLE_ENFORCE_GT(native_outputs.size(), 0,
                    platform::errors::InvalidArgument(
                        "The native outputs is empty. The native outputs "
                        "vector size must be bigger than 0"));
  PADDLE_ENFORCE_GT(analysis_outputs.size(), 0,
                    platform::errors::InvalidArgument(
                        "The analysis outputs is empty. The analysis outputs "
                        "vector size must be bigger than 0"));
771
  CompareResult(analysis_outputs.back(), native_outputs.back());
T
Tao Luo 已提交
772 773
}

774
void CompareQuantizedAndAnalysis(
775
    const AnalysisConfig *config, const AnalysisConfig *qconfig,
776 777
    const std::vector<std::vector<PaddleTensor>> &inputs,
    const int compared_idx = 1) {
778 779 780 781 782 783
  PADDLE_ENFORCE_EQ(
      inputs[0][0].shape[0], FLAGS_batch_size,
      platform::errors::InvalidArgument(
          "Input data has to be packed batch by batch. The batchsize is set to "
          "%d, but the real input is packed with batchsize = %d",
          FLAGS_batch_size, inputs[0][0].shape[0]));
784 785 786 787 788 789 790
  LOG(INFO) << "FP32 & INT8 prediction run: batch_size " << FLAGS_batch_size
            << ", warmup batch size " << FLAGS_warmup_batch_size << ".";

  LOG(INFO) << "--- FP32 prediction start ---";
  auto *cfg = reinterpret_cast<const PaddlePredictor::Config *>(config);
  PrintConfig(cfg, true);
  std::vector<std::vector<PaddleTensor>> analysis_outputs;
791
  float sample_latency_fp32{-1};
792 793 794 795 796

  if (FLAGS_enable_fp32) {
    TestOneThreadPrediction(cfg, inputs, &analysis_outputs, true, VarType::FP32,
                            &sample_latency_fp32);
  }
797 798 799 800 801

  LOG(INFO) << "--- INT8 prediction start ---";
  auto *qcfg = reinterpret_cast<const PaddlePredictor::Config *>(qconfig);
  PrintConfig(qcfg, true);
  std::vector<std::vector<PaddleTensor>> quantized_outputs;
802
  float sample_latency_int8{-1};
803

804 805 806 807
  if (FLAGS_enable_int8) {
    TestOneThreadPrediction(qcfg, inputs, &quantized_outputs, true,
                            VarType::INT8, &sample_latency_int8);
  }
808 809
  SummarizePerformance("FP32", sample_latency_fp32, "INT8",
                       sample_latency_int8);
810

811
  CompareAccuracy(quantized_outputs, analysis_outputs, compared_idx);
812 813
}

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
void CompareBFloat16AndAnalysis(
    const AnalysisConfig *config, const AnalysisConfig *qconfig,
    const std::vector<std::vector<PaddleTensor>> &inputs,
    const int compared_idx = 1) {
  PADDLE_ENFORCE_EQ(
      inputs[0][0].shape[0], FLAGS_batch_size,
      platform::errors::InvalidArgument(
          "Input data has to be packed batch by batch. The batchsize is set to "
          "%d, but the real input is packed with batchsize = %d",
          FLAGS_batch_size, inputs[0][0].shape[0]));
  LOG(INFO) << "FP32 & BF16 prediction run: batch_size " << FLAGS_batch_size;

  LOG(INFO) << "--- FP32 prediction start ---";
  auto *cfg = reinterpret_cast<const PaddlePredictor::Config *>(config);
  PrintConfig(cfg, true);
  std::vector<std::vector<PaddleTensor>> analysis_outputs;
  float sample_latency_fp32{-1};

  if (FLAGS_enable_fp32) {
    TestOneThreadPrediction(cfg, inputs, &analysis_outputs, true, VarType::FP32,
                            &sample_latency_fp32);
  }

  LOG(INFO) << "--- BF16 prediction start ---";
  auto *qcfg = reinterpret_cast<const PaddlePredictor::Config *>(qconfig);
  PrintConfig(qcfg, true);
  std::vector<std::vector<PaddleTensor>> bf16_outputs;
  float sample_latency_bf16{-1};

  if (FLAGS_enable_bf16) {
    TestOneThreadPrediction(qcfg, inputs, &bf16_outputs, true, VarType::FP32,
                            &sample_latency_bf16);
  }
  SummarizePerformance("FP32", sample_latency_fp32, "BF16",
                       sample_latency_bf16);

  CompareAccuracy(bf16_outputs, analysis_outputs, compared_idx);
}

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
void CompareAnalysisAndAnalysis(
    const AnalysisConfig *config1, const AnalysisConfig *config2,
    const std::vector<std::vector<PaddleTensor>> &inputs,
    const bool with_accuracy_layer = FLAGS_with_accuracy_layer,
    const int compared_idx = 1) {
  PADDLE_ENFORCE_EQ(
      inputs[0][0].shape[0], FLAGS_batch_size,
      platform::errors::InvalidArgument(
          "Input data has to be packed batch by batch. The batchsize is set to "
          "%d, but the real input is packed with batchsize = %d",
          FLAGS_batch_size, inputs[0][0].shape[0]));

  LOG(INFO) << "FP32 & INT8 prediction run: batch_size " << FLAGS_batch_size
            << ", warmup batch size " << FLAGS_warmup_batch_size << ".";

  LOG(INFO) << "--- FP32 prediction start ---";
  auto *cfg1 = reinterpret_cast<const PaddlePredictor::Config *>(config1);
  PrintConfig(cfg1, true);
  std::vector<std::vector<PaddleTensor>> analysis_outputs;
  float sample_latency_fp32{-1};

  if (FLAGS_enable_fp32) {
    TestOneThreadPrediction(cfg1, inputs, &analysis_outputs, true,
                            VarType::FP32, &sample_latency_fp32);
  }

  LOG(INFO) << "--- INT8 prediction start ---";
  auto *cfg2 = reinterpret_cast<const PaddlePredictor::Config *>(config2);
  PrintConfig(cfg2, true);
  std::vector<std::vector<PaddleTensor>> int8_outputs;
  float sample_latency_int8{-1};

  if (FLAGS_enable_int8) {
    TestOneThreadPrediction(cfg2, inputs, &int8_outputs, true, VarType::INT8,
                            &sample_latency_int8);
  }
889 890
  SummarizePerformance("FP32", sample_latency_fp32, "INT8",
                       sample_latency_int8);
891 892 893 894 895
  if (with_accuracy_layer) {
    CompareAccuracy(int8_outputs, analysis_outputs, compared_idx);
  }
}

N
nhzlx 已提交
896 897 898 899 900 901 902 903 904 905
void CompareNativeAndAnalysis(
    PaddlePredictor *native_pred, PaddlePredictor *analysis_pred,
    const std::vector<std::vector<PaddleTensor>> &inputs) {
  int batch_size = FLAGS_batch_size;
  std::vector<PaddleTensor> native_outputs, analysis_outputs;
  native_pred->Run(inputs[0], &native_outputs, batch_size);
  analysis_pred->Run(inputs[0], &analysis_outputs, batch_size);
  CompareResult(analysis_outputs, native_outputs);
}

906
void CompareAnalysisAndZeroCopy(
907
    PaddlePredictor::Config *config, PaddlePredictor::Config *config1,
908 909 910 911 912 913 914 915 916
    const std::vector<std::vector<PaddleTensor>> &inputs,
    const std::vector<std::string> &outputs_name) {
  int batch_size = FLAGS_batch_size;
  // analysis
  std::vector<PaddleTensor> analysis_outputs;
  auto predictor = CreateTestPredictor(config, true);
  predictor->Run(inputs[0], &analysis_outputs, batch_size);
  // analysis + zero_copy
  std::vector<ZeroCopyTensor> zerocopy_outputs;
917 918
  reinterpret_cast<AnalysisConfig *>(config1)->SwitchUseFeedFetchOps(false);
  predictor = CreateTestPredictor(config1, true);
919 920 921 922 923 924
  ConvertPaddleTensorToZeroCopyTensor(predictor.get(), inputs[0]);
  predictor->ZeroCopyRun();
  for (size_t i = 0; i < outputs_name.size(); i++) {
    ZeroCopyTensor zerocopy_output =
        *predictor->GetOutputTensor(outputs_name[i]).get();
    zerocopy_outputs.emplace_back(zerocopy_output);
L
luotao1 已提交
925
    LOG(INFO) << "ZeroCopy output: " << DescribeZeroCopyTensor(zerocopy_output);
926 927 928 929 930
  }
  // compare
  CompareResult(analysis_outputs, zerocopy_outputs);
}

931 932 933 934 935 936 937
void SaveOptimModel(AnalysisConfig *cfg, const std::string &dstPath) {
  auto predictor = CreateTestPredictor(
      reinterpret_cast<const PaddlePredictor::Config *>(cfg),
      FLAGS_use_analysis);
  (static_cast<AnalysisPredictor *>(predictor.get()))->SaveOptimModel(dstPath);
}

L
luotao1 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
template <typename T>
std::string LoDTensorSummary(const framework::LoDTensor &tensor) {
  std::stringstream ss;
  ss << "\n---- tensor ---" << '\n';
  ss << "lod: [";
  for (const auto &level : tensor.lod()) {
    ss << "[ ";
    for (auto i : level) {
      ss << i << ", ";
    }
    ss << "]";
  }
  ss << "]\n";

  ss << "shape: [";
  int size = 1;
  for (int i = 0; i < tensor.dims().size(); i++) {
    int dim = tensor.dims()[i];
    ss << dim << ", ";
    size *= dim;
  }
  ss << "]\n";

  ss << "data: ";
  for (int i = 0; i < std::min(20, size); i++) {
    ss << tensor.data<T>()[i] << " ";
  }
  ss << "\n";

  return ss.str();
}

static bool CompareLoD(const framework::LoD &a, const framework::LoD &b) {
  if (a.size() != b.size()) {
    LOG(ERROR) << string::Sprintf("lod size not match %d != %d", a.size(),
                                  b.size());
    return false;
  }
  for (size_t i = 0; i < a.size(); i++) {
    auto &al = a[i];
    auto &bl = b[i];
    if (al.size() != bl.size()) {
      LOG(ERROR) << string::Sprintf("level size %d != %d", al.size(),
                                    bl.size());
      return false;
    }
  }
  return true;
}

static bool CompareShape(const std::vector<int64_t> &a,
                         const std::vector<int64_t> &b) {
  if (a.size() != b.size()) {
    LOG(ERROR) << string::Sprintf("shape size not match %d != %d", a.size(),
                                  b.size());
    return false;
  }
  for (size_t i = 0; i < a.size(); i++) {
    if (a[i] != b[i]) {
      LOG(ERROR) << string::Sprintf("shape %d-th element not match %d != %d", i,
                                    a[i], b[i]);
      return false;
    }
  }
  return true;
}

static bool CompareTensorData(const framework::LoDTensor &a,
                              const framework::LoDTensor &b) {
  auto a_shape = framework::vectorize(a.dims());
  auto b_shape = framework::vectorize(b.dims());
1009
  size_t a_size = std::accumulate(a_shape.begin(), a_shape.end(), size_t{1},
L
luotao1 已提交
1010
                                  [](int a, int b) { return a * b; });
1011
  size_t b_size = std::accumulate(b_shape.begin(), b_shape.end(), size_t{1},
L
luotao1 已提交
1012 1013 1014 1015 1016 1017 1018
                                  [](int a, int b) { return a * b; });
  if (a_size != b_size) {
    LOG(ERROR) << string::Sprintf("tensor data size not match, %d != %d",
                                  a_size, b_size);
  }

  for (size_t i = 0; i < a_size; i++) {
1019
    if (a.type() == VarType::FP32) {
L
luotao1 已提交
1020 1021 1022 1023 1024 1025 1026 1027
      const auto *a_data = a.data<float>();
      const auto *b_data = b.data<float>();
      if (std::abs(a_data[i] - b_data[i]) > 1e-3) {
        LOG(ERROR) << string::Sprintf(
            "tensor data %d-th element not match, %f != %f", i, a_data[i],
            b_data[i]);
        return false;
      }
1028
    } else if (a.type() == VarType::INT64) {
L
luotao1 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
      const auto *a_data = a.data<int64_t>();
      const auto *b_data = b.data<int64_t>();
      if (std::abs(a_data[i] - b_data[i]) > 1e-3) {
        LOG(ERROR) << string::Sprintf(
            "tensor data %d-th element not match, %f != %f", i, a_data[i],
            b_data[i]);
        return false;
      }
    }
  }

  return true;
}

static bool CompareTensor(const framework::LoDTensor &a,
                          const framework::LoDTensor &b) {
  if (!CompareLoD(a.lod(), b.lod())) {
    return false;
  }
  if (!CompareShape(framework::vectorize(a.dims()),
                    framework::vectorize(b.dims()))) {
    return false;
  }

  if (!CompareTensorData(a, b)) {
    return false;
  }

  return true;
}

L
luotao1 已提交
1060 1061
}  // namespace inference
}  // namespace paddle