paddle_mobile.cpp 14.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 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. */

#include "io/paddle_mobile.h"
16
#ifdef PADDLE_MOBILE_CL
17 18
#include <CL/cl.h>
#include "framework/cl/cl_tensor.h"
19 20
#endif
#include "common/common.h"
21
#include "operators/math/gemm.h"
22 23
namespace paddle_mobile {

24 25 26 27 28
template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::SetThreadNum(int num) {
#ifdef _OPENMP
  omp_set_num_threads(num);
#endif
29
}
30

31
template <typename Dtype, Precision P>
32
bool PaddleMobile<Dtype, P>::Load(const std::string &dirname, bool optimize,
H
hjchen2 已提交
33 34
                                  bool quantification, int batch_size,
                                  bool loddable) {
35
  if (loader_.get() == nullptr) {
qnqinan's avatar
qnqinan 已提交
36
    loader_ = std::make_shared<framework::Loader<Dtype, P>>();
37 38 39 40 41
  } else {
    LOG(kLOG_INFO) << "loader inited";
  }

  if (executor_.get() == nullptr) {
qnqinan's avatar
qnqinan 已提交
42
    executor_ = std::make_shared<framework::Executor<Dtype, P>>(
H
hjchen2 已提交
43 44
        loader_->Load(dirname, optimize, quantification), batch_size, optimize,
        loddable);
45 46 47 48 49 50 51 52 53
  } else {
    LOG(kLOG_INFO) << "executor inited";
  }

  return true;
}

template <typename Dtype, Precision P>
bool PaddleMobile<Dtype, P>::Load(const std::string &model_path,
54
                                  const std::string &para_path, bool optimize,
H
hjchen2 已提交
55 56
                                  bool quantification, int batch_size,
                                  bool loddable) {
57
  if (loader_.get() == nullptr) {
qnqinan's avatar
qnqinan 已提交
58
    loader_ = std::make_shared<framework::Loader<Dtype, P>>();
59 60 61 62 63
  } else {
    LOG(kLOG_INFO) << "loader inited";
  }

  if (executor_.get() == nullptr) {
qnqinan's avatar
qnqinan 已提交
64
    executor_ = std::make_shared<framework::Executor<Dtype, P>>(
W
wangliu 已提交
65
        loader_->Load(model_path, para_path, optimize, quantification),
H
hjchen2 已提交
66
        batch_size, optimize, loddable);
67 68 69 70 71 72 73
  } else {
    LOG(kLOG_INFO) << "executor inited";
  }

  return true;
}

74
template <typename Dtype, Precision P>
qnqinan's avatar
qnqinan 已提交
75 76 77 78
bool PaddleMobile<Dtype, P>::LoadCombinedMemory(size_t model_len,
                                                const uint8_t *model_buf,
                                                size_t combined_params_len,
                                                uint8_t *combined_params_buf) {
H
hjchen2 已提交
79
  int batch_size = 1;
80 81 82 83
  bool optimise = true;
  bool quantification = false;

  if (loader_.get() == nullptr) {
qnqinan's avatar
qnqinan 已提交
84
    loader_ = std::make_shared<framework::Loader<Dtype, P>>();
85 86 87 88 89
  } else {
    LOG(kLOG_INFO) << "loader inited";
  }

  if (executor_.get() == nullptr) {
qnqinan's avatar
qnqinan 已提交
90
    executor_ = std::make_shared<framework::Executor<Dtype, P>>(
91 92
        loader_->LoadCombinedMemory(model_len, model_buf, combined_params_len,
                                    combined_params_buf, optimise,
93
                                    quantification),
H
hjchen2 已提交
94
        batch_size, optimise);
95 96 97 98 99 100
  } else {
    LOG(kLOG_INFO) << "executor inited";
  }

  return true;
}
101 102 103 104 105 106
template <typename Dtype, Precision P>
std::shared_ptr<framework::Tensor> PaddleMobile<Dtype, P>::Predict(
    const framework::Tensor &t) {
  return executor_->Predict(t);
}

xiebaiyuan's avatar
xiebaiyuan 已提交
107 108 109 110 111 112
template <typename Dtype, Precision P>
std::shared_ptr<framework::Tensor> PaddleMobile<Dtype, P>::PredictLod(
    const framework::LoDTensor &t) {
  return executor_->PredictLod(t);
}

113 114 115 116 117 118 119 120 121 122 123 124
template <typename Dtype, Precision P>
std::vector<typename PaddleMobile<Dtype, P>::Ptype>
PaddleMobile<Dtype, P>::Predict(const std::vector<Ptype> &input,
                                const std::vector<int64_t> &dims) {
  return executor_->Predict(input, dims);
}

template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::Clear() {
  executor_ = nullptr;
  loader_ = nullptr;
}
125
template <typename Dtype, Precision P>
Y
yangfei 已提交
126 127 128 129 130
double PaddleMobile<Dtype, P>::GetPredictTime() {}

#ifdef PADDLE_MOBILE_CPU
template <>
double PaddleMobile<CPU, Precision::FP32>::GetPredictTime() {
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  int m = 32;
  int n = 224 * 224;
  int k = 27;
  int lda = k;
  int ldb = n;
  int ldc = n;
  float *a =
      static_cast<float *>(paddle_mobile::memory::Alloc(sizeof(float) * m * k));
  float *b =
      static_cast<float *>(paddle_mobile::memory::Alloc(sizeof(float) * k * n));
  float *c =
      static_cast<float *>(paddle_mobile::memory::Alloc(sizeof(float) * m * n));
  int t1 = 1;
  int t2 = 1;
  for (int i = 0; i < m * k; ++i) {
    a[i] = t1 + rand() % t2;
  }
  for (int i = 0; i < k * n; ++i) {
    b[i] = t1 + rand() % t2;
  }
  paddle_mobile::operators::math::Gemm gemm;
  auto time1 = paddle_mobile::time();
Y
yangfei 已提交
153 154
  gemm.Sgemm(m, n, k, static_cast<float>(1), a, lda, b, ldb,
             static_cast<float>(0), c, ldc, false, nullptr);
155 156 157 158 159 160 161
  auto time2 = paddle_mobile::time();
  double cost = paddle_mobile::time_diff(time1, time2);
  paddle_mobile::memory::Free(a);
  paddle_mobile::memory::Free(b);
  paddle_mobile::memory::Free(c);
  return cost;
}
Y
yangfei 已提交
162
#endif
163

164
template <typename Dtype, Precision P>
L
liuruilong 已提交
165
PaddleMobile<Dtype, P>::~PaddleMobile() {
166 167 168 169
  executor_ = nullptr;
  loader_ = nullptr;
}

170 171 172 173
#ifdef PADDLE_MOBILE_FPGA

template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::InjectVariable(const framework::Tensor &t,
H
hjchen2 已提交
174
                                            std::string var_name) {
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
  executor_->InjectVariable(t, var_name);
}

template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::FeedData(const framework::Tensor &t) {
  executor_->FeedData(t);
}

template <typename Dtype, Precision P>
std::shared_ptr<framework::Tensor> PaddleMobile<Dtype, P>::FetchResult(int id) {
  return executor_->FetchResult(id);
}

template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::Predict_From_To(int start, int end) {
  executor_->Predict_From_To(start, end);
}

template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::Predict_From(int start) {
  executor_->Predict_From(start);
}

template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::Predict_To(int end) {
  executor_->Predict_To(end);
}
#endif

qnqinan's avatar
qnqinan 已提交
204
#ifdef PADDLE_MOBILE_CL
Z
zhangyang 已提交
205
static std::mutex lc;
qnqinan's avatar
qnqinan 已提交
206 207 208 209 210 211 212
template <typename Dtype, Precision P>
void PaddleMobile<Dtype, P>::SetCLPath(std::string path) {
  std::lock_guard<std::mutex> lock(lc);
  if (framework::CLEngine::Instance()->GetCLPath() == "") {
    framework::CLEngine::Instance()->setClPath(path);
  }
}
213 214
template <>
double PaddleMobile<GPU_CL, Precision::FP32>::GetPredictTime() {
215 216 217 218 219 220 221 222 223 224 225 226 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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  cl_int status;
  cl_uint nPlatform;
  clGetPlatformIDs(0, NULL, &nPlatform);
  cl_platform_id *listPlatform =
      (cl_platform_id *)malloc(nPlatform * sizeof(cl_platform_id));
  clGetPlatformIDs(nPlatform, listPlatform, NULL);
  cl_uint nDevice = 0;
  clGetDeviceIDs(listPlatform[0], CL_DEVICE_TYPE_GPU, 0, NULL, &nDevice);
  cl_device_id *listDevice =
      (cl_device_id *)malloc(nDevice * sizeof(cl_device_id));
  clGetDeviceIDs(listPlatform[0], CL_DEVICE_TYPE_GPU, nDevice, listDevice,
                 NULL);
  cl_context context =
      clCreateContext(NULL, nDevice, listDevice, NULL, NULL, &status);
  cl_command_queue queue =
      clCreateCommandQueue(context, listDevice[0], 0, &status);

  int n = 1;
  int c = 3;
  int h = 224;
  int w = 224;
  float *input = static_cast<float *>(
      paddle_mobile::memory::Alloc(sizeof(float) * 3 * 224 * 224));
  float *filter = static_cast<float *>(
      paddle_mobile::memory::Alloc(sizeof(float) * 32 * 27));
  int input_w = w * (c + 3) / 4;
  int input_h = n * h;
  int filter_w = 3 * (3 + 3) / 4;
  int filter_h = 32 * 3;
  int output_w = 224 * (32 + 3) / 4;
  int output_h = 1 * 224;

  framework::DDim input_dims = {1, 3, 224, 224};
  framework::CLTensor input_cl_tensor(context, queue);
  input_cl_tensor.Resize(input_dims);
  cl_mem inputBuffer = input_cl_tensor.mutable_with_data<float>(input);

  framework::DDim filter_dims = {32, 3, 3, 3};
  framework::CLTensor filter_cl_tensor(context, queue);
  input_cl_tensor.Resize(filter_dims);
  cl_mem filterBuffer = filter_cl_tensor.mutable_with_data<float>(filter);

  cl_mem cl_filter_image = NULL;
  cl_mem cl_input_image = NULL;
  cl_mem cl_output_image = NULL;
  cl_image_format cf = {.image_channel_order = CL_RGBA,
                        .image_channel_data_type = CL_HALF_FLOAT};
  cl_input_image = clCreateImage2D(context, CL_MEM_READ_WRITE | 0, &cf, input_w,
                                   input_h, 0, NULL, &status);
  cl_filter_image = clCreateImage2D(context, CL_MEM_READ_WRITE | 0, &cf,
                                    filter_w, filter_h, 0, NULL, &status);
  cl_output_image = clCreateImage2D(context, CL_MEM_READ_WRITE | 0, &cf,
                                    output_w, output_h, 0, NULL, &status);
  char *code;
  std::string path = framework::CLEngine::Instance()->GetCLPath() +
                     "/cl_kernel/feed_kernel.cl";
  size_t length = readText(path.c_str(), &code);
  cl_program program = clCreateProgramWithSource(
      context, 1, (const char **)&code, &length, NULL);
  std::string path1 = "-cl-fast-relaxed-math -I " +
                      framework::CLEngine::Instance()->GetCLPath() +
                      "/cl_kernel";
  clBuildProgram(program, 0, 0, path1.c_str(), NULL, NULL);
  cl_kernel kernel = clCreateKernel(program, "feed", &status);

  status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputBuffer);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 1, sizeof(cl_mem), &cl_input_image);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 2, sizeof(cl_int), &input_w);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 3, sizeof(cl_int), &input_h);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 4, sizeof(cl_int), &c);
  CL_CHECK_ERRORS(status);

  size_t global_work_size[2] = {input_w, input_h};

  //  cl_event out_event = param.Out()->GetClEvent();

  status = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, global_work_size,
                                  NULL, 0, NULL, NULL);
  CL_CHECK_ERRORS(status);

  status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &filterBuffer);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 1, sizeof(cl_mem), &cl_filter_image);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 2, sizeof(cl_int), &filter_w);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 3, sizeof(cl_int), &filter_h);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 4, sizeof(cl_int), &c);
  CL_CHECK_ERRORS(status);

  size_t global_work_size1[2] = {filter_w, filter_h};

  //  cl_event out_event = param.Out()->GetClEvent();

  status = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, global_work_size1,
                                  NULL, 0, NULL, NULL);
  CL_CHECK_ERRORS(status);

  clFinish(queue);
  queue = clCreateCommandQueue(context, listDevice[0], 0, &status);

  path = framework::CLEngine::Instance()->GetCLPath() +
         "/cl_kernel/conv_kernel.cl";
  size_t length1 = readText(path.c_str(), &code);
  program = clCreateProgramWithSource(context, 1, (const char **)&code,
                                      &length1, &status);
  CL_CHECK_ERRORS(status);
  clBuildProgram(program, 0, 0, path1.c_str(), NULL, NULL);
  kernel = clCreateKernel(program, "conv_3x3", &status);
  CL_CHECK_ERRORS(status);

  int c_block = (32 + 3) / 4;
  int nh = n * h;
  int stride = 1;
  int offset = 0;
  int input_c = (c + 3) / 4;
  int dilation = 1;
  int input_width = 224;
  int input_height = 224;
  int output_width = 224;
  int output_height = 224;
  status = clSetKernelArg(kernel, 0, sizeof(int), &c_block);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 1, sizeof(int), &w);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 2, sizeof(int), &nh);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 3, sizeof(cl_mem), &cl_input_image);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 4, sizeof(cl_mem), &cl_filter_image);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 5, sizeof(cl_mem), &cl_output_image);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 6, sizeof(int), &stride);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 7, sizeof(int), &offset);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 8, sizeof(int), &input_c);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 9, sizeof(int), &dilation);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 10, sizeof(int), &input_width);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 11, sizeof(int), &input_height);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 12, sizeof(int), &output_width);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 13, sizeof(int), &output_height);
  CL_CHECK_ERRORS(status);

  //  cl_event out_event = param.Output()->GetClEvent();
  //  cl_event wait_event = param.Input()->GetClEvent();
  size_t global_work_size2[3] = {8, 224, 224};
  auto time1 = paddle_mobile::time();
  status = clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size2,
                                  NULL, 0, NULL, NULL);
  CL_CHECK_ERRORS(status);
  clFinish(queue);
  auto time2 = paddle_mobile::time();
  paddle_mobile::memory::Free(input);
  paddle_mobile::memory::Free(filter);
  return paddle_mobile::time_diff(time1, time2);
}
template <typename Dtype, Precision P>
int PaddleMobile<Dtype, P>::readText(
    const char *kernelPath,
    char **pcode)  // 读取文本文件放入 pcode,返回字符串长度
{
  FILE *fp;
  int size;
  // printf("<readText> File: %s\n", kernelPath);
  fp = fopen(kernelPath, "rb");
  if (!fp) {
    printf("<readText> Open file failed\n");
    return -1;
  }
  if (fseek(fp, 0, SEEK_END) != 0) {
    printf("<readText> Seek end of file failed\n");
    return -1;
  }
  if ((size = ftell(fp)) < 0) {
    printf("<readText> Get file position failed\n");
    return -1;
  }
  rewind(fp);
  if ((*pcode = (char *)malloc(size + 1)) == NULL) {
    printf("<readText> Allocate space failed\n");
    return -1;
  }
  fread(*pcode, 1, size, fp);
  (*pcode)[size] = '\0';
  fclose(fp);
  return size + 1;
}

qnqinan's avatar
qnqinan 已提交
415 416
#endif

417 418 419 420
template class PaddleMobile<CPU, Precision::FP32>;
template class PaddleMobile<FPGA, Precision::FP32>;
template class PaddleMobile<GPU_MALI, Precision::FP32>;

qnqinan's avatar
qnqinan 已提交
421 422
template class PaddleMobile<GPU_CL, Precision::FP32>;

423
}  // namespace paddle_mobile