test_inference_nlp.cc 9.0 KB
Newer Older
T
tensor-tang 已提交
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. */

T
tensor-tang 已提交
15
#include <time.h>
T
tensor-tang 已提交
16
#include <fstream>
T
tensor-tang 已提交
17
#include <thread>  // NOLINT
T
tensor-tang 已提交
18 19 20
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "paddle/fluid/inference/tests/test_helper.h"
T
tensor-tang 已提交
21
#include "paddle/fluid/platform/cpu_helper.h"
T
tensor-tang 已提交
22

23 24
#include "paddle/fluid/framework/feed_fetch_method.h"

T
tensor-tang 已提交
25 26
DEFINE_string(model_path, "", "Directory of the inference model.");
DEFINE_string(data_file, "", "File of input index data.");
T
tensor-tang 已提交
27 28
DEFINE_int32(repeat, 100, "Running the inference program repeat times");
DEFINE_bool(prepare_vars, true, "Prepare variables before executor");
T
tensor-tang 已提交
29
DEFINE_int32(num_threads, 1, "Number of threads should be used");
T
tensor-tang 已提交
30
DECLARE_bool(use_mkldnn);
T
tensor-tang 已提交
31
DECLARE_int32(paddle_num_threads);
T
tensor-tang 已提交
32

T
tensor-tang 已提交
33
inline double GetCurrentMs() {
T
tensor-tang 已提交
34 35 36 37 38
  struct timeval time;
  gettimeofday(&time, NULL);
  return 1e+3 * time.tv_sec + 1e-3 * time.tv_usec;
}

T
tensor-tang 已提交
39 40 41 42 43 44 45 46
// This function just give dummy data for recognize_digits model.
size_t DummyData(std::vector<paddle::framework::LoDTensor>* out) {
  paddle::framework::LoDTensor input;
  SetupTensor<float>(&input, {1, 1, 28, 28}, -1.f, 1.f);
  out->emplace_back(input);
  return 1;
}

T
tensor-tang 已提交
47 48
// Load the input word index data from file and save into LodTensor.
// Return the size of words.
T
tensor-tang 已提交
49 50
size_t LoadData(std::vector<paddle::framework::LoDTensor>* out,
                const std::string& filename) {
T
tensor-tang 已提交
51 52 53 54
  if (filename.empty()) {
    return DummyData(out);
  }

T
tensor-tang 已提交
55
  size_t sz = 0;
T
tensor-tang 已提交
56 57
  std::fstream fin(filename);
  std::string line;
T
tensor-tang 已提交
58 59
  out->clear();
  while (getline(fin, line)) {
T
tensor-tang 已提交
60 61 62
    std::istringstream iss(line);
    std::vector<int64_t> ids;
    std::string field;
T
tensor-tang 已提交
63 64 65
    while (getline(iss, field, ' ')) {
      ids.push_back(stoi(field));
    }
T
tensor-tang 已提交
66
    if (ids.size() >= 1024) {
T
tensor-tang 已提交
67
      // Synced with NLP guys, they will ignore input larger then 1024
T
tensor-tang 已提交
68 69 70 71 72 73 74 75 76 77 78
      continue;
    }

    paddle::framework::LoDTensor words;
    paddle::framework::LoD lod{{0, ids.size()}};
    words.set_lod(lod);
    int64_t* pdata = words.mutable_data<int64_t>(
        {static_cast<int64_t>(ids.size()), 1}, paddle::platform::CPUPlace());
    memcpy(pdata, ids.data(), words.numel() * sizeof(int64_t));
    out->emplace_back(words);
    sz += ids.size();
T
tensor-tang 已提交
79
  }
T
tensor-tang 已提交
80 81 82
  return sz;
}

T
tensor-tang 已提交
83 84
// Split input data samples into small pieces jobs as balanced as possible,
// according to the number of threads.
T
tensor-tang 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
void SplitData(
    const std::vector<paddle::framework::LoDTensor>& datasets,
    std::vector<std::vector<const paddle::framework::LoDTensor*>>* jobs,
    const int num_threads) {
  size_t s = 0;
  jobs->resize(num_threads);
  while (s < datasets.size()) {
    for (auto it = jobs->begin(); it != jobs->end(); it++) {
      it->emplace_back(&datasets[s]);
      s++;
      if (s >= datasets.size()) {
        break;
      }
    }
  }
}

T
tensor-tang 已提交
102
void ThreadRunInfer(
T
tensor-tang 已提交
103
    const int tid, paddle::framework::Scope* scope,
T
tensor-tang 已提交
104
    const std::vector<std::vector<const paddle::framework::LoDTensor*>>& jobs) {
T
tensor-tang 已提交
105
  // maybe framework:ProgramDesc is not thread-safe
T
tensor-tang 已提交
106 107
  paddle::platform::CPUPlace place;
  paddle::framework::Executor executor(place);
T
tensor-tang 已提交
108
  auto& sub_scope = scope->NewScope();
T
tensor-tang 已提交
109 110
  auto inference_program =
      paddle::inference::Load(&executor, scope, FLAGS_model_path);
T
tensor-tang 已提交
111

T
tensor-tang 已提交
112 113
  auto ctx = executor.Prepare(*inference_program, /*block_id*/ 0);
  executor.CreateVariables(*inference_program, &sub_scope, /*block_id*/ 0);
T
tensor-tang 已提交
114 115

  const std::vector<std::string>& feed_target_names =
T
tensor-tang 已提交
116
      inference_program->GetFeedTargetNames();
T
tensor-tang 已提交
117
  const std::vector<std::string>& fetch_target_names =
T
tensor-tang 已提交
118
      inference_program->GetFetchTargetNames();
T
tensor-tang 已提交
119 120

  PADDLE_ENFORCE_EQ(fetch_target_names.size(), 1UL);
121 122
  std::map<std::string, paddle::framework::FetchType*> fetch_targets;
  paddle::framework::FetchType outtensor;
T
tensor-tang 已提交
123 124 125 126 127
  fetch_targets[fetch_target_names[0]] = &outtensor;

  std::map<std::string, const paddle::framework::LoDTensor*> feed_targets;
  PADDLE_ENFORCE_EQ(feed_target_names.size(), 1UL);

128 129 130 131
  // map the data of feed_targets to feed_holder
  for (auto* op : inference_program->Block(0).AllOps()) {
    if (op->Type() == "feed") {
      std::string feed_target_name = op->Output("Out")[0];
132
      int idx = BOOST_GET_CONST(int, op->GetAttr("col"));
133 134 135 136 137
      paddle::framework::SetFeedVariable(scope, *feed_targets[feed_target_name],
                                         "feed", idx);
    }
  }

T
tensor-tang 已提交
138
  auto& inputs = jobs[tid];
T
tensor-tang 已提交
139
  auto start_ms = GetCurrentMs();
T
tensor-tang 已提交
140 141
  for (size_t i = 0; i < inputs.size(); ++i) {
    feed_targets[feed_target_names[0]] = inputs[i];
142 143
    executor.RunPreparedContext(ctx.get(), &sub_scope,
                                false /*create_local_scope*/);
T
tensor-tang 已提交
144
  }
T
tensor-tang 已提交
145
  auto stop_ms = GetCurrentMs();
146 147 148 149 150

  // obtain the data of fetch_targets from fetch_holder
  for (auto* op : inference_program->Block(0).AllOps()) {
    if (op->Type() == "fetch") {
      std::string fetch_target_name = op->Input("X")[0];
151
      int idx = BOOST_GET_CONST(int, op->GetAttr("col"));
152
      *fetch_targets[fetch_target_name] =
153 154
          BOOST_GET(paddle::framework::LoDTensor,
                    paddle::framework::GetFetchVariable(*scope, "fetch", idx));
155 156 157
    }
  }

T
tensor-tang 已提交
158
  scope->DeleteScope(&sub_scope);
T
tensor-tang 已提交
159 160 161 162 163
  LOG(INFO) << "Tid: " << tid << ", process " << inputs.size()
            << " samples, avg time per sample: "
            << (stop_ms - start_ms) / inputs.size() << " ms";
}

T
tensor-tang 已提交
164
TEST(inference, nlp) {
T
tensor-tang 已提交
165 166
  if (FLAGS_model_path.empty()) {
    LOG(FATAL) << "Usage: ./example --model_path=path/to/your/model";
T
tensor-tang 已提交
167
  }
T
tensor-tang 已提交
168 169
  if (FLAGS_data_file.empty()) {
    LOG(WARNING) << "No data file provided, will use dummy data!"
T
tensor-tang 已提交
170
                 << "Note: if you use nlp model, please provide data file.";
T
tensor-tang 已提交
171
  }
T
tensor-tang 已提交
172 173
  LOG(INFO) << "Model Path: " << FLAGS_model_path;
  LOG(INFO) << "Data File: " << FLAGS_data_file;
T
tensor-tang 已提交
174

T
tensor-tang 已提交
175
  std::vector<paddle::framework::LoDTensor> datasets;
T
tensor-tang 已提交
176
  size_t num_total_words = LoadData(&datasets, FLAGS_data_file);
T
tensor-tang 已提交
177
  LOG(INFO) << "Number of samples (seq_len<1024): " << datasets.size();
T
tensor-tang 已提交
178 179 180
  LOG(INFO) << "Total number of words: " << num_total_words;

  // 0. Call `paddle::framework::InitDevices()` initialize all the devices
T
tensor-tang 已提交
181 182
  std::unique_ptr<paddle::framework::Scope> scope(
      new paddle::framework::Scope());
T
tensor-tang 已提交
183

T
tensor-tang 已提交
184
  paddle::platform::SetNumThreads(FLAGS_paddle_num_threads);
T
tensor-tang 已提交
185 186

  double start_ms = 0, stop_ms = 0;
T
tensor-tang 已提交
187
  if (FLAGS_num_threads > 1) {
T
tensor-tang 已提交
188
    std::vector<std::vector<const paddle::framework::LoDTensor*>> jobs;
T
tensor-tang 已提交
189
    SplitData(datasets, &jobs, FLAGS_num_threads);
T
tensor-tang 已提交
190
    std::vector<std::unique_ptr<std::thread>> threads;
191
    start_ms = GetCurrentMs();
T
tensor-tang 已提交
192
    for (int i = 0; i < FLAGS_num_threads; ++i) {
T
tensor-tang 已提交
193
      threads.emplace_back(
T
tensor-tang 已提交
194
          new std::thread(ThreadRunInfer, i, scope.get(), std::ref(jobs)));
T
tensor-tang 已提交
195 196 197 198
    }
    for (int i = 0; i < FLAGS_num_threads; ++i) {
      threads[i]->join();
    }
T
tensor-tang 已提交
199
    stop_ms = GetCurrentMs();
T
tensor-tang 已提交
200
  } else {
T
tensor-tang 已提交
201
    // 1. Define place, executor, scope
T
tensor-tang 已提交
202 203
    paddle::platform::CPUPlace place;
    paddle::framework::Executor executor(place);
T
tensor-tang 已提交
204 205 206 207 208

    // 2. Initialize the inference_program and load parameters
    std::unique_ptr<paddle::framework::ProgramDesc> inference_program;
    inference_program = InitProgram(&executor, scope.get(), FLAGS_model_path,
                                    /*model combined*/ false);
T
tensor-tang 已提交
209
    // always prepare context
T
tensor-tang 已提交
210 211
    std::unique_ptr<paddle::framework::ExecutorPrepareContext> ctx;
    ctx = executor.Prepare(*inference_program, 0);
T
tensor-tang 已提交
212 213 214
    if (FLAGS_prepare_vars) {
      executor.CreateVariables(*inference_program, scope.get(), 0);
    }
T
tensor-tang 已提交
215 216 217 218
    // preapre fetch
    const std::vector<std::string>& fetch_target_names =
        inference_program->GetFetchTargetNames();
    PADDLE_ENFORCE_EQ(fetch_target_names.size(), 1UL);
219 220
    std::map<std::string, paddle::framework::FetchType*> fetch_targets;
    paddle::framework::FetchType outtensor;
T
tensor-tang 已提交
221 222 223 224 225 226 227 228
    fetch_targets[fetch_target_names[0]] = &outtensor;

    // prepare feed
    const std::vector<std::string>& feed_target_names =
        inference_program->GetFeedTargetNames();
    PADDLE_ENFORCE_EQ(feed_target_names.size(), 1UL);
    std::map<std::string, const paddle::framework::LoDTensor*> feed_targets;

T
tensor-tang 已提交
229 230
    // feed data and run
    start_ms = GetCurrentMs();
T
tensor-tang 已提交
231 232
    for (size_t i = 0; i < datasets.size(); ++i) {
      feed_targets[feed_target_names[0]] = &(datasets[i]);
T
tensor-tang 已提交
233
      executor.RunPreparedContext(ctx.get(), scope.get(), &feed_targets,
T
tensor-tang 已提交
234 235
                                  &fetch_targets, !FLAGS_prepare_vars);
    }
T
tensor-tang 已提交
236
    stop_ms = GetCurrentMs();
T
tensor-tang 已提交
237 238 239
    LOG(INFO) << "Tid: 0, process " << datasets.size()
              << " samples, avg time per sample: "
              << (stop_ms - start_ms) / datasets.size() << " ms";
T
tensor-tang 已提交
240
  }
T
tensor-tang 已提交
241 242
  LOG(INFO) << "Total inference time with " << FLAGS_num_threads
            << " threads : " << (stop_ms - start_ms) / 1000.0
T
tensor-tang 已提交
243
            << " sec, QPS: " << datasets.size() / ((stop_ms - start_ms) / 1000);
T
tensor-tang 已提交
244
}