analyzer_tester.cc 14.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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.

#include "paddle/fluid/inference/analysis/analyzer.h"
16

17
#include <google/protobuf/text_format.h>
18
#include <gtest/gtest.h>
L
luotao1 已提交
19
#include <thread>  // NOLINT
Y
Yan Chunwei 已提交
20
#include "paddle/fluid/framework/ir/fuse_pass_base.h"
21
#include "paddle/fluid/framework/ir/pass.h"
22
#include "paddle/fluid/inference/analysis/ut_helper.h"
Y
Yan Chunwei 已提交
23
#include "paddle/fluid/inference/api/analysis_predictor.h"
24
#include "paddle/fluid/inference/api/helper.h"
25
#include "paddle/fluid/inference/api/paddle_inference_api.h"
L
luotao1 已提交
26
#include "paddle/fluid/inference/api/paddle_inference_pass.h"
Y
Yan Chunwei 已提交
27
#include "paddle/fluid/inference/utils/singleton.h"
28

29 30
DEFINE_string(infer_ditu_rnn_model, "", "model path for ditu RNN");
DEFINE_string(infer_ditu_rnn_data, "", "data path for ditu RNN");
31 32
DEFINE_int32(batch_size, 10, "batch size.");
DEFINE_int32(repeat, 1, "Running the inference program repeat times.");
L
luotao1 已提交
33
DEFINE_int32(num_threads, 1, "Running the inference program in multi-threads.");
34

35 36 37 38
namespace paddle {
namespace inference {
namespace analysis {

T
tensor-tang 已提交
39
using namespace framework;  // NOLINT
Y
Yan Chunwei 已提交
40

Y
Yan Chunwei 已提交
41
TEST(Analyzer, analysis_without_tensorrt) {
42
  FLAGS_IA_enable_tensorrt_subgraph_engine = false;
Y
Yan Chunwei 已提交
43 44
  Argument argument;
  argument.fluid_model_dir.reset(new std::string(FLAGS_inference_model_dir));
45 46 47 48
  Analyzer analyser;
  analyser.Run(&argument);
}

Y
Yan Chunwei 已提交
49
TEST(Analyzer, analysis_with_tensorrt) {
50
  FLAGS_IA_enable_tensorrt_subgraph_engine = true;
Y
Yan Chunwei 已提交
51 52
  Argument argument;
  argument.fluid_model_dir.reset(new std::string(FLAGS_inference_model_dir));
53 54 55 56
  Analyzer analyser;
  analyser.Run(&argument);
}

57
void TestWord2vecPrediction(const std::string &model_path) {
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  NativeConfig config;
  config.model_dir = model_path;
  config.use_gpu = false;
  config.device = 0;
  auto predictor =
      ::paddle::CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(
          config);

  // One single batch

  int64_t data[4] = {1, 2, 3, 4};
  PaddleTensor tensor;
  tensor.shape = std::vector<int>({4, 1});
  tensor.data = PaddleBuf(data, sizeof(data));
  tensor.dtype = PaddleDType::INT64;

  // For simplicity, we set all the slots with the same data.
  std::vector<PaddleTensor> slots(4, tensor);
  std::vector<PaddleTensor> outputs;
  CHECK(predictor->Run(slots, &outputs));

  PADDLE_ENFORCE(outputs.size(), 1UL);
  // Check the output buffer size and result of each tid.
  PADDLE_ENFORCE(outputs.front().data.length(), 33168UL);
  float result[5] = {0.00129761, 0.00151112, 0.000423564, 0.00108815,
                     0.000932706};
  const size_t num_elements = outputs.front().data.length() / sizeof(float);
  // The outputs' buffers are in CPU memory.
  for (size_t i = 0; i < std::min(5UL, num_elements); i++) {
    LOG(INFO) << "data: "
88 89
              << static_cast<float *>(outputs.front().data.data())[i];
    PADDLE_ENFORCE(static_cast<float *>(outputs.front().data.data())[i],
90 91 92 93
                   result[i]);
  }
}

94 95 96 97 98 99 100 101 102 103 104
namespace {

struct DataRecord {
  std::vector<std::vector<std::vector<float>>> link_step_data_all;
  std::vector<std::vector<float>> week_data_all, minute_data_all;
  std::vector<size_t> lod1, lod2, lod3;
  std::vector<std::vector<float>> rnn_link_data, rnn_week_datas,
      rnn_minute_datas;
  size_t batch_iter{0};
  size_t batch_size{1};
  DataRecord() = default;
105
  explicit DataRecord(const std::string &path, int batch_size = 1)
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 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
      : batch_size(batch_size) {
    Load(path);
  }
  DataRecord NextBatch() {
    DataRecord data;
    size_t batch_end = batch_iter + batch_size;
    // NOTE skip the final batch, if no enough data is provided.
    if (batch_end <= link_step_data_all.size()) {
      data.link_step_data_all.assign(link_step_data_all.begin() + batch_iter,
                                     link_step_data_all.begin() + batch_end);
      data.week_data_all.assign(week_data_all.begin() + batch_iter,
                                week_data_all.begin() + batch_end);
      data.minute_data_all.assign(minute_data_all.begin() + batch_iter,
                                  minute_data_all.begin() + batch_end);
      // Prepare LoDs
      data.lod1.push_back(0);
      data.lod2.push_back(0);
      data.lod3.push_back(0);
      CHECK(!data.link_step_data_all.empty()) << "empty";
      CHECK(!data.week_data_all.empty());
      CHECK(!data.minute_data_all.empty());
      CHECK_EQ(data.link_step_data_all.size(), data.week_data_all.size());
      CHECK_EQ(data.minute_data_all.size(), data.link_step_data_all.size());
      for (size_t j = 0; j < data.link_step_data_all.size(); j++) {
        for (const auto &d : data.link_step_data_all[j]) {
          data.rnn_link_data.push_back(d);
        }
        data.rnn_week_datas.push_back(data.week_data_all[j]);
        data.rnn_minute_datas.push_back(data.minute_data_all[j]);
        // calculate lod
        data.lod1.push_back(data.lod1.back() +
                            data.link_step_data_all[j].size());
        data.lod3.push_back(data.lod3.back() + 1);
        for (size_t i = 1; i < data.link_step_data_all[j].size() + 1; i++) {
          data.lod2.push_back(data.lod2.back() +
                              data.link_step_data_all[j].size());
        }
      }
    }
    batch_iter += batch_size;
    return data;
  }
  void Load(const std::string &path) {
    std::ifstream file(path);
    std::string line;
    int num_lines = 0;
    while (std::getline(file, line)) {
      num_lines++;
      std::vector<std::string> data;
      split(line, ':', &data);
      std::vector<std::vector<float>> link_step_data;
      std::vector<std::string> link_datas;
      split(data[0], '|', &link_datas);
      for (auto &step_data : link_datas) {
        std::vector<float> tmp;
        split_to_float(step_data, ',', &tmp);
        link_step_data.push_back(tmp);
      }
      // load week data
      std::vector<float> week_data;
      split_to_float(data[2], ',', &week_data);
      // load minute data
      std::vector<float> minute_data;
      split_to_float(data[1], ',', &minute_data);
      link_step_data_all.push_back(std::move(link_step_data));
      week_data_all.push_back(std::move(week_data));
      minute_data_all.push_back(std::move(minute_data));
    }
  }
};
void PrepareInputs(std::vector<PaddleTensor> *input_slots, DataRecord *data,
                   int batch_size) {
  PaddleTensor lod_attention_tensor, init_zero_tensor, lod_tensor_tensor,
      week_tensor, minute_tensor;
  lod_attention_tensor.name = "data_lod_attention";
  init_zero_tensor.name = "cell_init";
  lod_tensor_tensor.name = "data";
  week_tensor.name = "week";
  minute_tensor.name = "minute";
  auto one_batch = data->NextBatch();
186 187 188
  std::vector<int> rnn_link_data_shape(
      {static_cast<int>(one_batch.rnn_link_data.size()),
       static_cast<int>(one_batch.rnn_link_data.front().size())});
189 190 191 192 193 194
  lod_attention_tensor.shape.assign({1, 2});
  lod_attention_tensor.lod.assign({one_batch.lod1, one_batch.lod2});
  init_zero_tensor.shape.assign({batch_size, 15});
  init_zero_tensor.lod.assign({one_batch.lod3});
  lod_tensor_tensor.shape = rnn_link_data_shape;
  lod_tensor_tensor.lod.assign({one_batch.lod1});
195 196 197 198
  // clang-format off
  week_tensor.shape.assign(
      {static_cast<int>(one_batch.rnn_week_datas.size()),
       static_cast<int>(one_batch.rnn_week_datas.front().size())});
199
  week_tensor.lod.assign({one_batch.lod3});
200 201 202
  minute_tensor.shape.assign(
      {static_cast<int>(one_batch.rnn_minute_datas.size()),
       static_cast<int>(one_batch.rnn_minute_datas.front().size())});
203
  minute_tensor.lod.assign({one_batch.lod3});
204
  // clang-format on
205
  // assign data
L
luotao1 已提交
206 207
  TensorAssignData<float>(&lod_attention_tensor,
                          std::vector<std::vector<float>>({{0, 0}}));
208
  std::vector<float> tmp_zeros(batch_size * 15, 0.);
L
luotao1 已提交
209 210 211 212
  TensorAssignData<float>(&init_zero_tensor, {tmp_zeros});
  TensorAssignData<float>(&lod_tensor_tensor, one_batch.rnn_link_data);
  TensorAssignData<float>(&week_tensor, one_batch.rnn_week_datas);
  TensorAssignData<float>(&minute_tensor, one_batch.rnn_minute_datas);
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  // Set inputs.
  auto init_zero_tensor1 = init_zero_tensor;
  init_zero_tensor1.name = "hidden_init";
  input_slots->assign({week_tensor, init_zero_tensor, minute_tensor,
                       init_zero_tensor1, lod_attention_tensor,
                       lod_tensor_tensor});
  for (auto &tensor : *input_slots) {
    tensor.dtype = PaddleDType::FLOAT32;
  }
}

}  // namespace

const float ditu_rnn_target_data[] = {
    104.711, 11.2431, 1.35422, 0,       0,       0,       0,       0,
    27.7039, 1.41486, 7.09526, 0,       0,       0,       0,       0,
    7.6481,  6.5324,  56.383,  2.88018, 8.92918, 132.007, 4.27429, 2.02934,
    14.1727, 10.7461, 25.0616, 16.0197, 14.4163, 16.9199, 6.75517, 0,
    80.0249, 4.77739, 0,       0,       0,       0,       0,       0,
    47.5643, 2.67029, 8.76252, 0,       0,       0,       0,       0,
    51.8822, 4.4411,  0,       0,       0,       0,       0,       0,
    10.7286, 12.0595, 10.6672, 0,       0,       0,       0,       0,
    93.5771, 3.84641, 0,       0,       0,       0,       0,       0,
    169.426, 0,       0,       0,       0,       0,       0,       0};
L
luotao1 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
void CompareResult(const std::vector<PaddleTensor> &outputs,
                   const std::vector<PaddleTensor> &base_outputs) {
  PADDLE_ENFORCE_GT(outputs.size(), 0);
  PADDLE_ENFORCE_EQ(outputs.size(), base_outputs.size());
  for (size_t i = 0; i < outputs.size(); i++) {
    auto &out = outputs[i];
    auto &base_out = base_outputs[i];
    size_t size = std::accumulate(out.shape.begin(), out.shape.end(), 1,
                                  [](int a, int b) { return a * b; });
    size_t size1 = std::accumulate(base_out.shape.begin(), base_out.shape.end(),
                                   1, [](int a, int b) { return a * b; });
    PADDLE_ENFORCE_EQ(size, size1);
    PADDLE_ENFORCE_GT(size, 0);
    float *data = static_cast<float *>(out.data.data());
    float *base_data = static_cast<float *>(base_out.data.data());
    for (size_t i = 0; i < size; i++) {
      EXPECT_NEAR(data[i], base_data[i], 1e-3);
    }
  }
}
257
// Test with a really complicate model.
L
luotao1 已提交
258 259
void TestDituRNNPrediction(bool use_analysis_and_activate_ir = false,
                           int num_threads = FLAGS_num_threads) {
260
  NativeConfig config;
261 262
  config.prog_file = FLAGS_infer_ditu_rnn_model + "/__model__";
  config.param_file = FLAGS_infer_ditu_rnn_model + "/param";
263 264 265
  config.use_gpu = false;
  config.device = 0;
  config.specify_input_name = true;
L
luotao1 已提交
266 267
  int batch_size = FLAGS_batch_size;
  int num_times = FLAGS_repeat;
268

269
  auto base_predictor =
270
      CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kNative>(config);
271 272
  auto predictor =
      CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kAnalysis>(config);
273
  std::vector<PaddleTensor> input_slots;
L
luotao1 已提交
274
  DataRecord data(FLAGS_infer_ditu_rnn_data, batch_size);
275 276
  // Prepare inputs.
  PrepareInputs(&input_slots, &data, batch_size);
277 278 279
  std::vector<PaddleTensor> outputs, base_outputs;

  base_predictor->Run(input_slots, &base_outputs);
280

281
  LOG(INFO) << "===========profile result===========";
L
luotao1 已提交
282 283 284 285 286 287 288
  if (num_threads == 1) {
    // Prepare inputs.
    Timer timer;
    timer.tic();
    for (int i = 0; i < num_times; i++) {
      predictor->Run(input_slots, &outputs);
    }
L
luotao1 已提交
289 290
    PrintTime(batch_size, num_times, 1, 0, timer.toc() / num_times);
    CompareResult(outputs, base_outputs);
L
luotao1 已提交
291 292
  } else {
    std::vector<std::thread> threads;
L
luotao1 已提交
293 294 295 296 297 298 299 300
    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) {
      predictors.emplace_back(
          CreatePaddlePredictor<NativeConfig, PaddleEngineKind::kAnalysis>(
              config));
    }
L
luotao1 已提交
301 302
    for (int tid = 0; tid < num_threads; ++tid) {
      threads.emplace_back([&, tid]() {
L
luotao1 已提交
303 304 305 306 307
        // Each thread should have local input_slots and outputs.
        std::vector<PaddleTensor> input_slots;
        DataRecord data(FLAGS_infer_ditu_rnn_data, batch_size);
        PrepareInputs(&input_slots, &data, batch_size);
        std::vector<PaddleTensor> outputs;
L
luotao1 已提交
308 309 310
        Timer timer;
        timer.tic();
        for (int i = 0; i < num_times; i++) {
L
luotao1 已提交
311
          predictors[tid]->Run(input_slots, &outputs);
L
luotao1 已提交
312
        }
L
luotao1 已提交
313 314 315
        PrintTime(batch_size, num_times, num_threads, tid,
                  timer.toc() / num_times);
        CompareResult(outputs, base_outputs);
L
luotao1 已提交
316 317 318 319 320 321
      });
    }
    for (int i = 0; i < num_threads; ++i) {
      threads[i].join();
    }
  }
322
  LOG(INFO) << "=====================================";
323

L
luotao1 已提交
324
  if (use_analysis_and_activate_ir) {
Y
Yan Chunwei 已提交
325 326 327 328 329 330 331 332 333
    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;
    }

Y
Yan Chunwei 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347
    int num_ops = 0;
    for (auto &node :
         analysis_predictor->analysis_argument().main_dfg->nodes.nodes()) {
      if (node->IsFunction()) {
        ++num_ops;
      }
    }
    LOG(INFO) << "has num ops: " << num_ops;

    ASSERT_TRUE(fuse_statis.count("fc_fuse"));
    EXPECT_EQ(fuse_statis.at("fc_fuse"), 1);
    EXPECT_EQ(fuse_statis.at("fc_nobias_lstm_fuse"), 2);  // bi-directional LSTM
    EXPECT_EQ(num_ops,
              13);  // After graph optimization, only 13 operators exists.
Y
Yan Chunwei 已提交
348
  }
349 350
}

L
luotao1 已提交
351 352
// basic unit-test of DituRNN, easy for profiling independently.
TEST(Analyzer, DituRNN) { TestDituRNNPrediction(false, FLAGS_num_threads); }
353

L
luotao1 已提交
354 355
// advance unit-test of DituRNN, test use_analysis_and_activate_ir and
// multi-threads.
L
luotao1 已提交
356
TEST(Analyzer, DituRNN_multi_thread) {
L
luotao1 已提交
357
  TestDituRNNPrediction(true, 1);
L
luotao1 已提交
358 359
  TestDituRNNPrediction(false, 4);
  TestDituRNNPrediction(true, 4);
360 361
}

362 363 364
}  // namespace analysis
}  // namespace inference
}  // namespace paddle