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

N
nhzlx 已提交
40
DEFINE_string(model_name, "", "model name");
L
luotao1 已提交
41 42
DEFINE_string(infer_model, "", "model path");
DEFINE_string(infer_data, "", "data file");
T
Tao Luo 已提交
43
DEFINE_string(refer_result, "", "reference result for comparison");
44 45 46 47
DEFINE_int32(batch_size, 1, "batch size");
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 已提交
48 49 50
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 已提交
51 52
DEFINE_bool(use_analysis, true,
            "Running the inference program in analysis mode.");
N
nhzlx 已提交
53 54
DEFINE_bool(record_benchmark, false,
            "Record benchmark after profiling the model");
L
luotao1 已提交
55
DEFINE_double(accuracy, 1e-3, "Result Accuracy.");
56
DEFINE_double(quantized_accuracy, 1e-2, "Result Quantized Accuracy.");
L
luotao1 已提交
57
DEFINE_bool(zero_copy, false, "Use ZeroCopy to speedup Feed/Fetch.");
58 59 60
DEFINE_bool(warmup, false,
            "Use warmup to calculate elapsed_time more accurately. "
            "To reduce CI time, it sets false in default.");
L
luotao1 已提交
61

62
DECLARE_bool(profile);
L
luotao1 已提交
63
DECLARE_int32(paddle_num_threads);
64

L
luotao1 已提交
65 66 67
namespace paddle {
namespace inference {

68 69
using paddle::framework::proto::VarType;

70 71 72 73 74 75 76 77 78 79 80 81 82
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;
}

83
void PrintConfig(const PaddlePredictor::Config *config, bool use_analysis) {
84
  const auto *analysis_config =
85
      reinterpret_cast<const AnalysisConfig *>(config);
86
  if (use_analysis) {
87
    LOG(INFO) << *analysis_config;
88 89
    return;
  }
90
  LOG(INFO) << analysis_config->ToNativeConfig();
91
}
Y
Yan Chunwei 已提交
92

93
// Compare result between two PaddleTensor
L
luotao1 已提交
94
void CompareResult(const std::vector<PaddleTensor> &outputs,
T
tensor-tang 已提交
95
                   const std::vector<PaddleTensor> &ref_outputs) {
T
Tao Luo 已提交
96
  EXPECT_GT(outputs.size(), 0UL);
T
tensor-tang 已提交
97
  EXPECT_EQ(outputs.size(), ref_outputs.size());
L
luotao1 已提交
98 99
  for (size_t i = 0; i < outputs.size(); i++) {
    auto &out = outputs[i];
T
tensor-tang 已提交
100
    auto &ref_out = ref_outputs[i];
101 102
    size_t size = VecReduceToInt(out.shape);
    size_t ref_size = VecReduceToInt(ref_out.shape);
103
    EXPECT_GT(size, 0UL);
T
tensor-tang 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    EXPECT_EQ(size, ref_size);
    EXPECT_EQ(out.dtype, ref_out.dtype);
    switch (out.dtype) {
      case PaddleDType::INT64: {
        int64_t *pdata = static_cast<int64_t *>(out.data.data());
        int64_t *pdata_ref = static_cast<int64_t *>(ref_out.data.data());
        for (size_t j = 0; j < size; ++j) {
          EXPECT_EQ(pdata_ref[j], pdata[j]);
        }
        break;
      }
      case PaddleDType::FLOAT32: {
        float *pdata = static_cast<float *>(out.data.data());
        float *pdata_ref = static_cast<float *>(ref_out.data.data());
        for (size_t j = 0; j < size; ++j) {
Y
Yan Chunwei 已提交
119
          CHECK_LE(std::abs(pdata_ref[j] - pdata[j]), FLAGS_accuracy);
T
tensor-tang 已提交
120 121 122
        }
        break;
      }
123 124 125 126 127 128 129 130
      case PaddleDType::INT32: {
        int32_t *pdata = static_cast<int32_t *>(out.data.data());
        int32_t *pdata_ref = static_cast<int32_t *>(ref_out.data.data());
        for (size_t j = 0; j < size; ++j) {
          EXPECT_EQ(pdata_ref[j], pdata[j]);
        }
        break;
      }
131 132 133 134 135 136 137 138
      case PaddleDType::UINT8: {
        uint8_t *pdata = static_cast<uint8_t *>(out.data.data());
        uint8_t *pdata_ref = static_cast<uint8_t *>(ref_out.data.data());
        for (size_t j = 0; j < size; ++j) {
          EXPECT_EQ(pdata_ref[j], pdata[j]);
        }
        break;
      }
L
luotao1 已提交
139 140 141 142
    }
  }
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
// 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;
    switch (out.dtype) {
      case PaddleDType::INT64: {
        int64_t *pdata = static_cast<int64_t *>(out.data.data());
        int64_t *pdata_ref = ref_out.data<int64_t>(&place, &ref_size);
159
        EXPECT_EQ(size, static_cast<size_t>(ref_size));
160 161 162 163 164 165 166 167 168 169 170 171 172 173
        for (size_t j = 0; j < size; ++j) {
          EXPECT_EQ(pdata_ref[j], pdata[j]);
        }
        break;
      }
      case PaddleDType::FLOAT32: {
        float *pdata = static_cast<float *>(out.data.data());
        float *pdata_ref = ref_out.data<float>(&place, &ref_size);
        EXPECT_EQ(size, ref_size);
        for (size_t j = 0; j < size; ++j) {
          CHECK_LE(std::abs(pdata_ref[j] - pdata[j]), FLAGS_accuracy);
        }
        break;
      }
L
luotao1 已提交
174 175 176 177 178 179 180 181 182
      case PaddleDType::INT32: {
        int32_t *pdata = static_cast<int32_t *>(out.data.data());
        int32_t *pdata_ref = ref_out.data<int32_t>(&place, &ref_size);
        EXPECT_EQ(size, ref_size);
        for (size_t j = 0; j < size; ++j) {
          EXPECT_EQ(pdata_ref[j], pdata[j]);
        }
        break;
      }
183 184 185 186 187 188 189 190 191
      case PaddleDType::UINT8: {
        uint8_t *pdata = static_cast<uint8_t *>(out.data.data());
        uint8_t *pdata_ref = ref_out.data<uint8_t>(&place, &ref_size);
        EXPECT_EQ(size, ref_size);
        for (size_t j = 0; j < size; ++j) {
          EXPECT_EQ(pdata_ref[j], pdata[j]);
        }
        break;
      }
192 193 194 195
    }
  }
}

196
std::unique_ptr<PaddlePredictor> CreateTestPredictor(
197
    const PaddlePredictor::Config *config, bool use_analysis = true) {
198
  const auto *analysis_config =
199
      reinterpret_cast<const AnalysisConfig *>(config);
T
Tao Luo 已提交
200
  if (use_analysis) {
201
    return CreatePaddlePredictor<AnalysisConfig>(*analysis_config);
T
Tao Luo 已提交
202
  }
203 204
  auto native_config = analysis_config->ToNativeConfig();
  return CreatePaddlePredictor<NativeConfig>(native_config);
T
Tao Luo 已提交
205 206
}

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

209
std::unordered_map<std::string, int> GetFuseStatis(PaddlePredictor *predictor,
T
Tao Luo 已提交
210
                                                   int *num_ops) {
211
  std::unordered_map<std::string, int> res;
212
  auto *analysis_predictor = static_cast<AnalysisPredictor *>(predictor);
213 214 215 216 217 218
  auto *fusion_status =
      analysis_predictor->analysis_argument().fusion_statis_ptr();
  if (!fusion_status) {
    return res;
  }
  for (auto &item : *fusion_status) {
T
Tao Luo 已提交
219 220 221 222
    LOG(INFO) << "fused " << item.first << " " << item.second;
  }
  int num = 0;
  for (auto &node :
223 224
       analysis_predictor->analysis_argument().main_graph().Nodes()) {
    if (node->IsOp()) {
T
Tao Luo 已提交
225 226 227 228
      ++num;
    }
  }
  *num_ops = num;
229
  return *fusion_status;
T
Tao Luo 已提交
230 231
}

T
Tao Luo 已提交
232
void SetFakeImageInput(std::vector<std::vector<PaddleTensor>> *inputs,
233 234
                       const std::string &dirname, bool is_combined = true,
                       std::string model_filename = "model",
T
tensor-tang 已提交
235
                       std::string params_filename = "params",
N
nhzlx 已提交
236 237
                       const std::vector<std::string> *feed_names = nullptr,
                       const int continuous_inuput_index = 0) {
T
Tao Luo 已提交
238 239
  // Set fake_image_data
  PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0, "Only have single batch of data.");
240 241 242 243 244 245 246 247 248 249 250
  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 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  if (feed_names) {
    PADDLE_ENFORCE_EQ(feed_names->size(), feed_target_shapes.size());
  }
  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;
267
    size_t len = std::accumulate(shape.begin(), shape.end(), size_t{1},
T
tensor-tang 已提交
268 269 270 271 272 273
                                 [](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 已提交
274 275
      *(input_data + j) =
          static_cast<float>((j + continuous_inuput_index) % len) / len;
T
tensor-tang 已提交
276
    }
T
Tao Luo 已提交
277 278 279 280
  }
  (*inputs).emplace_back(input_slots);
}

281 282 283 284 285 286 287 288 289 290 291 292
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 已提交
293 294 295 296 297 298 299 300 301 302 303
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 已提交
304 305
    } else if (input.dtype == PaddleDType::INT32) {
      ZeroCopyTensorAssignData<int32_t>(tensor.get(), input.data);
306 307
    } else if (input.dtype == PaddleDType::UINT8) {
      ZeroCopyTensorAssignData<uint8_t>(tensor.get(), input.data);
L
luotao1 已提交
308 309 310 311 312
    } else {
      LOG(ERROR) << "unsupported feed type " << input.dtype;
    }
  }
}
313

L
luotao1 已提交
314 315
void PredictionWarmUp(PaddlePredictor *predictor,
                      const std::vector<std::vector<PaddleTensor>> &inputs,
316
                      std::vector<std::vector<PaddleTensor>> *outputs,
317 318
                      int num_threads, int tid,
                      const VarType::Type data_type = VarType::FP32) {
L
luotao1 已提交
319 320 321 322 323
  int batch_size = FLAGS_batch_size;
  LOG(INFO) << "Running thread " << tid << ", warm up run...";
  if (FLAGS_zero_copy) {
    ConvertPaddleTensorToZeroCopyTensor(predictor, inputs[0]);
  }
324
  outputs->resize(1);
L
luotao1 已提交
325 326 327
  Timer warmup_timer;
  warmup_timer.tic();
  if (!FLAGS_zero_copy) {
328
    predictor->Run(inputs[0], &(*outputs)[0], batch_size);
L
luotao1 已提交
329 330
  } else {
    predictor->ZeroCopyRun();
331
  }
332
  PrintTime(batch_size, 1, num_threads, tid, warmup_timer.toc(), 1, data_type);
L
luotao1 已提交
333 334 335 336
  if (FLAGS_profile) {
    paddle::platform::ResetProfiler();
  }
}
337

L
luotao1 已提交
338 339
void PredictionRun(PaddlePredictor *predictor,
                   const std::vector<std::vector<PaddleTensor>> &inputs,
340
                   std::vector<std::vector<PaddleTensor>> *outputs,
341
                   int num_threads, int tid,
342 343
                   const VarType::Type data_type = VarType::FP32,
                   float *sample_latency = nullptr) {
L
luotao1 已提交
344
  int num_times = FLAGS_repeat;
345
  int iterations = inputs.size();  // process the whole dataset ...
346 347
  if (FLAGS_iterations > 0 &&
      FLAGS_iterations < static_cast<int64_t>(inputs.size()))
348 349 350 351 352
    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 已提交
353 354
  Timer run_timer;
  double elapsed_time = 0;
Y
Yiqun Liu 已提交
355
#ifdef WITH_GPERFTOOLS
L
luotao1 已提交
356
  ProfilerStart("paddle_inference.prof");
Y
Yiqun Liu 已提交
357
#endif
358
  int predicted_num = 0;
L
luotao1 已提交
359
  if (!FLAGS_zero_copy) {
360
    for (int i = 0; i < iterations; i++) {
361
      run_timer.tic();
L
luotao1 已提交
362
      for (int j = 0; j < num_times; j++) {
363
        predictor->Run(inputs[i], &(*outputs)[i], FLAGS_batch_size);
364
      }
365 366 367 368 369 370
      elapsed_time += run_timer.toc();

      predicted_num += FLAGS_batch_size;
      if (predicted_num % 100 == 0) {
        LOG(INFO) << predicted_num << " samples";
      }
L
luotao1 已提交
371
    }
L
luotao1 已提交
372
  } else {
373
    for (int i = 0; i < iterations; i++) {
L
luotao1 已提交
374 375 376 377 378 379
      ConvertPaddleTensorToZeroCopyTensor(predictor, inputs[i]);
      run_timer.tic();
      for (int j = 0; j < num_times; j++) {
        predictor->ZeroCopyRun();
      }
      elapsed_time += run_timer.toc();
380 381 382 383 384

      predicted_num += FLAGS_batch_size;
      if (predicted_num % 100 == 0) {
        LOG(INFO) << predicted_num << " samples";
      }
L
luotao1 已提交
385 386
    }
  }
387

Y
Yiqun Liu 已提交
388
#ifdef WITH_GPERFTOOLS
L
luotao1 已提交
389
  ProfilerStop();
Y
Yiqun Liu 已提交
390
#endif
N
nhzlx 已提交
391

392 393
  auto batch_latency = elapsed_time / (iterations * num_times);
  PrintTime(FLAGS_batch_size, num_times, num_threads, tid, batch_latency,
394
            iterations, data_type);
395 396 397 398

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

L
luotao1 已提交
399 400 401
  if (FLAGS_record_benchmark) {
    Benchmark benchmark;
    benchmark.SetName(FLAGS_model_name);
402 403
    benchmark.SetBatchSize(FLAGS_batch_size);
    benchmark.SetLatency(batch_latency);
L
luotao1 已提交
404
    benchmark.PersistToFile("benchmark_record.txt");
L
luotao1 已提交
405 406 407
  }
}

L
luotao1 已提交
408 409 410
void TestOneThreadPrediction(
    const PaddlePredictor::Config *config,
    const std::vector<std::vector<PaddleTensor>> &inputs,
411
    std::vector<std::vector<PaddleTensor>> *outputs, bool use_analysis = true,
412 413
    const VarType::Type data_type = VarType::FP32,
    float *sample_latency = nullptr) {
L
luotao1 已提交
414
  auto predictor = CreateTestPredictor(config, use_analysis);
415
  if (FLAGS_warmup) {
416
    PredictionWarmUp(predictor.get(), inputs, outputs, 1, 0, data_type);
417
  }
418 419
  PredictionRun(predictor.get(), inputs, outputs, 1, 0, data_type,
                sample_latency);
L
luotao1 已提交
420 421
}

L
luotao1 已提交
422
void TestMultiThreadPrediction(
423
    const PaddlePredictor::Config *config,
424
    const std::vector<std::vector<PaddleTensor>> &inputs,
425
    std::vector<std::vector<PaddleTensor>> *outputs, int num_threads,
T
Tao Luo 已提交
426
    bool use_analysis = true) {
L
luotao1 已提交
427
  std::vector<std::thread> threads;
L
luotao1 已提交
428 429 430 431 432
  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());
  }
433

L
luotao1 已提交
434 435 436 437
  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.
438
      std::vector<std::vector<PaddleTensor>> outputs_tid;
L
luotao1 已提交
439
      auto &predictor = predictors[tid];
440 441 442 443
      if (FLAGS_warmup) {
        PredictionWarmUp(predictor.get(), inputs, &outputs_tid, num_threads,
                         tid);
      }
444
      PredictionRun(predictor.get(), inputs, &outputs_tid, num_threads, tid);
L
luotao1 已提交
445 446 447 448 449 450 451
    });
  }
  for (int i = 0; i < num_threads; ++i) {
    threads[i].join();
  }
}

452
void TestPrediction(const PaddlePredictor::Config *config,
453
                    const std::vector<std::vector<PaddleTensor>> &inputs,
454 455
                    std::vector<std::vector<PaddleTensor>> *outputs,
                    int num_threads, bool use_analysis = FLAGS_use_analysis) {
456
  PrintConfig(config, use_analysis);
L
luotao1 已提交
457
  if (num_threads == 1) {
T
Tao Luo 已提交
458
    TestOneThreadPrediction(config, inputs, outputs, use_analysis);
L
luotao1 已提交
459
  } else {
T
Tao Luo 已提交
460 461
    TestMultiThreadPrediction(config, inputs, outputs, num_threads,
                              use_analysis);
L
luotao1 已提交
462 463 464
  }
}

465 466
void SummarizeAccuracy(float avg_acc_fp32, float avg_acc_int8,
                       int compared_idx) {
467 468 469 470 471 472
  PADDLE_ENFORCE_LE(compared_idx, 2,
                    "Compare either top1 accuracy or mAP (top5), the "
                    "compared_idx is out of range");
  PADDLE_ENFORCE_GE(compared_idx, 1,
                    "Compare either top1 accuracy or mAP (top5), the "
                    "compared_idx is out of range");
473
  std::string prefix = (compared_idx == 1) ? "top1_accuracy " : "mAP ";
474
  LOG(INFO) << "--- Accuracy summary --- ";
475 476 477 478 479 480 481 482
  LOG(INFO) << "Accepted " << prefix
            << "drop threshold: " << FLAGS_quantized_accuracy
            << ". (condition: (FP32_" << prefix << " - INT8_" << prefix
            << ") <= threshold)";
  LOG(INFO) << "FP32: avg " << prefix << std::fixed << std::setw(6)
            << std::setprecision(4) << avg_acc_fp32;
  LOG(INFO) << "INT8: avg " << prefix << std::fixed << std::setw(6)
            << std::setprecision(4) << avg_acc_int8;
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
}

void SummarizePerformance(float sample_latency_fp32,
                          float sample_latency_int8) {
  // sample latency in ms
  auto throughput_fp32 = 1000.0 / sample_latency_fp32;
  auto throughput_int8 = 1000.0 / sample_latency_int8;
  LOG(INFO) << "--- Performance summary --- ";
  LOG(INFO) << "FP32: avg fps: " << std::fixed << std::setw(6)
            << std::setprecision(4) << throughput_fp32
            << ", avg latency: " << sample_latency_fp32 << " ms";
  LOG(INFO) << "INT8: avg fps: " << std::fixed << std::setw(6)
            << std::setprecision(4) << throughput_int8
            << ", avg latency: " << sample_latency_int8 << " ms";
}

499
void CompareAccuracy(
500
    const std::vector<std::vector<PaddleTensor>> &output_slots_quant,
501 502
    const std::vector<std::vector<PaddleTensor>> &output_slots_ref,
    int compared_idx) {
503
  if (output_slots_quant.size() == 0 || output_slots_ref.size() == 0)
504
    throw std::invalid_argument(
505
        "CompareAccuracy: output_slots vector is empty.");
506

507 508
  float total_accs_quant{0};
  float total_accs_ref{0};
509
  for (size_t i = 0; i < output_slots_quant.size(); ++i) {
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    if (compared_idx == 1) {
      PADDLE_ENFORCE_GE(
          output_slots_quant[i].size(), 2UL,
          "To achieve top 1 accuracy, output_slots_quant[i].size()>=2");
      PADDLE_ENFORCE_GE(
          output_slots_ref[i].size(), 2UL,
          "To achieve top 1 accuracy, output_slots_ref[i].size()>=2");
    } else if (compared_idx == 2) {
      PADDLE_ENFORCE_GE(output_slots_quant[i].size(), 3UL,
                        "To achieve mAP, output_slots_quant[i].size()>=3");
      PADDLE_ENFORCE_GE(output_slots_ref[i].size(), 3UL,
                        "To achieve mAP, output_slots_ref[i].size()>=3");
    } else {
      throw std::invalid_argument(
          "CompareAccuracy: compared_idx is out of range.");
    }

527 528 529 530 531 532
    if (output_slots_quant[i][compared_idx].lod.size() > 0 ||
        output_slots_ref[i][compared_idx].lod.size() > 0)
      throw std::invalid_argument("CompareAccuracy: output has nonempty LoD.");
    if (output_slots_quant[i][compared_idx].dtype !=
            paddle::PaddleDType::FLOAT32 ||
        output_slots_ref[i][compared_idx].dtype != paddle::PaddleDType::FLOAT32)
533
      throw std::invalid_argument(
534 535 536 537 538
          "CompareAccuracy: output is of a wrong type.");
    total_accs_quant +=
        *static_cast<float *>(output_slots_quant[i][compared_idx].data.data());
    total_accs_ref +=
        *static_cast<float *>(output_slots_ref[i][compared_idx].data.data());
539
  }
540 541
  float avg_acc_quant = total_accs_quant / output_slots_quant.size();
  float avg_acc_ref = total_accs_ref / output_slots_ref.size();
542

543 544 545 546
  SummarizeAccuracy(avg_acc_ref, avg_acc_quant, compared_idx);
  CHECK_GT(avg_acc_ref, 0.0);
  CHECK_GT(avg_acc_quant, 0.0);
  CHECK_LE(avg_acc_ref - avg_acc_quant, FLAGS_quantized_accuracy);
547 548
}

L
luotao1 已提交
549 550 551 552 553 554 555 556 557
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.
558 559 560 561
  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 已提交
562 563 564 565 566 567
      predictor->Run(inputs[j], &outputs, batch_size);
      CompareResult(outputs, warmup_outputs);
    }
  }
}

T
Tao Luo 已提交
568
void CompareNativeAndAnalysis(
569
    const PaddlePredictor::Config *config,
570
    const std::vector<std::vector<PaddleTensor>> &inputs) {
571
  PrintConfig(config, true);
572
  std::vector<std::vector<PaddleTensor>> native_outputs, analysis_outputs;
573
  TestOneThreadPrediction(config, inputs, &native_outputs, false);
T
Tao Luo 已提交
574
  TestOneThreadPrediction(config, inputs, &analysis_outputs, true);
575 576
  PADDLE_ENFORCE_GT(native_outputs.size(), 0, "Native output is empty.");
  PADDLE_ENFORCE_GT(analysis_outputs.size(), 0, "Analysis output is empty.");
577
  CompareResult(analysis_outputs.back(), native_outputs.back());
T
Tao Luo 已提交
578 579
}

580
void CompareQuantizedAndAnalysis(
581
    const AnalysisConfig *config, const AnalysisConfig *qconfig,
582 583
    const std::vector<std::vector<PaddleTensor>> &inputs,
    const int compared_idx = 1) {
584 585 586 587 588 589 590 591 592
  PADDLE_ENFORCE_EQ(inputs[0][0].shape[0], FLAGS_batch_size,
                    "Input data has to be packed batch by batch.");
  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;
593 594 595
  float sample_latency_fp32{-1};
  TestOneThreadPrediction(cfg, inputs, &analysis_outputs, true, VarType::FP32,
                          &sample_latency_fp32);
596 597 598 599 600

  LOG(INFO) << "--- INT8 prediction start ---";
  auto *qcfg = reinterpret_cast<const PaddlePredictor::Config *>(qconfig);
  PrintConfig(qcfg, true);
  std::vector<std::vector<PaddleTensor>> quantized_outputs;
601 602 603
  float sample_latency_int8{-1};
  TestOneThreadPrediction(qcfg, inputs, &quantized_outputs, true, VarType::INT8,
                          &sample_latency_int8);
604

605
  SummarizePerformance(sample_latency_fp32, sample_latency_int8);
606
  CompareAccuracy(quantized_outputs, analysis_outputs, compared_idx);
607 608
}

N
nhzlx 已提交
609 610 611 612 613 614 615 616 617 618
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);
}

619
void CompareAnalysisAndZeroCopy(
620
    PaddlePredictor::Config *config, PaddlePredictor::Config *config1,
621 622 623 624 625 626 627 628 629
    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;
630 631
  reinterpret_cast<AnalysisConfig *>(config1)->SwitchUseFeedFetchOps(false);
  predictor = CreateTestPredictor(config1, true);
632 633 634 635 636 637
  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 已提交
638
    LOG(INFO) << "ZeroCopy output: " << DescribeZeroCopyTensor(zerocopy_output);
639 640 641 642 643
  }
  // compare
  CompareResult(analysis_outputs, zerocopy_outputs);
}

644 645 646 647 648 649 650
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 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
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());
722
  size_t a_size = std::accumulate(a_shape.begin(), a_shape.end(), size_t{1},
L
luotao1 已提交
723
                                  [](int a, int b) { return a * b; });
724
  size_t b_size = std::accumulate(b_shape.begin(), b_shape.end(), size_t{1},
L
luotao1 已提交
725 726 727 728 729 730 731
                                  [](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++) {
732
    if (a.type() == VarType::FP32) {
L
luotao1 已提交
733 734 735 736 737 738 739 740
      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;
      }
741
    } else if (a.type() == VarType::INT64) {
L
luotao1 已提交
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
      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 已提交
773 774
}  // namespace inference
}  // namespace paddle