general_model.cpp 15.8 KB
Newer Older
G
guru4elephant 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2019 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.

G
guru4elephant 已提交
15
#include "core/general-client/include/general_model.h"
M
MRXLT 已提交
16
#include <fstream>
G
guru4elephant 已提交
17 18 19
#include "core/sdk-cpp/builtin_format.pb.h"
#include "core/sdk-cpp/include/common.h"
#include "core/sdk-cpp/include/predictor_sdk.h"
G
guru4elephant 已提交
20
#include "core/util/include/timer.h"
G
guru4elephant 已提交
21

22 23 24
DEFINE_bool(profile_client, false, "");
DEFINE_bool(profile_server, false, "");

G
guru4elephant 已提交
25
using baidu::paddle_serving::Timer;
G
guru4elephant 已提交
26 27 28 29 30 31
using baidu::paddle_serving::predictor::general_model::Request;
using baidu::paddle_serving::predictor::general_model::Response;
using baidu::paddle_serving::predictor::general_model::Tensor;
using baidu::paddle_serving::predictor::general_model::FeedInst;
using baidu::paddle_serving::predictor::general_model::FetchInst;

32 33
std::once_flag gflags_init_flag;

G
guru4elephant 已提交
34 35 36
namespace baidu {
namespace paddle_serving {
namespace general_model {
37
using configure::GeneralModelConfig;
G
guru4elephant 已提交
38

39 40
void PredictorClient::init_gflags(std::vector<std::string> argv) {
  std::call_once(gflags_init_flag, [&]() {
M
MRXLT 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53
    FLAGS_logtostderr = true;
    argv.insert(argv.begin(), "dummy");
    int argc = argv.size();
    char **arr = new char *[argv.size()];
    std::string line;
    for (size_t i = 0; i < argv.size(); i++) {
      arr[i] = &argv[i][0];
      line += argv[i];
      line += ' ';
    }
    google::ParseCommandLineFlags(&argc, &arr, true);
    VLOG(2) << "Init commandline: " << line;
  });
54 55
}

56 57 58
int PredictorClient::init(const std::string &conf_file) {
  try {
    GeneralModelConfig model_config;
M
MRXLT 已提交
59
    if (configure::read_proto_conf(conf_file.c_str(), &model_config) != 0) {
60 61 62 63
      LOG(ERROR) << "Failed to load general model config"
                 << ", file path: " << conf_file;
      return -1;
    }
64

65 66 67 68 69
    _feed_name_to_idx.clear();
    _fetch_name_to_idx.clear();
    _shape.clear();
    int feed_var_num = model_config.feed_var_size();
    int fetch_var_num = model_config.fetch_var_size();
70 71
    VLOG(2) << "feed var num: " << feed_var_num
            << "fetch_var_num: " << fetch_var_num;
72 73
    for (int i = 0; i < feed_var_num; ++i) {
      _feed_name_to_idx[model_config.feed_var(i).alias_name()] = i;
74 75
      VLOG(2) << "feed alias name: " << model_config.feed_var(i).alias_name()
              << " index: " << i;
76
      std::vector<int> tmp_feed_shape;
M
MRXLT 已提交
77 78
      VLOG(2) << "feed"
              << "[" << i << "] shape:";
79 80
      for (int j = 0; j < model_config.feed_var(i).shape_size(); ++j) {
        tmp_feed_shape.push_back(model_config.feed_var(i).shape(j));
M
MRXLT 已提交
81
        VLOG(2) << "shape[" << j << "]: " << model_config.feed_var(i).shape(j);
82 83
      }
      _type.push_back(model_config.feed_var(i).feed_type());
M
MRXLT 已提交
84 85 86
      VLOG(2) << "feed"
              << "[" << i
              << "] feed type: " << model_config.feed_var(i).feed_type();
87
      _shape.push_back(tmp_feed_shape);
G
guru4elephant 已提交
88 89
    }

90 91
    for (int i = 0; i < fetch_var_num; ++i) {
      _fetch_name_to_idx[model_config.fetch_var(i).alias_name()] = i;
M
MRXLT 已提交
92 93
      VLOG(2) << "fetch [" << i << "]"
              << " alias name: " << model_config.fetch_var(i).alias_name();
94 95
      _fetch_name_to_var_name[model_config.fetch_var(i).alias_name()] =
          model_config.fetch_var(i).name();
96 97
      _fetch_name_to_type[model_config.fetch_var(i).alias_name()] =
          model_config.fetch_var(i).fetch_type();
98
    }
M
MRXLT 已提交
99
  } catch (std::exception &e) {
100 101
    LOG(ERROR) << "Failed load general model config" << e.what();
    return -1;
G
guru4elephant 已提交
102
  }
103
  return 0;
G
guru4elephant 已提交
104 105
}

M
MRXLT 已提交
106 107
void PredictorClient::set_predictor_conf(const std::string &conf_path,
                                         const std::string &conf_file) {
G
guru4elephant 已提交
108 109 110 111
  _predictor_path = conf_path;
  _predictor_conf = conf_file;
}

112 113 114
int PredictorClient::destroy_predictor() {
  _api.thrd_finalize();
  _api.destroy();
B
barrierye 已提交
115
  return 0;
116 117
}

M
MRXLT 已提交
118
int PredictorClient::create_predictor_by_desc(const std::string &sdk_desc) {
G
guru4elephant 已提交
119 120 121 122 123
  if (_api.create(sdk_desc) != 0) {
    LOG(ERROR) << "Predictor Creation Failed";
    return -1;
  }
  _api.thrd_initialize();
B
barrierye 已提交
124
  return 0;
G
guru4elephant 已提交
125 126
}

G
guru4elephant 已提交
127
int PredictorClient::create_predictor() {
G
guru4elephant 已提交
128 129
  VLOG(2) << "Predictor path: " << _predictor_path
          << " predictor file: " << _predictor_conf;
G
guru4elephant 已提交
130 131 132 133 134
  if (_api.create(_predictor_path.c_str(), _predictor_conf.c_str()) != 0) {
    LOG(ERROR) << "Predictor Creation Failed";
    return -1;
  }
  _api.thrd_initialize();
B
barrierye 已提交
135
  return 0;
G
guru4elephant 已提交
136 137
}

M
MRXLT 已提交
138 139 140 141 142
int PredictorClient::predict(const std::vector<std::vector<float>> &float_feed,
                             const std::vector<std::string> &float_feed_name,
                             const std::vector<std::vector<int64_t>> &int_feed,
                             const std::vector<std::string> &int_feed_name,
                             const std::vector<std::string> &fetch_name,
M
MRXLT 已提交
143 144
                             PredictorRes &predict_res,
                             const int &pid) {  // NOLINT
B
barrierye 已提交
145
  predict_res.clear();
G
guru4elephant 已提交
146 147
  Timer timeline;
  int64_t preprocess_start = timeline.TimeStampUS();
G
guru4elephant 已提交
148
  _api.thrd_clear();
149 150 151
  std::string variant_tag;
  _predictor = _api.fetch_predictor("general_model", &variant_tag);
  predict_res.set_variant_tag(variant_tag);
G
guru4elephant 已提交
152

G
guru4elephant 已提交
153
  Request req;
M
MRXLT 已提交
154
  for (auto &name : fetch_name) {
155 156
    req.add_fetch_var_names(name);
  }
157

G
guru4elephant 已提交
158
  std::vector<Tensor *> tensor_vec;
M
MRXLT 已提交
159 160
  FeedInst *inst = req.add_insts();
  for (auto &name : float_feed_name) {
G
guru4elephant 已提交
161 162 163
    tensor_vec.push_back(inst->add_tensor_array());
  }

M
MRXLT 已提交
164
  for (auto &name : int_feed_name) {
G
guru4elephant 已提交
165 166 167 168
    tensor_vec.push_back(inst->add_tensor_array());
  }

  int vec_idx = 0;
M
MRXLT 已提交
169
  for (auto &name : float_feed_name) {
G
guru4elephant 已提交
170
    int idx = _feed_name_to_idx[name];
M
MRXLT 已提交
171
    Tensor *tensor = tensor_vec[idx];
B
barrierye 已提交
172
    for (uint32_t j = 0; j < _shape[idx].size(); ++j) {
G
guru4elephant 已提交
173 174 175
      tensor->add_shape(_shape[idx][j]);
    }
    tensor->set_elem_type(1);
B
barrierye 已提交
176
    for (uint32_t j = 0; j < float_feed[vec_idx].size(); ++j) {
177
      tensor->add_float_data(float_feed[vec_idx][j]);
G
guru4elephant 已提交
178 179 180 181
    }
    vec_idx++;
  }

182
  VLOG(2) << "feed float feed var done.";
G
guru4elephant 已提交
183
  vec_idx = 0;
184

M
MRXLT 已提交
185
  for (auto &name : int_feed_name) {
G
guru4elephant 已提交
186
    int idx = _feed_name_to_idx[name];
M
MRXLT 已提交
187
    Tensor *tensor = tensor_vec[idx];
B
barrierye 已提交
188
    for (uint32_t j = 0; j < _shape[idx].size(); ++j) {
G
guru4elephant 已提交
189 190 191
      tensor->add_shape(_shape[idx][j]);
    }
    tensor->set_elem_type(0);
B
barrierye 已提交
192
    for (uint32_t j = 0; j < int_feed[vec_idx].size(); ++j) {
193
      tensor->add_int64_data(int_feed[vec_idx][j]);
G
guru4elephant 已提交
194 195 196 197
    }
    vec_idx++;
  }

G
guru4elephant 已提交
198 199
  int64_t preprocess_end = timeline.TimeStampUS();
  int64_t client_infer_start = timeline.TimeStampUS();
G
guru4elephant 已提交
200 201
  Response res;

G
guru4elephant 已提交
202 203 204
  int64_t client_infer_end = 0;
  int64_t postprocess_start = 0;
  int64_t postprocess_end = 0;
205 206 207 208 209 210 211

  if (FLAGS_profile_client) {
    if (FLAGS_profile_server) {
      req.set_profile_server(true);
    }
  }

G
guru4elephant 已提交
212 213 214
  res.Clear();
  if (_predictor->inference(&req, &res) != 0) {
    LOG(ERROR) << "failed call predictor with req: " << req.ShortDebugString();
215
    return -1;
G
guru4elephant 已提交
216
  } else {
217
    VLOG(2) << "predict done.";
G
guru4elephant 已提交
218 219
    client_infer_end = timeline.TimeStampUS();
    postprocess_start = client_infer_end;
B
barrierye 已提交
220
    // multi-model output
B
barrierye 已提交
221
    uint32_t model_num = res.outputs_size();
B
barrierye 已提交
222
    // predict_res._models.resize(model_num);
B
barrierye 已提交
223 224 225
    for (uint32_t m_idx = 0; m_idx < model_num; ++m_idx) {
      VLOG(2) << "process model output index: " << m_idx;
      auto output = res.outputs(m_idx);
B
barrierye 已提交
226 227
      ModelRes model;
      model.set_engine_name(output.engine_name());
B
barrierye 已提交
228 229 230 231 232 233
      for (auto &name : fetch_name) {
        int idx = _fetch_name_to_idx[name];
        VLOG(2) << "fetch name: " << name;
        if (_fetch_name_to_type[name] == 0) {
          int len = output.insts(0).tensor_array(idx).int64_data_size();
          VLOG(2) << "fetch tensor : " << name << " type: int64 len : " << len;
B
barrierye 已提交
234 235
          model._int64_map[name].resize(1);
          model._int64_map[name][0].resize(len);
B
barrierye 已提交
236
          for (int i = 0; i < len; ++i) {
B
barrierye 已提交
237
            model._int64_map[name][0][i] =
B
barrierye 已提交
238 239 240 241
                output.insts(0).tensor_array(idx).int64_data(i);
          }
        } else if (_fetch_name_to_type[name] == 1) {
          int len = output.insts(0).tensor_array(idx).float_data_size();
B
barrierye 已提交
242 243 244 245
          VLOG(2) << "fetch tensor : " << name
                  << " type: float32 len : " << len;
          model._float_map[name].resize(1);
          model._float_map[name][0].resize(len);
B
barrierye 已提交
246
          for (int i = 0; i < len; ++i) {
B
barrierye 已提交
247
            model._float_map[name][0][i] =
B
barrierye 已提交
248 249
                output.insts(0).tensor_array(idx).float_data(i);
          }
250
        }
G
guru4elephant 已提交
251
      }
B
barrierye 已提交
252
      predict_res.add_model_res(std::move(model));
G
guru4elephant 已提交
253
    }
254
    postprocess_end = timeline.TimeStampUS();
G
guru4elephant 已提交
255 256
  }

257 258 259
  if (FLAGS_profile_client) {
    std::ostringstream oss;
    oss << "PROFILE\t"
M
MRXLT 已提交
260
        << "pid:" << pid << "\t"
261 262 263 264 265 266 267 268 269 270 271
        << "prepro_0:" << preprocess_start << " "
        << "prepro_1:" << preprocess_end << " "
        << "client_infer_0:" << client_infer_start << " "
        << "client_infer_1:" << client_infer_end << " ";
    if (FLAGS_profile_server) {
      int op_num = res.profile_time_size() / 2;
      for (int i = 0; i < op_num; ++i) {
        oss << "op" << i << "_0:" << res.profile_time(i * 2) << " ";
        oss << "op" << i << "_1:" << res.profile_time(i * 2 + 1) << " ";
      }
    }
M
MRXLT 已提交
272

273 274
    oss << "postpro_0:" << postprocess_start << " ";
    oss << "postpro_1:" << postprocess_end;
M
MRXLT 已提交
275

276
    fprintf(stderr, "%s\n", oss.str().c_str());
G
guru4elephant 已提交
277
  }
278
  return 0;
G
guru4elephant 已提交
279 280
}

M
MRXLT 已提交
281
int PredictorClient::batch_predict(
M
MRXLT 已提交
282 283 284 285
    const std::vector<std::vector<std::vector<float>>> &float_feed_batch,
    const std::vector<std::string> &float_feed_name,
    const std::vector<std::vector<std::vector<int64_t>>> &int_feed_batch,
    const std::vector<std::string> &int_feed_name,
M
MRXLT 已提交
286
    const std::vector<std::string> &fetch_name,
M
MRXLT 已提交
287
    PredictorRes &predict_res_batch,
M
MRXLT 已提交
288
    const int &pid) {
M
MRXLT 已提交
289
  int batch_size = std::max(float_feed_batch.size(), int_feed_batch.size());
M
MRXLT 已提交
290

B
barrierye 已提交
291
  predict_res_batch.clear();
M
MRXLT 已提交
292 293 294
  Timer timeline;
  int64_t preprocess_start = timeline.TimeStampUS();

M
MRXLT 已提交
295 296 297
  int fetch_name_num = fetch_name.size();

  _api.thrd_clear();
298 299 300
  std::string variant_tag;
  _predictor = _api.fetch_predictor("general_model", &variant_tag);
  predict_res_batch.set_variant_tag(variant_tag);
301 302 303
  VLOG(2) << "fetch general model predictor done.";
  VLOG(2) << "float feed name size: " << float_feed_name.size();
  VLOG(2) << "int feed name size: " << int_feed_name.size();
M
MRXLT 已提交
304
  Request req;
M
MRXLT 已提交
305
  for (auto &name : fetch_name) {
306 307
    req.add_fetch_var_names(name);
  }
B
barrierye 已提交
308

M
MRXLT 已提交
309
  for (int bi = 0; bi < batch_size; bi++) {
310
    VLOG(2) << "prepare batch " << bi;
M
MRXLT 已提交
311 312 313 314 315 316 317 318 319 320 321
    std::vector<Tensor *> tensor_vec;
    FeedInst *inst = req.add_insts();
    std::vector<std::vector<float>> float_feed = float_feed_batch[bi];
    std::vector<std::vector<int64_t>> int_feed = int_feed_batch[bi];
    for (auto &name : float_feed_name) {
      tensor_vec.push_back(inst->add_tensor_array());
    }

    for (auto &name : int_feed_name) {
      tensor_vec.push_back(inst->add_tensor_array());
    }
322

M
MRXLT 已提交
323
    VLOG(2) << "batch [" << bi << "] int_feed_name and float_feed_name "
324
            << "prepared";
M
MRXLT 已提交
325 326 327 328
    int vec_idx = 0;
    for (auto &name : float_feed_name) {
      int idx = _feed_name_to_idx[name];
      Tensor *tensor = tensor_vec[idx];
B
barrierye 已提交
329
      for (uint32_t j = 0; j < _shape[idx].size(); ++j) {
M
MRXLT 已提交
330 331 332
        tensor->add_shape(_shape[idx][j]);
      }
      tensor->set_elem_type(1);
B
barrierye 已提交
333
      for (uint32_t j = 0; j < float_feed[vec_idx].size(); ++j) {
334
        tensor->add_float_data(float_feed[vec_idx][j]);
M
MRXLT 已提交
335 336 337 338
      }
      vec_idx++;
    }

M
MRXLT 已提交
339 340
    VLOG(2) << "batch [" << bi << "] "
            << "float feed value prepared";
341

M
MRXLT 已提交
342 343 344 345
    vec_idx = 0;
    for (auto &name : int_feed_name) {
      int idx = _feed_name_to_idx[name];
      Tensor *tensor = tensor_vec[idx];
B
barrierye 已提交
346
      for (uint32_t j = 0; j < _shape[idx].size(); ++j) {
M
MRXLT 已提交
347 348 349
        tensor->add_shape(_shape[idx][j]);
      }
      tensor->set_elem_type(0);
M
MRXLT 已提交
350 351
      VLOG(3) << "feed var name " << name << " index " << vec_idx
              << "first data " << int_feed[vec_idx][0];
B
barrierye 已提交
352
      for (uint32_t j = 0; j < int_feed[vec_idx].size(); ++j) {
353
        tensor->add_int64_data(int_feed[vec_idx][j]);
M
MRXLT 已提交
354 355 356
      }
      vec_idx++;
    }
357

M
MRXLT 已提交
358
    VLOG(2) << "batch [" << bi << "] "
M
MRXLT 已提交
359
            << "int feed value prepared";
M
MRXLT 已提交
360 361
  }

M
MRXLT 已提交
362 363 364 365
  int64_t preprocess_end = timeline.TimeStampUS();

  int64_t client_infer_start = timeline.TimeStampUS();

M
MRXLT 已提交
366 367
  Response res;

M
MRXLT 已提交
368 369 370 371 372 373 374 375 376 377
  int64_t client_infer_end = 0;
  int64_t postprocess_start = 0;
  int64_t postprocess_end = 0;

  if (FLAGS_profile_client) {
    if (FLAGS_profile_server) {
      req.set_profile_server(true);
    }
  }

M
MRXLT 已提交
378 379 380
  res.Clear();
  if (_predictor->inference(&req, &res) != 0) {
    LOG(ERROR) << "failed call predictor with req: " << req.ShortDebugString();
D
dongdaxiang 已提交
381
    return -1;
M
MRXLT 已提交
382
  } else {
M
MRXLT 已提交
383 384
    client_infer_end = timeline.TimeStampUS();
    postprocess_start = client_infer_end;
385

B
barrierye 已提交
386
    uint32_t model_num = res.outputs_size();
B
barrierye 已提交
387
    // predict_res_batch._models.resize(model_num);
B
barrierye 已提交
388 389 390
    for (uint32_t m_idx = 0; m_idx < model_num; ++m_idx) {
      VLOG(2) << "process model output index: " << m_idx;
      auto output = res.outputs(m_idx);
B
barrierye 已提交
391 392
      ModelRes model;
      model.set_engine_name(output.engine_name());
M
MRXLT 已提交
393
      for (auto &name : fetch_name) {
B
barrierye 已提交
394 395
        model._int64_map[name].resize(batch_size);
        model._float_map[name].resize(batch_size);
B
barrierye 已提交
396
      }
397 398
      VLOG(2) << "response batch size " << output.insts_size();
      VLOG(2) << "response var nmae " << output.insts(0).tensor_array_size();
B
barrierye 已提交
399
      for (int bi = 0; bi < batch_size; bi++) {
400
        int idx = 0;
B
barrierye 已提交
401 402 403 404
        for (auto &name : fetch_name) {
          int len = output.insts(bi).tensor_array(idx).data_size();
          if (_fetch_name_to_type[name] == 0) {
            int len = output.insts(bi).tensor_array(idx).int64_data_size();
B
barrierye 已提交
405 406 407 408 409
            VLOG(2) << "fetch tensor : " << name
                    << " type: int64 len : " << len;
            model._int64_map[name][bi].resize(len);
            VLOG(2) << "fetch name " << name << " index " << idx
                    << " first data "
B
barrierye 已提交
410 411
                    << output.insts(bi).tensor_array(idx).int64_data(0);
            for (int i = 0; i < len; ++i) {
B
barrierye 已提交
412
              model._int64_map[name][bi][i] =
B
barrierye 已提交
413 414 415 416 417 418
                  output.insts(bi).tensor_array(idx).int64_data(i);
            }
          } else if (_fetch_name_to_type[name] == 1) {
            int len = output.insts(bi).tensor_array(idx).float_data_size();
            VLOG(2) << "fetch tensor : " << name
                    << " type: float32 len : " << len;
B
barrierye 已提交
419 420 421
            model._float_map[name][bi].resize(len);
            VLOG(2) << "fetch name " << name << " index " << idx
                    << " first data "
B
barrierye 已提交
422 423
                    << output.insts(bi).tensor_array(idx).float_data(0);
            for (int i = 0; i < len; ++i) {
B
barrierye 已提交
424
              model._float_map[name][bi][i] =
B
barrierye 已提交
425 426
                  output.insts(bi).tensor_array(idx).float_data(i);
            }
M
MRXLT 已提交
427
          }
B
barrierye 已提交
428
          idx += 1;
M
MRXLT 已提交
429
        }
M
MRXLT 已提交
430
      }
B
barrierye 已提交
431
      predict_res_batch.add_model_res(std::move(model));
M
MRXLT 已提交
432
    }
433
    postprocess_end = timeline.TimeStampUS();
M
MRXLT 已提交
434 435
  }

M
MRXLT 已提交
436 437 438
  if (FLAGS_profile_client) {
    std::ostringstream oss;
    oss << "PROFILE\t"
M
MRXLT 已提交
439
        << "pid:" << pid << "\t"
M
MRXLT 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        << "prepro_0:" << preprocess_start << " "
        << "prepro_1:" << preprocess_end << " "
        << "client_infer_0:" << client_infer_start << " "
        << "client_infer_1:" << client_infer_end << " ";
    if (FLAGS_profile_server) {
      int op_num = res.profile_time_size() / 2;
      for (int i = 0; i < op_num; ++i) {
        oss << "op" << i << "_0:" << res.profile_time(i * 2) << " ";
        oss << "op" << i << "_1:" << res.profile_time(i * 2 + 1) << " ";
      }
    }

    oss << "postpro_0:" << postprocess_start << " ";
    oss << "postpro_1:" << postprocess_end;

    fprintf(stderr, "%s\n", oss.str().c_str());
  }
M
MRXLT 已提交
457
  return 0;
M
MRXLT 已提交
458 459
}

G
guru4elephant 已提交
460 461 462
}  // namespace general_model
}  // namespace paddle_serving
}  // namespace baidu