Debian Codegraph @

Samples/2_Concepts_and_Techniques/MC_EstimatePiInlineQ/src/piestimator.cu

raw
1 /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2 *
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions
5 * are met:
6 * * Redistributions of source code must retain the above copyright
7 * notice, this list of conditions and the following disclaimer.
8 * * Redistributions in binary form must reproduce the above copyright
9 * notice, this list of conditions and the following disclaimer in the
10 * documentation and/or other materials provided with the distribution.
11 * * Neither the name of NVIDIA CORPORATION nor the names of its
12 * contributors may be used to endorse or promote products derived
13 * from this software without specific prior written permission.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
16 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28
29 #include "../inc/piestimator.h"
30
31 #include <string>
32 #include <vector>
33 #include <numeric>
34 #include <stdexcept>
35 #include <typeinfo>
36 #include <cuda_runtime.h>
37 #include <cooperative_groups.h>
38
39 namespace cg = cooperative_groups;
40 #include <curand.h>
41 #include <curand_kernel.h>
42
43 #include "../inc/cudasharedmem.h"
44
45 using std::string;
46 using std::vector;
47
48 // Helper templates to support float and double in same code
49 template <typename L, typename R>
50 struct TYPE_IS {
51 static const bool test = false;
52 };
53 template <typename L>
54 struct TYPE_IS<L, L> {
55 static const bool test = true;
56 };
57 template <bool, class L, class R>
58 struct IF {
59 typedef R type;
60 };
61 template <class L, class R>
62 struct IF<true, L, R> {
63 typedef L type;
64 };
65
66 // RNG init kernel
67 template <typename rngState_t, typename rngDirectionVectors_t>
68 __global__ void initRNG(rngState_t *const rngStates,
69 rngDirectionVectors_t *const rngDirections,
70 unsigned int numDrawsPerDirection) {
71 // Determine thread ID
72 unsigned int tid = blockIdx.x * blockDim.x + threadIdx.x;
73 unsigned int step = gridDim.x * blockDim.x;
74
75 // Determine offset to avoid overlapping sub-sequences
76 unsigned int offset = tid * ((numDrawsPerDirection + step - 1) / step);
77
78 // Initialise the RNG
79 curand_init(rngDirections[0], offset, &rngStates[tid]);
80 curand_init(rngDirections[1], offset, &rngStates[tid + step]);
81 }
82
83 __device__ unsigned int reduce_sum(unsigned int in, cg::thread_block cta) {
84 extern __shared__ unsigned int sdata[];
85
86 // Perform first level of reduction:
87 // - Write to shared memory
88 unsigned int ltid = threadIdx.x;
89
90 sdata[ltid] = in;
91 cg::sync(cta);
92
93 // Do reduction in shared mem
94 for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
95 if (ltid < s) {
96 sdata[ltid] += sdata[ltid + s];
97 }
98
99 cg::sync(cta);
100 }
101
102 return sdata[0];
103 }
104
105 __device__ inline void getPoint(float &x, float &y, curandStateSobol32 &state1,
106 curandStateSobol32 &state2) {
107 x = curand_uniform(&state1);
108 y = curand_uniform(&state2);
109 }
110 __device__ inline void getPoint(double &x, double &y,
111 curandStateSobol64 &state1,
112 curandStateSobol64 &state2) {
113 x = curand_uniform_double(&state1);
114 y = curand_uniform_double(&state2);
115 }
116
117 // Estimator kernel
118 template <typename Real, typename rngState_t>
119 __global__ void computeValue(unsigned int *const results,
120 rngState_t *const rngStates,
121 const unsigned int numSims) {
122 // Handle to thread block group
123 cg::thread_block cta = cg::this_thread_block();
124 // Determine thread ID
125 unsigned int bid = blockIdx.x;
126 unsigned int tid = blockIdx.x * blockDim.x + threadIdx.x;
127 unsigned int step = gridDim.x * blockDim.x;
128
129 // Initialise the RNG
130 rngState_t localState1 = rngStates[tid];
131 rngState_t localState2 = rngStates[tid + step];
132
133 // Count the number of points which lie inside the unit quarter-circle
134 unsigned int pointsInside = 0;
135
136 for (unsigned int i = tid; i < numSims; i += step) {
137 Real x;
138 Real y;
139 getPoint(x, y, localState1, localState2);
140 Real l2norm2 = x * x + y * y;
141
142 if (l2norm2 < static_cast<Real>(1)) {
143 pointsInside++;
144 }
145 }
146
147 // Reduce within the block
148 pointsInside = reduce_sum(pointsInside, cta);
149
150 // Store the result
151 if (threadIdx.x == 0) {
152 results[bid] = pointsInside;
153 }
154 }
155
156 template <typename Real>
157 PiEstimator<Real>::PiEstimator(unsigned int numSims, unsigned int device,
158 unsigned int threadBlockSize)
159 : m_numSims(numSims),
160 m_device(device),
161 m_threadBlockSize(threadBlockSize) {}
162
163 template <typename Real>
164 Real PiEstimator<Real>::operator()() {
165 cudaError_t cudaResult = cudaSuccess;
166 struct cudaDeviceProp deviceProperties;
167 struct cudaFuncAttributes funcAttributes;
168
169 // Determine type of generator to use (32- or 64-bit)
170 typedef typename IF<TYPE_IS<Real, double>::test, curandStateSobol64_t,
171 curandStateSobol32_t>::type curandStateSobol_sz;
172 typedef
173 typename IF<TYPE_IS<Real, double>::test, curandDirectionVectors64_t,
174 curandDirectionVectors32_t>::type curandDirectionVectors_sz;
175
176 // Get device properties
177 cudaResult = cudaGetDeviceProperties(&deviceProperties, m_device);
178
179 if (cudaResult != cudaSuccess) {
180 string msg("Could not get device properties: ");
181 msg += cudaGetErrorString(cudaResult);
182 throw std::runtime_error(msg);
183 }
184
185 // Check precision is valid
186 if (typeid(Real) == typeid(double) &&
187 (deviceProperties.major < 1 ||
188 (deviceProperties.major == 1 && deviceProperties.minor < 3))) {
189 throw std::runtime_error("Device does not have double precision support");
190 }
191
192 // Attach to GPU
193 cudaResult = cudaSetDevice(m_device);
194
195 if (cudaResult != cudaSuccess) {
196 string msg("Could not set CUDA device: ");
197 msg += cudaGetErrorString(cudaResult);
198 throw std::runtime_error(msg);
199 }
200
201 // Determine how to divide the work between cores
202 dim3 block;
203 dim3 grid;
204 block.x = m_threadBlockSize;
205 grid.x = (m_numSims + m_threadBlockSize - 1) / m_threadBlockSize;
206
207 // Aim to launch around ten or more times as many blocks as there
208 // are multiprocessors on the target device.
209 unsigned int blocksPerSM = 10;
210 unsigned int numSMs = deviceProperties.multiProcessorCount;
211
212 while (grid.x > 2 * blocksPerSM * numSMs) {
213 grid.x >>= 1;
214 }
215
216 // Get initRNG function properties and check the maximum block size
217 cudaResult = cudaFuncGetAttributes(
218 &funcAttributes, initRNG<curandStateSobol_sz, curandDirectionVectors_sz>);
219
220 if (cudaResult != cudaSuccess) {
221 string msg("Could not get function attributes: ");
222 msg += cudaGetErrorString(cudaResult);
223 throw std::runtime_error(msg);
224 }
225
226 if (block.x > (unsigned int)funcAttributes.maxThreadsPerBlock) {
227 throw std::runtime_error(
228 "Block X dimension is too large for initRNG kernel");
229 }
230
231 // Get computeValue function properties and check the maximum block size
232 cudaResult = cudaFuncGetAttributes(&funcAttributes,
233 computeValue<Real, curandStateSobol_sz>);
234
235 if (cudaResult != cudaSuccess) {
236 string msg("Could not get function attributes: ");
237 msg += cudaGetErrorString(cudaResult);
238 throw std::runtime_error(msg);
239 }
240
241 if (block.x > (unsigned int)funcAttributes.maxThreadsPerBlock) {
242 throw std::runtime_error(
243 "Block X dimension is too large for computeValue kernel");
244 }
245
246 // Check the dimensions are valid
247 if (block.x > (unsigned int)deviceProperties.maxThreadsDim[0]) {
248 throw std::runtime_error("Block X dimension is too large for device");
249 }
250
251 if (grid.x > (unsigned int)deviceProperties.maxGridSize[0]) {
252 throw std::runtime_error("Grid X dimension is too large for device");
253 }
254
255 // Allocate memory for RNG states and direction vectors
256 curandStateSobol_sz *d_rngStates = 0;
257 curandDirectionVectors_sz *d_rngDirections = 0;
258 cudaResult = cudaMalloc((void **)&d_rngStates,
259 2 * grid.x * block.x * sizeof(curandStateSobol_sz));
260
261 if (cudaResult != cudaSuccess) {
262 string msg("Could not allocate memory on device for RNG states: ");
263 msg += cudaGetErrorString(cudaResult);
264 throw std::runtime_error(msg);
265 }
266
267 cudaResult = cudaMalloc((void **)&d_rngDirections,
268 2 * sizeof(curandDirectionVectors_sz));
269
270 if (cudaResult != cudaSuccess) {
271 string msg(
272 "Could not allocate memory on device for RNG direction vectors: ");
273 msg += cudaGetErrorString(cudaResult);
274 throw std::runtime_error(msg);
275 }
276
277 // Allocate memory for result
278 // Each thread block will produce one result
279 unsigned int *d_results = 0;
280 cudaResult = cudaMalloc((void **)&d_results, grid.x * sizeof(unsigned int));
281
282 if (cudaResult != cudaSuccess) {
283 string msg("Could not allocate memory on device for partial results: ");
284 msg += cudaGetErrorString(cudaResult);
285 throw std::runtime_error(msg);
286 }
287
288 // Generate direction vectors on the host and copy to the device
289 if (typeid(Real) == typeid(float)) {
290 curandDirectionVectors32_t *rngDirections;
291 curandStatus_t curandResult = curandGetDirectionVectors32(
292 &rngDirections, CURAND_DIRECTION_VECTORS_32_JOEKUO6);
293
294 if (curandResult != CURAND_STATUS_SUCCESS) {
295 string msg(
296 "Could not get direction vectors for quasi-random number "
297 "generator: ");
298 msg += curandResult;
299 throw std::runtime_error(msg);
300 }
301
302 cudaResult = cudaMemcpy(d_rngDirections, rngDirections,
303 2 * sizeof(curandDirectionVectors32_t),
304 cudaMemcpyHostToDevice);
305
306 if (cudaResult != cudaSuccess) {
307 string msg("Could not copy direction vectors to device: ");
308 msg += cudaGetErrorString(cudaResult);
309 throw std::runtime_error(msg);
310 }
311 } else if (typeid(Real) == typeid(double)) {
312 curandDirectionVectors64_t *rngDirections;
313 curandStatus_t curandResult = curandGetDirectionVectors64(
314 &rngDirections, CURAND_DIRECTION_VECTORS_64_JOEKUO6);
315
316 if (curandResult != CURAND_STATUS_SUCCESS) {
317 string msg(
318 "Could not get direction vectors for quasi-random number "
319 "generator: ");
320 msg += curandResult;
321 throw std::runtime_error(msg);
322 }
323
324 cudaResult = cudaMemcpy(d_rngDirections, rngDirections,
325 2 * sizeof(curandDirectionVectors64_t),
326 cudaMemcpyHostToDevice);
327
328 if (cudaResult != cudaSuccess) {
329 string msg("Could not copy direction vectors to device: ");
330 msg += cudaGetErrorString(cudaResult);
331 throw std::runtime_error(msg);
332 }
333 } else {
334 string msg(
335 "Could not get direction vectors for random number generator of "
336 "specified type");
337 throw std::runtime_error(msg);
338 }
339
340 // Initialise RNG
341 initRNG<<<grid, block>>>(d_rngStates, d_rngDirections, m_numSims);
342
343 // Count the points inside unit quarter-circle
344 computeValue<Real><<<grid, block, block.x * sizeof(unsigned int)>>>(
345 d_results, d_rngStates, m_numSims);
346
347 // Copy partial results back
348 vector<unsigned int> results(grid.x);
349 cudaResult = cudaMemcpy(&results[0], d_results, grid.x * sizeof(unsigned int),
350 cudaMemcpyDeviceToHost);
351
352 if (cudaResult != cudaSuccess) {
353 string msg("Could not copy partial results to host: ");
354 msg += cudaGetErrorString(cudaResult);
355 throw std::runtime_error(msg);
356 }
357
358 // Complete sum-reduction on host
359 Real value =
360 static_cast<Real>(std::accumulate(results.begin(), results.end(), 0));
361
362 // Determine the proportion of points inside the quarter-circle,
363 // i.e. the area of the unit quarter-circle
364 value /= m_numSims;
365
366 // Value is currently an estimate of the area of a unit quarter-circle, so we
367 // can scale to a full circle by multiplying by four. Now since the area of a
368 // circle is pi * r^2, and r is one, the value will be an estimate for the
369 // value of pi.
370 value *= 4;
371
372 // Cleanup
373 if (d_rngStates) {
374 cudaFree(d_rngStates);
375 d_rngStates = 0;
376 }
377
378 if (d_rngDirections) {
379 cudaFree(d_rngDirections);
380 d_rngDirections = 0;
381 }
382
383 if (d_results) {
384 cudaFree(d_results);
385 d_results = 0;
386 }
387
388 return value;
389 }
390
391 // Explicit template instantiation
392 template class PiEstimator<float>;
393 template class PiEstimator<double>;