fluid_gpu_engine.h 7.3 KB
Newer Older
W
Wang Guibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 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

#include <pthread.h>
#include <fstream>
#include <map>
X
xulongteng 已提交
20
#include <memory>
W
Wang Guibao 已提交
21
#include <string>
X
xulongteng 已提交
22
#include <utility>
W
Wang Guibao 已提交
23
#include <vector>
G
guru4elephant 已提交
24 25 26
#include "core/configure/include/configure_parser.h"
#include "core/configure/inferencer_configure.pb.h"
#include "core/predictor/framework/infer.h"
B
barrierye 已提交
27
#include "paddle_inference_api.h"  // NOLINT
W
Wang Guibao 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

DECLARE_int32(gpuid);

namespace baidu {
namespace paddle_serving {
namespace fluid_gpu {

using configure::SigmoidConf;

class AutoLock {
 public:
  explicit AutoLock(pthread_mutex_t& mutex) : _mut(mutex) {
    pthread_mutex_lock(&mutex);
  }

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

 private:
  pthread_mutex_t& _mut;
};

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

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

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

  pthread_mutex_t _mut;
};

W
wangjiawei04 已提交
64 65 66 67
using paddle_infer::Config;
using paddle_infer::Predictor;
using paddle_infer::Tensor;
using paddle_infer::CreatePredictor;
W
Wang Guibao 已提交
68 69 70 71 72

// data interface
class FluidFamilyCore {
 public:
  virtual ~FluidFamilyCore() {}
W
wangjiawei04 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  virtual std::vector<std::string> GetInputNames() {
    return _core->GetInputNames();
  }

  virtual std::unique_ptr<Tensor> GetInputHandle(const std::string& name) {
      return _core->GetInputHandle(name);
  }

  virtual std::vector<std::string> GetOutputNames() {
    return _core->GetOutputNames();
  }

  virtual std::unique_ptr<Tensor> GetOutputHandle(const std::string& name) {
      return _core->GetOutputHandle(name);
  }

  virtual bool Run() {
    if (!_core->Run()) {
W
Wang Guibao 已提交
91 92 93 94 95 96
      LOG(ERROR) << "Failed call Run with paddle predictor";
      return false;
    }
    return true;
  }

97
  virtual int create(const predictor::InferEngineCreationParams& params) = 0;
W
Wang Guibao 已提交
98 99 100 101 102 103

  virtual int clone(void* origin_core) {
    if (origin_core == NULL) {
      LOG(ERROR) << "origin paddle Predictor is null.";
      return -1;
    }
W
wangjiawei04 已提交
104 105
    Predictor* p_predictor =
        (Predictor*)origin_core;
W
Wang Guibao 已提交
106 107 108 109 110 111 112 113 114 115 116
    _core = p_predictor->Clone();
    if (_core.get() == NULL) {
      LOG(ERROR) << "fail to clone paddle predictor: " << origin_core;
      return -1;
    }
    return 0;
  }

  virtual void* get() { return _core.get(); }

 protected:
W
wangjiawei04 已提交
117
  std::shared_ptr<Predictor> _core;
W
Wang Guibao 已提交
118 119 120 121 122
};

// infer interface
class FluidGpuAnalysisCore : public FluidFamilyCore {
 public:
123 124
  int create(const predictor::InferEngineCreationParams& params) {
    std::string data_path = params.get_path();
W
Wang Guibao 已提交
125 126 127 128 129 130
    if (access(data_path.c_str(), F_OK) == -1) {
      LOG(ERROR) << "create paddle predictor failed, path not exits: "
                 << data_path;
      return -1;
    }

W
wangjiawei04 已提交
131 132 133 134 135
    Config config;
    config.SetParamsFile(data_path + "/__params__");
    config.SetProgFile(data_path + "/__model__");
    config.EnableUseGpu(100, FLAGS_gpuid);
    config.SetCpuMathLibraryNumThreads(1);
136 137

    if (params.enable_memory_optimization()) {
W
wangjiawei04 已提交
138
      config.EnableMemoryOptim();
139 140
    }

W
wangjiawei04 已提交
141
    config.SwitchSpecifyInputNames(true);
W
Wang Guibao 已提交
142
    AutoLock lock(GlobalPaddleCreateMutex::instance());
W
wangjiawei04 已提交
143
    _core = CreatePredictor(config);
W
Wang Guibao 已提交
144 145 146 147 148
    if (NULL == _core.get()) {
      LOG(ERROR) << "create paddle predictor failed, path: " << data_path;
      return -1;
    }

149
    VLOG(2) << "create paddle predictor sucess, path: " << data_path;
W
Wang Guibao 已提交
150 151 152 153
    return 0;
  }
};

M
MRXLT 已提交
154
class FluidGpuAnalysisDirCore : public FluidFamilyCore {
W
Wang Guibao 已提交
155
 public:
156 157
  int create(const predictor::InferEngineCreationParams& params) {
    std::string data_path = params.get_path();
W
Wang Guibao 已提交
158 159 160 161 162 163
    if (access(data_path.c_str(), F_OK) == -1) {
      LOG(ERROR) << "create paddle predictor failed, path not exits: "
                 << data_path;
      return -1;
    }

W
wangjiawei04 已提交
164 165 166 167 168
    Config config;
    config.SetModel(data_path);
    config.EnableUseGpu(1500, FLAGS_gpuid);
    config.SwitchSpecifyInputNames(true);
    config.SetCpuMathLibraryNumThreads(1);
169 170

    if (params.enable_memory_optimization()) {
W
wangjiawei04 已提交
171
      config.EnableMemoryOptim();
172
    }
M
bug fix  
MRXLT 已提交
173
    int max_batch = 32;
M
MRXLT 已提交
174
    int min_subgraph_size = 3;
M
add trt  
MRXLT 已提交
175
    if (params.use_trt()) {
W
wangjiawei04 已提交
176
      config.EnableTensorRtEngine(
M
MRXLT 已提交
177 178
          1 << 20,
          max_batch,
M
MRXLT 已提交
179
          min_subgraph_size,
W
wangjiawei04 已提交
180
          Config::Precision::kFloat32,
M
bug fix  
MRXLT 已提交
181 182
          false,
          false);
M
bug fix  
MRXLT 已提交
183
      LOG(INFO) << "create TensorRT predictor";
M
MRXLT 已提交
184 185
    } else {
      if (params.enable_memory_optimization()) {
W
wangjiawei04 已提交
186
        config.EnableMemoryOptim();
M
MRXLT 已提交
187 188 189
      }

      if (params.enable_ir_optimization()) {
W
wangjiawei04 已提交
190
        config.SwitchIrOptim(true);
M
MRXLT 已提交
191
      } else {
W
wangjiawei04 已提交
192
        config.SwitchIrOptim(false);
M
MRXLT 已提交
193
      }
M
add trt  
MRXLT 已提交
194
    }
W
Wang Guibao 已提交
195
    AutoLock lock(GlobalPaddleCreateMutex::instance());
W
wangjiawei04 已提交
196
    _core = CreatePredictor(config);
W
Wang Guibao 已提交
197 198 199 200 201
    if (NULL == _core.get()) {
      LOG(ERROR) << "create paddle predictor failed, path: " << data_path;
      return -1;
    }

202
    VLOG(2) << "create paddle predictor sucess, path: " << data_path;
W
Wang Guibao 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    return 0;
  }
};


class Parameter {
 public:
  Parameter() : _row(0), _col(0), _params(NULL) {}
  ~Parameter() {
    LOG(INFO) << "before destroy Parameter, file_name[" << _file_name << "]";
    destroy();
  }

  int init(int row, int col, const char* file_name) {
    destroy();
    _file_name = file_name;
    _row = row;
    _col = col;
    _params = reinterpret_cast<float*>(malloc(_row * _col * sizeof(float)));
    if (_params == NULL) {
      LOG(ERROR) << "Load " << _file_name << " malloc error.";
      return -1;
    }
226
    VLOG(2) << "Load parameter file[" << _file_name << "] success.";
W
Wang Guibao 已提交
227 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 283 284 285 286 287 288 289 290 291
    return 0;
  }

  void destroy() {
    _row = 0;
    _col = 0;
    if (_params != NULL) {
      free(_params);
      _params = NULL;
    }
  }

  int load() {
    if (_params == NULL || _row <= 0 || _col <= 0) {
      LOG(ERROR) << "load parameter error [not inited].";
      return -1;
    }

    FILE* fs = fopen(_file_name.c_str(), "rb");
    if (fs == NULL) {
      LOG(ERROR) << "load " << _file_name << " fopen error.";
      return -1;
    }
    static const uint32_t MODEL_FILE_HEAD_LEN = 16;
    char head[MODEL_FILE_HEAD_LEN] = {0};
    if (fread(head, 1, MODEL_FILE_HEAD_LEN, fs) != MODEL_FILE_HEAD_LEN) {
      destroy();
      LOG(ERROR) << "Load " << _file_name << " read head error.";
      if (fs != NULL) {
        fclose(fs);
        fs = NULL;
      }
      return -1;
    }

    uint32_t matrix_size = _row * _col;
    if (matrix_size == fread(_params, sizeof(float), matrix_size, fs)) {
      if (fs != NULL) {
        fclose(fs);
        fs = NULL;
      }
      LOG(INFO) << "load " << _file_name << " read ok.";
      return 0;
    } else {
      LOG(ERROR) << "load " << _file_name << " read error.";
      destroy();
      if (fs != NULL) {
        fclose(fs);
        fs = NULL;
      }
      return -1;
    }
    return 0;
  }

 public:
  std::string _file_name;
  int _row;
  int _col;
  float* _params;
};

}  // namespace fluid_gpu
}  // namespace paddle_serving
}  // namespace baidu