我正在研究OpenCL代码,它计算数组元素的总和。对于1D输入阵列,每个都可以正常工作,大小为1.024 * 1e + 8,但是对于1.024 * 1e + 9,最终值为“-Nan”。
以下是this link
上代码的来源内核代码位于this link
和this link上的Makefile
这是最后一个数组大小的结果(最后一个有效的大小值是1.024 * 1e + 8):
$ ./sumReductionGPU 102400000
Max WorkGroup size = 4100
Number of WorkGroups = 800000
Problem size = 102400000
Final Sum Sequential = 5.2428800512000000000e+15
Final Sum GPU = 5.2428800512000000000e+15
Initializing Arrays : Wall Clock = 0 second 673785 micro
Preparing GPU/OpenCL : Wall Clock = 1 second 925451 micro
Time for one NDRangeKernel call and WorkGroups final Sum : Wall Clock = 0 second 30511 micro
Time for Sequential Sum computing : Wall Clock = 0 second 398485 micro
我已经local_item_size = 128
,如上所示,我800000 Work-Groups
NWorkItems = 1.024 * 1e+8
。
现在如果我取1.024 * 10 ^ 9,则不再计算部分和,我得到数组元素总和的“ -nan ”值。
$ ./sumReductionGPU 1024000000
Max WorkGroup size = 4100
Number of WorkGroups = 8000000
Problem size = 1024000000
Final Sum Sequential = 5.2428800006710899200e+17
Final Sum GPU = -nan
Initializing Arrays : Wall Clock = 24 second 360088 micro
Preparing GPU/OpenCL : Wall Clock = 19 second 494640 micro
Time for one NDRangeKernel call and WorkGroups final Sum : Wall Clock = 0 second 481910 micro
Time for Sequential Sum computing : Wall Clock = 166 second 214384 micro
也许我已达到GPU单位可以计算的极限。但我想得到你的建议,以确认这一点。
如果double
为8 bytes
,则输入数组需要1.024 * 1e9 * 8~8 GBytes:是不是太多了?我只有8 GB的RAM。
根据您的经验,这个问题可能来自哪里?
由于
答案 0 :(得分:0)
正如您已经发现的那样,您的1D输入数组需要大量内存。因此,malloc
或clCreateBuffer
的内存分配很容易失败。
对于malloc
,我建议使用辅助函数checked_malloc
来检测内存分配失败,打印出一条消息并退出程序。
#include <stdlib.h>
#include <stdio.h>
void * checked_malloc(size_t size, const char purpose[]) {
void *result = malloc(size);
if(result == NULL) {
fprintf(stderr, "ERROR: malloc failed for %s\n", purpose);
exit(1);
}
return result;
}
int main()
{
double *p1 = checked_malloc(1e8 * sizeof *p1, "array1");
double *p2 = checked_malloc(64 * 1e9 * sizeof *p2, "array2");
return 0;
}
在我的PC上只有48 GB的虚拟内存,第二次分配失败并打印程序:
ERROR: malloc failed for array2
您也可以将此方案应用于clCreateBuffer
。但是,你必须检查每个OpenCL调用的结果。所以,我建议使用一个宏:
#define CHECK_CL_ERROR(result) if(result != CL_SUCCESS) { \
fprintf(stderr, "OpenCL call failed at: %s:%d with code %d\n", __FILE__, __LINE__, result); }
示例用法是:
cl_mem inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY,
nWorkItems * sizeof(double), NULL, &ret);
CHECK_CL_ERROR(ret);