fluid_cpu_engine.h 15.1 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9
#pragma once

#include <pthread.h>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include "framework/infer.h"
#include "paddle/fluid/inference/paddle_inference_api.h"
10 11
#include "inferencer_configure.pb.h"
#include "configure_parser.h"
W
wangguibao 已提交
12 13 14 15 16

namespace baidu {
namespace paddle_serving {
namespace fluid_cpu {

17 18
using configure::SigmoidConf;

W
wangguibao 已提交
19 20 21 22 23 24 25 26 27 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 64 65 66 67 68 69 70 71 72 73 74 75 76
class AutoLock {
public:
    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;
};

class GlobalSigmoidCreateMutex {
public:
    pthread_mutex_t& mutex() {
        return _mut;
    }
    static pthread_mutex_t& instance() {
    static GlobalSigmoidCreateMutex gmutex;
        return gmutex.mutex();
    }
private:
    GlobalSigmoidCreateMutex() {
        pthread_mutex_init(&_mut, NULL);
    }

    pthread_mutex_t _mut;
};

// data interface
class FluidFamilyCore {
public:

    virtual ~FluidFamilyCore() {}
    virtual bool Run(const void* in_data, void* out_data) {
        if (!_core->Run(*(std::vector<paddle::PaddleTensor>*)in_data, 
                    (std::vector<paddle::PaddleTensor>*)out_data)) {
77
            LOG(ERROR) << "Failed call Run with paddle predictor";
W
wangguibao 已提交
78 79 80 81 82 83 84 85 86 87
            return false;
        }

        return true;
    }

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

    virtual int clone(void* origin_core) {
        if (origin_core == NULL) {
88
            LOG(ERROR) << "origin paddle Predictor is null.";
W
wangguibao 已提交
89 90 91 92 93
            return -1;
        }
        paddle::PaddlePredictor* p_predictor = (paddle::PaddlePredictor*)origin_core;
        _core = p_predictor->Clone();
        if (_core.get() == NULL) {
94
            LOG(ERROR) << "fail to clone paddle predictor: " << origin_core;
W
wangguibao 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
            return -1;
        }
        return 0;
    }

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

protected:
    std::unique_ptr<paddle::PaddlePredictor> _core;
};

// infer interface
class FluidCpuAnalysisCore : public FluidFamilyCore {
public:
    int create(const std::string& data_path) {
        if (access(data_path.c_str(), F_OK) == -1) {
113
            LOG(ERROR) << "create paddle predictor failed, path not exits: "
W
wangguibao 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127
                << data_path;
            return -1;
        }

        paddle::contrib::AnalysisConfig analysis_config;
        analysis_config.param_file = data_path + "/__params__";
        analysis_config.prog_file = data_path + "/__model__";
        analysis_config.use_gpu = false;
        analysis_config.device = 0;
        analysis_config.specify_input_name = true;
        AutoLock lock(GlobalPaddleCreateMutex::instance());
        _core = paddle::CreatePaddlePredictor<
            paddle::contrib::AnalysisConfig>(analysis_config);
        if (NULL == _core.get()) {
128
            LOG(ERROR) << "create paddle predictor failed, path: "
W
wangguibao 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141
                << data_path;
            return -1;
        }

        LOG(WARNING) << "create paddle predictor sucess, path: "<< data_path;
        return 0; 
    }
};

class FluidCpuNativeCore : public FluidFamilyCore {
public:
    int create(const std::string& data_path) {
        if (access(data_path.c_str(), F_OK) == -1) {
142
            LOG(ERROR) << "create paddle predictor failed, path not exits: "
W
wangguibao 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155
                << data_path;
            return -1;
        }

        paddle::NativeConfig native_config;
        native_config.param_file = data_path + "/__params__";
        native_config.prog_file = data_path + "/__model__";
        native_config.use_gpu = false;
        native_config.device = 0;
        AutoLock lock(GlobalPaddleCreateMutex::instance());
        _core = paddle::CreatePaddlePredictor<
            paddle::NativeConfig, paddle::PaddleEngineKind::kNative>(native_config);
        if (NULL == _core.get()) {
156
            LOG(ERROR) << "create paddle predictor failed, path: "
W
wangguibao 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169
                << data_path;
            return -1;
        }

        LOG(WARNING) << "create paddle predictor sucess, path: "<< data_path;
        return 0; 
    }
};

class FluidCpuAnalysisDirCore : public FluidFamilyCore {
public:
    int create(const std::string& data_path) {
        if (access(data_path.c_str(), F_OK) == -1) {
170
            LOG(ERROR) << "create paddle predictor failed, path not exits: "
W
wangguibao 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183
                << data_path;
            return -1;
        }

        paddle::contrib::AnalysisConfig analysis_config;
        analysis_config.model_dir = data_path;
        analysis_config.use_gpu = false;
        analysis_config.device = 0;
        analysis_config.specify_input_name = true;
        AutoLock lock(GlobalPaddleCreateMutex::instance());
        _core = paddle::CreatePaddlePredictor<
            paddle::contrib::AnalysisConfig>(analysis_config);
        if (NULL == _core.get()) {
184
            LOG(ERROR) << "create paddle predictor failed, path: "
W
wangguibao 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198
                << data_path;
            return -1;
        }

        LOG(WARNING) << "create paddle predictor sucess, path: "<< data_path;
        return 0; 
    }

};

class FluidCpuNativeDirCore : public FluidFamilyCore {
public:
    int create(const std::string& data_path) {
        if (access(data_path.c_str(), F_OK) == -1) {
199
            LOG(ERROR) << "create paddle predictor failed, path not exits: "
W
wangguibao 已提交
200 201 202 203 204 205 206 207 208 209 210 211
                << data_path;
            return -1;
        }

        paddle::NativeConfig native_config;
        native_config.model_dir = data_path;
        native_config.use_gpu = false;
        native_config.device = 0;
        AutoLock lock(GlobalPaddleCreateMutex::instance());
        _core = paddle::CreatePaddlePredictor<
            paddle::NativeConfig, paddle::PaddleEngineKind::kNative>(native_config);
        if (NULL == _core.get()) {
212
            LOG(ERROR) << "create paddle predictor failed, path: "
W
wangguibao 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
                << data_path;
            return -1;
        }

        LOG(WARNING) << "create paddle predictor sucess, path: "<< data_path;
        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 = (float*)malloc(_row * _col * sizeof(float));
        if (_params == NULL) {
238
            LOG(ERROR) << "Load " << _file_name << " malloc error.";
W
wangguibao 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
            return -1;
        }
        LOG(WARNING) << "Load parameter file[" << _file_name << "] success.";
        return 0;
    }

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

    int load() {
        if (_params == NULL || _row <= 0 || _col <= 0) {
256
            LOG(ERROR) << "load parameter error [not inited].";
W
wangguibao 已提交
257 258 259 260 261
            return -1;
        }

        FILE* fs = fopen(_file_name.c_str(), "rb");
        if (fs == NULL) {
262
            LOG(ERROR) << "load " << _file_name << " fopen error.";
W
wangguibao 已提交
263 264 265 266 267 268
            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();
269
            LOG(ERROR) << "Load " << _file_name << " read head error.";
W
wangguibao 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            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 {
286
            LOG(ERROR) << "load " << _file_name << " read error.";
W
wangguibao 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
            destroy();
            if (fs != NULL) {
                fclose(fs);
                fs = NULL;
            }
            return -1;
        }
        return 0;
    }

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

class SigmoidModel {
public:
    ~SigmoidModel() {
    }
    int load(const char* sigmoid_w_file, const char* sigmoid_b_file,
            float exp_max, float exp_min) {
        AutoLock lock(GlobalSigmoidCreateMutex::instance());
        if (0 != _sigmoid_w.init(2, 1, sigmoid_w_file) || 0 != _sigmoid_w.load()) {
312
            LOG(ERROR) << "load params sigmoid_w failed.";
W
wangguibao 已提交
313 314 315 316 317
            return -1;
        }
        LOG(WARNING) << "load sigmoid_w [" << _sigmoid_w._params[0]
                << "] [" << _sigmoid_w._params[1] << "].";
        if (0 != _sigmoid_b.init(2, 1, sigmoid_b_file) || 0 != _sigmoid_b.load()) {
318
            LOG(ERROR) << "load params sigmoid_b failed.";
W
wangguibao 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
            return -1;
        }
        LOG(WARNING) << "load sigmoid_b [" << _sigmoid_b._params[0]
                << "] [" << _sigmoid_b._params[1] << "].";
        _exp_max_input = exp_max;
        _exp_min_input = exp_min;
        return 0;
    }

    int softmax(float x, double& o) {
        float _y0 = x * _sigmoid_w._params[0] + _sigmoid_b._params[0];
        float _y1 = x * _sigmoid_w._params[1] + _sigmoid_b._params[1];
        _y0 = (_y0 > _exp_max_input) ? _exp_max_input
                : ((_y0 < _exp_min_input) ? _exp_min_input : _y0);
        _y1 = (_y1 > _exp_max_input) ? _exp_max_input
                : ((_y1 < _exp_min_input) ? _exp_min_input : _y1);
        o = 1.0f / (1.0f + exp(_y0 - _y1));
        return 0;
    }
public:
    Parameter _sigmoid_w;
    Parameter _sigmoid_b;
    float _exp_max_input;
    float _exp_min_input;
};

class SigmoidFluidModel {
public:
    int softmax(float x, double& o) {
        return  _sigmoid_core->softmax(x, o);
    }

    std::unique_ptr<SigmoidFluidModel> Clone() {
        std::unique_ptr<SigmoidFluidModel> clone_model;
        clone_model.reset(new SigmoidFluidModel()); 
        clone_model->_sigmoid_core = _sigmoid_core;
        clone_model->_fluid_core = _fluid_core->Clone();
        return std::move(clone_model);
    }

public:
    std::unique_ptr<paddle::PaddlePredictor> _fluid_core;
    std::shared_ptr<SigmoidModel> _sigmoid_core;
};

class FluidCpuWithSigmoidCore : public FluidFamilyCore {
public:
    virtual  ~FluidCpuWithSigmoidCore() {
    }
public:
    int create(const std::string& model_path) {
        size_t pos = model_path.find_last_of("/\\");
        std::string conf_path = model_path.substr(0, pos);
        std::string conf_file = model_path.substr(pos);
373 374
        configure::SigmoidConf conf;
        if (configure::read_proto_conf(conf_path, conf_file, &conf) != 0) {
375
            LOG(ERROR) << "failed load model path: " << model_path;
W
wangguibao 已提交
376 377 378 379 380
            return -1;
        }

        _core.reset(new SigmoidFluidModel);
    
381
        std::string fluid_model_data_path = conf.dnn_model_path();
W
wangguibao 已提交
382 383
        int ret = load_fluid_model(fluid_model_data_path);
        if (ret < 0) {
384
            LOG(ERROR) << "fail to load fluid model.";
W
wangguibao 已提交
385 386
            return -1;
        }
387 388 389 390
        const char* sigmoid_w_file = conf.sigmoid_w_file().c_str();
        const char* sigmoid_b_file = conf.sigmoid_b_file().c_str();
        float exp_max = conf.exp_max_input();
        float exp_min = conf.exp_min_input();
W
wangguibao 已提交
391 392 393 394 395
        _core->_sigmoid_core.reset(new SigmoidModel);
        LOG(INFO) << "create sigmoid core[" << _core->_sigmoid_core.get()
                << "], use count[" << _core->_sigmoid_core.use_count() << "].";
        ret = _core->_sigmoid_core->load(sigmoid_w_file, sigmoid_b_file, exp_max, exp_min);
        if (ret < 0) {
396
            LOG(ERROR) << "fail to load sigmoid model.";
W
wangguibao 已提交
397 398 399 400 401 402 403 404
            return -1;
        }
        return 0;
    }

    virtual bool Run(const void* in_data, void* out_data) {
        if (!_core->_fluid_core->Run(*(std::vector<paddle::PaddleTensor>*)in_data, 
                    (std::vector<paddle::PaddleTensor>*)out_data)) {
405
            LOG(ERROR) << "Failed call Run with paddle predictor";
W
wangguibao 已提交
406 407 408 409 410 411 412 413
            return false;
        }

        return true;
    }

    virtual int clone(SigmoidFluidModel* origin_core) {
        if (origin_core == NULL) {
414
            LOG(ERROR) << "origin paddle Predictor is null.";
W
wangguibao 已提交
415 416 417 418
            return -1;
        }
        _core = origin_core->Clone();
        if (_core.get() == NULL) {
419
            LOG(ERROR) << "fail to clone paddle predictor: " << origin_core;
W
wangguibao 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
            return -1;
        }
        LOG(INFO) << "clone sigmoid core[" << _core->_sigmoid_core.get()
                << "] use count[" << _core->_sigmoid_core.use_count() << "].";
        return 0;
    }
    
    virtual SigmoidFluidModel* get() {
        return _core.get();
    }

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

    int softmax(float x, double& o) {
        return _core->_sigmoid_core->softmax(x, o);
    }

protected:
    std::unique_ptr<SigmoidFluidModel> _core;
};

class FluidCpuNativeDirWithSigmoidCore : public FluidCpuWithSigmoidCore {
public:
    int load_fluid_model(const std::string& data_path) {
        if (access(data_path.c_str(), F_OK) == -1) {
445
            LOG(ERROR) << "create paddle predictor failed, path not exits: "
W
wangguibao 已提交
446 447 448 449 450 451 452 453 454 455 456 457
                << data_path;
            return -1;
        }

        paddle::NativeConfig native_config;
        native_config.model_dir = data_path;
        native_config.use_gpu = false;
        native_config.device = 0;
        AutoLock lock(GlobalPaddleCreateMutex::instance());
        _core->_fluid_core = paddle::CreatePaddlePredictor<
            paddle::NativeConfig, paddle::PaddleEngineKind::kNative>(native_config);
        if (NULL == _core.get()) {
458
            LOG(ERROR) << "create paddle predictor failed, path: "
W
wangguibao 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472
                << data_path;
            return -1;
        }

        LOG(WARNING) << "create paddle predictor sucess, path: "<< data_path;
        return 0; 
    }

};

class FluidCpuAnalysisDirWithSigmoidCore : public FluidCpuWithSigmoidCore {
public:
    int load_fluid_model(const std::string& data_path) {
        if (access(data_path.c_str(), F_OK) == -1) {
473
            LOG(ERROR) << "create paddle predictor failed, path not exits: "
W
wangguibao 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486
                << data_path;
            return -1;
        }

        paddle::contrib::AnalysisConfig analysis_config;
        analysis_config.model_dir = data_path;
        analysis_config.use_gpu = false;
        analysis_config.device = 0;
        analysis_config.specify_input_name = true;
        AutoLock lock(GlobalPaddleCreateMutex::instance());
        _core->_fluid_core = paddle::CreatePaddlePredictor<
            paddle::contrib::AnalysisConfig>(analysis_config);
        if (NULL == _core.get()) {
487
            LOG(ERROR) << "create paddle predictor failed, path: "
W
wangguibao 已提交
488 489 490 491 492 493 494 495 496 497 498 499
                << data_path;
            return -1;
        }

        LOG(WARNING) << "create paddle predictor sucess, path: "<< data_path;
        return 0; 
    }
};

} // namespace fluid_cpu
} // namespace paddle_serving
} // namespace baidu