Debian Codegraph @

Samples/2_Concepts_and_Techniques/MC_EstimatePiQ/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 #include "../inc/piestimator.h"
29
30 #include <string>
31 #include <vector>
32 #include <numeric>
33 #include <stdexcept>
34 #include <typeinfo>
35 #include <cuda_runtime.h>
36 #include <cooperative_groups.h>
37
38 namespace cg = cooperative_groups;
39 #include <curand.h>
40
41 using std::string;
42 using std::vector;
43
44 __device__ unsigned int reduce_sum(unsigned int in, cg::thread_block cta) {
45 extern __shared__ unsigned int sdata[];
46
47 // Perform first level of reduction:
48 // - Write to shared memory
49 unsigned int ltid = threadIdx.x;
50
51 sdata[ltid] = in;
52 cg::sync(cta);
53
54 // Do reduction in shared mem
55 for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
56 if (ltid < s) {
57 sdata[ltid] += sdata[ltid + s];
58 }
59
60 cg::sync(cta);
61 }
62
63 return sdata[0];
64 }
65
66 // Estimator kernel
67 template <typename Real>
68 __global__ void computeValue(unsigned int *const results,
69 const Real *const points,
70 const unsigned int numSims) {
71 // Handle to thread block group
72 cg::thread_block cta = cg::this_thread_block();
73 // Determine thread ID
74 unsigned int bid = blockIdx.x;
75 unsigned int tid = blockIdx.x * blockDim.x + threadIdx.x;
76 unsigned int step = gridDim.x * blockDim.x;
77
78 // Shift the input/output pointers
79 const Real *pointx = points + tid;
80 const Real *pointy = pointx + numSims;
81
82 // Count the number of points which lie inside the unit quarter-circle
83 unsigned int pointsInside = 0;
84
85 for (unsigned int i = tid; i < numSims;
86 i += step, pointx += step, pointy += step) {
87 Real x = *pointx;
88 Real y = *pointy;
89 Real l2norm2 = x * x + y * y;
90
91 if (l2norm2 < static_cast<Real>(1)) {
92 pointsInside++;
93 }
94 }
95
96 // Reduce within the block
97 pointsInside = reduce_sum(pointsInside, cta);
98
99 // Store the result
100 if (threadIdx.x == 0) {
101 results[bid] = pointsInside;
102 }
103 }
104
105 template <typename Real>
106 PiEstimator<Real>::PiEstimator(unsigned int numSims, unsigned int device,
107 unsigned int threadBlockSize)
108 : m_numSims(numSims),
109 m_device(device),
110 m_threadBlockSize(threadBlockSize) {}
111
112 template <typename Real>
113 Real PiEstimator<Real>::operator()() {
114 cudaError_t cudaResult = cudaSuccess;
115 struct cudaDeviceProp deviceProperties;
116 struct cudaFuncAttributes funcAttributes;
117
118 // Get device properties
119 cudaResult = cudaGetDeviceProperties(&deviceProperties, m_device);
120
121 if (cudaResult != cudaSuccess) {
122 string msg("Could not get device properties: ");
123 msg += cudaGetErrorString(cudaResult);
124 throw std::runtime_error(msg);
125 }
126
127 // Check precision is valid
128 if (typeid(Real) == typeid(double) &&
129 (deviceProperties.major < 1 ||
130 (deviceProperties.major == 1 && deviceProperties.minor < 3))) {
131 throw std::runtime_error("Device does not have double precision support");
132 }
133
134 // Attach to GPU
135 cudaResult = cudaSetDevice(m_device);
136
137 if (cudaResult != cudaSuccess) {
138 string msg("Could not set CUDA device: ");
139 msg += cudaGetErrorString(cudaResult);
140 throw std::runtime_error(msg);
141 }
142
143 // Determine how to divide the work between cores
144 dim3 block;
145 dim3 grid;
146 block.x = m_threadBlockSize;
147 grid.x = (m_numSims + m_threadBlockSize - 1) / m_threadBlockSize;
148
149 // Aim to launch around ten or more times as many blocks as there
150 // are multiprocessors on the target device.
151 unsigned int blocksPerSM = 10;
152 unsigned int numSMs = deviceProperties.multiProcessorCount;
153
154 while (grid.x > 2 * blocksPerSM * numSMs) {
155 grid.x >>= 1;
156 }
157
158 // Get computeValue function properties and check the maximum block size
159 cudaResult = cudaFuncGetAttributes(&funcAttributes, computeValue<Real>);
160
161 if (cudaResult != cudaSuccess) {
162 string msg("Could not get function attributes: ");
163 msg += cudaGetErrorString(cudaResult);
164 throw std::runtime_error(msg);
165 }
166
167 if (block.x > (unsigned int)funcAttributes.maxThreadsPerBlock) {
168 throw std::runtime_error(
169 "Block X dimension is too large for computeValue kernel");
170 }
171
172 // Check the dimensions are valid
173 if (block.x > (unsigned int)deviceProperties.maxThreadsDim[0]) {
174 throw std::runtime_error("Block X dimension is too large for device");
175 }
176
177 if (grid.x > (unsigned int)deviceProperties.maxGridSize[0]) {
178 throw std::runtime_error("Grid X dimension is too large for device");
179 }
180
181 // Allocate memory for points
182 // Each simulation has two random numbers to give X and Y coordinate
183 Real *d_points = 0;
184 cudaResult = cudaMalloc((void **)&d_points, 2 * m_numSims * sizeof(Real));
185
186 if (cudaResult != cudaSuccess) {
187 string msg("Could not allocate memory on device for random numbers: ");
188 msg += cudaGetErrorString(cudaResult);
189 throw std::runtime_error(msg);
190 }
191
192 // Allocate memory for result
193 // Each thread block will produce one result
194 unsigned int *d_results = 0;
195 cudaResult = cudaMalloc((void **)&d_results, grid.x * sizeof(unsigned int));
196
197 if (cudaResult != cudaSuccess) {
198 string msg("Could not allocate memory on device for partial results: ");
199 msg += cudaGetErrorString(cudaResult);
200 throw std::runtime_error(msg);
201 }
202
203 // Generate random points in unit square
204 curandStatus_t curandResult;
205 curandGenerator_t qrng;
206
207 if (typeid(Real) == typeid(float)) {
208 curandResult = curandCreateGenerator(&qrng, CURAND_RNG_QUASI_SOBOL32);
209 } else if (typeid(Real) == typeid(double)) {
210 curandResult = curandCreateGenerator(&qrng, CURAND_RNG_QUASI_SOBOL64);
211 } else {
212 string msg("Could not create random number generator of specified type");
213 throw std::runtime_error(msg);
214 }
215
216 if (curandResult != CURAND_STATUS_SUCCESS) {
217 string msg("Could not create quasi-random number generator: ");
218 msg += curandResult;
219 throw std::runtime_error(msg);
220 }
221
222 curandResult = curandSetQuasiRandomGeneratorDimensions(qrng, 2);
223
224 if (curandResult != CURAND_STATUS_SUCCESS) {
225 string msg(
226 "Could not set number of dimensions for quasi-random number "
227 "generator: ");
228 msg += curandResult;
229 throw std::runtime_error(msg);
230 }
231
232 curandResult =
233 curandSetGeneratorOrdering(qrng, CURAND_ORDERING_QUASI_DEFAULT);
234
235 if (curandResult != CURAND_STATUS_SUCCESS) {
236 string msg("Could not set order for quasi-random number generator: ");
237 msg += curandResult;
238 throw std::runtime_error(msg);
239 }
240
241 if (typeid(Real) == typeid(float)) {
242 curandResult =
243 curandGenerateUniform(qrng, (float *)d_points, 2 * m_numSims);
244 } else if (typeid(Real) == typeid(double)) {
245 curandResult =
246 curandGenerateUniformDouble(qrng, (double *)d_points, 2 * m_numSims);
247 } else {
248 string msg("Could not generate random numbers of specified type");
249 throw std::runtime_error(msg);
250 }
251
252 if (curandResult != CURAND_STATUS_SUCCESS) {
253 string msg("Could not generate quasi-random numbers: ");
254 msg += curandResult;
255 throw std::runtime_error(msg);
256 }
257
258 curandResult = curandDestroyGenerator(qrng);
259
260 if (curandResult != CURAND_STATUS_SUCCESS) {
261 string msg("Could not destroy quasi-random number generator: ");
262 msg += curandResult;
263 throw std::runtime_error(msg);
264 }
265
266 // Count the points inside unit quarter-circle
267 computeValue<Real><<<grid, block, block.x * sizeof(unsigned int)>>>(
268 d_results, d_points, m_numSims);
269
270 // Copy partial results back
271 vector<unsigned int> results(grid.x);
272 cudaResult = cudaMemcpy(&results[0], d_results, grid.x * sizeof(unsigned int),
273 cudaMemcpyDeviceToHost);
274
275 if (cudaResult != cudaSuccess) {
276 string msg("Could not copy partial results to host: ");
277 msg += cudaGetErrorString(cudaResult);
278 throw std::runtime_error(msg);
279 }
280
281 // Complete sum-reduction on host
282 Real value =
283 static_cast<Real>(std::accumulate(results.begin(), results.end(), 0));
284
285 // Determine the proportion of points inside the quarter-circle,
286 // i.e. the area of the unit quarter-circle
287 value /= m_numSims;
288
289 // Value is currently an estimate of the area of a unit quarter-circle, so we
290 // can scale to a full circle by multiplying by four. Now since the area of a
291 // circle is pi * r^2, and r is one, the value will be an estimate for the
292 // value of pi.
293 value *= 4;
294
295 // Cleanup
296 if (d_points) {
297 cudaFree(d_points);
298 d_points = 0;
299 }
300
301 if (d_results) {
302 cudaFree(d_results);
303 d_results = 0;
304 }
305
306 return value;
307 }
308
309 // Explicit template instantiation
310 template class PiEstimator<float>;
311 template class PiEstimator<double>;