paddle_engine.h 7.9 KB
Newer Older
Z
update  
zhangjun 已提交
1
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjun 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//
// 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>
Z
zhangjun 已提交
20
#include <memory>
Z
zhangjun 已提交
21
#include <string>
22
#include <utility>
Z
zhangjun 已提交
23 24 25
#include <vector>
#include "core/configure/include/configure_parser.h"
#include "core/configure/inferencer_configure.pb.h"
Z
zhangjun 已提交
26
#include "core/predictor/common/utils.h"
Z
zhangjun 已提交
27
#include "core/predictor/framework/infer.h"
Z
zhangjun 已提交
28 29 30 31 32 33 34
#include "paddle_inference_api.h"  // NOLINT

namespace baidu {
namespace paddle_serving {
namespace inference {

using paddle_infer::Config;
Z
zhangjun 已提交
35
using paddle_infer::PrecisionType;
Z
zhangjun 已提交
36 37 38 39
using paddle_infer::Predictor;
using paddle_infer::Tensor;
using paddle_infer::CreatePredictor;

Z
zhangjun 已提交
40
DECLARE_int32(gpuid);
Z
fix  
zhangjun 已提交
41 42
DECLARE_string(precision);
DECLARE_bool(use_calib);
Z
zhangjun 已提交
43

Z
zhangjun 已提交
44 45
static const int max_batch = 32;
static const int min_subgraph_size = 3;
Z
fix  
zhangjun 已提交
46 47
static PrecisionType precision_type;

Z
update  
zhangjun 已提交
48 49 50
std::shared_ptr<std::vector<paddle::PaddleTensor>> PrepareWarmupData() {
  auto warmup_data = std::make_shared<std::vector<paddle::PaddleTensor>>(1);
  paddle::PaddleTensor images;
Z
update  
zhangjun 已提交
51 52
  images.name = "image";
  images.shape = {2, 3, 300, 300};
Z
update  
zhangjun 已提交
53
  images.dtype = paddle::PaddleDType::FLOAT32;
Z
update  
zhangjun 已提交
54 55 56 57 58 59
  images.data.Resize(sizeof(float) * 2 * 3 * 300 * 300);

  (*warmup_data)[0] = std::move(images);
  return warmup_data;
}

Z
fix  
zhangjun 已提交
60 61 62 63 64 65 66 67 68 69 70
PrecisionType GetPrecision(const std::string& precision_data) {
  std::string precision_type = predictor::ToLower(precision_data);
  if (precision_type == "fp32") {
    return PrecisionType::kFloat32;
  } else if (precision_type == "int8") {
    return PrecisionType::kInt8;
  } else if (precision_type == "fp16") {
    return PrecisionType::kHalf;
  }
  return PrecisionType::kFloat32;
}
Z
zhangjun 已提交
71

Z
update  
zhangjun 已提交
72
// Engine Base
H
HexToString 已提交
73
class EngineCore {
Z
zhangjun 已提交
74
 public:
H
HexToString 已提交
75
  virtual ~EngineCore() {}
Z
zhangjun 已提交
76
  virtual std::vector<std::string> GetInputNames() {
Z
zhangjun 已提交
77
    return _predictor->GetInputNames();
Z
zhangjun 已提交
78 79 80
  }

  virtual std::unique_ptr<Tensor> GetInputHandle(const std::string& name) {
Z
zhangjun 已提交
81
    return _predictor->GetInputHandle(name);
Z
zhangjun 已提交
82 83 84
  }

  virtual std::vector<std::string> GetOutputNames() {
Z
zhangjun 已提交
85
    return _predictor->GetOutputNames();
Z
zhangjun 已提交
86 87 88
  }

  virtual std::unique_ptr<Tensor> GetOutputHandle(const std::string& name) {
Z
zhangjun 已提交
89
    return _predictor->GetOutputHandle(name);
Z
zhangjun 已提交
90 91 92
  }

  virtual bool Run() {
Z
zhangjun 已提交
93
    if (!_predictor->Run()) {
Z
zhangjun 已提交
94 95 96 97 98 99
      LOG(ERROR) << "Failed call Run with paddle predictor";
      return false;
    }
    return true;
  }

100
  virtual int create(const configure::EngineDesc& conf, int gpu_id) = 0;
Z
zhangjun 已提交
101

Z
update  
zhangjun 已提交
102 103
  virtual int clone(void* predictor) {
    if (predictor == NULL) {
Z
zhangjun 已提交
104 105 106
      LOG(ERROR) << "origin paddle Predictor is null.";
      return -1;
    }
Z
zhangjun 已提交
107 108
    Predictor* prep = static_cast<Predictor*>(predictor);
    _predictor = prep->Clone();
Z
update  
zhangjun 已提交
109 110
    if (_predictor.get() == NULL) {
      LOG(ERROR) << "fail to clone paddle predictor: " << predictor;
Z
zhangjun 已提交
111 112 113 114 115
      return -1;
    }
    return 0;
  }

Z
update  
zhangjun 已提交
116
  virtual void* get() { return _predictor.get(); }
Z
zhangjun 已提交
117 118

 protected:
Z
update  
zhangjun 已提交
119
  std::shared_ptr<Predictor> _predictor;
Z
zhangjun 已提交
120 121
};

Z
update  
zhangjun 已提交
122
// Paddle Inference Engine
H
HexToString 已提交
123
class PaddleInferenceEngine : public EngineCore {
Z
zhangjun 已提交
124
 public:
125
  int create(const configure::EngineDesc& engine_conf, int gpu_id) {
Z
update  
zhangjun 已提交
126 127
    std::string model_path = engine_conf.model_dir();
    if (access(model_path.c_str(), F_OK) == -1) {
Z
zhangjun 已提交
128
      LOG(ERROR) << "create paddle predictor failed, path not exits: "
Z
update  
zhangjun 已提交
129
                 << model_path;
Z
zhangjun 已提交
130 131 132 133
      return -1;
    }

    Config config;
Z
update  
zhangjun 已提交
134
    // todo, auto config(zhangjun)
Z
zhangjun 已提交
135 136 137
    if (engine_conf.has_encrypted_model() && engine_conf.encrypted_model()) {
      // decrypt model
      std::string model_buffer, params_buffer, key_buffer;
H
HexToString 已提交
138 139 140
      predictor::ReadBinaryFile(model_path + "/encrypt_model", &model_buffer);
      predictor::ReadBinaryFile(model_path + "/encrypt_params", &params_buffer);
      predictor::ReadBinaryFile(model_path + "/key", &key_buffer);
Z
zhangjun 已提交
141 142 143 144 145 146 147 148 149 150

      auto cipher = paddle::MakeCipher("");
      std::string real_model_buffer = cipher->Decrypt(model_buffer, key_buffer);
      std::string real_params_buffer =
          cipher->Decrypt(params_buffer, key_buffer);
      config.SetModelBuffer(&real_model_buffer[0],
                            real_model_buffer.size(),
                            &real_params_buffer[0],
                            real_params_buffer.size());
    } else if (engine_conf.has_combined_model()) {
Z
zhangjun 已提交
151
      if (!engine_conf.combined_model()) {
Z
zhangjun 已提交
152
        config.SetModel(model_path);
Z
update  
zhangjun 已提交
153 154 155 156 157 158 159
      } else {
        config.SetParamsFile(model_path + "/__params__");
        config.SetProgFile(model_path + "/__model__");
      }
    } else {
      config.SetParamsFile(model_path + "/__params__");
      config.SetProgFile(model_path + "/__model__");
Z
zhangjun 已提交
160
    }
Z
zhangjun 已提交
161

Z
zhangjun 已提交
162
    config.SwitchSpecifyInputNames(true);
Z
update  
zhangjun 已提交
163 164 165
    config.SetCpuMathLibraryNumThreads(1);
    if (engine_conf.has_use_gpu() && engine_conf.use_gpu()) {
      // 2000MB GPU memory
166 167 168 169 170
      config.EnableUseGpu(50, gpu_id);
      if (engine_conf.has_gpu_multi_stream() &&
          engine_conf.gpu_multi_stream()) {
        config.EnableGpuMultiStream();
      }
Z
zhangjun 已提交
171
    }
Z
fix  
zhangjun 已提交
172
    precision_type = GetPrecision(FLAGS_precision);
Z
zhangjun 已提交
173

Z
update  
zhangjun 已提交
174 175 176 177 178 179 180
    if (engine_conf.has_enable_ir_optimization() &&
        !engine_conf.enable_ir_optimization()) {
      config.SwitchIrOptim(false);
    } else {
      config.SwitchIrOptim(true);
    }

Z
update  
zhangjun 已提交
181
    if (engine_conf.has_use_trt() && engine_conf.use_trt()) {
182
      config.SwitchIrOptim(true);
Z
zhangjun 已提交
183
      if (!engine_conf.has_use_gpu() || !engine_conf.use_gpu()) {
184 185 186 187 188
        config.EnableUseGpu(50, gpu_id);
        if (engine_conf.has_gpu_multi_stream() &&
            engine_conf.gpu_multi_stream()) {
          config.EnableGpuMultiStream();
        }
Z
zhangjun 已提交
189
      }
Z
update  
zhangjun 已提交
190 191 192
      config.EnableTensorRtEngine(1 << 20,
                                  max_batch,
                                  min_subgraph_size,
193
                                  precision_type,
Z
update  
zhangjun 已提交
194
                                  false,
Z
fix  
zhangjun 已提交
195
                                  FLAGS_use_calib);
Z
update  
zhangjun 已提交
196
      LOG(INFO) << "create TensorRT predictor";
Z
zhangjun 已提交
197 198
    }

Z
zhangjun 已提交
199
    if (engine_conf.has_use_lite() && engine_conf.use_lite()) {
200 201 202 203 204 205
      config.EnableLiteEngine(precision_type, true);
    }

    if ((!engine_conf.has_use_lite() && !engine_conf.has_use_gpu()) ||
        (engine_conf.has_use_lite() && !engine_conf.use_lite() &&
         engine_conf.has_use_gpu() && !engine_conf.use_gpu())) {
Z
zhangjun 已提交
206
#ifdef WITH_MKLML
Z
update  
zhangjun 已提交
207 208 209 210 211 212
#ifdef WITH_MKLDNN
      config.EnableMKLDNN();
      config.SwitchIrOptim(true);
      config.DisableGpu();
      // config.SetCpuMathLibraryNumThreads(2);

Z
fix  
zhangjun 已提交
213
      if (precision_type == PrecisionType::kInt8) {
214
        config.EnableMkldnnQuantizer();
Z
update  
zhangjun 已提交
215
        auto quantizer_config = config.mkldnn_quantizer_config();
216
        // TODO(somebody): warmup data
Z
update  
zhangjun 已提交
217 218 219
        // quantizer_config -> SetWarmupData();
        // quantizer_config -> SetWarmupBatchSize();
        // quantizer_config -> SetEnabledOpTypes(4);
Z
fix  
zhangjun 已提交
220
      } else if (precision_type == PrecisionType::kHalf) {
221 222
        config.EnableMkldnnBfloat16();
      }
Z
update  
zhangjun 已提交
223
#endif
Z
zhangjun 已提交
224
#endif
Z
zhangjun 已提交
225 226
    }

Z
zhangjun 已提交
227
    if (engine_conf.has_use_xpu() && engine_conf.use_xpu()) {
Z
update  
zhangjun 已提交
228 229 230
      // 2 MB l3 cache
      config.EnableXpu(2 * 1024 * 1024);
    }
Z
zhangjun 已提交
231

Z
zhangjun 已提交
232 233
    if (engine_conf.has_enable_memory_optimization() &&
        engine_conf.enable_memory_optimization()) {
Z
update  
zhangjun 已提交
234
      config.EnableMemoryOptim();
Z
zhangjun 已提交
235
    }
Z
zhangjun 已提交
236

Z
zhangjun 已提交
237
    predictor::AutoLock lock(predictor::GlobalCreateMutex::instance());
Z
update  
zhangjun 已提交
238 239
    _predictor = CreatePredictor(config);
    if (NULL == _predictor.get()) {
Z
zhangjun 已提交
240
      LOG(ERROR) << "create paddle predictor failed, path: " << model_path;
Z
zhangjun 已提交
241 242
      return -1;
    }
Z
update  
zhangjun 已提交
243

Z
zhangjun 已提交
244
    VLOG(2) << "create paddle predictor sucess, path: " << model_path;
Z
zhangjun 已提交
245 246 247 248
    return 0;
  }
};

Z
update  
zhangjun 已提交
249
}  // namespace inference
Z
zhangjun 已提交
250 251
}  // namespace paddle_serving
}  // namespace baidu