PSCF v1.5.0
VecRandom.cu
1#include "VecRandom.h"
2#include "CUT.h"
3#include "ThreadArray.h"
4#include <util/global.h>
5#include <sys/time.h>
6#include <cstdint>
7#include <string>
8
9namespace Pscf {
10
11 using namespace Util;
12
13 // Anonymous namesapce, for functions that are only used in this file
14 namespace {
15
16 /*
17 * Linear array transformation a[i] => c*a[i] + s (float).
18 */
19 __global__
20 void _linearScale(float* a, float c, float s, int n)
21 {
22 int nThreads = blockDim.x * gridDim.x;
23 int startID = blockIdx.x * blockDim.x + threadIdx.x;
24 for (int i = startID; i < n; i += nThreads) {
25 a[i] = a[i] * c + s;
26 }
27 }
28
29 /*
30 * Linear array transformation a[i] => c*a[i] + s (double).
31 */
32 __global__
33 void _linearScale(double* a, double c, double s, int n)
34 {
35 int nThreads = blockDim.x * gridDim.x;
36 int startID = blockIdx.x * blockDim.x + threadIdx.x;
37 for (int i = startID; i < n; i += nThreads) {
38 a[i] = a[i] * c + s;
39 }
40 }
41
42 /*
43 * Linear array transformation a[i] => c*a[i] + s (float).
44 */
45 void linearScale(BackendArray<float,CUT>& a, float c, float s)
46 {
47 const int n = a.capacity();
48
49 // GPU resources
50 int nBlocks, nThreads;
51 ThreadArray::setThreadsLogical(n, nBlocks, nThreads);
52
53 // Launch kernel
54 _linearScale<<<nBlocks, nThreads>>>(a.cArray(), c, s, n);
55 }
56
57 /*
58 * Linear array transformation a[i] => c*a[i] + s (double).
59 */
60 void linearScale(BackendArray<double,CUT>& a, double c, double s)
61 {
62 const int n = a.capacity();
63
64 // GPU resources
65 int nBlocks, nThreads;
66 ThreadArray::setThreadsLogical(n, nBlocks, nThreads);
67
68 // Launch kernel
69 _linearScale<<<nBlocks, nThreads>>>(a.cArray(), c, s, n);
70 }
71
72 } // end anonymous namespace
73
74 // Public class member functions
75
76 /*
77 * Constructor.
78 */
80 : gen_(),
81 seed_(0),
82 isInitialized_(false)
83 {
84 // Create pseudo-random number generator on gpu
85 curandStatus_t status;
86 status = curandCreateGenerator(&gen_, CURAND_RNG_PSEUDO_DEFAULT);
87 errorCheck(status);
88 }
89
90 /*
91 * Destructor.
92 */
95
96 /*
97 * Set random random number generator seed.
98 *
99 * \param seed value for random seed (private member variable seed)
100 */
101 void VecRandom<CUT>::setSeed(unsigned long long seed)
102 {
103 if (seed == 0) {
104 timeval time;
105 gettimeofday(&time, NULL);
106 seed_ = time.tv_sec + 1123*time.tv_usec;
107 } else {
108 seed_ = seed;
109 }
110 curandStatus_t status;
111 status = curandSetPseudoRandomGeneratorSeed(gen_, seed_);
112 errorCheck(status);
113
114 isInitialized_ = true;
115 }
116
117 /*
118 * Populate array with uniform random floats in (0, 1].
119 */
121 {
122 const int n = data.capacity();
123 UTIL_CHECK(n > 0);
124 if (!isInitialized_) {
125 setSeed(0);
126 }
127
128 curandStatus_t status;
129 status = curandGenerateUniform(gen_, data.cArray(), n);
130 errorCheck(status);
131 }
132
133 /*
134 * Populate array with uniform random doubles in (0, 1].
135 */
137 {
138 const int n = data.capacity();
139 UTIL_CHECK(n > 0);
140 if (!isInitialized_) {
141 setSeed(0);
142 }
143
144 curandStatus_t status;
145 status = curandGenerateUniformDouble(gen_, data.cArray(), n);
146 errorCheck(status);
147 }
148
149 /*
150 * Populate array with uniform random floats in (min, max].
151 */
153 float min, float max)
154 {
155 UTIL_CHECK(max > min);
156 uniform(data);
157 linearScale(data, max - min, min);
158 }
159
160 /*
161 * Populate array with uniform random doubles in (min, max].
162 */
164 double min, double max)
165 {
166 UTIL_CHECK(max > min);
167 uniform(data);
168 linearScale(data, max - min, min);
169 }
170
171 /*
172 * Populate array with normal-distributed random floats.
173 */
175 float stddev, float mean)
176 {
177 UTIL_CHECK(data.capacity() > 0);
178 if (!isInitialized_) {
179 setSeed(0);
180 }
181
182 // cuRAND generates normal values in pairs. It requires an even
183 // number of values and an output array aligned to the size of a
184 // pair. Otherwise, generate an even number of values in an aligned
185 // work array and copy the required values to data.
186 int n = data.capacity();
187 int nGen = n + (n % 2);
188 float* ptr = data.cArray();
189 std::uintptr_t address = reinterpret_cast<std::uintptr_t>(ptr);
190 if (nGen != n || address % (2*sizeof(float)) != 0) {
191 if (floatWork_.capacity() < nGen) {
192 if (floatWork_.isAllocated()) {
193 floatWork_.deallocate();
194 }
195 floatWork_.allocate(nGen);
196 }
197 ptr = floatWork_.cArray();
198 }
199
200 curandStatus_t status;
201 status = curandGenerateNormal(gen_, ptr, nGen, mean, stddev);
202 errorCheck(status);
203 if (ptr != data.cArray()) {
204 cudaErrorCheck( cudaMemcpy(data.cArray(), ptr, n*sizeof(float),
205 cudaMemcpyDeviceToDevice) );
206 }
207 }
208
209 /*
210 * Populate array with normal-distributed random doubles.
211 */
213 double stddev, double mean)
214 {
215 UTIL_CHECK(data.capacity() > 0);
216 if (!isInitialized_) {
217 setSeed(0);
218 }
219
220 // cuRAND generates normal values in pairs. It requires an even
221 // number of values and an output array aligned to the size of a
222 // pair. Otherwise, generate an even number of values in an aligned
223 // work array and copy the required values to data.
224 int n = data.capacity();
225 int nGen = n + (n % 2);
226 double* ptr = data.cArray();
227 std::uintptr_t address = reinterpret_cast<std::uintptr_t>(ptr);
228 if (nGen != n || address % (2*sizeof(double)) != 0) {
229 if (doubleWork_.capacity() < nGen) {
230 if (doubleWork_.isAllocated()) {
231 doubleWork_.deallocate();
232 }
233 doubleWork_.allocate(nGen);
234 }
235 ptr = doubleWork_.cArray();
236 }
237
238 curandStatus_t status;
239 status = curandGenerateNormalDouble(gen_, ptr, nGen, mean, stddev);
240 errorCheck(status);
241 if (ptr != data.cArray()) {
242 cudaErrorCheck( cudaMemcpy(data.cArray(), ptr, n*sizeof(double),
243 cudaMemcpyDeviceToDevice) );
244 }
245 }
246
247 /*
248 * Check generator error status.
249 *
250 * If not success, print info and throw Exception.
251 */
252 void VecRandom<CUT>::errorCheck(curandStatus_t const & error)
253 {
254 if (error == CURAND_STATUS_SUCCESS) {
255 return;
256 } else {
257 std::string errString;
258 switch (error)
259 {
260 default:
261 errString = "UNKNOWN";
262 break;
263 case CURAND_STATUS_VERSION_MISMATCH:
264 errString = "CURAND_STATUS_VERSION_MISMATCH";
265 break;
266 case CURAND_STATUS_NOT_INITIALIZED:
267 errString = "CURAND_STATUS_NOT_INITIALIZED";
268 break;
269 case CURAND_STATUS_ALLOCATION_FAILED:
270 errString = "CURAND_STATUS_ALLOCATION_FAILED";
271 break;
272 case CURAND_STATUS_TYPE_ERROR:
273 errString = "CURAND_STATUS_TYPE_ERROR";
274 break;
275 case CURAND_STATUS_OUT_OF_RANGE:
276 errString = "CURAND_STATUS_OUT_OF_RANGE";
277 break;
278 case CURAND_STATUS_LENGTH_NOT_MULTIPLE:
279 errString = "CURAND_STATUS_LENGTH_NOT_MULTIPLE";
280 break;
281 case CURAND_STATUS_DOUBLE_PRECISION_REQUIRED:
282 errString = "CURAND_STATUS_DOUBLE_PRECISION_REQUIRED";
283 break;
284 case CURAND_STATUS_LAUNCH_FAILURE:
285 errString = "CURAND_STATUS_LAUNCH_FAILURE";
286 break;
287 case CURAND_STATUS_PREEXISTING_FAILURE:
288 errString = "CURAND_STATUS_PREEXISTING_FAILURE";
289 break;
290 case CURAND_STATUS_INITIALIZATION_FAILED:
291 errString = "CURAND_STATUS_INITIALIZATION_FAILED";
292 break;
293 case CURAND_STATUS_INTERNAL_ERROR:
294 errString = "CURAND_STATUS_INTERNAL_ERROR";
295 break;
296 case CURAND_STATUS_ARCH_MISMATCH:
297 errString = "CURAND_STATUS_ARCH_MISMATCH";
298 break;
299 }
300
301 Log::file() << "VecRandom error: " << errString << std::endl;
302 UTIL_THROW("VecRandom number generation failed.");
303 }
304 }
305
306 // Related free functions
307
308 /*
309 * Link vector and scalar random number generators, if needed.
310 *
311 * This specialization for a CUDA backend (T=CUT) does nothing, because
312 * scalar and vector RNGs are are independent in this case. The
313 * specialization for a C++ backend (T=CPT) instead links the two RNGs.
314 */
315 template <>
316 void linkVecRandom<CUT>(VecRandom<CUT>& vr, Random & sr)
317 {}
318
319 /*
320 * Set vector RNG seed, if needed.
321 *
322 * This specialization for a CUDA backend (T=CUT) sets the seed for the
323 * vector RNG. The specialization for a C++ backend (T=CPT) instead does
324 * nothing.
325 */
326 template <>
327 void seedVecRandom<CUT>(VecRandom<CUT>& vr, long seed)
328 { vr.setSeed(seed); }
329
330}
VecRandom()
Constructor.
Definition VecRandom.cu:79
void uniform(BackendArray< float, CUT > &data)
Populate array with uniform random floats in (0, 1].
Definition VecRandom.cu:120
long seed()
Returns value of random seed (private member variable seed_).
void setSeed(unsigned long long seed)
Set value of random seed (private member variable seed_).
Definition VecRandom.cu:101
static std::ostream & file()
Get log ostream by reference.
Definition Log.cpp:59
Random number generator.
Definition Random.h:47
File containing preprocessor macros for error handling.
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition global.h:68
#define UTIL_THROW(msg)
Macro for throwing an Exception, reporting function, file and line number.
Definition global.h:49
void setThreadsLogical(int nThreadsLogical)
Given total number of threads, set 1D execution configuration.
int nThreads()
Get the number of threads per block for execution.
int nBlocks()
Get the current number of blocks for execution.
PSCF package top-level namespace.