CUDA内存限制
问题描述:
如果我尝试向我的CUDA设备发送一个比可用内存大的结构体,CUDA会给我什么样的警告或错误?CUDA内存限制
我在问,因为我的GPU有1024兆字节(1073414144字节)全局内存总量,但我不知道该如何处理和最终出现问题。
这是我的代码:
#define VECSIZE 2250000
#define WIDTH 1500
#define HEIGHT 1500
// Matrices are stored in row-major order:
// M(row, col) = *(M.elements + row * M.width + col)
struct Matrix
{
int width;
int height;
int* elements;
};
int main()
{
Matrix M;
M.width = WIDTH;
M.height = HEIGHT;
M.elements = (int *) calloc(VECSIZE,sizeof(int));
int row, col;
// define Matrix M
// Matrix generator:
for (int i = 0; i < M.height; i++)
for(int j = 0; j < M.width; j++)
{
row = i;
col = j;
if (i == j)
M.elements[row * M.width + col] = INFINITY;
else
{
M.elements[row * M.width + col] = (rand() % 2); // because 'rand() % 1' just does not seems to work ta all.
if (M.elements[row * M.width + col] == 0) // can't have zero weight.
M.elements[row * M.width + col] = INFINITY;
else if (M.elements[row * M.width + col] == 2)
M.elements[row * M.width + col] = 1;
}
}
// Declare & send device Matrix to Device.
Matrix d_M;
d_M.width = M.width;
d_M.height = M.height;
size_t size = M.width * M.height * sizeof(int);
cudaMalloc(&d_M.elements, size);
cudaMemcpy(d_M.elements, M.elements, size, cudaMemcpyHostToDevice);
int *d_k= (int*) malloc(sizeof(int));
cudaMalloc((void**) &d_k, sizeof (int));
int *d_width=(int*)malloc(sizeof(int));
cudaMalloc((void**) &d_width, sizeof(int));
unsigned int *width=(unsigned int*)malloc(sizeof(unsigned int));
width[0] = M.width;
cudaMemcpy(d_width, width, sizeof(int), cudaMemcpyHostToDevice);
int *d_height=(int*)malloc(sizeof(int));
cudaMalloc((void**) &d_height, sizeof(int));
unsigned int *height=(unsigned int*)malloc(sizeof(unsigned int));
height[0] = M.height;
cudaMemcpy(d_height, height, sizeof(int), cudaMemcpyHostToDevice);
/*
et cetera .. */
答
虽然你可能目前不能发送足够的数据来GPU来最大程度的发挥它的记忆,当你这样做,你的cudaMalloc
将返回错误代码cudaErrorMemoryAllocation
其作为每cuda api docs ,表示内存分配失败。我注意到在你的示例代码中,你没有检查cuda调用的返回值。这些返回代码需要检查以确保您的程序正常运行。 cuda api不会抛出异常:您必须检查返回码。见this article的信息在检查错误,并获取有关错误
答
有意义的信息。如果您正在使用cutil.h
,那么它提供了两个非常有用的宏:CUDA_SAFE_CALL
(使用时发出的功能,如cudaMalloc,cudaMemcpy等)
和CUT_CHECK_ERROR
(在执行内核检查内核执行错误后使用)。
他们通过使用flipchart提供的文章中详细介绍的错误检查机制来处理错误(如果有)。
200万个元素* 4个字节只有8 ** MB **。你有1 ** GB **,即1024 MB可以玩! –
是的,我不是在这个例子中,但我的意愿是随着时间的推移使用更大的矩阵。 – Imperian