cl_engine.h 8.3 KB
Newer Older
L
liuruilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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. */

#pragma once

17
#include <cstring>
L
liuruilong 已提交
18 19
#include <memory>
#include <string>
20
#include <utility>
L
liuruilong 已提交
21

22
#include "CL/cl.h"
L
liuruilong 已提交
23
#include "common/enforce.h"
L
liuruilong 已提交
24
#include "common/log.h"
L
liuruilong 已提交
25
#include "framework/cl/cl_deleter.h"
L
liuruilong 已提交
26
#include "framework/cl/cl_tool.h"
L
liuruilong 已提交
27

L
liuruilong 已提交
28 29 30
namespace paddle_mobile {
namespace framework {

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
class CLLocalWorkSizeInfo {
 public:
  CLLocalWorkSizeInfo() {
    max_work_group_size = 0;
    max_work_item_size0 = 0;
    max_work_item_size1 = 0;
    max_work_item_size2 = 0;
  }
  CLLocalWorkSizeInfo(size_t total_size, size_t size0, size_t size1,
                      size_t size2) {
    max_work_group_size = total_size;
    max_work_item_size0 = size0;
    max_work_item_size1 = size1;
    max_work_item_size2 = size2;
  }
  bool isEmpty() {
    return max_work_group_size == 0 && max_work_item_size0 == 0 &&
           max_work_item_size1 == 0 && max_work_item_size2 == 0;
  }

  // max total number of work-items in the work-group
  size_t max_work_group_size;
  // max number of work-items in local_work_size in dim 0
  size_t max_work_item_size0;
  // max number of work-items in local_work_size in dim 1
  size_t max_work_item_size1;
  // max number of work-items in local_work_size in dim 2
  size_t max_work_item_size2;
};

L
liuruilong 已提交
61 62 63 64 65
class CLEngine {
 public:
  static CLEngine *Instance();

  bool Init();
xiebaiyuan's avatar
xiebaiyuan 已提交
66
  bool isInitSuccess();
L
liuruilong 已提交
67
  std::unique_ptr<_cl_context, CLContextDeleter> CreateContext() {
L
liuruilong 已提交
68 69
    cl_int status;
    cl_context c = clCreateContext(NULL, 1, devices_, NULL, NULL, &status);
L
liuruilong 已提交
70
    std::unique_ptr<_cl_context, CLContextDeleter> context_ptr(c);
L
liuruilong 已提交
71
    CL_CHECK_ERRORS(status);
L
liuruilong 已提交
72 73
    return std::move(context_ptr);
  }
L
liuruilong 已提交
74

L
liuruilong 已提交
75 76
  std::unique_ptr<_cl_command_queue, CLCommQueueDeleter> CreateClCommandQueue(
      cl_context context) {
L
liuruilong 已提交
77
    cl_int status;
78
    cl_command_queue queue =
L
liuruilong 已提交
79
        clCreateCommandQueue(context, devices_[0], 0, &status);
80 81
    std::unique_ptr<_cl_command_queue, CLCommQueueDeleter> command_queue_ptr(
        queue);
L
liuruilong 已提交
82
    CL_CHECK_ERRORS(status);
L
liuruilong 已提交
83 84
    return std::move(command_queue_ptr);
  }
L
liuruilong 已提交
85

xiebaiyuan's avatar
xiebaiyuan 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99
  cl_context getContext() {
    if (context_ == nullptr) {
      context_ = CreateContext();
    }
    return context_.get();
  }

  cl_command_queue getClCommandQueue() {
    if (command_queue_ == nullptr) {
      command_queue_ = CreateClCommandQueue(getContext());
    }
    return command_queue_.get();
  }

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  CLLocalWorkSizeInfo getLocalWorkSizeInfo() {
    if (!localWorkSizeInfo_.isEmpty()) {
      return localWorkSizeInfo_;
    }
    cl_int status;
    size_t max_work_group_size = 0;
    status = clGetDeviceInfo(devices_[0], CL_DEVICE_MAX_WORK_GROUP_SIZE,
                             sizeof(size_t), &max_work_group_size, NULL);
    if (status != CL_SUCCESS) {
      return CLLocalWorkSizeInfo(0, 0, 0, 0);
    }
    cl_uint max_dims_num = 0;
    status = clGetDeviceInfo(devices_[0], CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS,
                             sizeof(cl_uint), &max_dims_num, NULL);
    if (status != CL_SUCCESS) {
      return CLLocalWorkSizeInfo(0, 0, 0, 0);
    }
    DLOG << "max_work_item_sizes max_dims_num: " << max_dims_num;
    size_t *max_work_item_sizes =
        reinterpret_cast<size_t *>(calloc(max_dims_num, sizeof(size_t)));
    size_t ret_size = 0;
    status = clGetDeviceInfo(devices_[0], CL_DEVICE_MAX_WORK_ITEM_SIZES,
                             max_dims_num * sizeof(size_t), max_work_item_sizes,
                             &ret_size);
    if (status != CL_SUCCESS || ret_size / sizeof(size_t) < 3) {
      return CLLocalWorkSizeInfo(0, 0, 0, 0);
    }
    DLOG << max_work_item_sizes[0];
    DLOG << max_work_item_sizes[1];
    DLOG << max_work_item_sizes[2];
    localWorkSizeInfo_ =
        CLLocalWorkSizeInfo(max_work_group_size, max_work_item_sizes[0],
                            max_work_item_sizes[1], max_work_item_sizes[2]);
    free(max_work_item_sizes);
    return localWorkSizeInfo_;
  }
136 137 138 139 140 141 142 143 144 145 146 147
  size_t GetKernelWorkSize(cl_kernel kernel) {
    cl_int status;
    size_t kernel_work_size = 0;
    status =
        clGetKernelWorkGroupInfo(kernel, devices_[0], CL_KERNEL_WORK_GROUP_SIZE,
                                 sizeof(size_t), &kernel_work_size, NULL);
    if (status != CL_SUCCESS) {
      return 0;
    }
    DLOG << "kernel_work_size: " << kernel_work_size;
    return kernel_work_size;
  }
148

149 150
  std::unique_ptr<_cl_program, CLProgramDeleter> CreateProgramWith(
      cl_context context, std::string file_name) {
L
liuruilong 已提交
151 152
    FILE *file = fopen(file_name.c_str(), "rb");
    PADDLE_MOBILE_ENFORCE(file != nullptr, "can't open file: %s ",
L
liuruilong 已提交
153
                          file_name.c_str());
L
liuruilong 已提交
154 155 156 157 158 159 160 161 162 163 164 165
    fseek(file, 0, SEEK_END);
    int64_t size = ftell(file);
    PADDLE_MOBILE_ENFORCE(size > 0, "size is too small");
    rewind(file);
    char *data = new char[size + 1];
    size_t bytes_read = fread(data, 1, size, file);
    data[size] = '\0';
    PADDLE_MOBILE_ENFORCE(bytes_read == size,
                          "read binary file bytes do not match with fseek");
    fclose(file);

    const char *source = data;
L
liuruilong 已提交
166
    size_t sourceSize[] = {strlen(source)};
167
    cl_program p =
L
liuruilong 已提交
168 169 170 171 172 173
        clCreateProgramWithSource(context, 1, &source, sourceSize, &status_);

    DLOG << " cl kernel file name: " << file_name;
    DLOG << " source size: " << sourceSize[0];
    CL_CHECK_ERRORS(status_);

L
liuruilong 已提交
174
    std::unique_ptr<_cl_program, CLProgramDeleter> program_ptr(p);
L
liuruilong 已提交
175

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    return std::move(program_ptr);
  }

  std::unique_ptr<_cl_program, CLProgramDeleter> CreateProgramWithSource(
      cl_context context, const char *source) {
    size_t sourceSize[] = {strlen(source)};
    cl_program p =
        clCreateProgramWithSource(context, 1, &source, sourceSize, &status_);

    DLOG << " cl kernel from source";
    DLOG << " source size: " << sourceSize[0];
    CL_CHECK_ERRORS(status_);

    std::unique_ptr<_cl_program, CLProgramDeleter> program_ptr(p);

L
liuruilong 已提交
191 192
    return std::move(program_ptr);
  }
L
liuruilong 已提交
193

L
liuruilong 已提交
194
  std::unique_ptr<_cl_event, CLEventDeleter> CreateEvent(cl_context context) {
L
liuruilong 已提交
195
    cl_event event = clCreateUserEvent(context, &status_);
L
liuruilong 已提交
196
    std::unique_ptr<_cl_event, CLEventDeleter> event_ptr(event);
L
liuruilong 已提交
197
    CL_CHECK_ERRORS(status_);
L
liuruilong 已提交
198 199 200
    return std::move(event_ptr);
  }

201
  bool BuildProgram(cl_program program, const std::string &options = "") {
L
liuruilong 已提交
202
    cl_int status;
203
    std::string path = options + " -cl-fast-relaxed-math -I " +
204 205 206
                       CLEngine::Instance()->GetCLPath() + "/cl_kernel";

    status = clBuildProgram(program, 0, 0, path.c_str(), 0, 0);
L
liuruilong 已提交
207

L
liuruilong 已提交
208
    CL_CHECK_ERRORS(status);
L
liuruilong 已提交
209

210
    if (status == CL_BUILD_PROGRAM_FAILURE) {
L
liuruilong 已提交
211 212 213
      size_t log_size;
      clGetProgramBuildInfo(program, CLEngine::Instance()->DeviceID(),
                            CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);
L
liuruilong 已提交
214
      char *log = reinterpret_cast<char *>(malloc(log_size));
L
liuruilong 已提交
215 216 217 218 219 220 221 222 223 224
      clGetProgramBuildInfo(program, CLEngine::Instance()->DeviceID(),
                            CL_PROGRAM_BUILD_LOG, log_size, log, NULL);
      DLOG << " program build error: " << log;
    }

    if (status == CL_SUCCESS) {
      return true;
    } else {
      return false;
    }
L
liuruilong 已提交
225
  }
L
liuruilong 已提交
226

L
liuruilong 已提交
227 228
  cl_device_id DeviceID(int index = 0) { return devices_[index]; }

Y
yangfei 已提交
229 230 231
  std::string GetCLPath() { return cl_path_; }
  void setClPath(std::string cl_path) { cl_path_ = cl_path; }

L
liuruilong 已提交
232 233 234 235 236 237 238 239
 private:
  CLEngine() { initialized_ = false; }

  bool SetPlatform();

  bool SetClDeviceId();

  bool initialized_;
L
liuruilong 已提交
240

241 242
  CLLocalWorkSizeInfo localWorkSizeInfo_;

L
liuruilong 已提交
243
  cl_platform_id platform_;
L
liuruilong 已提交
244

L
liuruilong 已提交
245
  cl_device_id *devices_;
L
liuruilong 已提交
246

L
liuruilong 已提交
247 248
  cl_int status_;

249
  std::string cl_path_;
L
liuruilong 已提交
250
  std::unique_ptr<_cl_program, CLProgramDeleter> program_;
L
liuruilong 已提交
251

xiebaiyuan's avatar
xiebaiyuan 已提交
252 253 254 255 256
  std::unique_ptr<_cl_context, CLContextDeleter> context_ = nullptr;

  std::unique_ptr<_cl_command_queue, CLCommQueueDeleter> command_queue_ =
      nullptr;

257
  //  bool SetClContext();
L
liuruilong 已提交
258

259
  //  bool SetClCommandQueue();
L
liuruilong 已提交
260

261
  //  bool LoadKernelFromFile(const char *kernel_file);
L
liuruilong 已提交
262

263
  //  bool BuildProgram();
xiebaiyuan's avatar
xiebaiyuan 已提交
264
  bool is_init_success_ = false;
L
liuruilong 已提交
265 266 267 268
};

}  // namespace framework
}  // namespace paddle_mobile