analyzer_bert_tester.cc 8.3 KB
Newer Older
F
fuchang01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

15
#include "paddle/fluid/framework/transfer_scope_cache.h"
16
#include "paddle/fluid/inference/tests/api/tester_helper.h"
F
fuchang01 已提交
17 18 19 20 21 22

namespace paddle {
namespace inference {

using paddle::PaddleTensor;

23 24 25 26 27
void profile(bool use_mkldnn = false, bool use_bfloat16 = false);
std::vector<std::vector<paddle::PaddleTensor>> LoadInputData();
void CompareNativeAndAnalysisWrapper(bool use_mkldnn = false);
std::vector<paddle::PaddleTensor> ParseInputStreamToVector(
    const std::string &line);
F
fuchang01 已提交
28

29
AnalysisConfig SetConfig(bool use_mkldnn = false, bool use_bfloat16 = false);
F
fuchang01 已提交
30 31

template <typename T>
32
paddle::PaddleTensor ParseTensor(const std::string &field);
F
fuchang01 已提交
33 34

template <typename T>
35
std::vector<T> Split(const std::string &line, char separator);
F
fuchang01 已提交
36

37 38
template <typename T>
T GetValueFromStream(std::stringstream &ss);
F
fuchang01 已提交
39

40 41
template <>
std::string GetValueFromStream<std::string>(std::stringstream &ss);
F
fuchang01 已提交
42

W
Wangzheee 已提交
43 44 45 46 47 48
TEST(Analyzer_bert, profile) {
#if !defined(_WIN32)
  setenv("NVIDIA_TF32_OVERRIDE", "0", 1);
#endif
  profile();
}
F
fuchang01 已提交
49

50 51 52 53
#ifdef PADDLE_WITH_MKLDNN
TEST(Analyzer_bert, profile_mkldnn) {
  auto use_mkldnn = true;
  profile(use_mkldnn);
54
}
F
fuchang01 已提交
55

56 57 58 59
TEST(Analyzer_bert, profile_mkldnn_bf16) {
  auto use_mkldnn = true;
  auto use_bfloat16 = true;
  profile(use_mkldnn, use_bfloat16);
F
fuchang01 已提交
60
}
61 62 63 64
#endif

// Check the fuse status
TEST(Analyzer_bert, fuse_statis) {
W
Wangzheee 已提交
65 66 67
#if !defined(_WIN32)
  setenv("NVIDIA_TF32_OVERRIDE", "0", 1);
#endif
68
  auto cfg(SetConfig());
69 70 71 72 73 74 75
  int num_ops;
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
  auto fuse_statis = GetFuseStatis(
      static_cast<AnalysisPredictor *>(predictor.get()), &num_ops);
  LOG(INFO) << "num_ops: " << num_ops;
}

W
Wangzheee 已提交
76 77 78 79 80 81
TEST(Analyzer_bert, compare) {
#if !defined(_WIN32)
  setenv("NVIDIA_TF32_OVERRIDE", "0", 1);
#endif
  CompareNativeAndAnalysisWrapper();
}
F
fuchang01 已提交
82
#ifdef PADDLE_WITH_MKLDNN
83 84 85 86
TEST(Analyzer_bert, compare_mkldnn) {
  auto use_mkldnn = true;
  CompareNativeAndAnalysisWrapper(use_mkldnn);
}
F
fuchang01 已提交
87
#endif
88 89

// Compare Deterministic result
90
TEST(Analyzer_bert, compare_determine) {
W
Wangzheee 已提交
91 92 93
#if !defined(_WIN32)
  setenv("NVIDIA_TF32_OVERRIDE", "0", 1);
#endif
94
  auto cfg(SetConfig());
95

96
  auto inputs = LoadInputData();
97 98 99
  CompareDeterministic(reinterpret_cast<const PaddlePredictor::Config *>(&cfg),
                       inputs);
}
100

101
TEST(Analyzer_bert, transfer_scope_cache) {
W
Wangzheee 已提交
102 103 104
#if !defined(_WIN32)
  setenv("NVIDIA_TF32_OVERRIDE", "0", 1);
#endif
105
  auto config(SetConfig());
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

  std::vector<PaddleTensor> input, output;
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);

  int threads_num = 10;
  std::vector<std::thread> threads;
  std::unordered_set<std::unordered_set<paddle::framework::Scope *> *>
      global_transfer_scope_cache;
  std::unordered_set<std::unordered_map<size_t, paddle::framework::Scope *> *>
      global_transfer_data_cache;

  std::ifstream fin(FLAGS_infer_data);
  std::string line;

  for (int i = 0; i < threads_num; i++) {
    threads.emplace_back([&, i]() {
      std::getline(fin, line);
123
      input = ParseInputStreamToVector(line);
124 125 126 127 128 129 130 131 132 133
      predictor->Run(input, &output, FLAGS_batch_size);
      global_transfer_scope_cache.insert(
          &paddle::framework::global_transfer_scope_cache());
      global_transfer_data_cache.insert(
          &paddle::framework::global_transfer_data_cache());
    });
    threads[0].join();
    threads.clear();
    std::vector<PaddleTensor>().swap(input);
  }
134 135 136
  // Since paddle::framework::global_transfer_scope_cache() and
  // paddle::framework::global_transfer_data_cache() are thread_local,
  // their pointer should be different among different thread id.
137
  PADDLE_ENFORCE_EQ(
138 139
      global_transfer_scope_cache.size(),
      threads_num,
140 141 142
      paddle::platform::errors::Fatal(
          "The size of scope cache is not equal to thread number."));
  PADDLE_ENFORCE_EQ(
143 144
      global_transfer_data_cache.size(),
      threads_num,
145 146
      paddle::platform::errors::Fatal(
          "The size of data cache is not equal to thread number."));
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
void profile(bool use_mkldnn, bool use_bfloat16) {
  auto config(SetConfig(use_mkldnn, use_bfloat16));
  std::vector<std::vector<PaddleTensor>> outputs;
  auto inputs = LoadInputData();
  TestPrediction(reinterpret_cast<const PaddlePredictor::Config *>(&config),
                 inputs,
                 &outputs,
                 FLAGS_num_threads);
}

std::vector<std::vector<paddle::PaddleTensor>> LoadInputData() {
  if (FLAGS_infer_data.empty()) {
    LOG(ERROR) << "please set input data path";
    throw "missing input data path";
  }

  std::ifstream fin(FLAGS_infer_data);
  std::string line;
  int sample = 0;

  std::vector<std::vector<paddle::PaddleTensor>> inputs;

  // The unit-test dataset only have 10 samples, each sample have 5 feeds.
  while (std::getline(fin, line)) {
    inputs.push_back(ParseInputStreamToVector(line));
    sample++;
    if (!FLAGS_test_all_data && sample == FLAGS_batch_size) break;
  }
  LOG(INFO) << "number of samples: " << sample;

  return inputs;
}

void CompareNativeAndAnalysisWrapper(bool use_mkldnn) {
  auto cfg(SetConfig(use_mkldnn));
  auto inputs = LoadInputData();
  CompareNativeAndAnalysis(
      reinterpret_cast<const PaddlePredictor::Config *>(&cfg), inputs);
}

std::vector<paddle::PaddleTensor> ParseInputStreamToVector(
    const std::string &line) {
  const auto fields = Split<std::string>(line, ';');

  if (fields.size() < 5) throw "invalid input line";

  std::vector<paddle::PaddleTensor> tensors;

  tensors.reserve(5);

  const std::size_t src_id = 0;
  const std::size_t pos_id = 1;
  const std::size_t segment_id = 2;
  const std::size_t self_attention_bias = 3;
  const std::size_t next_segment_index = 4;

  tensors.push_back(ParseTensor<int64_t>(fields[src_id]));
  tensors.push_back(ParseTensor<int64_t>(fields[pos_id]));
  tensors.push_back(ParseTensor<int64_t>(fields[segment_id]));
  tensors.push_back(ParseTensor<float>(fields[self_attention_bias]));
  tensors.push_back(ParseTensor<int64_t>(fields[next_segment_index]));

  return tensors;
}

AnalysisConfig SetConfig(bool use_mkldnn, bool use_bfloat16) {
  AnalysisConfig config;
  config.SetModel(FLAGS_infer_model);
  config.DisableFCPadding();

  if (use_mkldnn) {
    config.EnableMKLDNN();
    config.pass_builder()->AppendPass("fc_mkldnn_pass");
    config.pass_builder()->AppendPass("fc_act_mkldnn_fuse_pass");
    config.pass_builder()->AppendPass("fc_elementwise_add_mkldnn_fuse_pass");
  }

  if (use_bfloat16) config.EnableMkldnnBfloat16();

  return config;
}

template <typename T>
paddle::PaddleTensor ParseTensor(const std::string &field) {
  const auto data = Split<std::string>(field, ':');
  if (data.size() < 2) throw "invalid data field";

  std::string shape_str = data[0];
  const auto shape = Split<int>(shape_str, ' ');
  paddle::PaddleTensor tensor;
  tensor.shape = shape;
  auto size =
      std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int>()) *
      sizeof(T);
  tensor.data.Resize(size);

  std::string mat_str = data[1];
  const auto mat = Split<T>(mat_str, ' ');
  std::copy(mat.cbegin(), mat.cend(), static_cast<T *>(tensor.data.data()));
  tensor.dtype = GetPaddleDType<T>();

  return tensor;
}

template <typename T>
std::vector<T> Split(const std::string &line, char separator) {
  std::vector<T> result;
  std::stringstream ss;
  for (auto c : line) {
    if (c != separator) {
      ss << c;
    } else {
      result.emplace_back(GetValueFromStream<T>(ss));
      ss.str({});
      ss.clear();
    }
  }

  auto ss_is_not_empty = !ss.str().empty();
  if (ss_is_not_empty) result.emplace_back(GetValueFromStream<T>(ss));

  return result;
}

template <typename T>
T GetValueFromStream(std::stringstream &ss) {
  T result;
  ss >> result;
  return result;
}

template <>
std::string GetValueFromStream<std::string>(std::stringstream &ss) {
  return ss.str();
}

F
fuchang01 已提交
285 286
}  // namespace inference
}  // namespace paddle