infer.h 27.1 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>
T
TeslaZhao 已提交
18
#include <sys/syscall.h>
W
wangguibao 已提交
19
#include <sys/types.h>
W
wangguibao 已提交
20
#include <unistd.h>
H
HexToString 已提交
21
#include <functional>
H
HexToString 已提交
22
#include <memory>
23
#include <numeric>
W
wangguibao 已提交
24
#include <string>
M
MRXLT 已提交
25
#include <utility>
W
wangguibao 已提交
26
#include <vector>
G
guru4elephant 已提交
27
#include "core/predictor/common/inner_common.h"
H
HexToString 已提交
28
#include "core/predictor/framework/bsf.h"
T
TeslaZhao 已提交
29
#include "core/predictor/framework/cache.h"
G
guru4elephant 已提交
30 31
#include "core/predictor/framework/factory.h"
#include "core/predictor/framework/infer_data.h"
32
#include "core/predictor/framework/memory.h"
S
ShiningZhang 已提交
33
#include "core/predictor/framework/predictor_metric.h"
H
HexToString 已提交
34
#include "paddle_inference_api.h"  // NOLINT
35 36
//#include "experimental/float16.h"
#include "experimental/phi/common/float16.h"
W
wangguibao 已提交
37 38 39 40
namespace baidu {
namespace paddle_serving {
namespace predictor {

W
wangguibao 已提交
41 42
using configure::ModelToolkitConf;

T
TeslaZhao 已提交
43
// Auto mutex lock
Z
zhangjun 已提交
44 45 46 47 48 49 50 51 52 53 54
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;
};

T
TeslaZhao 已提交
55
// Gloabl singleton mutex lock
Z
update  
zhangjun 已提交
56
class GlobalCreateMutex {
Z
zhangjun 已提交
57 58 59 60
 public:
  pthread_mutex_t& mutex() { return _mut; }

  static pthread_mutex_t& instance() {
Z
update  
zhangjun 已提交
61
    static GlobalCreateMutex gmutex;
Z
zhangjun 已提交
62 63 64 65
    return gmutex.mutex();
  }

 private:
Z
update  
zhangjun 已提交
66
  GlobalCreateMutex() { pthread_mutex_init(&_mut, NULL); }
Z
zhangjun 已提交
67 68 69
  pthread_mutex_t _mut;
};

T
TeslaZhao 已提交
70
// InferEngine
W
wangguibao 已提交
71
class InferEngine {
W
wangguibao 已提交
72 73 74 75 76 77 78 79 80 81
 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 已提交
82 83 84
  virtual int infer(const void* in, void* out, uint32_t batch_size = -1) {
    return infer_impl(in, out, batch_size);
  }
H
HexToString 已提交
85
  virtual void set_model_index(uint32_t index) { _model_index = index; }
W
wangguibao 已提交
86 87 88 89 90 91 92 93 94 95 96
  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 已提交
97
  virtual int infer_impl(const void* in,
98 99
                         void* out,
                         uint32_t batch_size = -1) = 0;
100
  virtual int task_infer_impl(const void* in, void* out) = 0;  // NOLINT
T
TeslaZhao 已提交
101
  virtual CubeCache* get_cube_cache() = 0;
H
HexToString 已提交
102

H
HexToString 已提交
103 104
 protected:
  uint32_t _model_index;
W
wangguibao 已提交
105 106
  // end: framework inner call
};
T
TeslaZhao 已提交
107

H
HexToString 已提交
108
typedef im::bsf::Task<paddle::PaddleTensor, paddle::PaddleTensor> TaskT;
W
wangguibao 已提交
109 110 111
class ReloadableInferEngine : public InferEngine {
 public:
  virtual ~ReloadableInferEngine() {}
W
wangguibao 已提交
112

113 114 115 116 117
  // Reloadable record
  union ReloadableRecord {
    time_t timestamp;
    uint64_t md5sum;
    uint64_t revision;
W
wangguibao 已提交
118
  };
W
wangguibao 已提交
119

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

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

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

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

128
  int thrd_initialize();
W
wangguibao 已提交
129

130
  int thrd_clear();
W
wangguibao 已提交
131

132
  int proc_finalize();
W
wangguibao 已提交
133

134
  int reload();
W
wangguibao 已提交
135 136 137

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

W
wangguibao 已提交
139
 private:
140
  int parse_version_info(const configure::EngineDesc& config, bool version);
W
wangguibao 已提交
141

142
  bool check_need_reload();
W
wangguibao 已提交
143

144
  bool check_timestamp_ne();
W
wangguibao 已提交
145

146
  bool check_timestamp_gt();
W
wangguibao 已提交
147 148 149 150 151 152

  bool check_md5sum() { return false; }

  bool check_revision() { return false; }

 protected:
153 154 155 156
  // Model directory
  std::string _model_dir;

  // The description of inference engine
Z
update  
zhangjun 已提交
157
  configure::EngineDesc _conf;
W
wangguibao 已提交
158 159

 private:
160
  // Tag file of reloadable model
W
wangguibao 已提交
161
  std::string _reload_tag_file;
162 163 164 165 166 167 168 169

  // 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 已提交
170
  uint32_t _infer_thread_num;
171 172

  // Size of inference batch
W
wangguibao 已提交
173
  uint32_t _infer_batch_size;
174 175

  // Need to align batch_size in inferring
H
HexToString 已提交
176
  bool _infer_overrun;
177

H
HexToString 已提交
178 179
  // allow to split request in inferring
  bool _allow_split_request;
180
  // model version
W
wangguibao 已提交
181 182
  uint64_t _version;
};
W
wangguibao 已提交
183

T
TeslaZhao 已提交
184
// Lock free switching two models and cube caches
W
wangguibao 已提交
185 186 187
template <typename EngineCore>
struct ModelData {
  ModelData() : current_idx(1) {
T
TeslaZhao 已提交
188 189
    cores[0] = nullptr;
    cores[1] = nullptr;
T
TeslaZhao 已提交
190 191
    caches[0] = nullptr;
    caches[1] = nullptr;
W
wangguibao 已提交
192 193 194 195 196
  }

  ~ModelData() {
    delete cores[0];
    delete cores[1];
T
TeslaZhao 已提交
197 198
    delete caches[0];
    delete caches[1];
W
wangguibao 已提交
199 200
  }

T
TeslaZhao 已提交
201 202
  void* get_core() { return cores[current_idx]->get(); }

T
TeslaZhao 已提交
203
  CubeCache* get_cache() { return caches[current_idx]; }
204

W
wangguibao 已提交
205
  EngineCore* cores[2];
T
TeslaZhao 已提交
206
  CubeCache* caches[2];
W
wangguibao 已提交
207 208 209 210 211 212 213 214 215 216 217
  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);
T
TeslaZhao 已提交
218
    _gpu_index = 0;
W
wangguibao 已提交
219 220 221
    return ReloadableInferEngine::proc_initialize(conf, version);
  }

222 223 224 225 226
  // 进程初始化会调用load,但由于未执行线程初始化,所以_reload_vec为空,不再继续执行。
  // 热加载的话会调用load,由于线程已经初始化,_reload_vec不为空,所以继续执行load_data操作加载数据。
  // 线程初始化会执行load_data操作加载数据,然后将engine加入_reload_vec中。
  // 每个模型只有一个CloneDBReloadableInferEngine对象。
  // 但一个CloneDBReloadableInferEngine对象,可以包含N个EngineCore。
Z
update  
zhangjun 已提交
227
  virtual int load(const configure::EngineDesc& conf) {
W
wangguibao 已提交
228 229
    if (_reload_vec.empty()) {
      return 0;
W
wangguibao 已提交
230
    }
T
TeslaZhao 已提交
231
    _gpu_index = 0;
W
wangguibao 已提交
232
    for (uint32_t ti = 0; ti < _reload_vec.size(); ++ti) {
Z
update  
zhangjun 已提交
233
      if (load_data(_reload_vec[ti], conf) != 0) {
W
wangguibao 已提交
234 235 236 237 238
        LOG(ERROR) << "Failed reload engine model: " << ti;
        return -1;
      }
    }

Z
update  
zhangjun 已提交
239
    LOG(WARNING) << "Succ load engine, path: " << conf.model_dir();
S
ShiningZhang 已提交
240
    RequestCache::GetSingleton()->Clear();
W
wangguibao 已提交
241 242
    return 0;
  }
W
wangguibao 已提交
243

244 245
  virtual int load_data(ModelData<EngineCore>* md,
                        const configure::EngineDesc& conf) {
W
wangguibao 已提交
246
    uint32_t next_idx = (md->current_idx + 1) % 2;
T
TeslaZhao 已提交
247 248

    // reload engine core
W
wangguibao 已提交
249 250
    if (md->cores[next_idx]) {
      delete md->cores[next_idx];
W
wangguibao 已提交
251
    }
W
wangguibao 已提交
252
    md->cores[next_idx] = new (std::nothrow) EngineCore;
T
TeslaZhao 已提交
253 254 255 256
    if (nullptr == md->cores[next_idx]) {
      LOG(ERROR) << "Allocating memory failed. ";
      return -1;
    }
257 258 259 260
    size_t gpu_ids_num = conf.gpu_ids_size();
    im::bsf::AutoMutex lock(_mutex);
    int gpu_id = -1;
    if (gpu_ids_num > 0) {
T
TeslaZhao 已提交
261
      gpu_id = conf.gpu_ids(_gpu_index % gpu_ids_num);
262
    }
T
TeslaZhao 已提交
263
    LOG(WARNING) << "Loading EngineCore[" << next_idx << "] ...";
264 265
    if (!md->cores[next_idx] ||
        md->cores[next_idx]->create(conf, gpu_id) != 0) {
Z
update  
zhangjun 已提交
266
      LOG(ERROR) << "Failed create model, path: " << conf.model_dir();
W
wangguibao 已提交
267
      return -1;
W
wangguibao 已提交
268
    }
T
TeslaZhao 已提交
269
    _gpu_index++;
T
TeslaZhao 已提交
270
    LOG(WARNING) << "Loading EngineCore[" << next_idx << "] done.";
T
TeslaZhao 已提交
271 272

    // reload cube cache
T
TeslaZhao 已提交
273 274 275 276 277 278 279 280 281
    if (nullptr == md->caches[next_idx]) {
      md->caches[next_idx] = new (std::nothrow) CubeCache;
    }

    if (nullptr == md->caches[next_idx]) {
      LOG(ERROR) << "Allocating memory failed.";
      return -1;
    }
    LOG(WARNING) << "Loading cube cache[" << next_idx << "] ...";
T
TeslaZhao 已提交
282 283
    std::string model_path = conf.model_dir();
    if (access(model_path.c_str(), F_OK) == 0) {
W
wangjiawei04 已提交
284
      std::string cube_cache_path = model_path + "/cube_cache";
T
TeslaZhao 已提交
285 286
      int reload_cache_ret = md->caches[next_idx]->reload_data(cube_cache_path);
      LOG(WARNING) << "Loading cube cache[" << next_idx << "] done.";
T
TeslaZhao 已提交
287 288 289 290 291
    } else {
      LOG(ERROR) << "model_path " << model_path
                 << " is not exits. Ignore cube cache!";
    }

T
TeslaZhao 已提交
292
    // switch current_idx
W
wangguibao 已提交
293
    md->current_idx = next_idx;
T
TeslaZhao 已提交
294 295 296
    LOG(WARNING)
        << "Reload model and cube cache done. switching to current_idx["
        << next_idx << "]";
W
wangguibao 已提交
297 298
    return 0;
  }
W
wangguibao 已提交
299

W
wangguibao 已提交
300 301
  virtual int thrd_initialize_impl() {
    ModelData<EngineCore>* md = new (std::nothrow) ModelData<EngineCore>;
Z
update  
zhangjun 已提交
302
    if (!md || load_data(md, _conf) != 0) {
303
      LOG(ERROR) << "Failed create thread data from " << _conf.model_dir();
W
wangguibao 已提交
304
      return -1;
W
wangguibao 已提交
305 306
    }

W
wangguibao 已提交
307
    THREAD_SETSPECIFIC(_skey, md);
H
HexToString 已提交
308
    im::bsf::AutoMutex lock(_mutex);
W
wangguibao 已提交
309 310 311 312 313
    _reload_vec.push_back(md);
    return 0;
  }

  int thrd_clear_impl() {
314 315 316 317
    // 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 已提交
318 319 320 321 322 323 324 325 326 327
    // 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。
328
    // there will be a ThreadPool called bsf TaskExecutor.
H
HexToString 已提交
329 330 331 332 333 334
    // 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.
335 336 337 338 339 340
    // 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 已提交
341 342 343 344
    return 0;
  }

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

W
wangguibao 已提交
346 347 348 349 350
  int proc_finalize_impl() {
    THREAD_KEY_DELETE(_skey);
    THREAD_MUTEX_DESTROY(&_mutex);
    return 0;
  }
W
wangguibao 已提交
351

W
wangguibao 已提交
352 353 354 355 356 357
  EngineCore* get_core() {
    ModelData<EngineCore>* md =
        (ModelData<EngineCore>*)THREAD_GETSPECIFIC(_skey);
    if (!md) {
      LOG(ERROR) << "Failed get thread specific data";
      return NULL;
W
wangguibao 已提交
358
    }
W
wangguibao 已提交
359 360
    return md->cores[md->current_idx];
  }
W
wangguibao 已提交
361

T
TeslaZhao 已提交
362 363 364 365 366 367 368 369 370 371
  CubeCache* get_cube_cache() {
    ModelData<EngineCore>* md =
        (ModelData<EngineCore>*)THREAD_GETSPECIFIC(_skey);
    if (!md) {
      LOG(ERROR) << "Failed get thread specific data";
      return NULL;
    }
    return md->get_cache();
  }

W
wangguibao 已提交
372 373 374
 protected:
  THREAD_KEY_T _skey;
  THREAD_MUTEX_T _mutex;
T
TeslaZhao 已提交
375 376

  // vector of all model engines
W
wangguibao 已提交
377
  std::vector<ModelData<EngineCore>*> _reload_vec;
T
TeslaZhao 已提交
378 379 380

  // gpu card id
  int _gpu_index = 0;
W
wangguibao 已提交
381
};
W
wangguibao 已提交
382

W
wangguibao 已提交
383 384 385 386 387 388 389
// 多个EngineCore共用同一份模型数据
template <typename EngineCore>
class CloneDBReloadableInferEngine
    : public DBReloadableInferEngine<EngineCore> {
 public:
  virtual ~CloneDBReloadableInferEngine() {}

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

396 397
  virtual int load_data(ModelData<EngineCore>* md,
                        const configure::EngineDesc& conf) {
T
TeslaZhao 已提交
398
    int tid = syscall(SYS_gettid);
399 400 401
    uint32_t next_idx = (md->current_idx + 1) % 2;
    if (md->cores[next_idx]) {
      delete md->cores[next_idx];
W
wangguibao 已提交
402
    }
403
    md->cores[next_idx] = new (std::nothrow) EngineCore;
W
wangguibao 已提交
404

T
TeslaZhao 已提交
405 406 407 408 409 410 411
    if (nullptr == md->caches[next_idx]) {
      md->caches[next_idx] = new (std::nothrow) CubeCache;
    }
    if (nullptr == md->cores[next_idx] || nullptr == md->caches[next_idx]) {
      LOG(ERROR) << "Allocating memory fail.";
      return -1;
    }
412
    // params.dump();
H
HexToString 已提交
413 414 415 416 417
    // 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.
418 419 420 421
    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) {
T
TeslaZhao 已提交
422
      gpu_id = conf.gpu_ids(DBReloadableInferEngine<EngineCore>::_gpu_index %
423
                            gpu_ids_num);
H
HexToString 已提交
424 425
    } else {
      gpu_ids_num = 1;
W
wangguibao 已提交
426
    }
T
TeslaZhao 已提交
427

T
TeslaZhao 已提交
428 429
    // _gpu_index will be set to be 0, when load() or proc_initial() is called.
    // _gpu_index < gpu_ids_num, means there are predictors still not create
H
HexToString 已提交
430
    // on some GPU card.
431
    // so we need to create the predictor.
T
TeslaZhao 已提交
432
    // _gpu_index >= gpu_ids_num, means each GPU card has already create one.
433
    // so we need to clone the predictor.
T
TeslaZhao 已提交
434
    LOG(WARNING) << "tid:" << tid << " Loading clone model ...";
T
TeslaZhao 已提交
435
    if (DBReloadableInferEngine<EngineCore>::_gpu_index < gpu_ids_num) {
T
TeslaZhao 已提交
436 437
      // create cores
      if (md->cores[next_idx]->create(conf, gpu_id) != 0) {
438
        LOG(ERROR) << "Failed create model, path: " << conf.model_dir();
W
wangguibao 已提交
439 440
        return -1;
      }
T
TeslaZhao 已提交
441 442 443
      // create caches
      std::string model_path = conf.model_dir();
      if (access(model_path.c_str(), F_OK) == 0) {
W
wangjiawei04 已提交
444
        std::string cube_cache_path = model_path + "/cube_cache";
T
TeslaZhao 已提交
445 446 447 448 449 450 451 452
        int reload_cache_ret =
            md->caches[next_idx]->reload_data(cube_cache_path);
        LOG(WARNING) << "create cube cache[" << next_idx << "] done.";
      } else {
        LOG(WARNING) << "model_path " << model_path
                     << " is not exits. Ignore cube cache!";
      }

T
TeslaZhao 已提交
453
      DBReloadableInferEngine<EngineCore>::_gpu_index++;
T
TeslaZhao 已提交
454
      // md->current_idx = next_idx;
455
      if (_cloneTemplate.size() <
T
TeslaZhao 已提交
456
          DBReloadableInferEngine<EngineCore>::_gpu_index) {
457 458
        _cloneTemplate.push_back(md);
      } else {
T
TeslaZhao 已提交
459 460
        _cloneTemplate[DBReloadableInferEngine<EngineCore>::_gpu_index - 1] =
            md;
461 462
      }
    } else {
T
TeslaZhao 已提交
463
      int template_index = DBReloadableInferEngine<EngineCore>::_gpu_index %
H
HexToString 已提交
464
                           _cloneTemplate.size();
T
TeslaZhao 已提交
465 466 467

      // clone cores
      if (md->cores[next_idx]->clone(
T
TeslaZhao 已提交
468
              _cloneTemplate[template_index]->get_core()) != 0) {
469 470 471
        LOG(ERROR) << "Failed clone model from core";
        return -1;
      }
T
TeslaZhao 已提交
472 473 474 475
      // clone caches
      md->caches[next_idx] = _cloneTemplate[template_index]->get_cache();
      LOG(WARNING) << "tid:" << tid << " clone caches done";

T
TeslaZhao 已提交
476
      DBReloadableInferEngine<EngineCore>::_gpu_index++;
W
wangguibao 已提交
477 478
    }

T
TeslaZhao 已提交
479 480 481 482 483 484 485
    // switch current_idx
    md->current_idx = next_idx;
    LOG(WARNING)
        << "[" << tid
        << "] Reload clone model and cube cache done. switching to current_idx["
        << next_idx << "]";

W
wangguibao 已提交
486 487
    return 0;
  }
W
wangguibao 已提交
488

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

H
HexToString 已提交
494
template <typename EngineCore>
M
bug fix  
MRXLT 已提交
495
#ifdef WITH_TRT
H
HexToString 已提交
496
class FluidInferEngine : public DBReloadableInferEngine<EngineCore> {
M
bug fix  
MRXLT 已提交
497
#else
H
HexToString 已提交
498
class FluidInferEngine : public CloneDBReloadableInferEngine<EngineCore> {
M
bug fix  
MRXLT 已提交
499 500
#endif
 public:  // NOLINT
W
wangguibao 已提交
501 502
  FluidInferEngine() {}
  ~FluidInferEngine() {}
H
HexToString 已提交
503
  typedef std::vector<paddle::PaddleTensor> TensorVector;
H
HexToString 已提交
504
  int infer_impl(const void* in, void* out, uint32_t batch_size = -1) {
S
ShiningZhang 已提交
505 506 507
    struct timeval tv;
    gettimeofday(&tv, NULL);
    long start = tv.tv_sec * 1000000 + tv.tv_usec;
H
HexToString 已提交
508 509 510
    // First of all, get the real core acording to the
    // Template parameter <EngineCore>.
    EngineCore* core = DBReloadableInferEngine<EngineCore>::get_core();
W
wangguibao 已提交
511 512 513
    if (!core || !core->get()) {
      LOG(ERROR) << "Failed get fluid core in infer_impl()";
      return -1;
W
wangguibao 已提交
514
    }
H
HexToString 已提交
515 516 517 518 519 520
    // 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 =
521 522
        reinterpret_cast<const TensorVector*>(in);
    for (int i = 0; i < tensorVector_in_pointer->size(); ++i) {
H
HexToString 已提交
523
      auto lod_tensor_in =
524
          core->GetInputHandle((*tensorVector_in_pointer)[i].name);
H
HexToString 已提交
525 526 527
      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 已提交
528 529 530 531
      // 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 已提交
532
      if ((*tensorVector_in_pointer)[i].dtype == paddle::PaddleDType::FLOAT32) {
H
HexToString 已提交
533
        float* data = static_cast<float*>(origin_data);
H
HexToString 已提交
534
        lod_tensor_in->CopyFromCpu(data);
H
HexToString 已提交
535
      } else if ((*tensorVector_in_pointer)[i].dtype ==
536
                 paddle::PaddleDType::INT64) {
H
HexToString 已提交
537
        int64_t* data = static_cast<int64_t*>(origin_data);
H
HexToString 已提交
538
        lod_tensor_in->CopyFromCpu(data);
H
HexToString 已提交
539
      } else if ((*tensorVector_in_pointer)[i].dtype ==
540
                 paddle::PaddleDType::INT32) {
H
HexToString 已提交
541
        int32_t* data = static_cast<int32_t*>(origin_data);
H
HexToString 已提交
542
        lod_tensor_in->CopyFromCpu(data);
S
ShiningZhang 已提交
543 544 545 546 547 548 549 550
      } else if ((*tensorVector_in_pointer)[i].dtype ==
                 paddle::PaddleDType::UINT8) {
        uint8_t* data = static_cast<uint8_t*>(origin_data);
        lod_tensor_in->CopyFromCpu(data);
      } else if ((*tensorVector_in_pointer)[i].dtype ==
                 paddle::PaddleDType::INT8) {
        int8_t* data = static_cast<int8_t*>(origin_data);
        lod_tensor_in->CopyFromCpu(data);
S
ShiningZhang 已提交
551
      } else if ((*tensorVector_in_pointer)[i].dtype ==
552 553 554
                 paddle::PaddleDType::FLOAT16) {
        phi::dtype::float16* data =
            static_cast<phi::dtype::float16*>(origin_data);
S
ShiningZhang 已提交
555
        lod_tensor_in->CopyFromCpu(data);
S
ShiningZhang 已提交
556 557
      } else {
        LOG(ERROR) << "Inference not support type["
558 559 560
                   << (*tensorVector_in_pointer)[i].dtype << "],name["
                   << (*tensorVector_in_pointer)[i].name << "]"
                   << " copy into core failed!";
H
HexToString 已提交
561
      }
S
ShiningZhang 已提交
562 563 564
      VLOG(2) << "Tensor:name=" << (*tensorVector_in_pointer)[i].name
              << ";in_dtype=" << (*tensorVector_in_pointer)[i].dtype
              << ";tensor_dtype=" << lod_tensor_in->type();
W
wangjiawei04 已提交
565
    }
H
HexToString 已提交
566 567
    // After the input data is passed in,
    // call 'core->Run()' perform the prediction process.
W
wangjiawei04 已提交
568
    if (!core->Run()) {
569 570
      LOG(ERROR) << "Failed run fluid family core";
      return -1;
W
wangjiawei04 已提交
571
    }
H
HexToString 已提交
572 573 574 575
    // 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 已提交
576
    std::vector<std::string> outnames = core->GetOutputNames();
H
HexToString 已提交
577
    std::vector<int> output_shape;
H
HexToString 已提交
578 579
    int out_num = 0;
    int dataType = 0;
H
HexToString 已提交
580 581 582
    void* databuf_data = NULL;
    char* databuf_char = NULL;
    size_t databuf_size = 0;
H
HexToString 已提交
583
    TensorVector* tensorVector_out_pointer =
584
        reinterpret_cast<TensorVector*>(out);
H
HexToString 已提交
585
    if (!tensorVector_out_pointer) {
H
HexToString 已提交
586
      LOG(ERROR) << "tensorVector_out_pointer is nullptr,error";
W
wangguibao 已提交
587 588
      return -1;
    }
H
HexToString 已提交
589 590 591 592
    // 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*.
593
    for (int i = 0; i < outnames.size(); ++i) {
H
HexToString 已提交
594
      auto lod_tensor_out = core->GetOutputHandle(outnames[i]);
H
HexToString 已提交
595
      output_shape = lod_tensor_out->shape();
H
HexToString 已提交
596 597
      out_num = std::accumulate(
          output_shape.begin(), output_shape.end(), 1, std::multiplies<int>());
H
HexToString 已提交
598
      dataType = lod_tensor_out->type();
H
HexToString 已提交
599
      if (dataType == paddle::PaddleDType::FLOAT32) {
600
        databuf_size = out_num * sizeof(float);
H
HexToString 已提交
601
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
H
HexToString 已提交
602
        if (!databuf_data) {
603 604
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
H
HexToString 已提交
605 606
        }
        float* data_out = reinterpret_cast<float*>(databuf_data);
H
HexToString 已提交
607
        lod_tensor_out->CopyToCpu(data_out);
H
HexToString 已提交
608
        databuf_char = reinterpret_cast<char*>(data_out);
H
HexToString 已提交
609
      } else if (dataType == paddle::PaddleDType::INT64) {
610
        databuf_size = out_num * sizeof(int64_t);
H
HexToString 已提交
611
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
H
HexToString 已提交
612
        if (!databuf_data) {
613 614
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
H
HexToString 已提交
615
        }
H
HexToString 已提交
616
        int64_t* data_out = reinterpret_cast<int64_t*>(databuf_data);
H
HexToString 已提交
617
        lod_tensor_out->CopyToCpu(data_out);
H
HexToString 已提交
618
        databuf_char = reinterpret_cast<char*>(data_out);
H
HexToString 已提交
619
      } else if (dataType == paddle::PaddleDType::INT32) {
620
        databuf_size = out_num * sizeof(int32_t);
H
HexToString 已提交
621
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
H
HexToString 已提交
622
        if (!databuf_data) {
623 624
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
H
HexToString 已提交
625 626 627 628
        }
        int32_t* data_out = reinterpret_cast<int32_t*>(databuf_data);
        lod_tensor_out->CopyToCpu(data_out);
        databuf_char = reinterpret_cast<char*>(data_out);
S
ShiningZhang 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
      } else if (dataType == paddle::PaddleDType::UINT8) {
        databuf_size = out_num * sizeof(uint8_t);
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
        if (!databuf_data) {
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
        }
        uint8_t* data_out = reinterpret_cast<uint8_t*>(databuf_data);
        lod_tensor_out->CopyToCpu(data_out);
        databuf_char = reinterpret_cast<char*>(data_out);
      } else if (dataType == paddle::PaddleDType::INT8) {
        databuf_size = out_num * sizeof(int8_t);
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
        if (!databuf_data) {
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
        }
        int8_t* data_out = reinterpret_cast<int8_t*>(databuf_data);
        lod_tensor_out->CopyToCpu(data_out);
        databuf_char = reinterpret_cast<char*>(data_out);
S
ShiningZhang 已提交
649
      } else if (dataType == paddle::PaddleDType::FLOAT16) {
650
        databuf_size = out_num * sizeof(phi::dtype::float16);
S
ShiningZhang 已提交
651 652 653 654 655
        databuf_data = MempoolWrapper::instance().malloc(databuf_size);
        if (!databuf_data) {
          LOG(ERROR) << "Malloc failed, size: " << databuf_size;
          return -1;
        }
656 657
        phi::dtype::float16* data_out =
            reinterpret_cast<phi::dtype::float16*>(databuf_data);
S
ShiningZhang 已提交
658 659
        lod_tensor_out->CopyToCpu(data_out);
        databuf_char = reinterpret_cast<char*>(data_out);
H
HexToString 已提交
660
      }
S
ShiningZhang 已提交
661

H
HexToString 已提交
662 663 664 665 666
      // 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 已提交
667 668 669 670 671
      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();
672
      for (int li = 0; li < out_lod.size(); ++li) {
H
HexToString 已提交
673 674 675 676
        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 已提交
677
      paddle::PaddleBuf paddleBuf(databuf_char, databuf_size);
H
HexToString 已提交
678 679
      tensor_out.data = paddleBuf;
      tensorVector_out_pointer->push_back(tensor_out);
H
HexToString 已提交
680
    }
S
ShiningZhang 已提交
681 682 683 684 685 686 687 688 689 690 691
    gettimeofday(&tv, NULL);
    long end = tv.tv_sec * 1000000 + tv.tv_usec;
    long total_time = end - start;
    if (PrometheusMetric::Enabled()) {
      PrometheusMetricManager::GetGeneralSingleton()
          ->MetricInferenceCount()
          .Increment(1);
      PrometheusMetricManager::GetGeneralSingleton()
          ->MetricInferenceDuration()
          .Increment(total_time);
    }
W
wangguibao 已提交
692 693
    return 0;
  }
H
HexToString 已提交
694

695 696
  int task_infer_impl(const void* in, void* out) {  // NOLINT
    return infer_impl(in, out);
H
HexToString 已提交
697
  }
T
TeslaZhao 已提交
698 699 700 701

  CubeCache* get_cube_cache() {
    return DBReloadableInferEngine<EngineCore>::get_cube_cache();
  }
W
wangguibao 已提交
702 703
};

W
wangguibao 已提交
704 705 706 707 708 709 710
typedef FactoryPool<InferEngine> StaticInferFactory;

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

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

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

715
  int proc_finalize();
W
wangguibao 已提交
716

717
  int thrd_initialize();
W
wangguibao 已提交
718

719
  int thrd_clear();
W
wangguibao 已提交
720

721
  int thrd_finalize();
W
wangguibao 已提交
722

723
  int reload();
W
wangguibao 已提交
724

725
  uint64_t version() const;
W
wangguibao 已提交
726 727

  // inference interface
728
  InferEngine* default_engine() const;
W
wangguibao 已提交
729

730
  int infer(const void* in, void* out, uint32_t batch_size);
W
wangguibao 已提交
731 732

  template <typename T>
733
  T* get_core();
W
wangguibao 已提交
734

T
TeslaZhao 已提交
735 736
  CubeCache* get_cube_cache();

W
wangguibao 已提交
737
  // versioned inference interface
738
  int infer(const void* in, void* out, uint32_t batch_size, uint64_t version);
W
wangguibao 已提交
739 740

  template <typename T>
741
  T* get_core(const uint64_t version);
W
wangguibao 已提交
742

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

745 746 747 748 749 750 751 752 753 754
  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);

755
  int task_infer_impl(const void* in, void* out);
W
wangguibao 已提交
756 757 758

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

W
wangguibao 已提交
761 762 763 764 765 766 767
class InferManager {
 public:
  static InferManager& instance() {
    static InferManager ins;
    return ins;
  }

H
HexToString 已提交
768 769 770
  int proc_initialize(const char* path,
                      const char* file,
                      std::shared_ptr<int> engine_index_ptr);
W
wangguibao 已提交
771

H
HexToString 已提交
772 773
  int set_taskexecutor_num(size_t total_engine_num);

774
  int thrd_initialize();
W
wangguibao 已提交
775

776
  int thrd_clear();
W
wangguibao 已提交
777

778
  int reload();
W
wangguibao 已提交
779

780
  int thrd_finalize();
W
wangguibao 已提交
781

782
  int proc_finalize();
W
wangguibao 已提交
783 784

  // Inference interface
H
HexToString 已提交
785 786 787
  int infer(const char* model_name,
            const void* in,
            void* out,
788
            uint32_t batch_size = -1);
W
wangguibao 已提交
789

T
TeslaZhao 已提交
790
  // get engine core
W
wangguibao 已提交
791
  template <typename T>
792
  T* get_core(const char* model_name);
W
wangguibao 已提交
793

T
TeslaZhao 已提交
794 795 796
  // get cube cache
  CubeCache* get_cube_cache(const char* model_name);

W
wangguibao 已提交
797
  // Versioned inference interface
H
HexToString 已提交
798
  int infer(const char* model_name,
H
HexToString 已提交
799 800 801
            const void* in,
            void* out,
            uint32_t batch_size,
802
            uint64_t version);
W
wangguibao 已提交
803

T
TeslaZhao 已提交
804
  // Versioned get engine core
W
wangguibao 已提交
805
  template <typename T>
806
  T* get_core(const char* model_name, const uint64_t version);
W
wangguibao 已提交
807

T
TeslaZhao 已提交
808
  // query model version
809
  int query_version(const std::string& model, uint64_t& version);
W
wangguibao 已提交
810 811 812 813

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

W
wangguibao 已提交
815 816 817
}  // namespace predictor
}  // namespace paddle_serving
}  // namespace baidu