PSCF v1.5.0
ThreadMesh.cu
1/*
2* PSCF - Polymer Self-Consistent Field
3*
4* Copyright 2015 - 2026, David Morse (morse012@um.edu) and co-authors
5* Distributed under the terms of the GNU General Public License.
6*/
7
8#include "ThreadMesh.h"
9#include <cuda_runtime.h>
10
11namespace Pscf {
12namespace ThreadMesh {
13
14 using namespace Util;
15
16 namespace {
17
18 /*
19 * Anonymous namespace containing "static" variables and functions
20 * only used by global functions defined in namespace ThreadMesh.
21 * These are thus persistent pseudo-private variables and functions,
22 * much like private static class members.
23 */
24
25 // Max threads per streaming multiprocessor, set by querying hardware.
26 int MAX_THREADS_PER_SM = -1;
27
28 // Max threads per block, set by querying hardware and optimizing.
29 int MAX_THREADS_PER_BLOCK = -1;
30
31 // Threads per block in current configuration.
32 // This may be either user-defined or equal to MAX_THREADS_PER_BLOCK.
33 int THREADS_PER_BLOCK = -1;
34
35 // Number of threads per warp.
36 int WARP_SIZE = -1;
37
38 // Multidimensional array of threads requested for execution.
39 dim3 MESH_DIMS(0, 0, 0);
40
41 // Dimensions of multidimensional thread block for execution.
42 dim3 BLOCK_DIMS(0, 0, 0);
43
44 // Dimensions of multidimensional grid of blocks for execution.
45 dim3 GRID_DIMS(0, 0, 0);
46
47 // Will threads go unused?
48 bool UNUSED_THREADS;
49
50 /*
51 * Initialize the ThreadMesh namespace
52 */
53 void init()
54 {
55 // Check that a CUDA device is available.
56 int count = 0;
57 cudaGetDeviceCount(&count);
58
59 if (count == 0) {
60 UTIL_THROW("No CUDA devices found.");
61 } else if (count > 1) {
62 Log::file() << "\nWarning: multiple GPUs detected.\n"
63 << "This program is not compatible with multiple devices.\n"
64 << "Only the first device will be used." << std::endl;
65 }
66
67 // Get properties, assuming one GPU.
68 cudaDeviceProp dprop;
69 cudaGetDeviceProperties(&dprop, 0);
70 WARP_SIZE = dprop.warpSize;
71 MAX_THREADS_PER_SM = dprop.maxThreadsPerMultiProcessor;
72
73 // Find the highest power of two that evenly divides into the
74 // maximum number of threads per streaming multiprocessor
75 // This will lead to the highest occupancy!
76 MAX_THREADS_PER_BLOCK = (MAX_THREADS_PER_SM &
77 (~(MAX_THREADS_PER_SM - 1)));
78
79 // If this value is > maxThreadsPerBlock, reduce
80 while (MAX_THREADS_PER_BLOCK > dprop.maxThreadsPerBlock) {
81 MAX_THREADS_PER_BLOCK /= 2;
82 }
83 }
84
85 }
86
87 template <int D>
88 void setConfig(IntVec<D> const & meshDims, bool invert, int blockSize)
89 {
90 // Verify that requested thread grid is valid
91 for (int i = 0; i < D; i++) {
92 UTIL_CHECK(meshDims[i] > 0);
93 }
94
95 // If MAX_THREADS_PER_BLOCK hasn't been set at all, initialize
96 if (MAX_THREADS_PER_BLOCK == -1) {
97 init();
98 }
99
100 // Check if requested number of threads matches the previous request
101 bool match = true;
102 if ((blockSize > 0) && (blockSize != THREADS_PER_BLOCK)) {
103 match = false;
104 } else if (invert) {
105 if (meshDims[D-1] != MESH_DIMS.x) match = false;
106 if (D > 1) {
107 if (meshDims[D-2] != MESH_DIMS.y) match = false;
108 } else {
109 if (1 != MESH_DIMS.y) match = false;
110 }
111 if (D > 2) {
112 if (meshDims[D-3] != MESH_DIMS.z) match = false;
113 } else {
114 if (1 != MESH_DIMS.z) match = false;
115 }
116 } else {
117 if (meshDims[0] != MESH_DIMS.x) match = false;
118 if (D > 1) {
119 if (meshDims[1] != MESH_DIMS.y) match = false;
120 } else {
121 if (1 != MESH_DIMS.y) match = false;
122 }
123 if (D > 2) {
124 if (meshDims[2] != MESH_DIMS.z) match = false;
125 } else {
126 if (1 != MESH_DIMS.z) match = false;
127 }
128 }
129
130 if (match) {
131 // Do nothing. Reuse previous execution configuration.
132 return;
133 }
134
135 // Store meshDims in MESH_DIMS in dim3 format
136 MESH_DIMS.y = 1;
137 MESH_DIMS.z = 1;
138 if (invert) {
139 MESH_DIMS.x = meshDims[D-1];
140 if (D > 1) MESH_DIMS.y = meshDims[D-2];
141 if (D > 2) MESH_DIMS.z = meshDims[D-3];
142 } else {
143 MESH_DIMS.x = meshDims[0];
144 if (D > 1) MESH_DIMS.y = meshDims[1];
145 if (D > 2) MESH_DIMS.z = meshDims[2];
146 }
147
148 // Assign the total block size parameter if not provided
149 bool manualBlockSize = false;
150 if (blockSize < 0) {
151 blockSize = MAX_THREADS_PER_BLOCK;
152 } else {
153 manualBlockSize = true;
154 if ((blockSize & (blockSize - 1)) != 0) { // blockSize not power of 2
155 UTIL_THROW("Manual block size entry must be a power of 2.");
156 }
157 if (blockSize < WARP_SIZE) {
158 Log::file() << "\nRequested threads per block: " << blockSize
159 << "\nWarp size: " << WARP_SIZE << std::endl;
160 UTIL_THROW("Threads per block cannot be smaller than warp size.");
161 }
162 }
163 THREADS_PER_BLOCK = blockSize;
164
165 // Set BLOCK_DIMS.x to maximize opportunities for coalescence.
166 // (Note: we restrict block dimensions to powers of 2.)
167 if (MESH_DIMS.x % WARP_SIZE == 0) {
168 // If MESH_DIMS.x is a multiple of WARP_SIZE, BLOCK_DIMS.x can be
169 // set to WARP_SIZE, resulting in no unused threads along x and
170 // optimal coalescence.
171 BLOCK_DIMS.x = WARP_SIZE;
172 } else if ((MESH_DIMS.x & (MESH_DIMS.x - 1)) == 0) {
173 // MESH_DIMS.x is a small power of two, so we can set BLOCK_DIMS.x
174 // equal to MESH_DIMS.x and have no unused threads along x,
175 // resulting in optimal coalescence.
176 BLOCK_DIMS.x = MESH_DIMS.x;
177 } else {
178 // MESH_DIMS.x is not a power of 2 or multiple of WARP_SIZE.
179 // Choose block dimensions to be either a warp or half-warp in the
180 // x dimension depending on the number of unused threads.
181 if ((MESH_DIMS.x / (WARP_SIZE/2)) % 2 == 0) {
182 // half warp will have smaller number of unused threads
183 BLOCK_DIMS.x = WARP_SIZE / 2;
184 } else {
185 // half and full warp will have same number of unused threads
186 BLOCK_DIMS.x = WARP_SIZE;
187 }
188 }
189
190 // Set BLOCK_DIMS.y to lowest power of 2 that is >= MESH_DIMS.y
191 BLOCK_DIMS.y = 1;
192 while (BLOCK_DIMS.y < MESH_DIMS.y) {
193 BLOCK_DIMS.y *= 2;
194 }
195 GRID_DIMS.y = 1; // set GRID_DIMS.y
196
197 // Set BLOCK_DIMS.z to lowest power of 2 that is >= MESH_DIMS.z
198 BLOCK_DIMS.z = 1;
199 while (BLOCK_DIMS.z < MESH_DIMS.z) {
200 BLOCK_DIMS.z *= 2;
201 }
202
203 // BLOCK_DIMS.z cannot exceed 64. Adjust if needed.
204 if (BLOCK_DIMS.z > 64) {
205 BLOCK_DIMS.z = 64;
206 }
207
208 // Set GRID_DIMS.z
209 GRID_DIMS.z = MESH_DIMS.z / BLOCK_DIMS.z;
210 if (MESH_DIMS.z % BLOCK_DIMS.z) GRID_DIMS.z++;
211
212 // Shrink BLOCK_DIMS until block size size equals THREADS_PER_BLOCK
213 blockSize = BLOCK_DIMS.x * BLOCK_DIMS.y * BLOCK_DIMS.z;
214 if (blockSize >= THREADS_PER_BLOCK) {
215
216 while (blockSize > THREADS_PER_BLOCK) {
217 // Determine how many unused gridpoints lie along y and z
218 int yOvershoot = BLOCK_DIMS.y * GRID_DIMS.y - MESH_DIMS.y;
219 int zOvershoot = BLOCK_DIMS.z * GRID_DIMS.z - MESH_DIMS.z;
220
221 // Halve the element of BLOCK_DIMS with largest overshoot
222 if ((yOvershoot > zOvershoot) || (BLOCK_DIMS.z == 1)) {
223 UTIL_CHECK(BLOCK_DIMS.y > 1);
224 BLOCK_DIMS.y /= 2;
225 GRID_DIMS.y = MESH_DIMS.y / BLOCK_DIMS.y;
226 if (MESH_DIMS.y % BLOCK_DIMS.y) GRID_DIMS.y++;
227 } else {
228 BLOCK_DIMS.z /= 2;
229 GRID_DIMS.z = MESH_DIMS.z / BLOCK_DIMS.z;
230 if (MESH_DIMS.z % BLOCK_DIMS.z) GRID_DIMS.z++;
231 }
232
233 blockSize = BLOCK_DIMS.x * BLOCK_DIMS.y * BLOCK_DIMS.z;
234 }
235 UTIL_CHECK(blockSize == THREADS_PER_BLOCK);
236 UTIL_CHECK(blockSize % WARP_SIZE == 0);
237
238 } else {
239 // blockSize is less than THREADS_PER_BLOCK.
240 // BLOCK_DIMS.x can be increased.
241 while ((BLOCK_DIMS.x < MESH_DIMS.x) && (blockSize < THREADS_PER_BLOCK))
242 {
243 BLOCK_DIMS.x *= 2;
244 blockSize *= 2;
245 }
246 if (blockSize < WARP_SIZE) {
247 // Make sure blockSize is at least one warp
248 UTIL_CHECK(blockSize > 0);
249 while (blockSize < WARP_SIZE) {
250 BLOCK_DIMS.x *= 2;
251 blockSize *= 2;
252 }
253 }
254
255 THREADS_PER_BLOCK = blockSize;
256 }
257
258 // Set GRID_DIMS.x
259 GRID_DIMS.x = MESH_DIMS.x / BLOCK_DIMS.x;
260 if (MESH_DIMS.x % BLOCK_DIMS.x) GRID_DIMS.x++;
261
262 // If block is smaller than manually requested size, print warning
263 if ((manualBlockSize) && (blockSize < THREADS_PER_BLOCK)) {
264 Log::file() << "WARNING: The number of threads per block ("
265 << blockSize
266 << ") will be smaller than \nthe requested size of "
267 << THREADS_PER_BLOCK << "." << std::endl;
268 }
269
270 // Set UNUSED_THREADS
271 if ((MESH_DIMS.x % BLOCK_DIMS.x) || (MESH_DIMS.y % BLOCK_DIMS.y) ||
272 (MESH_DIMS.z % BLOCK_DIMS.z)) {
273 UNUSED_THREADS = true;
274 } else {
275 UNUSED_THREADS = false;
276 }
277
278 checkConfig();
279 }
280
281 // Instantiate setConfig methods for D = 1, 2, 3
282 template void setConfig<1>(IntVec<1> const & meshDims,
283 bool invert, int blockSize);
284 template void setConfig<2>(IntVec<2> const & meshDims,
285 bool invert, int blockSize);
286 template void setConfig<3>(IntVec<3> const & meshDims,
287 bool invert, int blockSize);
288
290 {
291 // Check that max threads per block is a power of two.
292 if ((MAX_THREADS_PER_BLOCK & (MAX_THREADS_PER_BLOCK - 1)) != 0) {
293 Log::file() << "\nMax threads per block: " << MAX_THREADS_PER_BLOCK
294 << std::endl;
295 UTIL_THROW("Max threads per block must be a power of two.");
296 }
297
298 // Check that max threads per block is multiple of WARP_SIZE.
299 if (MAX_THREADS_PER_BLOCK % WARP_SIZE != 0)
300 {
301 Log::file() << "\nMax threads per block: " << MAX_THREADS_PER_BLOCK
302 << "\nWarp size: " << WARP_SIZE << std::endl;
303 UTIL_THROW("Max threads per block must be a multiple of warp size.");
304 }
305
306 // Check that threads per block is multiple of WARP_SIZE.
307 if (THREADS_PER_BLOCK % WARP_SIZE != 0)
308 {
309 Log::file() << "\nThreads per block: " << THREADS_PER_BLOCK
310 << "\nWarp size: " << WARP_SIZE << std::endl;
311 UTIL_THROW("Threads per block must be a multiple of warp size.");
312 }
313
314 // Check that block dimensions are each 1 or greater
315 if ((BLOCK_DIMS.x < 1) || (BLOCK_DIMS.y < 1) || (BLOCK_DIMS.z < 1)) {
316 Log::file() << "\nBlock dimensions: " << BLOCK_DIMS.x << " "
317 << BLOCK_DIMS.y << " " << BLOCK_DIMS.z << std::endl;
318 UTIL_THROW("Block dimensions must each be a power of two.");
319 }
320
321 // Check that BLOCK_DIMS multiply to THREADS_PER_BLOCK
322 if (BLOCK_DIMS.x * BLOCK_DIMS.y * BLOCK_DIMS.z != THREADS_PER_BLOCK) {
323 UTIL_THROW("THREADS_PER_BLOCK not properly set.");
324 }
325
326 // Check that the thread grid is at least as big as the requested mesh
327 if ((BLOCK_DIMS.x * GRID_DIMS.x < MESH_DIMS.x) ||
328 (BLOCK_DIMS.y * GRID_DIMS.y < MESH_DIMS.y) ||
329 (BLOCK_DIMS.z * GRID_DIMS.z < MESH_DIMS.z)) {
330 Log::file() << "\nBlock dimensions: " << BLOCK_DIMS.x << " "
331 << BLOCK_DIMS.y << " " << BLOCK_DIMS.z << std::endl;
332 Log::file() << "\nGrid dimensions: " << GRID_DIMS.x << " "
333 << GRID_DIMS.y << " " << GRID_DIMS.z << std::endl;
334 Log::file() << "\nMesh dimensions: " << MESH_DIMS.x << " "
335 << MESH_DIMS.y << " " << MESH_DIMS.z << std::endl;
336 UTIL_THROW("Thread grid smaller than the requested mesh.");
337 }
338
339 // Check that the maximum number of threads per multiprocessor is an
340 // integer multiple of the threads per block. This is not required
341 // for validity, but performance will be suboptimal if not the case,
342 // as it will limit the total number of threads that can be
343 // scheduled at any given time.
344 if (MAX_THREADS_PER_SM % MAX_THREADS_PER_BLOCK != 0) {
345 Log::file() << "WARNING: The number of threads per block ("
346 << MAX_THREADS_PER_BLOCK
347 << ") is not an even divisor of the maximum number"
348 << " of threads per streaming multiprocessor ("
349 << MAX_THREADS_PER_SM
350 << "). Performance will be suboptimal."
351 << std::endl;
352 }
353 }
354
358 void setThreadsPerBlock(int blockSize)
359 {
360 // If MAX_THREADS_PER_BLOCK hasn't been set at all, initialize
361 if (MAX_THREADS_PER_BLOCK == -1) {
362 init();
363 }
364
365 if ((blockSize & (blockSize - 1)) != 0) { // blockSize not power of 2
366 UTIL_THROW("Manual block size entry must be a power of 2.");
367 }
368
369 if (blockSize < WARP_SIZE) {
370 Log::file() << "\nRequested threads per block: " << blockSize
371 << "\nWarp size: " << WARP_SIZE << std::endl;
372 UTIL_THROW("Threads per block cannot be smaller than warp size.");
373 }
374
375 MAX_THREADS_PER_BLOCK = blockSize;
376 }
377
378 // Accessors
379
380 dim3 gridDims()
381 { return GRID_DIMS; }
382
384 { return BLOCK_DIMS; }
385
386 dim3 meshDims()
387 { return MESH_DIMS; }
388
390 { return WARP_SIZE; }
391
393 { return UNUSED_THREADS; }
394
395} // namespace ThreadMesh
396} // namespace Pscf
An IntVec<D, T> is a D-component vector of elements of integer type T.
Definition IntVec.h:27
static std::ostream & file()
Get log ostream by reference.
Definition Log.cpp:59
#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
int warpSize()
Get the warp size.
void setConfig(IntVec< D > const &meshDims, bool invert, int blockSize)
Given a multidimensional grid of threads, set execution configuration.
Definition ThreadMesh.cu:88
void checkConfig()
Check the execution configuration (grid and block dimensions).
bool hasUnusedThreads()
Will there be unused threads?
dim3 gridDims()
Get the multidimensional grid of blocks determined by setConfig.
dim3 meshDims()
Return last requested multidimensional grid of threads.
dim3 blockDims()
Get the dimensions of a single block determined by setConfig.
void setThreadsPerBlock(int blockSize)
Manually set the block size that should be used by default.
Multidimensional GPU thread execution configurations.
Definition ThreadMesh.cu:12
PSCF package top-level namespace.
Utility classes for scientific computation.