tester_helper.h 7.1 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>
T
Tao Luo 已提交
18
#include <string>
L
luotao1 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <thread>  // NOLINT
#include <vector>
#include "paddle/fluid/framework/ir/fuse_pass_base.h"
#include "paddle/fluid/inference/analysis/analyzer.h"
#include "paddle/fluid/inference/analysis/ut_helper.h"
#include "paddle/fluid/inference/api/analysis_predictor.h"
#include "paddle/fluid/inference/api/helper.h"
#include "paddle/fluid/inference/api/paddle_inference_pass.h"
#include "paddle/fluid/platform/profiler.h"

DEFINE_string(infer_model, "", "model path");
DEFINE_string(infer_data, "", "data file");
DEFINE_int32(batch_size, 1, "batch size.");
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 已提交
35 36
DEFINE_bool(use_analysis, true,
            "Running the inference program in analysis mode.");
L
luotao1 已提交
37 38 39 40

namespace paddle {
namespace inference {

Y
Yan Chunwei 已提交
41 42
using contrib::AnalysisConfig;

L
luotao1 已提交
43
void CompareResult(const std::vector<PaddleTensor> &outputs,
T
tensor-tang 已提交
44
                   const std::vector<PaddleTensor> &ref_outputs) {
T
Tao Luo 已提交
45
  EXPECT_GT(outputs.size(), 0UL);
T
tensor-tang 已提交
46
  EXPECT_EQ(outputs.size(), ref_outputs.size());
L
luotao1 已提交
47 48
  for (size_t i = 0; i < outputs.size(); i++) {
    auto &out = outputs[i];
T
tensor-tang 已提交
49
    auto &ref_out = ref_outputs[i];
L
luotao1 已提交
50 51
    size_t size = std::accumulate(out.shape.begin(), out.shape.end(), 1,
                                  [](int a, int b) { return a * b; });
T
tensor-tang 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    size_t ref_size =
        std::accumulate(ref_out.shape.begin(), ref_out.shape.end(), 1,
                        [](int a, int b) { return a * b; });
    EXPECT_GT(size, 0);
    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) {
          EXPECT_NEAR(pdata_ref[j], pdata[j], 1e-3);
        }
        break;
      }
L
luotao1 已提交
75 76 77 78
    }
  }
}

79 80
std::unique_ptr<PaddlePredictor> CreateTestPredictor(
    const AnalysisConfig &config, bool use_analysis = true) {
T
Tao Luo 已提交
81
  if (use_analysis) {
Y
Yan Chunwei 已提交
82 83
    return CreatePaddlePredictor<contrib::AnalysisConfig,
                                 PaddleEngineKind::kAnalysis>(config);
T
Tao Luo 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96
  } else {
    return CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(
        config);
  }
}

size_t GetSize(const PaddleTensor &out) {
  return std::accumulate(out.shape.begin(), out.shape.end(), 1,
                         [](int a, int b) { return a * b; });
}

std::unordered_map<std::string, int> GetFuseStatis(AnalysisConfig config,
                                                   int *num_ops) {
97
  auto predictor = CreateTestPredictor(config);
T
Tao Luo 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  AnalysisPredictor *analysis_predictor =
      dynamic_cast<AnalysisPredictor *>(predictor.get());
  auto &fuse_statis = analysis_predictor->analysis_argument()
                          .Get<std::unordered_map<std::string, int>>(
                              framework::ir::kFuseStatisAttr);
  for (auto &item : fuse_statis) {
    LOG(INFO) << "fused " << item.first << " " << item.second;
  }
  int num = 0;
  for (auto &node :
       analysis_predictor->analysis_argument().main_dfg->nodes.nodes()) {
    if (node->IsFunction()) {
      ++num;
    }
  }
  *num_ops = num;
  return fuse_statis;
}

L
luotao1 已提交
117
void TestOneThreadPrediction(
118 119
    const AnalysisConfig &config,
    const std::vector<std::vector<PaddleTensor>> &inputs,
T
Tao Luo 已提交
120
    std::vector<PaddleTensor> *outputs, bool use_analysis = true) {
L
luotao1 已提交
121 122
  int batch_size = FLAGS_batch_size;
  int num_times = FLAGS_repeat;
123
  auto predictor = CreateTestPredictor(config, use_analysis);
L
luotao1 已提交
124 125 126 127 128 129 130 131 132 133 134 135
  Timer timer;
  timer.tic();
  for (int i = 0; i < num_times; i++) {
    for (size_t j = 0; j < inputs.size(); j++) {
      predictor->Run(inputs[j], outputs);
    }
  }
  PrintTime(batch_size, num_times, 1, 0, timer.toc() / num_times,
            inputs.size());
}

void TestMultiThreadPrediction(
136 137
    const AnalysisConfig &config,
    const std::vector<std::vector<PaddleTensor>> &inputs,
T
Tao Luo 已提交
138 139
    std::vector<PaddleTensor> *outputs, int num_threads,
    bool use_analysis = true) {
L
luotao1 已提交
140 141 142 143 144 145 146
  int batch_size = FLAGS_batch_size;
  int num_times = FLAGS_repeat;
  std::vector<std::thread> threads;
  std::vector<std::unique_ptr<PaddlePredictor>> predictors;
  // TODO(yanchunwei): Bug here, the analyzer phase can't be parallelled
  // because AttentionLSTM's hard code nodeid will be damanged.
  for (int tid = 0; tid < num_threads; ++tid) {
147
    predictors.emplace_back(CreateTestPredictor(config, use_analysis));
L
luotao1 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  }
  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.
      std::vector<std::vector<PaddleTensor>> inputs_tid = inputs;
      std::vector<PaddleTensor> outputs_tid;
      Timer timer;
      timer.tic();
      for (int i = 0; i < num_times; i++) {
        for (size_t j = 0; j < inputs_tid.size(); j++) {
          predictors[tid]->Run(inputs_tid[j], &outputs_tid);
        }
      }
      PrintTime(batch_size, num_times, num_threads, tid,
                timer.toc() / num_times, inputs_tid.size());
    });
  }
  for (int i = 0; i < num_threads; ++i) {
    threads[i].join();
  }
}

171 172
void TestPrediction(const AnalysisConfig &config,
                    const std::vector<std::vector<PaddleTensor>> &inputs,
T
Tao Luo 已提交
173 174 175
                    std::vector<PaddleTensor> *outputs, int num_threads,
                    bool use_analysis = FLAGS_use_analysis) {
  LOG(INFO) << "use_analysis: " << use_analysis;
L
luotao1 已提交
176
  if (num_threads == 1) {
T
Tao Luo 已提交
177
    TestOneThreadPrediction(config, inputs, outputs, use_analysis);
L
luotao1 已提交
178
  } else {
T
Tao Luo 已提交
179 180
    TestMultiThreadPrediction(config, inputs, outputs, num_threads,
                              use_analysis);
L
luotao1 已提交
181 182 183
  }
}

T
Tao Luo 已提交
184
void CompareNativeAndAnalysis(
185 186
    const AnalysisConfig &config,
    const std::vector<std::vector<PaddleTensor>> &inputs) {
T
Tao Luo 已提交
187 188 189 190 191 192
  std::vector<PaddleTensor> native_outputs, analysis_outputs;
  TestOneThreadPrediction(config, inputs, &native_outputs, false);
  TestOneThreadPrediction(config, inputs, &analysis_outputs, true);
  CompareResult(analysis_outputs, native_outputs);
}

L
luotao1 已提交
193 194
}  // namespace inference
}  // namespace paddle