general_model.cpp 14.2 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 96
      _fetch_name_to_var_name[model_config.fetch_var(i).alias_name()] =
          model_config.fetch_var(i).name();
    }
M
MRXLT 已提交
97
  } catch (std::exception &e) {
98 99
    LOG(ERROR) << "Failed load general model config" << e.what();
    return -1;
G
guru4elephant 已提交
100
  }
101
  return 0;
G
guru4elephant 已提交
102 103
}

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

110 111 112 113 114
int PredictorClient::destroy_predictor() {
  _api.thrd_finalize();
  _api.destroy();
}

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

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

M
MRXLT 已提交
133 134 135 136 137 138 139
std::vector<std::vector<float>> 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) {
  std::vector<std::vector<float>> fetch_result;
G
guru4elephant 已提交
140 141 142
  if (fetch_name.size() == 0) {
    return fetch_result;
  }
143

G
guru4elephant 已提交
144 145 146
  Timer timeline;
  int64_t preprocess_start = timeline.TimeStampUS();

147
  // we save infer_us at fetch_result[fetch_name.size()]
M
MRXLT 已提交
148
  fetch_result.resize(fetch_name.size());
G
guru4elephant 已提交
149 150 151

  _api.thrd_clear();
  _predictor = _api.fetch_predictor("general_model");
G
guru4elephant 已提交
152

153 154 155
  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();
156
  VLOG(2) << "fetch name size: " << fetch_name.size();
G
guru4elephant 已提交
157

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

M
MRXLT 已提交
168
  for (auto &name : int_feed_name) {
G
guru4elephant 已提交
169 170
    tensor_vec.push_back(inst->add_tensor_array());
  }
171
  VLOG(2) << "prepare tensor vec done.";
G
guru4elephant 已提交
172 173

  int vec_idx = 0;
M
MRXLT 已提交
174
  for (auto &name : float_feed_name) {
G
guru4elephant 已提交
175
    int idx = _feed_name_to_idx[name];
M
MRXLT 已提交
176
    Tensor *tensor = tensor_vec[idx];
G
guru4elephant 已提交
177 178 179 180 181
    for (int j = 0; j < _shape[idx].size(); ++j) {
      tensor->add_shape(_shape[idx][j]);
    }
    tensor->set_elem_type(1);
    for (int j = 0; j < float_feed[vec_idx].size(); ++j) {
M
MRXLT 已提交
182 183 184
      tensor->add_data(const_cast<char *>(reinterpret_cast<const char *>(
                           &(float_feed[vec_idx][j]))),
                       sizeof(float));
G
guru4elephant 已提交
185 186 187 188
    }
    vec_idx++;
  }

189 190
  VLOG(2) << "feed float feed var done.";

G
guru4elephant 已提交
191
  vec_idx = 0;
M
MRXLT 已提交
192
  for (auto &name : int_feed_name) {
G
guru4elephant 已提交
193
    int idx = _feed_name_to_idx[name];
M
MRXLT 已提交
194
    Tensor *tensor = tensor_vec[idx];
G
guru4elephant 已提交
195 196 197 198 199
    for (int j = 0; j < _shape[idx].size(); ++j) {
      tensor->add_shape(_shape[idx][j]);
    }
    tensor->set_elem_type(0);
    for (int j = 0; j < int_feed[vec_idx].size(); ++j) {
M
MRXLT 已提交
200 201 202
      tensor->add_data(const_cast<char *>(reinterpret_cast<const char *>(
                           &(int_feed[vec_idx][j]))),
                       sizeof(int64_t));
G
guru4elephant 已提交
203 204 205 206
    }
    vec_idx++;
  }

G
guru4elephant 已提交
207
  int64_t preprocess_end = timeline.TimeStampUS();
208

G
guru4elephant 已提交
209
  int64_t client_infer_start = timeline.TimeStampUS();
G
guru4elephant 已提交
210 211
  Response res;

G
guru4elephant 已提交
212 213 214
  int64_t client_infer_end = 0;
  int64_t postprocess_start = 0;
  int64_t postprocess_end = 0;
215 216 217 218 219 220 221

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

G
guru4elephant 已提交
222 223 224 225 226
  res.Clear();
  if (_predictor->inference(&req, &res) != 0) {
    LOG(ERROR) << "failed call predictor with req: " << req.ShortDebugString();
    exit(-1);
  } else {
G
guru4elephant 已提交
227 228
    client_infer_end = timeline.TimeStampUS();
    postprocess_start = client_infer_end;
M
MRXLT 已提交
229
    for (auto &name : fetch_name) {
G
guru4elephant 已提交
230 231
      int idx = _fetch_name_to_idx[name];
      int len = res.insts(0).tensor_array(idx).data_size();
232 233
      VLOG(2) << "fetch name: " << name;
      VLOG(2) << "tensor data size: " << len;
G
guru4elephant 已提交
234 235
      fetch_result[idx].resize(len);
      for (int i = 0; i < len; ++i) {
M
MRXLT 已提交
236 237
        fetch_result[idx][i] =
            *(const float *)res.insts(0).tensor_array(idx).data(i).c_str();
G
guru4elephant 已提交
238 239
      }
    }
G
guru4elephant 已提交
240
    postprocess_end = timeline.TimeStampUS();
G
guru4elephant 已提交
241 242
  }

243 244 245 246 247 248 249
  if (FLAGS_profile_client) {
    std::ostringstream oss;
    oss << "PROFILE\t"
        << "prepro_0:" << preprocess_start << " "
        << "prepro_1:" << preprocess_end << " "
        << "client_infer_0:" << client_infer_start << " "
        << "client_infer_1:" << client_infer_end << " ";
M
MRXLT 已提交
250

251 252 253 254 255 256 257
    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 已提交
258

259 260 261 262
    oss << "postpro_0:" << postprocess_start << " ";
    oss << "postpro_1:" << postprocess_end;

    fprintf(stderr, "%s\n", oss.str().c_str());
G
guru4elephant 已提交
263 264 265 266 267
  }

  return fetch_result;
}

M
MRXLT 已提交
268
std::vector<std::vector<std::vector<float>>> PredictorClient::batch_predict(
M
MRXLT 已提交
269 270 271 272
    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 已提交
273 274
    const std::vector<std::string> &fetch_name) {
  int batch_size = std::max(float_feed_batch.size(), int_feed_batch.size());
M
MRXLT 已提交
275 276 277 278
  std::vector<std::vector<std::vector<float>>> fetch_result_batch;
  if (fetch_name.size() == 0) {
    return fetch_result_batch;
  }
M
MRXLT 已提交
279 280 281 282 283

  Timer timeline;
  int64_t preprocess_start = timeline.TimeStampUS();

  fetch_result_batch.resize(batch_size);
M
MRXLT 已提交
284 285 286 287 288 289 290
  int fetch_name_num = fetch_name.size();
  for (int bi = 0; bi < batch_size; bi++) {
    fetch_result_batch[bi].resize(fetch_name_num);
  }

  _api.thrd_clear();
  _predictor = _api.fetch_predictor("general_model");
291 292 293
  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 已提交
294
  Request req;
M
MRXLT 已提交
295
  for (auto &name : fetch_name) {
296 297
    req.add_fetch_var_names(name);
  }
M
MRXLT 已提交
298 299
  //
  for (int bi = 0; bi < batch_size; bi++) {
300
    VLOG(2) << "prepare batch " << bi;
M
MRXLT 已提交
301 302 303 304 305 306 307 308 309 310 311
    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());
    }
312

313 314
    VLOG(2) << "batch [" << bi << "] int_feed_name and float_feed_name"
            << "prepared";
M
MRXLT 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    int vec_idx = 0;
    for (auto &name : float_feed_name) {
      int idx = _feed_name_to_idx[name];
      Tensor *tensor = tensor_vec[idx];
      for (int j = 0; j < _shape[idx].size(); ++j) {
        tensor->add_shape(_shape[idx][j]);
      }
      tensor->set_elem_type(1);
      for (int j = 0; j < float_feed[vec_idx].size(); ++j) {
        tensor->add_data(const_cast<char *>(reinterpret_cast<const char *>(
                             &(float_feed[vec_idx][j]))),
                         sizeof(float));
      }
      vec_idx++;
    }

M
MRXLT 已提交
331 332
    VLOG(2) << "batch [" << bi << "] "
            << "float feed value prepared";
333

M
MRXLT 已提交
334 335 336 337 338 339 340 341
    vec_idx = 0;
    for (auto &name : int_feed_name) {
      int idx = _feed_name_to_idx[name];
      Tensor *tensor = tensor_vec[idx];
      for (int j = 0; j < _shape[idx].size(); ++j) {
        tensor->add_shape(_shape[idx][j]);
      }
      tensor->set_elem_type(0);
M
MRXLT 已提交
342 343
      VLOG(3) << "feed var name " << name << " index " << vec_idx
              << "first data " << int_feed[vec_idx][0];
M
MRXLT 已提交
344 345 346 347 348 349 350
      for (int j = 0; j < int_feed[vec_idx].size(); ++j) {
        tensor->add_data(const_cast<char *>(reinterpret_cast<const char *>(
                             &(int_feed[vec_idx][j]))),
                         sizeof(int64_t));
      }
      vec_idx++;
    }
351

M
MRXLT 已提交
352 353
    VLOG(2) << "batch [" << bi << "] "
            << "itn feed value prepared";
M
MRXLT 已提交
354 355
  }

M
MRXLT 已提交
356 357 358 359
  int64_t preprocess_end = timeline.TimeStampUS();

  int64_t client_infer_start = timeline.TimeStampUS();

M
MRXLT 已提交
360 361
  Response res;

M
MRXLT 已提交
362 363 364 365 366 367 368 369 370 371
  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 已提交
372 373 374 375 376
  res.Clear();
  if (_predictor->inference(&req, &res) != 0) {
    LOG(ERROR) << "failed call predictor with req: " << req.ShortDebugString();
    exit(-1);
  } else {
M
MRXLT 已提交
377 378 379
    client_infer_end = timeline.TimeStampUS();
    postprocess_start = client_infer_end;

M
MRXLT 已提交
380 381 382
    for (int bi = 0; bi < batch_size; bi++) {
      for (auto &name : fetch_name) {
        int idx = _fetch_name_to_idx[name];
M
MRXLT 已提交
383
        int len = res.insts(bi).tensor_array(idx).data_size();
384 385
        VLOG(2) << "fetch name: " << name;
        VLOG(2) << "tensor data size: " << len;
M
MRXLT 已提交
386
        fetch_result_batch[bi][idx].resize(len);
387
        VLOG(2)
M
MRXLT 已提交
388 389
            << "fetch name " << name << " index " << idx << " first data "
            << *(const float *)res.insts(bi).tensor_array(idx).data(0).c_str();
M
MRXLT 已提交
390 391
        for (int i = 0; i < len; ++i) {
          fetch_result_batch[bi][idx][i] =
M
MRXLT 已提交
392
              *(const float *)res.insts(bi).tensor_array(idx).data(i).c_str();
M
MRXLT 已提交
393 394 395
        }
      }
    }
M
MRXLT 已提交
396
    postprocess_end = timeline.TimeStampUS();
M
MRXLT 已提交
397 398
  }

M
MRXLT 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  if (FLAGS_profile_client) {
    std::ostringstream oss;
    oss << "PROFILE\t"
        << "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 已提交
420 421 422 423 424 425 426 427 428 429
  return fetch_result_batch;
}

std::vector<std::vector<float>> PredictorClient::predict_with_profile(
    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) {
  std::vector<std::vector<float>> res;
G
guru4elephant 已提交
430 431 432 433 434 435
  return res;
}

}  // namespace general_model
}  // namespace paddle_serving
}  // namespace baidu