cuda_random.hpp 1.84 KB
Newer Older
1
2
3
4
/*!
 * Copyright (c) 2021 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
5
6
#ifndef LIGHTGBM_INCLUDE_LIGHTGBM_CUDA_CUDA_RANDOM_HPP_
#define LIGHTGBM_INCLUDE_LIGHTGBM_CUDA_CUDA_RANDOM_HPP_
7

8
#ifdef USE_CUDA
9

10
#ifndef USE_ROCM
11
12
#include <cuda.h>
#include <cuda_runtime.h>
13
#endif
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
61
62
63
64
65
66
67
68
69
70
71
72
73

namespace LightGBM {

/*!
* \brief A wrapper for random generator
*/
class CUDARandom {
 public:
  /*!
  * \brief Set specific seed
  */
  __device__ void SetSeed(int seed) {
    x = seed;
  }
  /*!
  * \brief Generate random integer, int16 range. [0, 65536]
  * \param lower_bound lower bound
  * \param upper_bound upper bound
  * \return The random integer between [lower_bound, upper_bound)
  */
  __device__ inline int NextShort(int lower_bound, int upper_bound) {
    return (RandInt16()) % (upper_bound - lower_bound) + lower_bound;
  }

  /*!
  * \brief Generate random integer, int32 range
  * \param lower_bound lower bound
  * \param upper_bound upper bound
  * \return The random integer between [lower_bound, upper_bound)
  */
  __device__ inline int NextInt(int lower_bound, int upper_bound) {
    return (RandInt32()) % (upper_bound - lower_bound) + lower_bound;
  }

  /*!
  * \brief Generate random float data
  * \return The random float between [0.0, 1.0)
  */
  __device__ inline float NextFloat() {
    // get random float in [0,1)
    return static_cast<float>(RandInt16()) / (32768.0f);
  }

 private:
  __device__ inline int RandInt16() {
    x = (214013 * x + 2531011);
    return static_cast<int>((x >> 16) & 0x7FFF);
  }

  __device__ inline int RandInt32() {
    x = (214013 * x + 2531011);
    return static_cast<int>(x & 0x7FFFFFFF);
  }

  unsigned int x = 123456789;
};


}  // namespace LightGBM

74
#endif  // USE_CUDA
75

76
#endif  // LIGHTGBM_INCLUDE_LIGHTGBM_CUDA_CUDA_RANDOM_HPP_