infer.h 20.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
16
#include <pthread.h>
W
wangguibao 已提交
17
#include <sys/stat.h>
W
wangguibao 已提交
18
#include <sys/types.h>
W
wangguibao 已提交
19
#include <unistd.h>
H
HexToString 已提交
20
#include <functional>
21
#include <numeric>
W
wangguibao 已提交
22
#include <string>
M
MRXLT 已提交
23
#include <utility>
W
wangguibao 已提交
24
#include <vector>
H
HexToString 已提交
25
#include <memory>
G
guru4elephant 已提交
26
#include "core/predictor/common/inner_common.h"
H
HexToString 已提交
27
#include "core/predictor/framework/bsf.h"
G
guru4elephant 已提交
28 29
#include "core/predictor/framework/factory.h"
#include "core/predictor/framework/infer_data.h"
30
#include "core/predictor/framework/memory.h"
W
wangjiawei04 已提交
31
#include "paddle_inference_api.h"  // NOLINT
W
wangguibao 已提交
32 33 34 35
namespace baidu {
namespace paddle_serving {
namespace predictor {

W
wangguibao 已提交
36 37
using configure::ModelToolkitConf;

Z
zhangjun 已提交
38 39 40 41 42 43 44 45 46 47 48
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;
};

Z
update  
zhangjun 已提交
49
class GlobalCreateMutex {
Z
zhangjun 已提交
50 51 52 53
 public:
  pthread_mutex_t& mutex() { return _mut; }

  static pthread_mutex_t& instance() {
Z
update  
zhangjun 已提交
54
    static GlobalCreateMutex gmutex;
Z
zhangjun 已提交
55 56 57 58
    return gmutex.mutex();
  }

 private:
Z
update  
zhangjun 已提交
59
  GlobalCreateMutex() { pthread_mutex_init(&_mut, NULL); }
Z
zhangjun 已提交
60 61 62
  pthread_mutex_t _mut;
};

W
wangguibao 已提交
63
class InferEngine {
W
wangguibao 已提交
64 65 66 67 68 69 70 71 72 73
 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(); }
H
HexToString 已提交
74 75 76
  virtual int infer(const void* in, void* out, uint32_t batch_size = -1) {
    return infer_impl(in, out, batch_size);
  }
H
HexToString 已提交
77
  virtual void set_model_index(uint32_t index) { _model_index = index; }
W
wangguibao 已提交
78 79 80 81 82 83 84 85 86 87 88
  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;
H
HexToString 已提交
89
  virtual int infer_impl(const void* in,
90 91
                         void* out,
                         uint32_t batch_size = -1) = 0;
92
  virtual int task_infer_impl(const void* in, void* out) = 0;  // NOLINT
H
HexToString 已提交
93

H
HexToString 已提交
94 95
 protected:
  uint32_t _model_index;
W
wangguibao 已提交
96 97
  // end: framework inner call
};
H
HexToString 已提交
98
typedef im::bsf::Task<paddle::PaddleTensor, paddle::PaddleTensor> TaskT;
W
wangguibao 已提交
99 100 101
class ReloadableInferEngine : public InferEngine {
 public:
  virtual ~ReloadableInferEngine() {}
W
wangguibao 已提交
102

103 104 105 106 107
  // Reloadable record
  union ReloadableRecord {
    time_t timestamp;
    uint64_t md5sum;
    uint64_t revision;
W
wangguibao 已提交
108
  };
W
wangguibao 已提交
109

Z
update  
zhangjun 已提交
110
  virtual int load(const configure::EngineDesc& conf) = 0;
W
wangguibao 已提交
111

112
  int proc_initialize_impl(const configure::EngineDesc& conf, bool version);
W
wangguibao 已提交
113

114
  int proc_initialize(const configure::EngineDesc& conf, bool version);
H
HexToString 已提交
115

116
  int infer(const void* in, void* out, uint32_t batch_size = -1);
W
wangguibao 已提交
117

118
  int thrd_initialize();
W
wangguibao 已提交
119

120
  int thrd_clear();
W
wangguibao 已提交
121

122
  int proc_finalize();
W
wangguibao 已提交
123

124
  int reload();
W
wangguibao 已提交
125 126 127

  uint64_t version() const { return _version; }
  uint32_t thread_num() const { return _infer_thread_num; }
W
wangguibao 已提交
128

W
wangguibao 已提交
129
 private:
130
  int parse_version_info(const configure::EngineDesc& config, bool version);
W
wangguibao 已提交
131

132
  bool check_need_reload();
W
wangguibao 已提交
133

134
  bool check_timestamp_ne();
W
wangguibao 已提交
135

136
  bool check_timestamp_gt();
W
wangguibao 已提交
137 138 139 140 141 142

  bool check_md5sum() { return false; }

  bool check_revision() { return false; }

 protected:
143 144 145 146
  // Model directory
  std::string _model_dir;

  // The description of inference engine
Z
update  
zhangjun 已提交
147
  configure::EngineDesc _conf;
W
wangguibao 已提交
148 149

 private:
150
  // Tag file of reloadable model
W
wangguibao 已提交
151
  std::string _reload_tag_file;
152 153 154 155 156 157 158 159

  // Type of reload, e.g. timestamp_ne, timestamp_gt, md5sum, reversion
  std::string _reload_type;

  // Record the last loading infermation
  ReloadableRecord _last_record;

  // Number of inference threads
W
wangguibao 已提交
160
  uint32_t _infer_thread_num;
161 162

  // Size of inference batch
W
wangguibao 已提交
163
  uint32_t _infer_batch_size;
164 165

  // Need to align batch_size in inferring
W
wangguibao 已提交
166
  bool _infer_batch_align;
167 168

  // model version
W
wangguibao 已提交
169 170
  uint64_t _version;
};
W
wangguibao 已提交
171

172
// Lock free switching two models
W
wangguibao 已提交
173 174 175 176 177 178 179 180 181 182 183 184
template <typename EngineCore>
struct ModelData {
  ModelData() : current_idx(1) {
    cores[0] = NULL;
    cores[1] = NULL;
  }

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

185 186
  void* get() { return cores[current_idx]->get(); }

W
wangguibao 已提交
187 188 189 190 191 192 193 194 195 196 197 198
  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);
199
    gpu_index = 0;
W
wangguibao 已提交
200 201 202
    return ReloadableInferEngine::proc_initialize(conf, version);
  }

203 204 205 206 207
  // 进程初始化会调用load,但由于未执行线程初始化,所以_reload_vec为空,不再继续执行。
  // 热加载的话会调用load,由于线程已经初始化,_reload_vec不为空,所以继续执行load_data操作加载数据。
  // 线程初始化会执行load_data操作加载数据,然后将engine加入_reload_vec中。
  // 每个模型只有一个CloneDBReloadableInferEngine对象。
  // 但一个CloneDBReloadableInferEngine对象,可以包含N个EngineCore。
Z
update  
zhangjun 已提交
208
  virtual int load(const configure::EngineDesc& conf) {
W
wangguibao 已提交
209 210
    if (_reload_vec.empty()) {
      return 0;
W
wangguibao 已提交
211
    }
212
    gpu_index = 0;
W
wangguibao 已提交
213
    for (uint32_t ti = 0; ti < _reload_vec.size(); ++ti) {
Z
update  
zhangjun 已提交
214
      if (load_data(_reload_vec[ti], conf) != 0) {
W
wangguibao 已提交
215 216 217 218 219
        LOG(ERROR) << "Failed reload engine model: " << ti;
        return -1;
      }
    }

Z
update  
zhangjun 已提交
220
    LOG(WARNING) << "Succ load engine, path: " << conf.model_dir();
W
wangguibao 已提交
221 222
    return 0;
  }
W
wangguibao 已提交
223

224 225
  virtual int load_data(ModelData<EngineCore>* md,
                        const configure::EngineDesc& conf) {
W
wangguibao 已提交
226 227 228
    uint32_t next_idx = (md->current_idx + 1) % 2;
    if (md->cores[next_idx]) {
      delete md->cores[next_idx];
W
wangguibao 已提交
229 230
    }

W
wangguibao 已提交
231
    md->cores[next_idx] = new (std::nothrow) EngineCore;
232

H
HexToString 已提交
233
    // params.dump();
234 235 236 237 238 239 240 241
    size_t gpu_ids_num = conf.gpu_ids_size();
    im::bsf::AutoMutex lock(_mutex);
    int gpu_id = -1;
    if (gpu_ids_num > 0) {
      gpu_id = conf.gpu_ids(gpu_index % gpu_ids_num);
    }
    if (!md->cores[next_idx] ||
        md->cores[next_idx]->create(conf, gpu_id) != 0) {
Z
update  
zhangjun 已提交
242
      LOG(ERROR) << "Failed create model, path: " << conf.model_dir();
W
wangguibao 已提交
243
      return -1;
W
wangguibao 已提交
244
    }
245
    gpu_index++;
W
wangguibao 已提交
246 247 248
    md->current_idx = next_idx;
    return 0;
  }
W
wangguibao 已提交
249

W
wangguibao 已提交
250 251
  virtual int thrd_initialize_impl() {
    ModelData<EngineCore>* md = new (std::nothrow) ModelData<EngineCore>;
Z
update  
zhangjun 已提交
252
    if (!md || load_data(md, _conf) != 0) {
253
      LOG(ERROR) << "Failed create thread data from " << _conf.model_dir();
W
wangguibao 已提交
254
      return -1;
W
wangguibao 已提交
255 256
    }

W
wangguibao 已提交
257
    THREAD_SETSPECIFIC(_skey, md);
H
HexToString 已提交
258
    im::bsf::AutoMutex lock(_mutex);
W
wangguibao 已提交
259 260 261 262 263
    _reload_vec.push_back(md);
    return 0;
  }

  int thrd_clear_impl() {
264 265 266 267
    // actually, there are 2 kinds of multi-thread.
    // 1. brpc thread 2. bsf Task thread
    // each request is in 1-single brpc thread.
    // IF (bsf Task thread is not used)
H
HexToString 已提交
268 269 270 271 272 273 274 275 276 277
    // every single brpc thread corresponds to all the DBReloadableInferEngines.
    // each request runs all models in 1-single brpc thread.
    // every single brpc thread will create or clone N predictor.
    // N = the number of Model.
    // so if there are 2 models, and --thread 10.
    // each brpc thread will create predictor of Model-1 and Model-2.
    // there are totally 10 predictors of Model-1 and 10 predictors of Model-2
    // cause there are 10 brpc threads.

    // IF bsf Task thread is used。
278
    // there will be a ThreadPool called bsf TaskExecutor.
H
HexToString 已提交
279 280 281 282 283 284
    // TaskExecutorVector is the vector of TaskExecutor.
    // the number of TaskExecutor equals to the number of Model.
    // 1 TaskExecutor corresponding to 1 Model.
    // 1 TaskExecutor have N bsf threads.
    // 1 bsf thread corresponds to 1 predictor of
    // the Model corresponding to the TaskExecutor.
285 286 287 288 289 290
    // brpc thread only put the data into the task_queue(which is in
    // TaskExecutor)
    // EngineCore->infer() is running in bsf Task thread.

    // MempoolWrapper::instance() is actually a Thread-Local Mempool.
    // so it belongs to a single Thread.
W
wangguibao 已提交
291 292 293 294
    return 0;
  }

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

W
wangguibao 已提交
296 297 298 299 300
  int proc_finalize_impl() {
    THREAD_KEY_DELETE(_skey);
    THREAD_MUTEX_DESTROY(&_mutex);
    return 0;
  }
W
wangguibao 已提交
301

W
wangguibao 已提交
302 303 304 305 306 307
  EngineCore* get_core() {
    ModelData<EngineCore>* md =
        (ModelData<EngineCore>*)THREAD_GETSPECIFIC(_skey);
    if (!md) {
      LOG(ERROR) << "Failed get thread specific data";
      return NULL;
W
wangguibao 已提交
308
    }
W
wangguibao 已提交
309 310
    return md->cores[md->current_idx];
  }
W
wangguibao 已提交
311

W
wangguibao 已提交
312 313 314 315
 protected:
  THREAD_KEY_T _skey;
  THREAD_MUTEX_T _mutex;
  std::vector<ModelData<EngineCore>*> _reload_vec;
316
  int gpu_index = 0;
W
wangguibao 已提交
317
};
W
wangguibao 已提交
318

W
wangguibao 已提交
319 320 321 322 323 324 325
// 多个EngineCore共用同一份模型数据
template <typename EngineCore>
class CloneDBReloadableInferEngine
    : public DBReloadableInferEngine<EngineCore> {
 public:
  virtual ~CloneDBReloadableInferEngine() {}

326 327 328 329 330
  // 进程初始化会调用load,但由于未执行线程初始化,所以_reload_vec为空,不再继续执行。
  // 热加载的话会调用load,由于线程已经初始化,_reload_vec不为空,所以继续执行load_data操作加载数据。
  // 线程初始化会执行load_data操作加载数据,然后将engine加入_reload_vec中。
  // 每个模型只有一个CloneDBReloadableInferEngine对象。
  // 但一个CloneDBReloadableInferEngine对象,可以包含N个EngineCore。
W
wangguibao 已提交
331

332 333 334 335 336
  virtual int load_data(ModelData<EngineCore>* md,
                        const configure::EngineDesc& conf) {
    uint32_t next_idx = (md->current_idx + 1) % 2;
    if (md->cores[next_idx]) {
      delete md->cores[next_idx];
W
wangguibao 已提交
337
    }
338
    md->cores[next_idx] = new (std::nothrow) EngineCore;
W
wangguibao 已提交
339

340
    // params.dump();
H
HexToString 已提交
341 342 343 344 345
    // gpu_ids_num > 0 is always true.
    // if use CPU, gpu_ids = [-1].
    // if gpu_ids_num = 0, which means no gpuid is given.
    // so we should set gpu_ids_num = 1, and gpu_id = -1.
    // so that we can create at least 1 predictor.
346 347 348 349 350 351
    size_t gpu_ids_num = conf.gpu_ids_size();
    im::bsf::AutoMutex lock(DBReloadableInferEngine<EngineCore>::_mutex);
    int gpu_id = -1;
    if (gpu_ids_num > 0) {
      gpu_id = conf.gpu_ids(DBReloadableInferEngine<EngineCore>::gpu_index %
                            gpu_ids_num);
H
HexToString 已提交
352 353
    } else {
      gpu_ids_num = 1;
W
wangguibao 已提交
354
    }
355
    // gpu_index will be set to be 0, when load() or proc_initial() is called.
H
HexToString 已提交
356 357
    // gpu_index < gpu_ids_num, means there are predictors still not create
    // on some GPU card.
358 359 360 361 362 363 364
    // so we need to create the predictor.
    // gpu_index >= gpu_ids_num, means each GPU card has already create one.
    // so we need to clone the predictor.
    if (DBReloadableInferEngine<EngineCore>::gpu_index < gpu_ids_num) {
      if (!md->cores[next_idx] ||
          md->cores[next_idx]->create(conf, gpu_id) != 0) {
        LOG(ERROR) << "Failed create model, path: " << conf.model_dir();
W
wangguibao 已提交
365 366
        return -1;
      }
367 368 369 370 371 372 373 374 375
      DBReloadableInferEngine<EngineCore>::gpu_index++;
      md->current_idx = next_idx;
      if (_cloneTemplate.size() <
          DBReloadableInferEngine<EngineCore>::gpu_index) {
        _cloneTemplate.push_back(md);
      } else {
        _cloneTemplate[DBReloadableInferEngine<EngineCore>::gpu_index - 1] = md;
      }
    } else {
H
HexToString 已提交
376 377
      int template_index = DBReloadableInferEngine<EngineCore>::gpu_index %
                           _cloneTemplate.size();
378
      if (!md->cores[next_idx] ||
H
HexToString 已提交
379 380
          md->cores[next_idx]->clone(_cloneTemplate[template_index]->get()) !=
              0) {
381 382 383 384 385 386 387
        LOG(ERROR) << "Failed clone model from core";
        return -1;
      }
      DBReloadableInferEngine<EngineCore>::gpu_index++;
      md->current_idx = next_idx;
      LOG(WARNING) << "core clone model succ, cur_idx[" << md->current_idx
                   << "].";
W
wangguibao 已提交
388 389
    }

W
wangguibao 已提交
390 391
    return 0;
  }
W
wangguibao 已提交
392

W
wangguibao 已提交
393
 protected:
394
  // 模板EngineCore,如果已创建,则多个线程级EngineCore共用该对象的模型数据
H
HexToString 已提交
395
  std::vector<ModelData<EngineCore>*> _cloneTemplate;
W
wangguibao 已提交
396 397
};

H
HexToString 已提交
398
template <typename EngineCore>
M
bug fix  
MRXLT 已提交
399
#ifdef WITH_TRT
H
HexToString 已提交
400
class FluidInferEngine : public DBReloadableInferEngine<EngineCore> {
M
bug fix  
MRXLT 已提交
401
#else
H
HexToString 已提交
402
class FluidInferEngine : public CloneDBReloadableInferEngine<EngineCore> {
M
bug fix  
MRXLT 已提交
403 404
#endif
 public:  // NOLINT
W
wangguibao 已提交
405 406
  FluidInferEngine() {}
  ~FluidInferEngine() {}
H
HexToString 已提交
407
  typedef std::vector<paddle::PaddleTensor> TensorVector;
H
HexToString 已提交
408
  int infer_impl(const void* in, void* out, uint32_t batch_size = -1) {
H
HexToString 已提交
409 410 411
    // First of all, get the real core acording to the
    // Template parameter <EngineCore>.
    EngineCore* core = DBReloadableInferEngine<EngineCore>::get_core();
W
wangguibao 已提交
412 413 414
    if (!core || !core->get()) {
      LOG(ERROR) << "Failed get fluid core in infer_impl()";
      return -1;
W
wangguibao 已提交
415
    }
H
HexToString 已提交
416 417 418 419 420 421
    // We use the for loop to process the input data.
    // Inside each for loop, use the in[i]->name as inputName and call
    // 'core->GetInputHandle(inputName)' to get the pointer of InputData.
    // Set the lod and shape information of InputData first.
    // Then copy data from cpu to the core.
    const TensorVector* tensorVector_in_pointer =
422 423
        reinterpret_cast<const TensorVector*>(in);
    for (int i = 0; i < tensorVector_in_pointer->size(); ++i) {
H
HexToString 已提交
424
      auto lod_tensor_in =
425
          core->GetInputHandle((*tensorVector_in_pointer)[i].name);
H
HexToString 已提交
426 427 428
      lod_tensor_in->SetLoD((*tensorVector_in_pointer)[i].lod);
      lod_tensor_in->Reshape((*tensorVector_in_pointer)[i].shape);
      void* origin_data = (*tensorVector_in_pointer)[i].data.data();
H
HexToString 已提交
429 430 431 432
      // Because the core needs to determine the size of memory space
      // according to the data type passed in.
      // The pointer type of data must be one of
      // float *,int64_t*,int32_t* instead void*.
H
HexToString 已提交
433
      if ((*tensorVector_in_pointer)[i].dtype == paddle::PaddleDType::FLOAT32) {
H
HexToString 已提交
434
        float* data = static_cast<float*>(origin_data);
H
HexToString 已提交
435
        lod_tensor_in->CopyFromCpu(data);
H
HexToString 已提交
436
      } else if ((*tensorVector_in_pointer)[i].dtype ==
437
                 paddle::PaddleDType::INT64) {
H
HexToString 已提交
438
        int64_t* data = static_cast<int64_t*>(origin_data);
H
HexToString 已提交
439
        lod_tensor_in->CopyFromCpu(data);
H
HexToString 已提交
440
      } else if ((*tensorVector_in_pointer)[i].dtype ==
441
                 paddle::PaddleDType::INT32) {
H
HexToString 已提交
442
        int32_t* data = static_cast<int32_t*>(origin_data);
H
HexToString 已提交
443
        lod_tensor_in->CopyFromCpu(data);
H
HexToString 已提交
444
      }
W
wangjiawei04 已提交
445
    }
H
HexToString 已提交
446 447
    // After the input data is passed in,
    // call 'core->Run()' perform the prediction process.
W
wangjiawei04 已提交
448
    if (!core->Run()) {
449 450
      LOG(ERROR) << "Failed run fluid family core";
      return -1;
W
wangjiawei04 已提交
451
    }
H
HexToString 已提交
452 453 454 455
    // In order to get the results,
    // first, call the 'core->GetOutputNames()' to get the name of output
    // (which is a dict like {OutputName:pointer of OutputValue}).
    // Then, use for-loop to get OutputValue by calling 'core->GetOutputHandle'.
H
HexToString 已提交
456
    std::vector<std::string> outnames = core->GetOutputNames();
H
HexToString 已提交
457
    std::vector<int> output_shape;
H
HexToString 已提交
458 459
    int out_num = 0;
    int dataType = 0;
H
HexToString 已提交
460 461 462
    void* databuf_data = NULL;
    char* databuf_char = NULL;
    size_t databuf_size = 0;
H
HexToString 已提交
463
    TensorVector* tensorVector_out_pointer =
464
        reinterpret_cast<TensorVector*>(out);
H
HexToString 已提交
465
    if (!tensorVector_out_pointer) {
H
HexToString 已提交
466
      LOG(ERROR) << "tensorVector_out_pointer is nullptr,error";
W
wangguibao 已提交
467 468
      return -1;
    }
H
HexToString 已提交
469 470 471 472
    // Get the type and shape information of OutputData first.
    // then copy data to cpu from the core.
    // The pointer type of data_out must be one of
    // float *,int64_t*,int32_t* instead void*.
473
    for (int i = 0; i < outnames.size(); ++i) {
H
HexToString 已提交
474
      auto lod_tensor_out = core->GetOutputHandle(outnames[i]);
H
HexToString 已提交
475
      output_shape = lod_tensor_out->shape();
H
HexToString 已提交
476 477
      out_num = std::accumulate(
          output_shape.begin(), output_shape.end(), 1, std::multiplies<int>());
H
HexToString 已提交
478
      dataType = lod_tensor_out->type();
H
HexToString 已提交
479
      if (dataType == paddle::PaddleDType::FLOAT32) {
480
        databuf_size = out_num * sizeof(float);
H
HexToString 已提交
481
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
H
HexToString 已提交
482
        if (!databuf_data) {
483 484
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
H
HexToString 已提交
485 486
        }
        float* data_out = reinterpret_cast<float*>(databuf_data);
H
HexToString 已提交
487
        lod_tensor_out->CopyToCpu(data_out);
H
HexToString 已提交
488
        databuf_char = reinterpret_cast<char*>(data_out);
H
HexToString 已提交
489
      } else if (dataType == paddle::PaddleDType::INT64) {
490
        databuf_size = out_num * sizeof(int64_t);
H
HexToString 已提交
491
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
H
HexToString 已提交
492
        if (!databuf_data) {
493 494
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
H
HexToString 已提交
495
        }
H
HexToString 已提交
496
        int64_t* data_out = reinterpret_cast<int64_t*>(databuf_data);
H
HexToString 已提交
497
        lod_tensor_out->CopyToCpu(data_out);
H
HexToString 已提交
498
        databuf_char = reinterpret_cast<char*>(data_out);
H
HexToString 已提交
499
      } else if (dataType == paddle::PaddleDType::INT32) {
500
        databuf_size = out_num * sizeof(int32_t);
H
HexToString 已提交
501
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
H
HexToString 已提交
502
        if (!databuf_data) {
503 504
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
H
HexToString 已提交
505 506 507 508
        }
        int32_t* data_out = reinterpret_cast<int32_t*>(databuf_data);
        lod_tensor_out->CopyToCpu(data_out);
        databuf_char = reinterpret_cast<char*>(data_out);
H
HexToString 已提交
509
      }
H
HexToString 已提交
510 511 512 513 514
      // Because task scheduling requires OPs to use 'Channel'
      // (which is a data structure) to transfer data between OPs.
      // We need to copy the processed data to the 'Channel' for the next OP.
      // In this function, it means we should copy the 'databuf_char' to
      // 'void* out'.(which is also called ‘tensorVector_out_pointer’)
H
HexToString 已提交
515 516 517 518 519
      paddle::PaddleTensor tensor_out;
      tensor_out.name = outnames[i];
      tensor_out.dtype = paddle::PaddleDType(dataType);
      tensor_out.shape.assign(output_shape.begin(), output_shape.end());
      std::vector<std::vector<size_t>> out_lod = lod_tensor_out->lod();
520
      for (int li = 0; li < out_lod.size(); ++li) {
H
HexToString 已提交
521 522 523 524
        std::vector<size_t> lod_element;
        lod_element.assign(out_lod[li].begin(), out_lod[li].end());
        tensor_out.lod.push_back(lod_element);
      }
H
HexToString 已提交
525
      paddle::PaddleBuf paddleBuf(databuf_char, databuf_size);
H
HexToString 已提交
526 527
      tensor_out.data = paddleBuf;
      tensorVector_out_pointer->push_back(tensor_out);
H
HexToString 已提交
528
    }
W
wangguibao 已提交
529 530
    return 0;
  }
H
HexToString 已提交
531

532 533
  int task_infer_impl(const void* in, void* out) {  // NOLINT
    return infer_impl(in, out);
H
HexToString 已提交
534
  }
W
wangguibao 已提交
535 536
};

W
wangguibao 已提交
537 538 539 540 541 542 543
typedef FactoryPool<InferEngine> StaticInferFactory;

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

544
  int proc_initialize(const configure::EngineDesc& conf);
W
wangguibao 已提交
545

546
  int proc_initialize(const configure::EngineDesc& conf, bool version);
W
wangguibao 已提交
547

548
  int proc_finalize();
W
wangguibao 已提交
549

550
  int thrd_initialize();
W
wangguibao 已提交
551

552
  int thrd_clear();
W
wangguibao 已提交
553

554
  int thrd_finalize();
W
wangguibao 已提交
555

556
  int reload();
W
wangguibao 已提交
557

558
  uint64_t version() const;
W
wangguibao 已提交
559 560

  // inference interface
561
  InferEngine* default_engine() const;
W
wangguibao 已提交
562

563
  int infer(const void* in, void* out, uint32_t batch_size);
W
wangguibao 已提交
564 565

  template <typename T>
566
  T* get_core();
W
wangguibao 已提交
567 568

  // versioned inference interface
569
  int infer(const void* in, void* out, uint32_t batch_size, uint64_t version);
W
wangguibao 已提交
570 571

  template <typename T>
572
  T* get_core(uint64_t version);
W
wangguibao 已提交
573

574
  int proc_initialize_impl(const configure::EngineDesc& conf, bool);
W
wangguibao 已提交
575

576 577 578 579 580 581 582 583 584 585
  int thrd_initialize_impl();

  int thrd_finalize_impl();

  int thrd_clear_impl();

  int proc_finalize_impl();

  int infer_impl(const void* in, void* out, uint32_t batch_size = -1);

586
  int task_infer_impl(const void* in, void* out);
W
wangguibao 已提交
587 588 589

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

W
wangguibao 已提交
592 593 594 595 596 597 598
class InferManager {
 public:
  static InferManager& instance() {
    static InferManager ins;
    return ins;
  }

H
HexToString 已提交
599 600 601
  int proc_initialize(const char* path,
                      const char* file,
                      std::shared_ptr<int> engine_index_ptr);
W
wangguibao 已提交
602

603
  int thrd_initialize();
W
wangguibao 已提交
604

605
  int thrd_clear();
W
wangguibao 已提交
606

607
  int reload();
W
wangguibao 已提交
608

609
  int thrd_finalize();
W
wangguibao 已提交
610

611
  int proc_finalize();
W
wangguibao 已提交
612 613

  // Inference interface
H
HexToString 已提交
614 615 616
  int infer(const char* model_name,
            const void* in,
            void* out,
617
            uint32_t batch_size = -1);
W
wangguibao 已提交
618 619

  template <typename T>
620
  T* get_core(const char* model_name);
W
wangguibao 已提交
621 622

  // Versioned inference interface
H
HexToString 已提交
623
  int infer(const char* model_name,
H
HexToString 已提交
624 625 626
            const void* in,
            void* out,
            uint32_t batch_size,
627
            uint64_t version);
W
wangguibao 已提交
628 629

  template <typename T>
630
  T* get_core(const char* model_name, uint64_t version);
W
wangguibao 已提交
631

632
  int query_version(const std::string& model, uint64_t& version);
W
wangguibao 已提交
633 634 635 636

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

W
wangguibao 已提交
638 639 640
}  // namespace predictor
}  // namespace paddle_serving
}  // namespace baidu