hl_cuda_device.cc 23.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yu Yang 已提交
15 16 17
// clang-format off
// Because clang-format 4.X and clang-format 3.8+ format 
// following lines in different. So disable clang-format.
Y
Yu Yang 已提交
18
#include "hl_cuda.h"
L
liaogang 已提交
19
#include <cuda_profiler_api.h>
Z
zhangjinchao01 已提交
20 21
#include <string.h>
#include <sys/syscall.h>
L
liaogang 已提交
22 23
#include <sys/time.h>
#include <unistd.h>
Z
zhangjinchao01 已提交
24 25 26
#include <mutex>
#include "hl_cuda.ph"
#include "hl_dso_loader.h"
L
liaogang 已提交
27
#include "hl_thread.ph"
Z
zhangjinchao01 已提交
28
#include "paddle/utils/Logging.h"
Y
Yu Yang 已提交
29
// clang-format on
Z
zhangjinchao01 已提交
30 31 32 33

namespace dynload {

std::once_flag curand_dso_flag;
34
void *curand_dso_handle = nullptr;
Z
zhangjinchao01 已提交
35 36 37 38 39 40 41 42 43

/**
 * The following macro definition can generate structs
 * (for each function) to dynamic load curand routine
 * via operator overloading.
 *
 * note: default dynamic linked libs
 */
#ifdef PADDLE_USE_DSO
44 45 46 47 48 49 50 51 52 53
#define DYNAMIC_LOAD_CURAND_WRAP(__name)                                       \
  struct DynLoad__##__name {                                                   \
    template <typename... Args>                                                \
    curandStatus_t operator()(Args... args) {                                  \
      typedef curandStatus_t (*curandFunc)(Args...);                           \
      std::call_once(curand_dso_flag, GetCurandDsoHandle, &curand_dso_handle); \
      void *p_##__name = dlsym(curand_dso_handle, #__name);                    \
      return reinterpret_cast<curandFunc>(p_##__name)(args...);                \
    }                                                                          \
  } __name; /* struct DynLoad__##__name */
Z
zhangjinchao01 已提交
54
#else
55 56 57 58 59 60 61
#define DYNAMIC_LOAD_CURAND_WRAP(__name)      \
  struct DynLoad__##__name {                  \
    template <typename... Args>               \
    curandStatus_t operator()(Args... args) { \
      return __name(args...);                 \
    }                                         \
  } __name; /* struct DynLoad__##__name */
Z
zhangjinchao01 已提交
62 63 64
#endif

/* include all needed curand functions in HPPL */
L
Luo Tao 已提交
65
// clang-format off
Z
zhangjinchao01 已提交
66 67 68 69 70 71
#define CURAND_RAND_ROUTINE_EACH(__macro)    \
  __macro(curandCreateGenerator)             \
  __macro(curandSetStream)                   \
  __macro(curandSetPseudoRandomGeneratorSeed)\
  __macro(curandGenerateUniform)             \
  __macro(curandGenerateUniformDouble)
L
Luo Tao 已提交
72
// clang-format on
Z
zhangjinchao01 已提交
73 74 75 76 77 78 79

CURAND_RAND_ROUTINE_EACH(DYNAMIC_LOAD_CURAND_WRAP)

#undef CURAND_RAND_ROUTINE_EACH
#undef DYNAMIC_LOAD_CURAND_WRAP

std::once_flag cudart_dso_flag;
80
void *cudart_dso_handle = nullptr;
Z
zhangjinchao01 已提交
81 82 83 84 85 86 87 88 89

/**
 * The following macro definition can generate structs
 * (for each function) to dynamic load cuda routine
 * via operator overloading.
 *
 * note: default dynamic linked libs
 */
#ifdef PADDLE_USE_DSO
90 91 92 93 94 95 96 97 98 99
#define DYNAMIC_LOAD_CUDART_WRAP(__name)                                       \
  struct DynLoad__##__name {                                                   \
    template <typename... Args>                                                \
    auto operator()(Args... args) -> decltype(__name(args...)) {               \
      using cudart_func = decltype(__name(args...)) (*)(Args...);              \
      std::call_once(cudart_dso_flag, GetCudartDsoHandle, &cudart_dso_handle); \
      void *p_##__name = dlsym(cudart_dso_handle, #__name);                    \
      return reinterpret_cast<cudart_func>(p_##__name)(args...);               \
    }                                                                          \
  } __name; /* struct DynLoad__##__name */
Z
zhangjinchao01 已提交
100
#else
101 102 103 104 105 106 107
#define DYNAMIC_LOAD_CUDART_WRAP(__name)                         \
  struct DynLoad__##__name {                                     \
    template <typename... Args>                                  \
    auto operator()(Args... args) -> decltype(__name(args...)) { \
      return __name(args...);                                    \
    }                                                            \
  } __name; /* struct DynLoad__##__name */
Z
zhangjinchao01 已提交
108 109 110
#endif

/* include all needed cuda functions in HPPL */
L
Luo Tao 已提交
111
// clang-format off
Z
zhangjinchao01 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
#define CUDA_ROUTINE_EACH(__macro)        \
  __macro(cudaMalloc)                     \
  __macro(cudaHostAlloc)                  \
  __macro(cudaFree)                       \
  __macro(cudaFreeHost)                   \
  __macro(cudaMemcpy)                     \
  __macro(cudaMemset)                     \
  __macro(cudaMemcpyAsync)                \
  __macro(cudaSetDevice)                  \
  __macro(cudaGetDevice)                  \
  __macro(cudaGetDeviceCount)             \
  __macro(cudaGetDeviceProperties)        \
  __macro(cudaDeviceSynchronize)          \
  __macro(cudaDeviceCanAccessPeer)        \
  __macro(cudaDeviceEnablePeerAccess)     \
  __macro(cudaStreamCreate)               \
  __macro(cudaStreamDestroy)              \
  __macro(cudaStreamSynchronize)          \
  __macro(cudaStreamWaitEvent)            \
  __macro(cudaEventCreate)                \
  __macro(cudaEventRecord)                \
  __macro(cudaEventQuery)                 \
  __macro(cudaEventDestroy)               \
  __macro(cudaEventSynchronize)           \
  __macro(cudaEventElapsedTime)           \
  __macro(cudaSetDeviceFlags)             \
  __macro(cudaGetLastError)               \
  __macro(cudaFuncSetCacheConfig)         \
140
  __macro(cudaRuntimeGetVersion)          \
L
liaogang 已提交
141 142 143
  __macro(cudaGetErrorString)             \
  __macro(cudaProfilerStart)              \
  __macro(cudaProfilerStop)
L
Luo Tao 已提交
144
// clang-format on
Z
zhangjinchao01 已提交
145 146 147 148 149 150

CUDA_ROUTINE_EACH(DYNAMIC_LOAD_CUDART_WRAP)

#undef CUDA_ROUNTINE_EACH
#undef DYNAMIC_LOAD_CUDART_WRAP

151
} /* namespace dynload */
Z
zhangjinchao01 已提交
152 153 154 155

/**
 * @brief   global resource.
 */
156 157 158 159
int g_system_device_num = 0;                /* system device number */
int device_num = 0;                         /* use    device number */
hl_device_prop *g_device;                   /* device info table */
__thread thread_device_resources *t_device; /* device resources table */
Z
zhangjinchao01 已提交
160 161 162
int g_cuda_lib_version = 0;

/* number of global stream */
163
#define NUMBER_OF_GLOBAL_STREAM (HPPL_THREAD_STREAM_1)
Z
zhangjinchao01 已提交
164
/* number of thread stream */
165
#define NUMBER_OF_THREAD_STREAM (HPPL_STREAM_END - HPPL_THREAD_STREAM_1)
Z
zhangjinchao01 已提交
166
/* sizeof of device memory */
167
#define HPPL_GPU_MEMORY_SIZE (256 * 4)
Z
zhangjinchao01 已提交
168 169

/**
170
 * Check build-in cuda function using glog and it **does not**
Z
zhangjinchao01 已提交
171 172
 * support << operator for more details error info.
 */
173 174 175 176 177
#define CHECK_CUDA(cudaFunc)                                                  \
  do {                                                                        \
    cudaError_t cudaStat = cudaFunc;                                          \
    CHECK_EQ(cudaSuccess, cudaStat) << "Cuda Error: "                         \
                                    << dynload::cudaGetErrorString(cudaStat); \
178
  } while (0)
Z
zhangjinchao01 已提交
179 180 181 182

/**
 * @brief   thread resource.
 */
183 184 185 186 187 188 189 190 191 192 193 194
__thread _hl_thread_resource t_resource = {{0},    /* stream */
                                           0,      /* handle */
                                           0,      /* gen */
                                           0,      /* cudnn_handle */
                                           0,      /* cudnn_desc */
                                           NULL,   /* gen_mutex */
                                           NULL,   /* gpu_mem */
                                           NULL,   /* cpu_mem */
                                           0,      /* event */
                                           -1,     /* device */
                                           0,      /* major */
                                           false}; /* is_init */
Z
zhangjinchao01 已提交
195 196 197 198 199

__thread cudaStream_t default_stream = 0;
__thread bool g_sync_flag = true;
bool hl_start_flag = false;

L
liaogang 已提交
200 201
inline pid_t gettid() {
#if defined(__APPLE__) || defined(__OSX__)
G
gangliao 已提交
202 203 204 205 206
  // syscall is deprecated: first deprecated in macOS 10.12.
  // syscall is unsupported;
  // syscall pid_t tid = syscall(SYS_thread_selfid);
  uint64_t tid;
  pthread_threadid_np(NULL, &tid);
L
liaogang 已提交
207
#else
208 209 210
#ifndef __NR_gettid
#define __NR_gettid 224
#endif
L
liaogang 已提交
211 212
  pid_t tid = syscall(__NR_gettid);
#endif
213 214
  CHECK_NE((int)tid, -1);
  return tid;
L
liaogang 已提交
215
}
Z
zhangjinchao01 已提交
216 217

void hl_init(int device) {
218
  CHECK(hl_start_flag) << "[Init failed] hl_start() did not succeed.";
Z
zhangjinchao01 已提交
219 220 221 222 223 224 225 226 227 228

  /* thread has been initialized */
  if (true == t_resource.is_init) {
    hl_set_device(device);
    return;
  }

  /* create thread devcie resources */
  char *tmp;
  thread_device_resources device_res;
229 230
  tmp = (char *)malloc(g_system_device_num * sizeof(thread_device_resources *) +
                       device_num * sizeof(_thread_device_resources));
Z
zhangjinchao01 已提交
231
  CHECK_NOTNULL(tmp);
232 233 234 235
  t_device = (thread_device_resources *)tmp;
  device_res = (thread_device_resources)(
      (char *)tmp + g_system_device_num * sizeof(thread_device_resources *));
  memset(t_device, 0, g_system_device_num * sizeof(thread_device_resources *));
Z
zhangjinchao01 已提交
236

237 238
  char *tmp_stream = (char *)malloc(device_num * NUMBER_OF_THREAD_STREAM *
                                    sizeof(cudaStream_t));
Z
zhangjinchao01 已提交
239 240 241 242 243 244 245 246 247
  CHECK_NOTNULL(tmp_stream);

  int num = 0;
  for (int dev = 0; dev < g_system_device_num; dev++) {
    if (!g_device[dev]) {
      continue;
    }

    t_device[dev] = &device_res[num];
248 249 250
    t_device[dev]->stream =
        (cudaStream_t *)(tmp_stream +
                         num * NUMBER_OF_THREAD_STREAM * sizeof(cudaStream_t));
Z
zhangjinchao01 已提交
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

    hl_create_thread_resources(dev, t_device[dev]);
    num++;
  }

  hl_cudnn_desc_init(&t_resource.cudnn_desc);

  /* thread initialization is complete */
  t_resource.is_init = true;
  /* set device */
  t_resource.device = -1;
  hl_set_device(device);
}

void hl_fini() {
  if (false == t_resource.is_init) {
    return;
  }

  /* hppl stream fini */
  t_resource.device = -1;
  for (int i = NUMBER_OF_GLOBAL_STREAM; i < HPPL_STREAM_END; i++) {
    t_resource.stream[i] = 0;
  }

276 277
  char *tmp = (char *)t_device;
  char *tmp_stream = NULL;
Z
zhangjinchao01 已提交
278 279 280 281 282
  for (int dev = 0; dev < g_system_device_num; dev++) {
    if (!t_device[dev]) {
      continue;
    }
    if (!tmp_stream) {
283
      tmp_stream = (char *)t_device[dev]->stream;
Z
zhangjinchao01 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    }
    for (int j = 0; j < NUMBER_OF_THREAD_STREAM; j++) {
      CHECK_CUDA(dynload::cudaStreamDestroy(t_device[dev]->stream[j]));
    }

    /* free device memory */
    hl_free_mem_device(t_device[dev]->gpu_mem);
    hl_free_mem_host(t_device[dev]->cpu_mem);
    CHECK_CUDA(dynload::cudaEventDestroy(t_device[dev]->mem_event));
  }

  free(tmp);
  free(tmp_stream);
  t_resource.is_init = false;
}

300
int hl_get_device_count() { return device_num; }
Z
zhangjinchao01 已提交
301 302 303 304 305 306 307

void hl_set_device(int device) {
  if (device == t_resource.device) {
    return;
  }

  CHECK(device >= 0 && device < g_system_device_num && g_device[device])
308
      << "Device: " << device << " is not specified in startup.";
Z
zhangjinchao01 已提交
309 310 311 312 313 314 315 316 317 318 319

  CHECK_CUDA(dynload::cudaSetDevice(device));

  /* switch thread stream */
  for (int i = 0; i < NUMBER_OF_GLOBAL_STREAM; i++) {
    t_resource.stream[i] = g_device[device]->device_resources->stream[i];
  }

  if (true == t_resource.is_init) {
    for (int i = NUMBER_OF_GLOBAL_STREAM; i < HPPL_STREAM_END; i++) {
      t_resource.stream[i] =
320
          t_device[device]->stream[i - NUMBER_OF_GLOBAL_STREAM];
Z
zhangjinchao01 已提交
321 322 323
    }
    t_resource.gpu_mem = t_device[device]->gpu_mem;
    t_resource.cpu_mem = t_device[device]->cpu_mem;
324
    t_resource.event = t_device[device]->mem_event;
Z
zhangjinchao01 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
  }

  t_resource.handle = g_device[device]->device_resources->handle;
  t_resource.gen = g_device[device]->device_resources->gen;
  t_resource.cudnn_handle = g_device[device]->device_resources->cudnn_handle;
  t_resource.gen_mutex = g_device[device]->device_resources->gen_mutex;
  t_resource.device = device;
  t_resource.major = g_device[device]->major;
  default_stream = t_resource.stream[0];
}

int hl_get_device() {
  int device;
  CHECK_CUDA(dynload::cudaGetDevice(&device));
  return device;
}

342
void *hl_malloc_device(size_t size) {
Z
zhangjinchao01 已提交
343 344 345
  void *dest_d;

  CHECK(size) << __func__ << ": the size for device memory is 0, please check.";
346
  CHECK_CUDA(dynload::cudaMalloc((void **)&dest_d, size));
Z
zhangjinchao01 已提交
347 348 349 350 351 352 353 354 355

  return dest_d;
}

void hl_free_mem_device(void *dest_d) {
  CHECK_NOTNULL(dest_d);

  cudaError_t err = dynload::cudaFree(dest_d);
  CHECK(cudaSuccess == err || cudaErrorCudartUnloading == err)
356
      << hl_get_device_error_string();
Z
zhangjinchao01 已提交
357 358
}

359
void *hl_malloc_host(size_t size) {
Z
zhangjinchao01 已提交
360 361 362
  void *dest_h;

  CHECK(size) << __func__ << ": the size for device memory is 0, please check.";
363 364
  CHECK_CUDA(
      dynload::cudaHostAlloc((void **)&dest_h, size, cudaHostAllocDefault));
Z
zhangjinchao01 已提交
365 366 367 368 369 370 371 372

  return dest_h;
}

void hl_free_mem_host(void *dest_h) {
  CHECK_NOTNULL(dest_h);

  cudaError_t err = dynload::cudaFreeHost(dest_h);
373
  CHECK(cudaSuccess == err || cudaErrorCudartUnloading == err)
374
      << hl_get_device_error_string();
Z
zhangjinchao01 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
}

void hl_memcpy(void *dst, void *src, size_t size) {
  if (0 == size) {
    return;
  }
  CHECK_NOTNULL(dst);
  CHECK_NOTNULL(src);
  CHECK_CUDA(dynload::cudaMemcpy(dst, src, size, cudaMemcpyDefault));
}

void hl_memset_device(void *dest_d, int value, size_t size) {
  CHECK_CUDA(dynload::cudaMemset(dest_d, value, size));
}

void hl_memcpy_host2device(void *dest_d, void *src_h, size_t size) {
  if (0 == size) {
    return;
  }
  CHECK_NOTNULL(src_h);
  CHECK_NOTNULL(dest_d);
396
  CHECK_CUDA(dynload::cudaMemcpy(dest_d, src_h, size, cudaMemcpyHostToDevice));
Z
zhangjinchao01 已提交
397 398 399 400 401 402 403 404
}

void hl_memcpy_device2host(void *dest_h, void *src_d, size_t size) {
  if (0 == size) {
    return;
  }
  CHECK_NOTNULL(dest_h);
  CHECK_NOTNULL(src_d);
405
  CHECK_CUDA(dynload::cudaMemcpy(dest_h, src_d, size, cudaMemcpyDeviceToHost));
Z
zhangjinchao01 已提交
406 407 408 409 410 411 412 413
}

void hl_memcpy_device2device(void *dest_d, void *src_d, size_t size) {
  if (0 == size) {
    return;
  }
  CHECK_NOTNULL(dest_d);
  CHECK_NOTNULL(src_d);
414 415
  CHECK_CUDA(
      dynload::cudaMemcpy(dest_d, src_d, size, cudaMemcpyDeviceToDevice));
Z
zhangjinchao01 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428
}

void hl_memcpy_async(void *dst, void *src, size_t size, hl_stream_t stream) {
  cudaStream_t cu_stream;

  if (0 == size) {
    return;
  }
  CHECK_NOTNULL(dst);
  CHECK_NOTNULL(src);
  CHECK_LT(stream, HPPL_STREAM_END);
  cu_stream = t_resource.stream[stream];

429 430
  CHECK_CUDA(
      dynload::cudaMemcpyAsync(dst, src, size, cudaMemcpyDefault, cu_stream));
Z
zhangjinchao01 已提交
431 432 433 434 435 436 437 438 439 440
}

void hl_start() {
  hl_specify_devices_start(NULL, 0);
  /* set default device */
  hl_set_device(0);
}

bool hl_device_can_access_peer(int device, int peerDevice) {
  int canAccessPeer;
441 442
  CHECK_CUDA(
      dynload::cudaDeviceCanAccessPeer(&canAccessPeer, device, peerDevice));
Z
zhangjinchao01 已提交
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 470 471 472 473 474 475 476 477 478 479 480 481 482 483

  if (canAccessPeer == 1) {
    return true;
  } else {
    return false;
  }
}

void hl_device_enable_peer_access(int peerDevice) {
  cudaError_t err = dynload::cudaDeviceEnablePeerAccess(peerDevice, 0);
  if (cudaErrorPeerAccessAlreadyEnabled == err) {
    dynload::cudaGetLastError();
  } else {
    CHECK_CUDA(err);
  }
}

void hl_create_global_resources(hl_device_prop device_prop) {
  struct cudaDeviceProp cu_prop;
  int device = device_prop->device;
  global_device_resources device_res = device_prop->device_resources;

  CHECK_CUDA(dynload::cudaSetDevice(device));
  /* device properties */
  CHECK_CUDA(dynload::cudaGetDeviceProperties(&cu_prop, device));

  device_prop->major = cu_prop.major;
  device_prop->minor = cu_prop.minor;
  strncpy(device_prop->device_name, cu_prop.name, 256);
  device_prop->device_mem = cu_prop.totalGlobalMem;

  /* create device stream */
  for (int j = 0; j < NUMBER_OF_GLOBAL_STREAM; j++) {
    CHECK_CUDA(dynload::cudaStreamCreate(&device_res->stream[j]));
  }

  /* cublas init */
  hl_cublas_init(&device_res->handle, device_res->stream[0]);

  /* create curand gen */
  CHECK_EQ(dynload::curandCreateGenerator(&device_res->gen,
484 485 486
                                          CURAND_RNG_PSEUDO_DEFAULT),
           CURAND_STATUS_SUCCESS)
      << "[Start failed] Curand init failed.";
Z
zhangjinchao01 已提交
487

488 489 490
  CHECK_EQ(dynload::curandSetStream(device_res->gen, device_res->stream[0]),
           CURAND_STATUS_SUCCESS)
      << "[Start failed] Curand set stream failed!";
Z
zhangjinchao01 已提交
491 492 493 494 495

  /* create cudnn handle */
  hl_cudnn_init(&device_res->cudnn_handle, device_res->stream[0]);

  int seed = gettid();
496 497 498
  CHECK_EQ(dynload::curandSetPseudoRandomGeneratorSeed(device_res->gen,
                                                       seed + device),
           CURAND_STATUS_SUCCESS);
Z
zhangjinchao01 已提交
499

500
  device_res->gen_mutex = (pthread_mutex_t *)(malloc(sizeof(pthread_mutex_t)));
Z
zhangjinchao01 已提交
501 502 503 504 505
  pthread_mutex_init(device_res->gen_mutex, NULL);

  CHECK_CUDA(dynload::cudaRuntimeGetVersion(&g_cuda_lib_version));
}

506
int hl_get_cuda_version() { return g_cuda_lib_version; }
Z
zhangjinchao01 已提交
507

508
void hl_create_thread_resources(int device,
509
                                thread_device_resources device_res) {
Z
zhangjinchao01 已提交
510 511 512 513 514 515 516 517
  CHECK_CUDA(dynload::cudaSetDevice(device));

  /* create thread stream */
  for (int j = 0; j < NUMBER_OF_THREAD_STREAM; j++) {
    CHECK_CUDA(dynload::cudaStreamCreate(&device_res->stream[j]));
  }

  /* allocation device memory */
518
  device_res->gpu_mem = (real *)hl_malloc_device(HPPL_GPU_MEMORY_SIZE);
Z
zhangjinchao01 已提交
519 520

  /* allocation host memory */
521
  device_res->cpu_mem = (real *)hl_malloc_host(HPPL_GPU_MEMORY_SIZE);
Z
zhangjinchao01 已提交
522 523 524 525

  CHECK_CUDA(dynload::cudaEventCreate(&device_res->mem_event));
}

526
void hl_specify_devices_start(int *device, int number) {
Z
zhangjinchao01 已提交
527 528 529 530 531 532 533 534 535 536 537
  if (hl_start_flag) return;

  /* 1. get the number of devices */
  CHECK_CUDA(dynload::cudaGetDeviceCount(&g_system_device_num));
  CHECK_NE(g_system_device_num, 0) << "[Start failed] there is no GPU device";
  if (device == NULL) {
    number = g_system_device_num;
  }

  /* 2. check device & create device property table */
  CHECK_LE(number, g_system_device_num)
538 539
      << "[Start failed] System does not have enough device. "
      << "Device number: " << g_system_device_num << "Input number: " << number;
Z
zhangjinchao01 已提交
540 541 542

  char *tmp;
  hl_device_prop device_prop;
543 544
  tmp = (char *)malloc(g_system_device_num * sizeof(hl_device_prop *) +
                       number * sizeof(_hl_device_prop));
Z
zhangjinchao01 已提交
545 546
  CHECK(tmp) << "[Start failed] System memory is not enough.";

547 548 549 550
  g_device = (hl_device_prop *)tmp;
  device_prop = (hl_device_prop)(
      (char *)tmp + g_system_device_num * sizeof(hl_device_prop *));
  memset(g_device, 0, g_system_device_num * sizeof(hl_device_prop *));
Z
zhangjinchao01 已提交
551 552 553 554 555 556 557 558 559 560
  int num = 0;
  for (int i = 0; i < number; i++) {
    int dev;
    if (device == NULL) {
      dev = i;
    } else {
      dev = device[i];
    }

    CHECK_LT(dev, g_system_device_num)
561 562 563
        << "[Start failed] The specified device number is "
        << "out of range. Max device number: " << g_system_device_num - 1
        << " Specified devcie number: " << dev;
Z
zhangjinchao01 已提交
564 565 566

    if (g_device[dev]) {
      /* Warning */
567
      LOG(WARNING) << "[Warning] Repeat specify device: " << dev;
Z
zhangjinchao01 已提交
568 569 570 571 572 573 574 575 576 577
      continue;
    }

    g_device[dev] = &device_prop[num];
    g_device[dev]->device = dev;
    num++;
  }
  device_num = num;

  /* 3.  create global device resources */
578
  char *tmp_res = (char *)malloc(device_num * sizeof(_global_device_resources));
Z
zhangjinchao01 已提交
579 580
  CHECK_NOTNULL(tmp_res);

581 582
  char *tmp_stream = (char *)malloc(device_num * NUMBER_OF_GLOBAL_STREAM *
                                    sizeof(cudaStream_t));
Z
zhangjinchao01 已提交
583 584 585 586 587 588 589 590
  CHECK_NOTNULL(tmp_stream);

  num = 0;
  for (int i = 0; i < g_system_device_num; i++) {
    if (!g_device[i]) {
      continue;
    }

591 592 593 594 595
    g_device[i]->device_resources = (global_device_resources)(
        tmp_res + num * sizeof(_global_device_resources));
    g_device[i]->device_resources->stream =
        (cudaStream_t *)(tmp_stream +
                         num * NUMBER_OF_GLOBAL_STREAM * sizeof(cudaStream_t));
Z
zhangjinchao01 已提交
596 597 598 599 600 601 602 603 604

    hl_create_global_resources(g_device[i]);
    num++;
  }

  /* hl_start() is ok */
  hl_start_flag = true;
  /* set default device */
  if (device == NULL) {
605
    hl_set_device(0);
Z
zhangjinchao01 已提交
606
  } else {
607
    hl_set_device(device[0]);
Z
zhangjinchao01 已提交
608 609 610 611 612 613
  }
}

void hl_rand(real *dest_d, size_t num) {
  pthread_mutex_lock(t_resource.gen_mutex);
  CHECK_EQ(
614
#ifndef PADDLE_TYPE_DOUBLE
615
      dynload::curandGenerateUniform(t_resource.gen, dest_d, num),
Z
zhangjinchao01 已提交
616
#else
617
      dynload::curandGenerateUniformDouble(t_resource.gen, dest_d, num),
Z
zhangjinchao01 已提交
618
#endif
619
      CURAND_STATUS_SUCCESS);
Z
zhangjinchao01 已提交
620 621 622 623 624 625
  pthread_mutex_unlock(t_resource.gen_mutex);
  CHECK_SYNC("hl_rand failed");
}

void hl_srand(unsigned int seed) {
  pthread_mutex_lock(t_resource.gen_mutex);
626 627
  CHECK_EQ(dynload::curandSetPseudoRandomGeneratorSeed(t_resource.gen, seed),
           CURAND_STATUS_SUCCESS);
Z
zhangjinchao01 已提交
628 629 630
  pthread_mutex_unlock(t_resource.gen_mutex);
}

631
void hl_set_sync_flag(bool flag) { g_sync_flag = flag; }
Z
zhangjinchao01 已提交
632

633
bool hl_get_sync_flag() { return g_sync_flag; }
Z
zhangjinchao01 已提交
634 635 636 637

void hl_stream_synchronize(hl_stream_t stream) {
  cudaStream_t cu_stream;

638 639
  CHECK_LT(stream, HPPL_STREAM_END) << __func__
                                    << ": the parameter stream is error.";
Z
zhangjinchao01 已提交
640 641 642 643 644 645 646 647

  cu_stream = t_resource.stream[stream];
  CHECK_CUDA(dynload::cudaStreamSynchronize(cu_stream));
}

void hl_create_event(hl_event_t *event) {
  CHECK_NOTNULL(event);

648 649
  struct _hl_event_st *st_event =
      (struct _hl_event_st *)malloc(sizeof(struct _hl_event_st));
Z
zhangjinchao01 已提交
650 651 652 653 654 655 656 657 658 659 660

  CHECK_CUDA(dynload::cudaEventCreate(&st_event->cu_event));

  *event = st_event;
}

float hl_event_elapsed_time(hl_event_t start, hl_event_t end) {
  float time;
  CHECK_NOTNULL(start);
  CHECK_NOTNULL(end);

661 662
  CHECK_CUDA(
      dynload::cudaEventElapsedTime(&time, start->cu_event, end->cu_event));
Z
zhangjinchao01 已提交
663 664 665 666 667 668 669
  return time;
}

void hl_stream_record_event(hl_stream_t stream, hl_event_t event) {
  cudaStream_t cu_stream;

  CHECK_NOTNULL(event);
670 671
  CHECK_LT(stream, HPPL_STREAM_END) << __func__
                                    << ": the parameter stream is error.";
Z
zhangjinchao01 已提交
672 673

  cu_stream = t_resource.stream[stream];
674
  CHECK_CUDA(dynload::cudaEventRecord(event->cu_event, cu_stream));
Z
zhangjinchao01 已提交
675 676 677 678 679 680
}

void hl_stream_wait_event(hl_stream_t stream, hl_event_t event) {
  cudaStream_t cu_stream;

  CHECK_NOTNULL(event);
681 682
  CHECK_LT(stream, HPPL_STREAM_END) << __func__
                                    << ": the parameter stream is error.";
Z
zhangjinchao01 已提交
683 684

  cu_stream = t_resource.stream[stream];
685
  CHECK_CUDA(dynload::cudaStreamWaitEvent(cu_stream, event->cu_event, 0));
Z
zhangjinchao01 已提交
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
}

void hl_destroy_event(hl_event_t event) {
  CHECK_NOTNULL(event);
  CHECK_CUDA(dynload::cudaEventDestroy(event->cu_event));

  free(event);
  event = NULL;
}

void hl_event_synchronize(hl_event_t event) {
  CHECK_NOTNULL(event);
  CHECK_CUDA(dynload::cudaEventSynchronize(event->cu_event));
}

void hl_get_device_name(char *name, int len, int device) {
  CHECK_NOTNULL(name);
  CHECK(device >= 0 && device < g_system_device_num && g_device[device])
704
      << "Device(" << device << ") is not specified in startup.";
Z
zhangjinchao01 已提交
705

706
  strncpy(name, g_device[device]->device_name, len);
Z
zhangjinchao01 已提交
707 708 709 710 711
}

void hl_get_device_memory(size_t *mem_size, int device) {
  CHECK_NOTNULL(mem_size);
  CHECK(device >= 0 && device < g_system_device_num && g_device[device])
712
      << "Device(" << device << ") is not specified in startup.";
Z
zhangjinchao01 已提交
713 714 715 716 717 718 719 720

  *mem_size = g_device[device]->device_mem;
}

void hl_get_device_compute_capability(int *major, int *minor, int device) {
  CHECK_NOTNULL(major);
  CHECK_NOTNULL(minor);
  CHECK(device >= 0 && device < g_system_device_num && g_device[device])
721
      << "Device(" << device << ") is not specified in startup.";
Z
zhangjinchao01 已提交
722 723 724 725 726

  *major = g_device[device]->major;
  *minor = g_device[device]->minor;
}

727
int hl_get_device_last_error() { return (int)dynload::cudaGetLastError(); }
Z
zhangjinchao01 已提交
728

729
const char *hl_get_device_error_string() {
Z
zhangjinchao01 已提交
730 731 732 733
  cudaError_t err = dynload::cudaGetLastError();
  return dynload::cudaGetErrorString(err);
}

734
const char *hl_get_device_error_string(size_t err) {
Z
zhangjinchao01 已提交
735 736 737
  return dynload::cudaGetErrorString((cudaError_t)err);
}

738
void hl_device_synchronize() { CHECK_CUDA(dynload::cudaDeviceSynchronize()); }
Z
zhangjinchao01 已提交
739
void hl_set_device_flags_block() {
740
  CHECK_CUDA(dynload::cudaSetDeviceFlags(cudaDeviceScheduleBlockingSync));
Z
zhangjinchao01 已提交
741 742
}

L
liaogang 已提交
743
bool hl_cuda_event_is_ready(hl_event_t event) {
Z
zhangjinchao01 已提交
744 745 746 747
  cudaError_t err = dynload::cudaEventQuery(event->cu_event);
  CHECK(cudaSuccess == err || cudaErrorNotReady == err);

  if (cudaErrorNotReady == err) {
L
liaogang 已提交
748
    return false;
Z
zhangjinchao01 已提交
749
  }
L
liaogang 已提交
750
  return true;
Z
zhangjinchao01 已提交
751
}
L
liaogang 已提交
752

L
liaogang 已提交
753
void hl_profiler_start() { CHECK_CUDA(dynload::cudaProfilerStart()); }
L
liaogang 已提交
754

L
liaogang 已提交
755
void hl_profiler_end() { CHECK_CUDA(dynload::cudaProfilerStop()); }