| 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, unsigned int seed) |
| 108 |
: m_numSims(numSims), |
| 109 |
m_device(device), |
| 110 |
m_threadBlockSize(threadBlockSize), |
| 111 |
m_seed(seed) {} |
| 112 |
|
| 113 |
template <typename Real> |
| 114 |
Real PiEstimator<Real>::operator()() { |
| 115 |
cudaError_t cudaResult = cudaSuccess; |
| 116 |
struct cudaDeviceProp deviceProperties; |
| 117 |
struct cudaFuncAttributes funcAttributes; |
| 118 |
|
| 119 |
// Get device properties |
| 120 |
cudaResult = cudaGetDeviceProperties(&deviceProperties, m_device); |
| 121 |
|
| 122 |
if (cudaResult != cudaSuccess) { |
| 123 |
string msg("Could not get device properties: "); |
| 124 |
msg += cudaGetErrorString(cudaResult); |
| 125 |
throw std::runtime_error(msg); |
| 126 |
} |
| 127 |
|
| 128 |
// Check precision is valid |
| 129 |
if (typeid(Real) == typeid(double) && |
| 130 |
(deviceProperties.major < 1 || |
| 131 |
(deviceProperties.major == 1 && deviceProperties.minor < 3))) { |
| 132 |
throw std::runtime_error("Device does not have double precision support"); |
| 133 |
} |
| 134 |
|
| 135 |
// Attach to GPU |
| 136 |
cudaResult = cudaSetDevice(m_device); |
| 137 |
|
| 138 |
if (cudaResult != cudaSuccess) { |
| 139 |
string msg("Could not set CUDA device: "); |
| 140 |
msg += cudaGetErrorString(cudaResult); |
| 141 |
throw std::runtime_error(msg); |
| 142 |
} |
| 143 |
|
| 144 |
// Determine how to divide the work between cores |
| 145 |
dim3 block; |
| 146 |
dim3 grid; |
| 147 |
block.x = m_threadBlockSize; |
| 148 |
grid.x = (m_numSims + m_threadBlockSize - 1) / m_threadBlockSize; |
| 149 |
|
| 150 |
// Aim to launch around ten or more times as many blocks as there |
| 151 |
// are multiprocessors on the target device. |
| 152 |
unsigned int blocksPerSM = 10; |
| 153 |
unsigned int numSMs = deviceProperties.multiProcessorCount; |
| 154 |
|
| 155 |
while (grid.x > 2 * blocksPerSM * numSMs) { |
| 156 |
grid.x >>= 1; |
| 157 |
} |
| 158 |
|
| 159 |
// Get computeValue function properties and check the maximum block size |
| 160 |
cudaResult = cudaFuncGetAttributes(&funcAttributes, computeValue<Real>); |
| 161 |
|
| 162 |
if (cudaResult != cudaSuccess) { |
| 163 |
string msg("Could not get function attributes: "); |
| 164 |
msg += cudaGetErrorString(cudaResult); |
| 165 |
throw std::runtime_error(msg); |
| 166 |
} |
| 167 |
|
| 168 |
if (block.x > (unsigned int)funcAttributes.maxThreadsPerBlock) { |
| 169 |
throw std::runtime_error( |
| 170 |
"Block X dimension is too large for computeValue kernel"); |
| 171 |
} |
| 172 |
|
| 173 |
// Check the dimensions are valid |
| 174 |
if (block.x > (unsigned int)deviceProperties.maxThreadsDim[0]) { |
| 175 |
throw std::runtime_error("Block X dimension is too large for device"); |
| 176 |
} |
| 177 |
|
| 178 |
if (grid.x > (unsigned int)deviceProperties.maxGridSize[0]) { |
| 179 |
throw std::runtime_error("Grid X dimension is too large for device"); |
| 180 |
} |
| 181 |
|
| 182 |
// Allocate memory for points |
| 183 |
// Each simulation has two random numbers to give X and Y coordinate |
| 184 |
Real *d_points = 0; |
| 185 |
cudaResult = cudaMalloc((void **)&d_points, 2 * m_numSims * sizeof(Real)); |
| 186 |
|
| 187 |
if (cudaResult != cudaSuccess) { |
| 188 |
string msg("Could not allocate memory on device for random numbers: "); |
| 189 |
msg += cudaGetErrorString(cudaResult); |
| 190 |
throw std::runtime_error(msg); |
| 191 |
} |
| 192 |
|
| 193 |
// Allocate memory for result |
| 194 |
// Each thread block will produce one result |
| 195 |
unsigned int *d_results = 0; |
| 196 |
cudaResult = cudaMalloc((void **)&d_results, grid.x * sizeof(unsigned int)); |
| 197 |
|
| 198 |
if (cudaResult != cudaSuccess) { |
| 199 |
string msg("Could not allocate memory on device for partial results: "); |
| 200 |
msg += cudaGetErrorString(cudaResult); |
| 201 |
throw std::runtime_error(msg); |
| 202 |
} |
| 203 |
|
| 204 |
// Generate random points in unit square |
| 205 |
curandStatus_t curandResult; |
| 206 |
curandGenerator_t prng; |
| 207 |
curandResult = curandCreateGenerator(&prng, CURAND_RNG_PSEUDO_DEFAULT); |
| 208 |
|
| 209 |
if (curandResult != CURAND_STATUS_SUCCESS) { |
| 210 |
string msg("Could not create pseudo-random number generator: "); |
| 211 |
msg += curandResult; |
| 212 |
throw std::runtime_error(msg); |
| 213 |
} |
| 214 |
|
| 215 |
curandResult = curandSetPseudoRandomGeneratorSeed(prng, m_seed); |
| 216 |
|
| 217 |
if (curandResult != CURAND_STATUS_SUCCESS) { |
| 218 |
string msg("Could not set seed for pseudo-random number generator: "); |
| 219 |
msg += curandResult; |
| 220 |
throw std::runtime_error(msg); |
| 221 |
} |
| 222 |
|
| 223 |
if (typeid(Real) == typeid(float)) { |
| 224 |
curandResult = |
| 225 |
curandGenerateUniform(prng, (float *)d_points, 2 * m_numSims); |
| 226 |
} else if (typeid(Real) == typeid(double)) { |
| 227 |
curandResult = |
| 228 |
curandGenerateUniformDouble(prng, (double *)d_points, 2 * m_numSims); |
| 229 |
} else { |
| 230 |
string msg("Could not generate random numbers of specified type"); |
| 231 |
throw std::runtime_error(msg); |
| 232 |
} |
| 233 |
|
| 234 |
if (curandResult != CURAND_STATUS_SUCCESS) { |
| 235 |
string msg("Could not generate pseudo-random numbers: "); |
| 236 |
msg += curandResult; |
| 237 |
throw std::runtime_error(msg); |
| 238 |
} |
| 239 |
|
| 240 |
curandResult = curandDestroyGenerator(prng); |
| 241 |
|
| 242 |
if (curandResult != CURAND_STATUS_SUCCESS) { |
| 243 |
string msg("Could not destroy pseudo-random number generator: "); |
| 244 |
msg += curandResult; |
| 245 |
throw std::runtime_error(msg); |
| 246 |
} |
| 247 |
|
| 248 |
// Count the points inside unit quarter-circle |
| 249 |
computeValue<Real><<<grid, block, block.x * sizeof(unsigned int)>>>( |
| 250 |
d_results, d_points, m_numSims); |
| 251 |
|
| 252 |
// Copy partial results back |
| 253 |
vector<unsigned int> results(grid.x); |
| 254 |
cudaResult = cudaMemcpy(&results[0], d_results, grid.x * sizeof(unsigned int), |
| 255 |
cudaMemcpyDeviceToHost); |
| 256 |
|
| 257 |
if (cudaResult != cudaSuccess) { |
| 258 |
string msg("Could not copy partial results to host: "); |
| 259 |
msg += cudaGetErrorString(cudaResult); |
| 260 |
throw std::runtime_error(msg); |
| 261 |
} |
| 262 |
|
| 263 |
// Complete sum-reduction on host |
| 264 |
Real value = |
| 265 |
static_cast<Real>(std::accumulate(results.begin(), results.end(), 0)); |
| 266 |
|
| 267 |
// Determine the proportion of points inside the quarter-circle, |
| 268 |
// i.e. the area of the unit quarter-circle |
| 269 |
value /= m_numSims; |
| 270 |
|
| 271 |
// Value is currently an estimate of the area of a unit quarter-circle, so we |
| 272 |
// can scale to a full circle by multiplying by four. Now since the area of a |
| 273 |
// circle is pi * r^2, and r is one, the value will be an estimate for the |
| 274 |
// value of pi. |
| 275 |
value *= 4; |
| 276 |
|
| 277 |
// Cleanup |
| 278 |
if (d_points) { |
| 279 |
cudaFree(d_points); |
| 280 |
d_points = 0; |
| 281 |
} |
| 282 |
|
| 283 |
if (d_results) { |
| 284 |
cudaFree(d_results); |
| 285 |
d_results = 0; |
| 286 |
} |
| 287 |
|
| 288 |
return value; |
| 289 |
} |
| 290 |
|
| 291 |
// Explicit template instantiation |
| 292 |
template class PiEstimator<float>; |
| 293 |
template class PiEstimator<double>; |