infer.h 31.1 KB
Newer Older
W
wangguibao 已提交
1 2 3
#ifndef BAIDU_PADDLE_SERVING_PREDICTOR_INFER_H
#define BAIDU_PADDLE_SERVING_PREDICTOR_INFER_H

W
wangguibao 已提交
4 5 6
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
W
wangguibao 已提交
7 8 9 10 11 12 13 14 15
#include "common/inner_common.h"
#include "framework/infer_data.h"
#include "framework/factory.h"
#include "framework/bsf.h"

namespace baidu {
namespace paddle_serving {
namespace predictor {

W
wangguibao 已提交
16 17
using configure::ModelToolkitConf;

W
wangguibao 已提交
18 19 20 21 22
class InferEngine {
public:

    virtual ~InferEngine() {}

W
wangguibao 已提交
23
    virtual int proc_initialize(const configure::EngineDesc& conf, bool version) {
W
wangguibao 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
        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();
    }
    virtual int infer(const void* in, void* out, uint32_t batch_size = -1) {
        return infer_impl1(in, out, batch_size);
    }

    virtual int reload() = 0;

    virtual uint64_t version() const = 0;

    // begin: framework inner call
    virtual int proc_initialize_impl(
W
wangguibao 已提交
48
            const configure::EngineDesc& conf, bool version) = 0;
W
wangguibao 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    virtual int thrd_initialize_impl() = 0;
    virtual int thrd_finalize_impl() = 0;
    virtual int thrd_clear_impl() = 0;
    virtual int proc_finalize_impl() = 0;
    virtual int infer_impl1(
            const void* in, void* out, uint32_t batch_size = -1) = 0;
    virtual int infer_impl2(const BatchTensor& in, BatchTensor& out) = 0;
    // end: framework inner call
};

class ReloadableInferEngine : public InferEngine {
public:
    virtual ~ReloadableInferEngine() {}

    union last_check_status {
        time_t last_timestamp;
        uint64_t last_md5sum;
        uint64_t last_revision;
    };

    typedef im::bsf::Task<Tensor, Tensor> TaskT;

    virtual int load(const std::string& data_path) = 0;

W
wangguibao 已提交
73 74 75 76 77 78 79
    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();
W
wangguibao 已提交
80
        if (!check_need_reload() || load(_model_data_path) != 0) {
81
            LOG(ERROR) << "Failed load model_data_path" << _model_data_path;
W
wangguibao 已提交
82 83 84 85
            return -1;
        }

        if (parse_version_info(conf, version) != 0) {
86
            LOG(ERROR) << "Failed parse version info";
W
wangguibao 已提交
87 88 89 90 91 92 93
            return -1;
        }

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

W
wangguibao 已提交
94
    int proc_initialize(const configure::EngineDesc& conf, bool version) {
W
wangguibao 已提交
95
        if (proc_initialize_impl(conf, version) != 0) {
96
            LOG(ERROR) << "Failed proc initialize impl";
W
wangguibao 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
            return -1;
        }

        // init bsf framework
        if (_infer_thread_num <= 0) {
            return 0;
        }

        im::bsf::TaskExecutor<TaskT>::instance()->set_thread_init_fn(
                boost::bind(&InferEngine::thrd_initialize_impl, this));
        im::bsf::TaskExecutor<TaskT>::instance()->set_thread_reset_fn(
                boost::bind(&InferEngine::thrd_clear_impl, this));
        im::bsf::TaskExecutor<TaskT>::instance()->set_thread_callback_fn(
                boost::bind(&InferEngine::infer_impl2, this, _1, _2));
        im::bsf::TaskExecutor<TaskT>::instance()->set_batch_size(_infer_batch_size);
        im::bsf::TaskExecutor<TaskT>::instance()->set_batch_align(_infer_batch_align);
        if (im::bsf::TaskExecutor<TaskT>::instance()->start(_infer_thread_num)
                != 0) {
115
            LOG(ERROR) << "Failed start bsf executor, threads:" << _infer_thread_num;
W
wangguibao 已提交
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
            return -1;
        }

        LOG(WARNING) << "Enable batch schedule framework, thread_num:"
            << _infer_thread_num << ", batch_size:" << _infer_batch_size
            << ", enable_batch_align:" << _infer_batch_align;

        return 0;
    }

    int infer(const void* in, void* out, uint32_t batch_size = -1) {
        if (_infer_thread_num <= 0) {
            return infer_impl1(in, out, batch_size);
        }

        im::bsf::TaskManager<Tensor, Tensor> task_manager;
        task_manager.schedule(*(const BatchTensor*)in, *(BatchTensor*)out);
        task_manager.wait();
        return 0;
    }

    int thrd_initialize() {
        if (_infer_thread_num > 0) {
            return 0;
        }

        return thrd_initialize_impl();
    }

    int thrd_clear() {
        if (_infer_thread_num > 0) {
            return 0;
        }

        return thrd_clear_impl();
    }

    int proc_finalize() {
        if (proc_finalize_impl() != 0) {
155
            LOG(ERROR) << "Failed proc finalize impl";
W
wangguibao 已提交
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
            return -1;
        }

        if (_infer_thread_num > 0) {
            im::bsf::TaskExecutor<TaskT>::instance()->stop();
        }

        return 0;
    }

    int reload() {
        if (check_need_reload()) {
            LOG(WARNING) << "begin reload model[" << _model_data_path << "].";
            return load(_model_data_path);
        }
        return 0;
    }

    uint64_t version() const {
        return _version; 
    }

    uint32_t thread_num() const {
        return _infer_thread_num;
    }

private:
W
wangguibao 已提交
183
    int parse_version_info(const configure::EngineDesc& config, bool version) {
W
wangguibao 已提交
184
        _version = uint64_t(-1);
W
wangguibao 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        return 0;
    }


    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 {
201
            LOG(ERROR) << "Not support check type: "
W
wangguibao 已提交
202 203 204 205 206 207 208 209
                << _reload_mode_tag;
            return false;
        }
    }

    bool check_timestamp_ne() {
        struct stat st;
        if (stat(_reload_tag_file.c_str(), &st) != 0) {
210
            LOG(ERROR) << "Failed stat config file:"
W
wangguibao 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
                << _reload_tag_file;
            return false;
        }

        if ((st.st_mode & S_IFREG) &&
                st.st_mtime != _last_status.last_timestamp) {
            _last_status.last_timestamp = st.st_mtime;
            return true;
        }

        return false;
    }

    bool check_timestamp_gt() {
        struct stat st;
        if (stat(_reload_tag_file.c_str(), &st) != 0) {
227
            LOG(ERROR) << "Failed stat config file:"
W
wangguibao 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
                << _reload_tag_file;
            return false;
        }

        if ((st.st_mode & S_IFREG) &&
                st.st_mtime > _last_status.last_timestamp) {
            _last_status.last_timestamp = st.st_mtime;
            return true;
        }

        return false;
    }

    bool check_md5sum() {
        return false;
    }

    bool check_revision() {
        return false;
    }

protected:
    std::string _model_data_path;

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;
};

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() {}

W
wangguibao 已提交
283
    int proc_initialize(const configure::EngineDesc& conf, bool version) {
W
wangguibao 已提交
284 285 286 287 288 289 290 291 292 293 294 295
        THREAD_KEY_CREATE(&_skey, NULL);
        THREAD_MUTEX_INIT(&_mutex, NULL);
        return ReloadableInferEngine::proc_initialize(conf, version);
    }

    virtual int load(const std::string& model_data_dir) {
        if (_reload_vec.empty()) {
            return 0;
        }

        for (uint32_t ti = 0; ti < _reload_vec.size(); ++ti) {
            if (load_data(_reload_vec[ti], model_data_dir) != 0) {
296
                LOG(ERROR) << "Failed reload engine model: " << ti;
W
wangguibao 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
                return -1;
            }
        }
        
        LOG(WARNING) << "Succ load engine, path: " << model_data_dir;

        return 0;
    }

    int load_data(ModelData<EngineCore>* md, const std::string& data_path) {
        uint32_t next_idx = (md->current_idx + 1) % 2;
        if (md->cores[next_idx]) {
            delete md->cores[next_idx];
        }

        md->cores[next_idx] = new (std::nothrow) EngineCore;
        if (!md->cores[next_idx]
                || md->cores[next_idx]->create(data_path) != 0) {
315
            LOG(ERROR) << "Failed create model, path: " << data_path;
W
wangguibao 已提交
316 317 318 319 320 321 322 323 324
            return -1;
        }
        md->current_idx = next_idx;
        return 0;
    }

    virtual int thrd_initialize_impl() {
        // memory pool to be inited in non-serving-threads
        if (MempoolWrapper::instance().thread_initialize() != 0) {
325
            LOG(ERROR) << "Failed thread initialize mempool";
W
wangguibao 已提交
326 327 328 329 330
            return -1;
        }
        
        ModelData<EngineCore>* md = new(std::nothrow) ModelData<EngineCore>;
        if (!md || load_data(md, _model_data_path) != 0) {
331
            LOG(ERROR) << "Failed create thread data from " << _model_data_path;
W
wangguibao 已提交
332 333 334 335 336 337 338 339 340 341 342 343
            return -1;
        }

        THREAD_SETSPECIFIC(_skey, md);
        im::bsf::AutoMutex lock(_mutex);
        _reload_vec.push_back(md);
        return 0;
    }

    int thrd_clear_impl() {
        // for non-serving-threads
        if (MempoolWrapper::instance().thread_clear() != 0) {
344
            LOG(ERROR) << "Failed thread clear mempool";
W
wangguibao 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
            return -1;
        }
        return 0;
    }

    int thrd_finalize_impl() {
        return 0;
    }

    int proc_finalize_impl() {
        THREAD_KEY_DELETE(_skey);
        THREAD_MUTEX_DESTROY(&_mutex);
        return 0;
    }

    EngineCore* get_core() {
        ModelData<EngineCore>* md = (ModelData<EngineCore>*)THREAD_GETSPECIFIC(_skey);
        if (!md) {
363
            LOG(ERROR) << "Failed get thread specific data";
W
wangguibao 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
            return NULL;
        }
        return md->cores[md->current_idx];
    }

protected:
    THREAD_KEY_T _skey;
    THREAD_MUTEX_T _mutex;
    std::vector<ModelData<EngineCore>*> _reload_vec;
private:
};

// 多个EngineCore共用同一份模型数据
template<typename EngineCore>
class CloneDBReloadableInferEngine : public DBReloadableInferEngine<EngineCore> {
public:
    virtual ~CloneDBReloadableInferEngine() {}

W
wangguibao 已提交
382
    virtual int proc_initialize(const configure::EngineDesc& conf, bool version) {
W
wangguibao 已提交
383 384
        _pd = new (std::nothrow) ModelData<EngineCore>;
        if (!_pd) {
385
            LOG(ERROR) << "Failed to allocate for ProcData";
W
wangguibao 已提交
386 387 388 389 390 391 392 393 394 395
            return -1;
        }
        return DBReloadableInferEngine<EngineCore>::proc_initialize(
                conf, version);
    }

    virtual int load(const std::string& model_data_dir) {
        // 加载进程级模型数据
        if (!_pd || DBReloadableInferEngine<EngineCore>::load_data(
                    _pd, model_data_dir) != 0) {
396
            LOG(ERROR) 
W
wangguibao 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
                << "Failed to create common model from [" 
                << model_data_dir << "].";
            return -1;
        }
        LOG(WARNING) 
            << "Succ load common model[" << _pd->cores[_pd->current_idx] 
            << "], path[" << model_data_dir << "].";

        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) {
412
                LOG(ERROR) << "Failed reload engine model: " << ti;
W
wangguibao 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
                return -1;
            }
        }
        
        LOG(WARNING) << "Succ load clone model, path[" << model_data_dir << "]";

        return 0;
    }

    // 加载线程级对象,多个线程级对象共用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];
        }

        td->cores[next_idx] = new (std::nothrow) EngineCore;
        if (!td->cores[next_idx]
                || td->cores[next_idx]->clone(pd_core->get()) != 0) {
434
            LOG(ERROR) << "Failed clone model from pd_core[ " << pd_core
W
wangguibao 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448
                    << "], idx[" << next_idx << "]";
            return -1;
        }
        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;
    }

    virtual int thrd_initialize_impl() {
        // memory pool to be inited in non-serving-threads
        if (MempoolWrapper::instance().thread_initialize() != 0) {
449
            LOG(ERROR) << "Failed thread initialize mempool";
W
wangguibao 已提交
450 451 452 453 454
            return -1;
        }
        
        ModelData<EngineCore>* md = new(std::nothrow) ModelData<EngineCore>;
        if (!md || load_data(md, _pd->cores[_pd->current_idx]) != 0) {
455
            LOG(ERROR) << "Failed clone thread data, origin_core["
W
wangguibao 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
                    << _pd->cores[_pd->current_idx] << "].";
            return -1;
        }

        THREAD_SETSPECIFIC(DBReloadableInferEngine<EngineCore>::_skey, md);
        im::bsf::AutoMutex lock(DBReloadableInferEngine<EngineCore>::_mutex);
        DBReloadableInferEngine<EngineCore>::_reload_vec.push_back(md);
        return 0;
    }

protected:
    ModelData<EngineCore>* _pd; // 进程级EngineCore,多个线程级EngineCore共用该对象的模型数据
};

template<typename FluidFamilyCore>
class FluidInferEngine : public DBReloadableInferEngine<FluidFamilyCore> {
public:
    FluidInferEngine() {}
    ~FluidInferEngine() {}
    
    int infer_impl1(const void* in, void* out, uint32_t batch_size = -1) {
        FluidFamilyCore* core
            = DBReloadableInferEngine<FluidFamilyCore>::get_core();
        if (!core || !core->get()) {
480
            LOG(ERROR) << "Failed get fluid core in infer_impl()";
W
wangguibao 已提交
481 482 483 484
            return -1;
        }
        
        if (!core->Run(in, out)) {
485
            LOG(ERROR) << "Failed run fluid family core";
W
wangguibao 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
            return -1;
        }
        return 0;
    }

    int infer_impl2(const BatchTensor& in, BatchTensor& out) {
        return infer_impl1(&in, &out);
    }
};

template<typename TensorrtFamilyCore>
class TensorrtInferEngine : public DBReloadableInferEngine<TensorrtFamilyCore> {
public:
    TensorrtInferEngine() {}
    ~TensorrtInferEngine() {}

    int infer_impl1(const void* in, void* out, uint32_t batch_size) {
        TensorrtFamilyCore* core
            = DBReloadableInferEngine<TensorrtFamilyCore>::get_core();
        if (!core || !core->get()) {
506
            LOG(ERROR) << "Failed get fluid core in infer_impl()";
W
wangguibao 已提交
507 508 509 510
            return -1;
        }

        if (!core->Run(in, out, batch_size)) {
511
            LOG(ERROR) << "Failed run fluid family core";
W
wangguibao 已提交
512 513 514 515 516 517
            return -1;
        }
        return 0;
    }

    int infer_impl2(const BatchTensor& in, BatchTensor& out) {
518
        LOG(ERROR) << "Tensortrt donot supports infer_impl2 yet!";
W
wangguibao 已提交
519 520 521 522 523 524 525 526 527 528 529
        return -1;
    }
};

template<typename AbacusFamilyCore>
class AbacusInferEngine : public CloneDBReloadableInferEngine<AbacusFamilyCore> {
public:
    AbacusInferEngine() {}
    ~AbacusInferEngine() {}

    int infer_impl1(const void* in, void* out, uint32_t batch_size = -1) {
530
        LOG(ERROR) << "Abacus dnn engine must use predict interface";
W
wangguibao 已提交
531 532 533 534
        return -1;
    }

    int infer_impl2(const BatchTensor& in, BatchTensor& out) {
535
        LOG(ERROR) << "Abacus dnn engine must use predict interface";
W
wangguibao 已提交
536 537 538 539 540 541 542 543
        return -1;
    }

    // Abacus special interface
    int predict(uint32_t ins_num) {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
544
            LOG(ERROR) << "Failed get abacus core in predict()";
W
wangguibao 已提交
545 546 547 548 549 550 551 552 553
            return -1;
        }

        return core->predict(ins_num);
    }
    int set_use_fpga(bool use_fpga) {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
554
            LOG(ERROR) << "Failed get abacus core in predict()";
W
wangguibao 已提交
555 556 557 558 559 560 561 562 563
            return -1;
        }

        return core->set_use_fpga(use_fpga);
    }
    int debug() {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
564
            LOG(ERROR) << "Failed get abacus core in debug()";
W
wangguibao 已提交
565 566 567 568 569 570 571 572 573
            return -1;
        }
        return core->debug();
    }

    int set_search_id(uint64_t sid) {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
574
            LOG(ERROR) << "Failed get abacus core in set_serach_id()";
W
wangguibao 已提交
575 576 577 578 579 580 581 582 583
            return -1;
        }
        return core->set_search_id(sid);
    }

    int set_hidden_layer_dim(uint32_t dim) {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
584
            LOG(ERROR) << "Failed get abacus core in set_layer_dim()";
W
wangguibao 已提交
585 586 587 588 589 590 591 592 593 594
            return -1;
        }
        return core->set_hidden_layer_dim(dim);
    }

    int get_input(
            uint32_t ins_idx, uint32_t* fea_num, void* in) {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
595
            LOG(ERROR) << "Failed get abacus core in get_input()";
W
wangguibao 已提交
596 597 598 599 600 601 602 603 604 605
            return -1;
        }
        return core->get_input(ins_idx, fea_num, in);
    }

    int get_layer_value(const std::string& name,
            uint32_t ins_num, uint32_t fea_dim, void* out) {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
606
            LOG(ERROR) << "Failed get abacus core in get_layer_value()";
W
wangguibao 已提交
607 608 609 610 611 612 613 614 615
            return -1;
        }
        return core->get_layer_value(name, ins_num, fea_dim, out);
    }
    
    void set_position_idx(void* input, uint64_t fea, uint32_t ins_idx) {
        AbacusFamilyCore* core
                = CloneDBReloadableInferEngine<AbacusFamilyCore>::get_core();
        if (!core || !core->get()) {
616
            LOG(ERROR) << "Failed get abacus core in set_position_idx()";
W
wangguibao 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630
            return;
        }
        core->set_position_idx(input, fea, ins_idx);
        return;
    }
};

template<typename PaddleV2FamilyCore>
class PaddleV2InferEngine : public CloneDBReloadableInferEngine<PaddleV2FamilyCore> {
public:
    PaddleV2InferEngine() {}
    ~PaddleV2InferEngine() {}
    
    int infer_impl1(const void* in, void* out, uint32_t batch_size = -1) {
631
        LOG(ERROR) << "Paddle V2 engine must use predict interface";
W
wangguibao 已提交
632 633 634 635
        return -1;
    }

    int infer_impl2(const BatchTensor& in, BatchTensor& out) {
636
        LOG(ERROR) << "Paddle V2 engine must use predict interface";
W
wangguibao 已提交
637 638 639 640 641 642 643 644 645 646 647 648 649
        return -1;
    }
};

typedef FactoryPool<InferEngine> StaticInferFactory;

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

W
wangguibao 已提交
650 651
    int proc_initialize(const configure::EngineDesc& conf) {
        if (proc_initialize(conf, false) != 0) {
652
            LOG(ERROR) << "Failed proc intialize engine: " 
W
wangguibao 已提交
653 654
                        << conf.name().c_str();
            return -1;
W
wangguibao 已提交
655 656 657
        }

        LOG(WARNING) 
W
wangguibao 已提交
658
            << "Succ proc initialize engine: " << conf.name().c_str();
W
wangguibao 已提交
659 660 661
        return 0;
    }

W
wangguibao 已提交
662 663
    int proc_initialize(const configure::EngineDesc& conf, bool version) {
        std::string engine_type = conf.type();
W
wangguibao 已提交
664 665 666 667
        InferEngine* engine
            = StaticInferFactory::instance().generate_object(
                    engine_type);
        if (!engine) {
668
            LOG(ERROR) << "Failed generate engine with type:"
W
wangguibao 已提交
669 670 671 672 673
                << engine_type;
            return -1;
        }

        if (engine->proc_initialize(conf, version) != 0) {
674
            LOG(ERROR) << "Failed initialize engine, type:"
W
wangguibao 已提交
675 676 677 678 679 680
                << engine_type;
            return -1;
        }

        auto r = _versions.insert(std::make_pair(engine->version(), engine));
        if (!r.second) {
681
            LOG(ERROR) << "Failed insert item: " << engine->version() 
W
wangguibao 已提交
682 683 684 685 686 687 688 689 690 691 692
                << ", 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) {
693
                LOG(ERROR) << "Failed proc finalize version engine: " <<
W
wangguibao 已提交
694 695 696 697 698 699 700 701 702 703 704
                    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) {
705
                LOG(ERROR) << "Failed thrd initialize version engine: " <<
W
wangguibao 已提交
706 707 708 709 710 711 712 713 714 715 716 717
                    iter->first;
                return -1;
            }
            LOG(WARNING) 
                << "Succ thrd initialize version engine: " << iter->first;
        }
        return 0;
    }

    int thrd_clear() {
        for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
            if (iter->second->thrd_clear() != 0) {
718
                LOG(ERROR) << "Failed thrd clear version engine: " << 
W
wangguibao 已提交
719 720 721
                    iter->first;
                return -1;
            }
W
wangguibao 已提交
722
            LOG(INFO) << "Succ thrd clear version engine: " << iter->first;
W
wangguibao 已提交
723 724 725 726 727 728 729
        }
        return 0;
    }

    int thrd_finalize() {
        for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
            if (iter->second->thrd_finalize() != 0) {
730
                LOG(ERROR) << "Failed thrd finalize version engine: " << 
W
wangguibao 已提交
731 732 733 734 735 736 737 738 739 740 741
                    iter->first;
                return -1;
            }
            LOG(WARNING) << "Succ thrd finalize version engine: " << iter->first;
        }
        return 0;
    }

    int reload() {
        for (auto iter = _versions.begin(); iter != _versions.end(); ++iter) {
            if (iter->second->reload() != 0) {
742
                LOG(ERROR) << "Failed reload version engine: " << 
W
wangguibao 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
                    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) {
763
            LOG(ERROR) << "Ambiguous default engine version:" 
W
wangguibao 已提交
764 765 766 767 768 769 770 771 772 773 774
                << _versions.size();
            return NULL;
        }

        return _versions.begin()->second;
    }
    
    int infer(const void* in, void* out, uint32_t batch_size) {
        InferEngine* engine = default_engine();
        if (!engine) {
            LOG(WARNING) << "fail to get default engine";
W
wangguibao 已提交
775
            return -1;
W
wangguibao 已提交
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        }
        return engine->infer(in, out, batch_size);
    }

    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
    int infer(
            const void* in, void* out, uint32_t batch_size, uint64_t version) {
        auto iter = _versions.find(version);
        if (iter == _versions.end()) {
800
            LOG(ERROR) << "Not found version engine: " << version;
W
wangguibao 已提交
801 802 803 804 805 806 807 808 809 810
            return -1;
        }

        return iter->second->infer(in, out, batch_size);
    }
    
    template<typename T>
    T* get_core(uint64_t version) {
        auto iter = _versions.find(version);
        if (iter == _versions.end()) {
811
            LOG(ERROR) << "Not found version engine: "  << version;
W
wangguibao 已提交
812 813 814 815 816 817 818 819 820 821 822 823
            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;
    }

    // --
W
wangguibao 已提交
824
    int proc_initialize_impl(const configure::EngineDesc& conf, bool) { return -1; }
W
wangguibao 已提交
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    int thrd_initialize_impl() { return -1; }
    int thrd_finalize_impl() { return -1; }
    int thrd_clear_impl() { return -1; }
    int proc_finalize_impl() { return -1; }
    int infer_impl1(const void* in, void* out, uint32_t batch_size = -1) { return -1; }
    int infer_impl2(const BatchTensor& in, BatchTensor& out) { return -1; }

private:
    boost::unordered_map<uint64_t, InferEngine*> _versions;
};

class InferManager {
public:
    static InferManager& instance() {
        static InferManager ins;
        return ins;
    }

    int proc_initialize(const char* path, const char* file) {
W
wangguibao 已提交
844 845
        ModelToolkitConf model_toolkit_conf;
        if (configure::read_proto_conf(path, file, &model_toolkit_conf) != 0) {
846
            LOG(ERROR) << "failed load infer config, path: "
W
wangguibao 已提交
847 848 849 850
                << path << "/" << file;
            return -1;
        }

W
wangguibao 已提交
851
        size_t engine_num = model_toolkit_conf.engines_size();
W
wangguibao 已提交
852
        for (size_t ei = 0; ei < engine_num; ++ei) {
W
wangguibao 已提交
853
            std::string engine_name = model_toolkit_conf.engines(ei).name();
W
wangguibao 已提交
854 855
            VersionedInferEngine* engine = new (std::nothrow) VersionedInferEngine();
            if (!engine) {
856
                LOG(ERROR) << "Failed generate versioned engine: " << engine_name;
W
wangguibao 已提交
857 858 859
                return -1;
            }

W
wangguibao 已提交
860
            if (engine->proc_initialize(model_toolkit_conf.engines(ei)) != 0) {
861
                LOG(ERROR) << "Failed initialize version engine, name:"
W
wangguibao 已提交
862 863 864 865 866 867
                    << engine_name;
                return -1;
            }

            auto r = _map.insert(std::make_pair(engine_name, engine));
            if (!r.second) {
868
                LOG(ERROR) << "Failed insert item: " << engine_name;
W
wangguibao 已提交
869 870 871 872 873 874 875 876 877 878 879
                return -1;
            }
            LOG(WARNING) << "Succ proc initialize engine: " << engine_name;
        }

        return 0;
    }

    int thrd_initialize() {
        for (auto it = _map.begin(); it != _map.end(); ++it) {
            if (it->second->thrd_initialize() != 0) {
880
                LOG(ERROR) << "Failed thrd initialize engine, name: "
W
wangguibao 已提交
881 882 883 884 885 886 887 888 889 890 891 892
                    << it->first;
                return -1;
            }
            LOG(WARNING) << "Succ thrd initialize engine, name: "
                << it->first;
        }
        return 0;
    }

    int thrd_clear() {
        for (auto it = _map.begin(); it != _map.end(); ++it) {
            if (it->second->thrd_clear() != 0) {
893
                LOG(ERROR) << "Failed thrd clear engine, name: "
W
wangguibao 已提交
894 895 896 897 898 899 900 901 902 903
                    << it->first;
                return -1;
            }
        }
        return 0;
    }

    int reload() {
        for (auto it = _map.begin(); it != _map.end(); ++it) {
            if (it->second->reload() != 0) {
904
                LOG(ERROR) << "Failed reload engine, name: "
W
wangguibao 已提交
905 906 907 908 909 910 911 912 913 914
                    << it->first;
                return -1;
            }
        }
        return 0;
    }

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

    int proc_finalize() {
        for (auto it = _map.begin(); it != _map.end(); ++it) {
            if (it->second->proc_finalize() != 0) {
928
                LOG(ERROR) << "Failed proc finalize engine, name: "
W
wangguibao 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
                    << it->first;
                return -1;
            }
            LOG(WARNING) << "Succ proc finalize engine, name: "
                << it->first;
        }
        return 0;
    }

    // Inference interface
    int infer(const char* model_name, const void* in, void* out, uint32_t batch_size = -1) {
        auto it = _map.find(model_name);
        if (it == _map.end()) {
            LOG(WARNING) << "Cannot find engine in map, model name:"
                << model_name;
            return -1;
        }
        return it->second->infer(in, out, batch_size);
    }

    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
    int infer(const char* model_name, const void* in, void* out, 
            uint32_t batch_size, 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 -1;
        }
        return it->second->infer(in, out, batch_size, version);
    }

    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) {
        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();
W
wangguibao 已提交
1003
        LOG(INFO) << "Succ get version: " << version << " for model: " 
W
wangguibao 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
            << model;
        return 0;
    }

private:
    boost::unordered_map<std::string, VersionedInferEngine*> _map;
};

} // predictor
} // paddle_serving
} // baidu

#endif // BAIDU_PADDLE_SERVING_PREDICTOR_INFER_H