paddle_mobile.cpp 17.5 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 17
#include <utility>
#include "common/common.h"
18 19 20
#ifdef _OPENMP
#include <omp.h>
#endif  // _OPENMP
21
#ifdef PADDLE_MOBILE_CL
22
#include <CL/cl.h>
23 24
#include <mutex>
#include "framework/cl/cl_engine.h"
25
#include "framework/cl/cl_tensor.h"
26
#endif
27
#include "operators/math/gemm.h"
28

29 30
namespace paddle_mobile {

31
template <typename Device, typename T>
32 33 34
void PaddleMobile<Device, T>::SetThreadNum(int thread_num,
                                           PowerMode power_mode) {
  executor_->SetThreadNum(thread_num, power_mode);
35
}
36

37 38 39
template <typename Device, typename T>
PMStatus PaddleMobile<Device, T>::Load(const std::string &dirname,
                                       bool optimize, bool quantification,
40
                                       int batch_size, bool lod_mode) {
41
  if (loader_.get() == nullptr) {
42
    loader_ = std::make_shared<framework::Loader<Device, T>>();
43 44 45 46 47
  } else {
    LOG(kLOG_INFO) << "loader inited";
  }

  if (executor_.get() == nullptr) {
48
    executor_ = std::make_shared<framework::Executor<Device, T>>(
L
liuruilong 已提交
49 50
        loader_->Load(dirname, optimize, quantification), config_, batch_size,
        optimize, lod_mode);
51 52 53 54
  } else {
    LOG(kLOG_INFO) << "executor inited";
  }

55
  return PMSuccess;
56 57
}

58 59 60 61
template <typename Device, typename T>
PMStatus PaddleMobile<Device, T>::Load(const std::string &model_path,
                                       const std::string &para_path,
                                       bool optimize, bool quantification,
62
                                       int batch_size, bool lod_mode) {
63
  if (loader_.get() == nullptr) {
64
    loader_ = std::make_shared<framework::Loader<Device, T>>();
65 66 67 68 69
  } else {
    LOG(kLOG_INFO) << "loader inited";
  }

  if (executor_.get() == nullptr) {
70
    executor_ = std::make_shared<framework::Executor<Device, T>>(
L
liuruilong 已提交
71
        loader_->Load(model_path, para_path, optimize, quantification), config_,
72
        batch_size, optimize, lod_mode);
73 74 75 76
  } else {
    LOG(kLOG_INFO) << "executor inited";
  }

77
  return PMSuccess;
78 79
}

80
template <typename Device, typename T>
81 82 83 84 85 86 87 88 89 90 91 92 93 94
PMStatus PaddleMobile<Device, T>::Load(const PaddleMobileConfig &config) {
  if (!config.model_dir.empty()) {
    return this->Load(config.model_dir, config.optimize, config.quantification,
                      config.batch_size, config.lod_mode);
  } else if (!config.prog_file.empty() && !config.param_file.empty()) {
    return this->Load(config.prog_file, config.param_file, config.optimize,
                      config.quantification, config.batch_size,
                      config.lod_mode);
  } else {
    LOG(kLOG_ERROR) << "Failed to load inference model";
    return PMNotInitialized;
  }
}

95
template <typename Device, typename T>
L
liuruilong 已提交
96 97 98
bool PaddleMobile<Device, T>::LoadCombinedMemory(
    size_t model_len, const uint8_t *model_buf, size_t combined_params_len,
    uint8_t *combined_params_buf, bool optimize, bool quantification,
99
    int batch_size, bool lod_mode) {
100
  if (loader_.get() == nullptr) {
101
    loader_ = std::make_shared<framework::Loader<Device, T>>();
102 103 104 105
  } else {
    LOG(kLOG_INFO) << "loader inited";
  }
  if (executor_.get() == nullptr) {
106
    executor_ = std::make_shared<framework::Executor<Device, T>>(
107
        loader_->LoadCombinedMemory(model_len, model_buf, combined_params_len,
L
liuruilong 已提交
108
                                    combined_params_buf, optimize,
L
liuruilong 已提交
109 110
                                    quantification),
        config_, batch_size, optimize, lod_mode);
111 112 113 114
  } else {
    LOG(kLOG_INFO) << "executor inited";
  }

115 116 117 118 119 120 121 122
  return PMSuccess;
}

template <typename Device, typename T>
PMStatus PaddleMobile<Device, T>::Predict(const framework::Tensor &input) {
  std::vector<std::pair<std::string, framework::Tensor>> inputs;
  inputs.push_back(std::make_pair("feed", input));
  return this->Predict(inputs);
123
}
124 125 126 127 128 129 130 131 132 133 134 135

template <typename Device, typename T>
PMStatus PaddleMobile<Device, T>::Predict(const framework::LoDTensor &input) {
  std::vector<std::pair<std::string, framework::LoDTensor>> inputs;
  inputs.push_back(std::make_pair("feed", input));
  return this->Predict(inputs);
}

template <typename Device, typename T>
PMStatus PaddleMobile<Device, T>::Predict(
    const std::vector<std::pair<std::string, framework::Tensor>> &inputs) {
  return executor_->Predict(inputs);
136 137
}

138 139 140 141
template <typename Device, typename T>
PMStatus PaddleMobile<Device, T>::Predict(
    const std::vector<std::pair<std::string, framework::LoDTensor>> &inputs) {
  return executor_->Predict(inputs);
xiebaiyuan's avatar
xiebaiyuan 已提交
142 143
}

144 145 146
template <typename Device, typename T>
std::vector<T> PaddleMobile<Device, T>::Predict(
    const std::vector<T> &input, const std::vector<int64_t> &dims) {
147 148 149
  return executor_->Predict(input, dims);
}

150 151 152 153 154 155
template <typename Device, typename T>
PMStatus PaddleMobile<Device, T>::Predict() {
  return executor_->Predict();
}

template <typename Device, typename T>
H
update  
hjchen2 已提交
156 157
void PaddleMobile<Device, T>::Feed(const std::string &var_name,
                                   const framework::Tensor &input) {
158 159 160 161
  executor_->SetInput(input, var_name);
}

template <typename Device, typename T>
H
update  
hjchen2 已提交
162 163
void PaddleMobile<Device, T>::Feed(const std::string &var_name,
                                   const framework::LoDTensor &input) {
164 165 166 167 168 169 170 171 172 173 174
  executor_->SetInput(input, var_name);
}

typedef std::shared_ptr<framework::LoDTensor> LoDTensorPtr;
template <typename Device, typename T>
LoDTensorPtr PaddleMobile<Device, T>::Fetch(const std::string &var_name) {
  return executor_->GetOutput(var_name);
}

template <typename Device, typename T>
void PaddleMobile<Device, T>::Clear() {
175 176 177
  executor_ = nullptr;
  loader_ = nullptr;
}
178 179 180

template <typename Device, typename T>
double PaddleMobile<Device, T>::GetPredictTime() {}
Y
yangfei 已提交
181 182 183

#ifdef PADDLE_MOBILE_CPU
template <>
184
double PaddleMobile<CPU, float>::GetPredictTime() {
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  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) {
200
    a[i] = t1 + rand() % t2;  // NOLINT
201 202
  }
  for (int i = 0; i < k * n; ++i) {
203
    b[i] = t1 + rand() % t2;  // NOLINT
204
  }
205 206

  operators::math::Gemm gemm;
207
  auto time1 = paddle_mobile::time();
208 209 210 211 212 213 214
  int times = 4;
  for (int j = 0; j < times; ++j) {
    gemm.Sgemm(m, n, k, static_cast<float>(1), a, lda, b, ldb,
               static_cast<float>(0), c, ldc, false,
               static_cast<float *>(nullptr));
  }

215
  auto time2 = paddle_mobile::time();
216
  double cost = paddle_mobile::time_diff(time1, time2) / times;
217 218 219 220 221
  paddle_mobile::memory::Free(a);
  paddle_mobile::memory::Free(b);
  paddle_mobile::memory::Free(c);
  return cost;
}
Y
yangfei 已提交
222
#endif
223

224
#ifdef PADDLE_MOBILE_FPGA
H
hjchen2 已提交
225 226
template <typename Device, typename T>
void PaddleMobile<Device, T>::InjectVariable(const framework::Tensor &t,
227
                                             std::string var_name) {
228 229 230
  executor_->InjectVariable(t, var_name);
}

H
hjchen2 已提交
231 232
template <typename Device, typename T>
void PaddleMobile<Device, T>::FeedData(const framework::Tensor &t) {
233 234 235
  executor_->FeedData(t);
}

236
template <typename Device, typename T>
237
void PaddleMobile<Device, T>::FeedData(const std::vector<void *> &v) {
238
  executor_->FeedData(v);
H
hjchen2 已提交
239
}
240 241 242 243 244
template <typename Device, typename T>
void PaddleMobile<Device, T>::FeedTensorData(
    const std::vector<framework::Tensor> &v) {
  executor_->FeedTensorData(v);
}
H
hjchen2 已提交
245

246 247 248 249 250
template <typename Device, typename T>
void PaddleMobile<Device, T>::GetResults(std::vector<void *> *v) {
  executor_->GetResults(v);
}

251
template <typename Device, typename T>
252 253 254
void PaddleMobile<Device, T>::GetTensorResults(
    std::vector<framework::Tensor *> *v) {
  executor_->GetTensorResults(v);
255 256
}

257 258 259 260
template <typename Device, typename T>
framework::Tensor *PaddleMobile<Device, T>::GetTensorByName(
    const std::string &name) {
  return executor_->GetTensorByName(name);
H
hjchen2 已提交
261
}
262

H
hjchen2 已提交
263 264
template <typename Device, typename T>
std::shared_ptr<framework::Tensor> PaddleMobile<Device, T>::FetchResult(
265
    int id) {
266 267 268
  return executor_->FetchResult(id);
}

H
hjchen2 已提交
269 270
template <typename Device, typename T>
void PaddleMobile<Device, T>::Predict_From_To(int start, int end) {
271 272 273
  executor_->Predict_From_To(start, end);
}

H
hjchen2 已提交
274 275
template <typename Device, typename T>
void PaddleMobile<Device, T>::Predict_From(int start) {
276 277 278
  executor_->Predict_From(start);
}

H
hjchen2 已提交
279 280
template <typename Device, typename T>
void PaddleMobile<Device, T>::Predict_To(int end) {
281 282 283 284
  executor_->Predict_To(end);
}
#endif

Y
yangfei 已提交
285
#ifdef PADDLE_MOBILE_CL
Z
zhangyang 已提交
286
static std::mutex lc;
H
hjchen2 已提交
287 288
template <typename Device, typename T>
void PaddleMobile<Device, T>::SetCLPath(std::string path) {
Y
yangfei 已提交
289 290 291 292
  std::lock_guard<std::mutex> lock(lc);
  if (framework::CLEngine::Instance()->GetCLPath() == "") {
    framework::CLEngine::Instance()->setClPath(path);
  }
Y
yangfei 已提交
293
}
294
template <>
H
hjchen2 已提交
295
double PaddleMobile<GPU_CL, float>::GetPredictTime() {
296
  cl_int status;
297 298 299 300 301
  if (!framework::CLEngine::Instance()->isInitSuccess()) {
    return -1;
  }
  cl_context context = framework::CLEngine::Instance()->getContext();
  cl_command_queue queue = framework::CLEngine::Instance()->getClCommandQueue();
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

  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);

Y
yangfei 已提交
351 352 353 354 355 356
  int out_H = 224;
  int out_W = 224;
  int out_C = 3;
  int Stride2 = out_C * out_H * out_W;
  int Stride1 = out_H * out_W;
  int Stride0 = out_W;
357 358 359 360
  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);
Y
yangfei 已提交
361
  status = clSetKernelArg(kernel, 2, sizeof(cl_int), &out_H);
362
  CL_CHECK_ERRORS(status);
Y
yangfei 已提交
363
  status = clSetKernelArg(kernel, 3, sizeof(cl_int), &out_W);
364
  CL_CHECK_ERRORS(status);
Y
yangfei 已提交
365 366 367 368 369 370 371
  status = clSetKernelArg(kernel, 4, sizeof(cl_int), &out_C);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 5, sizeof(cl_int), &Stride0);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 6, sizeof(cl_int), &Stride1);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 7, sizeof(cl_int), &Stride2);
372 373
  CL_CHECK_ERRORS(status);

Y
yangfei 已提交
374
  size_t global_work_size[3] = {1, 224, 224};
375 376 377

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

Y
yangfei 已提交
378
  status = clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size,
379 380 381
                                  NULL, 0, NULL, NULL);
  CL_CHECK_ERRORS(status);

Y
yangfei 已提交
382 383 384 385 386 387 388
  out_H = 3;
  out_W = 3;
  out_C = 3;
  Stride2 = out_C * out_H * out_W;
  Stride1 = out_H * out_W;
  Stride0 = out_W;

389 390 391 392
  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);
Y
yangfei 已提交
393 394 395
  status = clSetKernelArg(kernel, 2, sizeof(cl_int), &out_H);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 3, sizeof(cl_int), &out_W);
396
  CL_CHECK_ERRORS(status);
Y
yangfei 已提交
397
  status = clSetKernelArg(kernel, 4, sizeof(cl_int), &out_C);
398
  CL_CHECK_ERRORS(status);
Y
yangfei 已提交
399 400 401 402 403
  status = clSetKernelArg(kernel, 5, sizeof(cl_int), &Stride0);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 6, sizeof(cl_int), &Stride1);
  CL_CHECK_ERRORS(status);
  status = clSetKernelArg(kernel, 7, sizeof(cl_int), &Stride2);
404 405
  CL_CHECK_ERRORS(status);

Y
yangfei 已提交
406
  size_t global_work_size1[3] = {1, 3, 96};
407 408 409

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

Y
yangfei 已提交
410
  status = clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size1,
411 412 413 414
                                  NULL, 0, NULL, NULL);
  CL_CHECK_ERRORS(status);

  clFinish(queue);
415
  //  queue = clCreateCommandQueue(context, listDevice[0], 0, &status);
416 417 418 419 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 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

  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();
470 471 472 473 474
  int times = 10;
  for (int i = 0; i < times; ++i) {
    status = clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size2,
                                    NULL, 0, NULL, NULL);
  }
475 476 477 478 479
  CL_CHECK_ERRORS(status);
  clFinish(queue);
  auto time2 = paddle_mobile::time();
  paddle_mobile::memory::Free(input);
  paddle_mobile::memory::Free(filter);
Y
yangfei 已提交
480
  if (status == CL_SUCCESS) {
481
    return paddle_mobile::time_diff(time1, time2) / times;
Y
yangfei 已提交
482 483 484
  } else {
    return -1;
  }
485
}
H
hjchen2 已提交
486 487
template <typename Device, typename T>
int PaddleMobile<Device, T>::readText(
488
    const char *kernelPath,
Y
yangfei 已提交
489
    char **pcode) {  // 读取文本文件放入 pcode,返回字符串长度
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  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);
Y
yangfei 已提交
507
  if ((*pcode = reinterpret_cast<char *>(malloc(size + 1))) == NULL) {
508 509 510 511 512 513 514 515
    printf("<readText> Allocate space failed\n");
    return -1;
  }
  fread(*pcode, 1, size, fp);
  (*pcode)[size] = '\0';
  fclose(fp);
  return size + 1;
}
Y
yangfei 已提交
516 517
#endif

518 519 520 521
template class PaddleMobile<CPU, float>;
template class PaddleMobile<FPGA, float>;
template class PaddleMobile<GPU_MALI, float>;
template class PaddleMobile<GPU_CL, float>;
Y
yangfei 已提交
522

523
}  // namespace paddle_mobile