infer.h 31.7 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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.

#pragma once
W
wangguibao 已提交
16
#include <sys/stat.h>
W
wangguibao 已提交
17
#include <sys/types.h>
W
wangguibao 已提交
18
#include <unistd.h>
Z
zhangjun 已提交
19
#include <pthread.h>
W
wangguibao 已提交
20
#include <string>
M
MRXLT 已提交
21
#include <utility>
W
wangguibao 已提交
22
#include <vector>
G
guru4elephant 已提交
23 24 25
#include "core/predictor/common/inner_common.h"
#include "core/predictor/framework/factory.h"
#include "core/predictor/framework/infer_data.h"
W
wangjiawei04 已提交
26
#include "paddle_inference_api.h"  // NOLINT
W
wangguibao 已提交
27 28 29 30
namespace baidu {
namespace paddle_serving {
namespace predictor {

W
wangguibao 已提交
31 32
using configure::ModelToolkitConf;

33 34 35 36 37
class InferEngineCreationParams {
 public:
  InferEngineCreationParams() {
    _path = "";
    _enable_memory_optimization = false;
M
MRXLT 已提交
38
    _enable_ir_optimization = false;
39 40
    _static_optimization = false;
    _force_update_static_cache = false;
M
MRXLT 已提交
41
    _use_trt = false;
Z
zhangjun 已提交
42 43 44
    _use_lite = false;
    _use_xpu = false;
  }
45 46 47 48 49 50 51

  void set_path(const std::string& path) { _path = path; }

  void set_enable_memory_optimization(bool enable_memory_optimization) {
    _enable_memory_optimization = enable_memory_optimization;
  }

M
MRXLT 已提交
52 53 54 55
  void set_enable_ir_optimization(bool enable_ir_optimization) {
    _enable_ir_optimization = enable_ir_optimization;
  }

M
MRXLT 已提交
56 57
  void set_use_trt(bool use_trt) { _use_trt = use_trt; }

Z
zhangjun 已提交
58 59 60 61
  void set_use_lite(bool use_lite) { _use_lite = use_lite; }

  void set_use_xpu(bool use_xpu) { _use_xpu = use_xpu; }

62 63 64 65
  bool enable_memory_optimization() const {
    return _enable_memory_optimization;
  }

M
MRXLT 已提交
66 67
  bool enable_ir_optimization() const { return _enable_ir_optimization; }

M
MRXLT 已提交
68 69
  bool use_trt() const { return _use_trt; }

Z
zhangjun 已提交
70 71 72 73
  bool use_lite() const { return _use_lite; }

  bool use_xpu() const { return _use_xpu; }

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  void set_static_optimization(bool static_optimization = false) {
    _static_optimization = static_optimization;
  }

  void set_force_update_static_cache(bool force_update_static_cache = false) {
    _force_update_static_cache = force_update_static_cache;
  }

  bool static_optimization() const { return _static_optimization; }

  bool force_update_static_cache() const { return _force_update_static_cache; }

  std::string get_path() const { return _path; }

  void dump() const {
    LOG(INFO) << "InferEngineCreationParams: "
              << "model_path = " << _path << ", "
              << "enable_memory_optimization = " << _enable_memory_optimization
              << ", "
Z
zhangjun 已提交
93 94 95
              << "enable_tensorrt = " << _use_trt << ", "
              << "enable_lite = " << _use_lite << ", "
              << "enable_xpu = " << _use_xpu << ", "
M
MRXLT 已提交
96
              << "enable_ir_optimization = " << _enable_ir_optimization << ", "
97 98 99 100 101 102 103
              << "static_optimization = " << _static_optimization << ", "
              << "force_update_static_cache = " << _force_update_static_cache;
  }

 private:
  std::string _path;
  bool _enable_memory_optimization;
M
MRXLT 已提交
104
  bool _enable_ir_optimization;
105 106
  bool _static_optimization;
  bool _force_update_static_cache;
M
MRXLT 已提交
107
  bool _use_trt;
Z
zhangjun 已提交
108 109
  bool _use_lite;
  bool _use_xpu;
110 111
};

Z
zhangjun 已提交
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
class AutoLock {
 public:
  explicit AutoLock(pthread_mutex_t& mutex) : _mut(mutex) {
    pthread_mutex_lock(&mutex);
  }

  ~AutoLock() { pthread_mutex_unlock(&_mut); }

 private:
  pthread_mutex_t& _mut;
};

class GlobalPaddleCreateMutex {
 public:
  pthread_mutex_t& mutex() { return _mut; }

  static pthread_mutex_t& instance() {
    static GlobalPaddleCreateMutex gmutex;
    return gmutex.mutex();
  }

 private:
  GlobalPaddleCreateMutex() { pthread_mutex_init(&_mut, NULL); }

  pthread_mutex_t _mut;
};

W
wangguibao 已提交
139
class InferEngine {
W
wangguibao 已提交
140 141 142 143 144 145 146 147 148 149
 public:
  virtual ~InferEngine() {}

  virtual int proc_initialize(const configure::EngineDesc& conf, bool version) {
    return proc_initialize_impl(conf, version);
  }
  virtual int proc_finalize() { return proc_finalize_impl(); }
  virtual int thrd_initialize() { return thrd_initialize_impl(); }
  virtual int thrd_clear() { return thrd_clear_impl(); }
  virtual int thrd_finalize() { return thrd_finalize_impl(); }
W
wangjiawei04 已提交
150
  virtual int infer() { return infer_impl(); }
W
wangguibao 已提交
151 152 153 154 155 156 157 158 159 160 161 162

  virtual int reload() = 0;

  virtual uint64_t version() const = 0;

  // begin: framework inner call
  virtual int proc_initialize_impl(const configure::EngineDesc& conf,
                                   bool version) = 0;
  virtual int thrd_initialize_impl() = 0;
  virtual int thrd_finalize_impl() = 0;
  virtual int thrd_clear_impl() = 0;
  virtual int proc_finalize_impl() = 0;
W
wangjiawei04 已提交
163 164
  virtual std::vector<std::string> GetInputNames() = 0;
  virtual std::vector<std::string> GetOutputNames() = 0;
W
wangjiawei04 已提交
165 166 167 168
  virtual std::unique_ptr<paddle_infer::Tensor> GetInputHandle(
      const std::string& name) = 0;
  virtual std::unique_ptr<paddle_infer::Tensor> GetOutputHandle(
      const std::string& name) = 0;
W
wangjiawei04 已提交
169
  virtual int infer_impl() = 0;
W
wangguibao 已提交
170 171 172 173 174 175
  // end: framework inner call
};

class ReloadableInferEngine : public InferEngine {
 public:
  virtual ~ReloadableInferEngine() {}
W
wangguibao 已提交
176

W
wangguibao 已提交
177 178 179 180 181
  union last_check_status {
    time_t last_timestamp;
    uint64_t last_md5sum;
    uint64_t last_revision;
  };
W
wangguibao 已提交
182

183
  virtual int load(const InferEngineCreationParams& params) = 0;
W
wangguibao 已提交
184 185 186 187 188 189 190 191

  int proc_initialize_impl(const configure::EngineDesc& conf, bool version) {
    _reload_tag_file = conf.reloadable_meta();
    _reload_mode_tag = conf.reloadable_type();
    _model_data_path = conf.model_data_path();
    _infer_thread_num = conf.runtime_thread_num();
    _infer_batch_size = conf.batch_infer_size();
    _infer_batch_align = conf.enable_batch_align();
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

    bool enable_memory_optimization = false;
    if (conf.has_enable_memory_optimization()) {
      enable_memory_optimization = conf.enable_memory_optimization();
    }

    bool static_optimization = false;
    if (conf.has_static_optimization()) {
      static_optimization = conf.static_optimization();
    }

    bool force_update_static_cache = false;
    if (conf.has_force_update_static_cache()) {
      force_update_static_cache = conf.force_update_static_cache();
    }

M
MRXLT 已提交
208 209 210 211 212
    if (conf.has_enable_ir_optimization()) {
      _infer_engine_params.set_enable_ir_optimization(
          conf.enable_ir_optimization());
    }

213 214 215 216 217 218 219 220
    _infer_engine_params.set_path(_model_data_path);
    if (enable_memory_optimization) {
      _infer_engine_params.set_enable_memory_optimization(true);
      _infer_engine_params.set_static_optimization(static_optimization);
      _infer_engine_params.set_force_update_static_cache(
          force_update_static_cache);
    }

M
MRXLT 已提交
221 222 223 224
    if (conf.has_use_trt()) {
      _infer_engine_params.set_use_trt(conf.use_trt());
    }

Z
zhangjun 已提交
225 226 227 228
    if (conf.has_use_lite()) {
      _infer_engine_params.set_use_lite(conf.use_lite());
    }

Z
zhangjun 已提交
229
    if (conf.has_use_xpu()) {
Z
zhangjun 已提交
230 231 232
      _infer_engine_params.set_use_xpu(conf.use_xpu());
    }

233
    if (!check_need_reload() || load(_infer_engine_params) != 0) {
W
wangguibao 已提交
234 235
      LOG(ERROR) << "Failed load model_data_path" << _model_data_path;
      return -1;
W
wangguibao 已提交
236
    }
W
wangguibao 已提交
237 238 239 240

    if (parse_version_info(conf, version) != 0) {
      LOG(ERROR) << "Failed parse version info";
      return -1;
W
wangguibao 已提交
241
    }
W
wangguibao 已提交
242 243 244 245 246 247 248 249 250

    LOG(WARNING) << "Succ load model_data_path" << _model_data_path;
    return 0;
  }

  int proc_initialize(const configure::EngineDesc& conf, bool version) {
    if (proc_initialize_impl(conf, version) != 0) {
      LOG(ERROR) << "Failed proc initialize impl";
      return -1;
W
wangguibao 已提交
251
    }
W
wangguibao 已提交
252 253
    return 0;
  }
W
wangguibao 已提交
254

W
wangjiawei04 已提交
255
  int infer() { return infer_impl(); }
W
wangguibao 已提交
256

W
wangguibao 已提交
257 258 259 260
  int thrd_initialize() {
    if (_infer_thread_num > 0) {
      return 0;
    }
W
wangguibao 已提交
261

W
wangguibao 已提交
262 263
    return thrd_initialize_impl();
  }
W
wangguibao 已提交
264

W
wangguibao 已提交
265 266 267 268
  int thrd_clear() {
    if (_infer_thread_num > 0) {
      return 0;
    }
W
wangguibao 已提交
269

W
wangguibao 已提交
270 271
    return thrd_clear_impl();
  }
W
wangguibao 已提交
272

W
wangguibao 已提交
273 274 275 276 277
  int proc_finalize() {
    if (proc_finalize_impl() != 0) {
      LOG(ERROR) << "Failed proc finalize impl";
      return -1;
    }
W
wangguibao 已提交
278

W
wangguibao 已提交
279 280
    return 0;
  }
W
wangguibao 已提交
281

W
wangguibao 已提交
282 283 284
  int reload() {
    if (check_need_reload()) {
      LOG(WARNING) << "begin reload model[" << _model_data_path << "].";
285
      return load(_infer_engine_params);
W
wangguibao 已提交
286 287 288 289 290 291 292
    }
    return 0;
  }

  uint64_t version() const { return _version; }

  uint32_t thread_num() const { return _infer_thread_num; }
W
wangguibao 已提交
293

W
wangguibao 已提交
294 295 296 297 298
 private:
  int parse_version_info(const configure::EngineDesc& config, bool version) {
    _version = uint64_t(-1);
    return 0;
  }
W
wangguibao 已提交
299

W
wangguibao 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  bool check_need_reload() {
    if (_reload_mode_tag == "timestamp_ne") {
      return check_timestamp_ne();
    } else if (_reload_mode_tag == "timestamp_gt") {
      return check_timestamp_gt();
    } else if (_reload_mode_tag == "md5sum") {
      return check_md5sum();
    } else if (_reload_mode_tag == "revision") {
      return check_revision();
    } else if (_reload_mode_tag == "none") {
      return false;
    } else {
      LOG(ERROR) << "Not support check type: " << _reload_mode_tag;
      return false;
    }
  }

  bool check_timestamp_ne() {
    struct stat st;
    if (stat(_reload_tag_file.c_str(), &st) != 0) {
      LOG(ERROR) << "Failed stat config file:" << _reload_tag_file;
      return false;
    }
W
wangguibao 已提交
323

W
wangguibao 已提交
324 325 326
    if ((st.st_mode & S_IFREG) && st.st_mtime != _last_status.last_timestamp) {
      _last_status.last_timestamp = st.st_mtime;
      return true;
W
wangguibao 已提交
327 328
    }

W
wangguibao 已提交
329 330
    return false;
  }
W
wangguibao 已提交
331

W
wangguibao 已提交
332 333 334 335 336 337
  bool check_timestamp_gt() {
    struct stat st;
    if (stat(_reload_tag_file.c_str(), &st) != 0) {
      LOG(ERROR) << "Failed stat config file:" << _reload_tag_file;
      return false;
    }
W
wangguibao 已提交
338

W
wangguibao 已提交
339 340 341
    if ((st.st_mode & S_IFREG) && st.st_mtime > _last_status.last_timestamp) {
      _last_status.last_timestamp = st.st_mtime;
      return true;
W
wangguibao 已提交
342 343
    }

W
wangguibao 已提交
344 345 346 347 348 349 350 351 352
    return false;
  }

  bool check_md5sum() { return false; }

  bool check_revision() { return false; }

 protected:
  std::string _model_data_path;
353
  InferEngineCreationParams _infer_engine_params;
W
wangguibao 已提交
354 355 356 357 358 359 360 361 362 363

 private:
  std::string _reload_tag_file;
  std::string _reload_mode_tag;
  last_check_status _last_status;
  uint32_t _infer_thread_num;
  uint32_t _infer_batch_size;
  bool _infer_batch_align;
  uint64_t _version;
};
W
wangguibao 已提交
364

W
wangguibao 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
template <typename EngineCore>
struct ModelData {
  ModelData() : current_idx(1) {
    cores[0] = NULL;
    cores[1] = NULL;
  }

  ~ModelData() {
    delete cores[0];
    delete cores[1];
  }

  EngineCore* cores[2];
  uint32_t current_idx;
};

template <typename EngineCore>
class DBReloadableInferEngine : public ReloadableInferEngine {
 public:
  virtual ~DBReloadableInferEngine() {}

  int proc_initialize(const configure::EngineDesc& conf, bool version) {
    THREAD_KEY_CREATE(&_skey, NULL);
    THREAD_MUTEX_INIT(&_mutex, NULL);
    return ReloadableInferEngine::proc_initialize(conf, version);
  }

392
  virtual int load(const InferEngineCreationParams& params) {
W
wangguibao 已提交
393 394
    if (_reload_vec.empty()) {
      return 0;
W
wangguibao 已提交
395 396
    }

W
wangguibao 已提交
397
    for (uint32_t ti = 0; ti < _reload_vec.size(); ++ti) {
398
      if (load_data(_reload_vec[ti], params) != 0) {
W
wangguibao 已提交
399 400 401 402 403
        LOG(ERROR) << "Failed reload engine model: " << ti;
        return -1;
      }
    }

404
    LOG(WARNING) << "Succ load engine, path: " << params.get_path();
W
wangguibao 已提交
405

W
wangguibao 已提交
406 407
    return 0;
  }
W
wangguibao 已提交
408

409 410
  int load_data(ModelData<EngineCore>* md,
                const InferEngineCreationParams& params) {
W
wangguibao 已提交
411 412 413
    uint32_t next_idx = (md->current_idx + 1) % 2;
    if (md->cores[next_idx]) {
      delete md->cores[next_idx];
W
wangguibao 已提交
414 415
    }

W
wangguibao 已提交
416
    md->cores[next_idx] = new (std::nothrow) EngineCore;
417 418 419 420

    params.dump();
    if (!md->cores[next_idx] || md->cores[next_idx]->create(params) != 0) {
      LOG(ERROR) << "Failed create model, path: " << params.get_path();
W
wangguibao 已提交
421
      return -1;
W
wangguibao 已提交
422
    }
W
wangguibao 已提交
423 424 425
    md->current_idx = next_idx;
    return 0;
  }
W
wangguibao 已提交
426

W
wangguibao 已提交
427 428
  virtual int thrd_initialize_impl() {
    // memory pool to be inited in non-serving-threads
W
wangguibao 已提交
429

W
wangguibao 已提交
430
    ModelData<EngineCore>* md = new (std::nothrow) ModelData<EngineCore>;
431 432 433
    if (!md || load_data(md, _infer_engine_params) != 0) {
      LOG(ERROR) << "Failed create thread data from "
                 << _infer_engine_params.get_path();
W
wangguibao 已提交
434
      return -1;
W
wangguibao 已提交
435 436
    }

W
wangguibao 已提交
437 438 439 440 441 442 443 444 445 446 447
    THREAD_SETSPECIFIC(_skey, md);
    _reload_vec.push_back(md);
    return 0;
  }

  int thrd_clear_impl() {
    // for non-serving-threads
    return 0;
  }

  int thrd_finalize_impl() { return 0; }
W
wangguibao 已提交
448

W
wangguibao 已提交
449 450 451 452 453
  int proc_finalize_impl() {
    THREAD_KEY_DELETE(_skey);
    THREAD_MUTEX_DESTROY(&_mutex);
    return 0;
  }
W
wangguibao 已提交
454

W
wangguibao 已提交
455 456 457 458 459 460
  EngineCore* get_core() {
    ModelData<EngineCore>* md =
        (ModelData<EngineCore>*)THREAD_GETSPECIFIC(_skey);
    if (!md) {
      LOG(ERROR) << "Failed get thread specific data";
      return NULL;
W
wangguibao 已提交
461
    }
W
wangguibao 已提交
462 463
    return md->cores[md->current_idx];
  }
W
wangguibao 已提交
464

W
wangguibao 已提交
465 466 467 468
 protected:
  THREAD_KEY_T _skey;
  THREAD_MUTEX_T _mutex;
  std::vector<ModelData<EngineCore>*> _reload_vec;
W
wangguibao 已提交
469

W
wangguibao 已提交
470 471
 private:
};
W
wangguibao 已提交
472

W
wangguibao 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
// 多个EngineCore共用同一份模型数据
template <typename EngineCore>
class CloneDBReloadableInferEngine
    : public DBReloadableInferEngine<EngineCore> {
 public:
  virtual ~CloneDBReloadableInferEngine() {}

  virtual int proc_initialize(const configure::EngineDesc& conf, bool version) {
    _pd = new (std::nothrow) ModelData<EngineCore>;
    if (!_pd) {
      LOG(ERROR) << "Failed to allocate for ProcData";
      return -1;
    }
    return DBReloadableInferEngine<EngineCore>::proc_initialize(conf, version);
  }

489
  virtual int load(const InferEngineCreationParams& params) {
W
wangguibao 已提交
490 491
    // 加载进程级模型数据
    if (!_pd ||
492 493
        DBReloadableInferEngine<EngineCore>::load_data(_pd, params) != 0) {
      LOG(ERROR) << "Failed to create common model from [" << params.get_path()
W
wangguibao 已提交
494 495 496 497
                 << "].";
      return -1;
    }
    LOG(WARNING) << "Succ load common model[" << _pd->cores[_pd->current_idx]
498
                 << "], path[" << params.get_path() << "].";
W
wangguibao 已提交
499 500 501 502 503 504 505 506 507 508 509 510 511

    if (DBReloadableInferEngine<EngineCore>::_reload_vec.empty()) {
      return 0;
    }

    for (uint32_t ti = 0;
         ti < DBReloadableInferEngine<EngineCore>::_reload_vec.size();
         ++ti) {
      if (load_data(DBReloadableInferEngine<EngineCore>::_reload_vec[ti],
                    _pd->cores[_pd->current_idx]) != 0) {
        LOG(ERROR) << "Failed reload engine model: " << ti;
        return -1;
      }
W
wangguibao 已提交
512 513
    }

514
    LOG(WARNING) << "Succ load clone model, path[" << params.get_path() << "]";
W
wangguibao 已提交
515

W
wangguibao 已提交
516 517
    return 0;
  }
W
wangguibao 已提交
518

W
wangguibao 已提交
519 520 521 522 523
  // 加载线程级对象,多个线程级对象共用pd_core的模型数据
  int load_data(ModelData<EngineCore>* td, EngineCore* pd_core) {
    uint32_t next_idx = (td->current_idx + 1) % 2;
    if (td->cores[next_idx]) {
      delete td->cores[next_idx];
W
wangguibao 已提交
524 525
    }

W
wangguibao 已提交
526 527 528 529 530 531
    td->cores[next_idx] = new (std::nothrow) EngineCore;
    if (!td->cores[next_idx] ||
        td->cores[next_idx]->clone(pd_core->get()) != 0) {
      LOG(ERROR) << "Failed clone model from pd_core[ " << pd_core << "], idx["
                 << next_idx << "]";
      return -1;
W
wangguibao 已提交
532
    }
W
wangguibao 已提交
533 534 535 536 537 538
    td->current_idx = next_idx;
    LOG(WARNING) << "td_core[" << td->cores[td->current_idx]
                 << "] clone model from pd_core[" << pd_core
                 << "] succ, cur_idx[" << td->current_idx << "].";
    return 0;
  }
W
wangguibao 已提交
539

W
wangguibao 已提交
540 541 542 543 544 545 546 547 548 549 550 551
  virtual int thrd_initialize_impl() {
    ModelData<EngineCore>* md = new (std::nothrow) ModelData<EngineCore>;
    if (!md || load_data(md, _pd->cores[_pd->current_idx]) != 0) {
      LOG(ERROR) << "Failed clone thread data, origin_core["
                 << _pd->cores[_pd->current_idx] << "].";
      return -1;
    }

    THREAD_SETSPECIFIC(DBReloadableInferEngine<EngineCore>::_skey, md);
    DBReloadableInferEngine<EngineCore>::_reload_vec.push_back(md);
    return 0;
  }
W
wangguibao 已提交
552

W
wangguibao 已提交
553 554 555
 protected:
  ModelData<EngineCore>*
      _pd;  // 进程级EngineCore,多个线程级EngineCore共用该对象的模型数据
W
wangguibao 已提交
556 557
};

W
wangguibao 已提交
558
template <typename FluidFamilyCore>
M
bug fix  
MRXLT 已提交
559
#ifdef WITH_TRT
M
MRXLT 已提交
560
class FluidInferEngine : public DBReloadableInferEngine<FluidFamilyCore> {
M
bug fix  
MRXLT 已提交
561 562 563 564
#else
class FluidInferEngine : public CloneDBReloadableInferEngine<FluidFamilyCore> {
#endif
 public:  // NOLINT
W
wangguibao 已提交
565 566
  FluidInferEngine() {}
  ~FluidInferEngine() {}
W
wangjiawei04 已提交
567
  std::vector<std::string> GetInputNames() {
W
wangjiawei04 已提交
568 569
    FluidFamilyCore* core =
        DBReloadableInferEngine<FluidFamilyCore>::get_core();
W
wangjiawei04 已提交
570 571 572 573 574
    if (!core || !core->get()) {
      LOG(ERROR) << "Failed get fluid core in GetInputHandle()";
    }
    return core->GetInputNames();
  }
W
wangguibao 已提交
575

W
wangjiawei04 已提交
576
  std::vector<std::string> GetOutputNames() {
W
wangjiawei04 已提交
577 578
    FluidFamilyCore* core =
        DBReloadableInferEngine<FluidFamilyCore>::get_core();
W
wangjiawei04 已提交
579 580 581 582 583 584
    if (!core || !core->get()) {
      LOG(ERROR) << "Failed get fluid core in GetInputHandle()";
    }
    return core->GetOutputNames();
  }

W
wangjiawei04 已提交
585 586 587 588
  std::unique_ptr<paddle_infer::Tensor> GetInputHandle(
      const std::string& name) {
    FluidFamilyCore* core =
        DBReloadableInferEngine<FluidFamilyCore>::get_core();
W
wangjiawei04 已提交
589 590 591 592 593 594
    if (!core || !core->get()) {
      LOG(ERROR) << "Failed get fluid core in GetInputHandle()";
    }
    return core->GetInputHandle(name);
  }

W
wangjiawei04 已提交
595 596 597 598
  std::unique_ptr<paddle_infer::Tensor> GetOutputHandle(
      const std::string& name) {
    FluidFamilyCore* core =
        DBReloadableInferEngine<FluidFamilyCore>::get_core();
W
wangjiawei04 已提交
599 600 601 602 603
    if (!core || !core->get()) {
      LOG(ERROR) << "Failed get fluid core in GetOutputHandle()";
    }
    return core->GetOutputHandle(name);
  }
W
wangguibao 已提交
604

W
wangjiawei04 已提交
605
  int infer_impl() {
W
wangguibao 已提交
606 607 608 609 610
    FluidFamilyCore* core =
        DBReloadableInferEngine<FluidFamilyCore>::get_core();
    if (!core || !core->get()) {
      LOG(ERROR) << "Failed get fluid core in infer_impl()";
      return -1;
W
wangguibao 已提交
611 612
    }

W
wangjiawei04 已提交
613
    if (!core->Run()) {
W
wangguibao 已提交
614 615 616 617 618
      LOG(ERROR) << "Failed run fluid family core";
      return -1;
    }
    return 0;
  }
W
wangguibao 已提交
619 620
};

W
wangguibao 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
typedef FactoryPool<InferEngine> StaticInferFactory;

class VersionedInferEngine : public InferEngine {
 public:
  VersionedInferEngine() { _versions.clear(); }
  ~VersionedInferEngine() {}

  int proc_initialize(const configure::EngineDesc& conf) {
    if (proc_initialize(conf, false) != 0) {
      LOG(ERROR) << "Failed proc intialize engine: " << conf.name().c_str();
      return -1;
    }

    LOG(WARNING) << "Succ proc initialize engine: " << conf.name().c_str();
    return 0;
  }

  int proc_initialize(const configure::EngineDesc& conf, bool version) {
    std::string engine_type = conf.type();
    InferEngine* engine =
        StaticInferFactory::instance().generate_object(engine_type);
    if (!engine) {
      LOG(ERROR) << "Failed generate engine with type:" << engine_type;
      return -1;
    }
646
#ifndef BCLOUD
M
MRXLT 已提交
647
    VLOG(2) << "FLAGS_logtostderr " << FLAGS_logtostderr;
M
MRXLT 已提交
648
    int tmp = FLAGS_logtostderr;
W
wangguibao 已提交
649 650 651 652
    if (engine->proc_initialize(conf, version) != 0) {
      LOG(ERROR) << "Failed initialize engine, type:" << engine_type;
      return -1;
    }
M
bug fix  
MRXLT 已提交
653
    VLOG(2) << "FLAGS_logtostderr " << FLAGS_logtostderr;
M
MRXLT 已提交
654
    FLAGS_logtostderr = tmp;
655 656 657 658 659 660
#else
    if (engine->proc_initialize(conf, version) != 0) {
      LOG(ERROR) << "Failed initialize engine, type:" << engine_type;
      return -1;
    }
#endif
W
wangguibao 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    auto r = _versions.insert(std::make_pair(engine->version(), engine));
    if (!r.second) {
      LOG(ERROR) << "Failed insert item: " << engine->version()
                 << ", type: " << engine_type;
      return -1;
    }
    LOG(WARNING) << "Succ proc initialize version engine: "
                 << engine->version();
    return 0;
  }

  int proc_finalize() {
    for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
      if (iter->second->proc_finalize() != 0) {
        LOG(ERROR) << "Failed proc finalize version engine: " << iter->first;
      }
      LOG(WARNING) << "Succ proc finalize version engine: " << iter->first;
    }
    return 0;
  }

  int thrd_initialize() {
    for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
      if (iter->second->thrd_initialize() != 0) {
        LOG(ERROR) << "Failed thrd initialize version engine: " << iter->first;
W
wangguibao 已提交
686
        return -1;
W
wangguibao 已提交
687 688
      }
      LOG(WARNING) << "Succ thrd initialize version engine: " << iter->first;
W
wangguibao 已提交
689
    }
W
wangguibao 已提交
690 691
    return 0;
  }
W
wangguibao 已提交
692

W
wangguibao 已提交
693 694 695 696
  int thrd_clear() {
    for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
      if (iter->second->thrd_clear() != 0) {
        LOG(ERROR) << "Failed thrd clear version engine: " << iter->first;
W
wangguibao 已提交
697
        return -1;
W
wangguibao 已提交
698
      }
W
wangguibao 已提交
699
    }
W
wangguibao 已提交
700 701
    return 0;
  }
W
wangguibao 已提交
702

W
wangguibao 已提交
703 704 705 706 707 708 709
  int thrd_finalize() {
    for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
      if (iter->second->thrd_finalize() != 0) {
        LOG(ERROR) << "Failed thrd finalize version engine: " << iter->first;
        return -1;
      }
      LOG(WARNING) << "Succ thrd finalize version engine: " << iter->first;
W
wangguibao 已提交
710
    }
W
wangguibao 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
    return 0;
  }

  int reload() {
    for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
      if (iter->second->reload() != 0) {
        LOG(ERROR) << "Failed reload version engine: " << iter->first;
        return -1;
      }
      LOG(WARNING) << "Succ reload version engine: " << iter->first;
    }
    return 0;
  }

  uint64_t version() const {
    InferEngine* engine = default_engine();
    if (engine) {
      return engine->version();
    } else {
      return uint64_t(-1);
    }
  }

  // inference interface
  InferEngine* default_engine() const {
    if (_versions.size() != 1) {
      LOG(ERROR) << "Ambiguous default engine version:" << _versions.size();
      return NULL;
    }

    return _versions.begin()->second;
  }

W
wangjiawei04 已提交
744
  int infer() {
W
wangguibao 已提交
745 746 747 748 749
    InferEngine* engine = default_engine();
    if (!engine) {
      LOG(WARNING) << "fail to get default engine";
      return -1;
    }
W
wangjiawei04 已提交
750 751 752
    return engine->infer();
  }

W
wangjiawei04 已提交
753 754 755 756 757 758 759 760 761 762 763 764 765 766
  std::vector<std::string> GetInputNames() {
    InferEngine* engine = default_engine();
    if (!engine) {
      LOG(WARNING) << "fail to get default engine";
    }
    return engine->GetInputNames();
  }
  std::vector<std::string> GetOutputNames() {
    InferEngine* engine = default_engine();
    if (!engine) {
      LOG(WARNING) << "fail to get default engine";
    }
    return engine->GetOutputNames();
  }
W
wangjiawei04 已提交
767 768
  std::unique_ptr<paddle_infer::Tensor> GetInputHandle(
      const std::string& name) {
W
wangjiawei04 已提交
769 770 771 772 773 774 775
    InferEngine* engine = default_engine();
    if (!engine) {
      LOG(WARNING) << "fail to get default engine";
    }
    return engine->GetInputHandle(name);
  }

W
wangjiawei04 已提交
776 777
  std::unique_ptr<paddle_infer::Tensor> GetOutputHandle(
      const std::string& name) {
W
wangjiawei04 已提交
778 779 780 781 782
    InferEngine* engine = default_engine();
    if (!engine) {
      LOG(WARNING) << "fail to get default engine";
    }
    return engine->GetOutputHandle(name);
W
wangguibao 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
  }

  template <typename T>
  T* get_core() {
    InferEngine* engine = default_engine();
    if (!engine) {
      LOG(WARNING) << "fail to get core";
      return NULL;
    }
    auto db_engine = dynamic_cast<DBReloadableInferEngine<T>*>(engine);
    if (db_engine) {
      return db_engine->get_core();
    }
    LOG(WARNING) << "fail to get core";
    return NULL;
  }

  // versioned inference interface
W
wangjiawei04 已提交
801
  int infer(uint64_t version) {
W
wangguibao 已提交
802 803 804 805 806 807
    auto iter = _versions.find(version);
    if (iter == _versions.end()) {
      LOG(ERROR) << "Not found version engine: " << version;
      return -1;
    }

W
wangjiawei04 已提交
808 809
    return iter->second->infer();
  }
W
wangjiawei04 已提交
810 811 812 813
  std::vector<std::string> GetInputNames(uint64_t version) {
    auto iter = _versions.find(version);
    if (iter == _versions.end()) {
      LOG(ERROR) << "Not found version engine: " << version;
W
wangjiawei04 已提交
814
    }
W
wangjiawei04 已提交
815 816 817 818 819 820 821 822 823 824
    return iter->second->GetInputNames();
  }

  std::vector<std::string> GetOutputNames(uint64_t version) {
    auto iter = _versions.find(version);
    if (iter == _versions.end()) {
      LOG(ERROR) << "Not found version engine: " << version;
    }
    return iter->second->GetOutputNames();
  }
W
wangjiawei04 已提交
825

W
wangjiawei04 已提交
826 827
  std::unique_ptr<paddle_infer::Tensor> GetInputHandle(
      uint64_t version, const std::string& name) {
W
wangjiawei04 已提交
828 829 830 831 832 833 834
    auto iter = _versions.find(version);
    if (iter == _versions.end()) {
      LOG(ERROR) << "Not found version engine: " << version;
    }
    return iter->second->GetInputHandle(name);
  }

W
wangjiawei04 已提交
835 836
  std::unique_ptr<paddle_infer::Tensor> GetOutputHandle(
      uint64_t version, const std::string& name) {
W
wangjiawei04 已提交
837 838 839 840 841
    auto iter = _versions.find(version);
    if (iter == _versions.end()) {
      LOG(ERROR) << "Not found version engine: " << version;
    }
    return iter->second->GetOutputHandle(name);
W
wangguibao 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  }

  template <typename T>
  T* get_core(uint64_t version) {
    auto iter = _versions.find(version);
    if (iter == _versions.end()) {
      LOG(ERROR) << "Not found version engine: " << version;
      return NULL;
    }

    auto db_engine = dynamic_cast<DBReloadableInferEngine<T>*>(iter->second);
    if (db_engine) {
      return db_engine->get_core();
    }
    LOG(WARNING) << "fail to get core for " << version;
    return NULL;
  }

  // --
  int proc_initialize_impl(const configure::EngineDesc& conf, bool) {
    return -1;
  }
  int thrd_initialize_impl() { return -1; }
  int thrd_finalize_impl() { return -1; }
  int thrd_clear_impl() { return -1; }
  int proc_finalize_impl() { return -1; }
W
wangjiawei04 已提交
868
  int infer_impl() { return -1; }
W
wangguibao 已提交
869 870 871

 private:
  boost::unordered_map<uint64_t, InferEngine*> _versions;
W
wangguibao 已提交
872 873
};

W
wangguibao 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
class InferManager {
 public:
  static InferManager& instance() {
    static InferManager ins;
    return ins;
  }

  int proc_initialize(const char* path, const char* file) {
    ModelToolkitConf model_toolkit_conf;
    if (configure::read_proto_conf(path, file, &model_toolkit_conf) != 0) {
      LOG(ERROR) << "failed load infer config, path: " << path << "/" << file;
      return -1;
    }
    size_t engine_num = model_toolkit_conf.engines_size();
    for (size_t ei = 0; ei < engine_num; ++ei) {
B
barrierye 已提交
889 890
      LOG(INFO) << "model_toolkit_conf.engines(" << ei
                << ").name: " << model_toolkit_conf.engines(ei).name();
W
wangguibao 已提交
891 892 893 894 895 896 897 898
      std::string engine_name = model_toolkit_conf.engines(ei).name();
      VersionedInferEngine* engine = new (std::nothrow) VersionedInferEngine();
      if (!engine) {
        LOG(ERROR) << "Failed generate versioned engine: " << engine_name;
        return -1;
      }
      if (engine->proc_initialize(model_toolkit_conf.engines(ei)) != 0) {
        LOG(ERROR) << "Failed initialize version engine, name:" << engine_name;
W
wangguibao 已提交
899
        return -1;
W
wangguibao 已提交
900 901 902 903 904 905 906
      }
      auto r = _map.insert(std::make_pair(engine_name, engine));
      if (!r.second) {
        LOG(ERROR) << "Failed insert item: " << engine_name;
        return -1;
      }
      LOG(WARNING) << "Succ proc initialize engine: " << engine_name;
W
wangguibao 已提交
907
    }
W
wangguibao 已提交
908 909 910 911 912 913 914
    return 0;
  }

  int thrd_initialize() {
    for (auto it = _map.begin(); it != _map.end(); ++it) {
      if (it->second->thrd_initialize() != 0) {
        LOG(ERROR) << "Failed thrd initialize engine, name: " << it->first;
W
wangguibao 已提交
915
        return -1;
W
wangguibao 已提交
916 917
      }
      LOG(WARNING) << "Succ thrd initialize engine, name: " << it->first;
W
wangguibao 已提交
918
    }
W
wangguibao 已提交
919 920
    return 0;
  }
W
wangguibao 已提交
921

W
wangguibao 已提交
922 923 924 925 926 927 928 929 930
  int thrd_clear() {
    for (auto it = _map.begin(); it != _map.end(); ++it) {
      if (it->second->thrd_clear() != 0) {
        LOG(ERROR) << "Failed thrd clear engine, name: " << it->first;
        return -1;
      }
    }
    return 0;
  }
W
wangguibao 已提交
931

W
wangguibao 已提交
932 933 934 935 936 937 938 939 940
  int reload() {
    for (auto it = _map.begin(); it != _map.end(); ++it) {
      if (it->second->reload() != 0) {
        LOG(ERROR) << "Failed reload engine, name: " << it->first;
        return -1;
      }
    }
    return 0;
  }
W
wangguibao 已提交
941

W
wangguibao 已提交
942 943 944 945 946 947 948 949 950 951
  int thrd_finalize() {
    for (auto it = _map.begin(); it != _map.end(); ++it) {
      if (it->second->thrd_finalize() != 0) {
        LOG(ERROR) << "Failed thrd finalize engine, name: " << it->first;
        return -1;
      }
      LOG(WARNING) << "Succ thrd finalize engine, name: " << it->first;
    }
    return 0;
  }
W
wangguibao 已提交
952

W
wangguibao 已提交
953 954 955 956 957 958 959 960
  int proc_finalize() {
    for (auto it = _map.begin(); it != _map.end(); ++it) {
      if (it->second->proc_finalize() != 0) {
        LOG(ERROR) << "Failed proc finalize engine, name: " << it->first;
        return -1;
      }
      LOG(WARNING) << "Succ proc finalize engine, name: " << it->first;
    }
W
wangguibao 已提交
961
    _map.clear();
W
wangguibao 已提交
962 963 964 965
    return 0;
  }

  // Inference interface
W
wangjiawei04 已提交
966
  int infer(const char* model_name) {
W
wangguibao 已提交
967 968 969 970 971
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
      return -1;
    }
W
wangjiawei04 已提交
972 973
    return it->second->infer();
  }
W
wangjiawei04 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988

  std::vector<std::string> GetInputNames(const char* model_name) {
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetInputNames();
  }
  std::vector<std::string> GetOutputNames(const char* model_name) {
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetOutputNames();
  }
W
wangjiawei04 已提交
989 990
  std::unique_ptr<paddle_infer::Tensor> GetInputHandle(
      const char* model_name, const std::string& name) {
W
wangjiawei04 已提交
991 992 993 994 995 996
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetInputHandle(name);
  }
W
wangjiawei04 已提交
997 998
  std::unique_ptr<paddle_infer::Tensor> GetOutputHandle(
      const char* model_name, const std::string& name) {
W
wangjiawei04 已提交
999 1000 1001 1002 1003
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetOutputHandle(name);
W
wangguibao 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
  }

  template <typename T>
  T* get_core(const char* model_name) {
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
      return NULL;
    }
    auto infer_engine =
        dynamic_cast<DBReloadableInferEngine<T>*>(it->second->default_engine());
    if (infer_engine) {
      return infer_engine->get_core();
    }
    LOG(WARNING) << "fail to get core for " << model_name;
    return NULL;
  }

  // Versioned inference interface
W
wangjiawei04 已提交
1023
  int infer(const char* model_name, uint64_t version) {
W
wangguibao 已提交
1024 1025 1026 1027 1028
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
      return -1;
    }
W
wangjiawei04 已提交
1029 1030
    return it->second->infer(version);
  }
W
wangjiawei04 已提交
1031 1032
  std::vector<std::string> GetInputNames(const char* model_name,
                                         uint64_t version) {
W
wangjiawei04 已提交
1033 1034 1035 1036 1037
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetInputNames(version);
W
wangguibao 已提交
1038 1039
  }

W
wangjiawei04 已提交
1040 1041
  std::vector<std::string> GetOutputNames(const char* model_name,
                                          uint64_t version) {
W
wangjiawei04 已提交
1042 1043 1044 1045 1046 1047 1048
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetOutputNames(version);
  }

W
wangjiawei04 已提交
1049 1050
  std::unique_ptr<paddle_infer::Tensor> GetInputHandle(
      const char* model_name, uint64_t version, const std::string& name) {
W
wangjiawei04 已提交
1051 1052 1053 1054 1055 1056
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetInputHandle(version, name);
  }
W
wangjiawei04 已提交
1057 1058
  std::unique_ptr<paddle_infer::Tensor> GetOutputHandle(
      const char* model_name, uint64_t version, const std::string& name) {
W
wangjiawei04 已提交
1059 1060 1061 1062 1063
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
    }
    return it->second->GetOutputHandle(version, name);
W
wangguibao 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  }
  template <typename T>
  T* get_core(const char* model_name, uint64_t version) {
    auto it = _map.find(model_name);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model_name;
      return NULL;
    }
    return it->second->get_core<T>(version);
  }

  int query_version(const std::string& model, uint64_t& version) {  // NOLINT
    auto it = _map.find(model);
    if (it == _map.end()) {
      LOG(WARNING) << "Cannot find engine in map, model name:" << model;
      return -1;
    }
    auto infer_engine = it->second->default_engine();
    if (!infer_engine) {
      LOG(WARNING) << "Cannot get default engine for model:" << model;
      return -1;
    }
    version = infer_engine->version();
    LOG(INFO) << "Succ get version: " << version << " for model: " << model;
    return 0;
  }

 private:
  boost::unordered_map<std::string, VersionedInferEngine*> _map;
};
W
wangguibao 已提交
1094

W
wangguibao 已提交
1095 1096 1097
}  // namespace predictor
}  // namespace paddle_serving
}  // namespace baidu