gpt4 book ai didi

cuda - CUDA 内核中主机浮点常量的使用

转载 作者:行者123 更新时间:2023-12-05 07:57:37 25 4
gpt4 key购买 nike

我正在使用 CUDA 5.0。我注意到编译器将允许我在内核中使用主机声明的 int 常量。但是,它拒绝编译任何使用主机声明的 float 常量的内核。有谁知道这种看似差异的原因?

例如,下面的代码可以正常运行,但如果内核中的最后一行未被注释,它将无法编译。

#include <cstdio>
#include <cuda_runtime.h>

static int __constant__ DEV_INT_CONSTANT = 1;
static float __constant__ DEV_FLOAT_CONSTANT = 2.0f;

static int const HST_INT_CONSTANT = 3;
static float const HST_FLOAT_CONSTANT = 4.0f;

__global__ void uselessKernel(float * val)
{
*val = 0.0f;

// Use device int and float constants
*val += DEV_INT_CONSTANT;
*val += DEV_FLOAT_CONSTANT;

// Use host int and float constants
*val += HST_INT_CONSTANT;
//*val += HST_FLOAT_CONSTANT; // won't compile if uncommented
}

int main(void)
{
float * d_val;
cudaMalloc((void **)&d_val, sizeof(float));

uselessKernel<<<1, 1>>>(d_val);

cudaFree(d_val);
}

最佳答案

在设备代码中添加一个常量数字是可以的,但在设备代码中添加一个存储在主机内存中的数字是不行的。

当从未引用该变量的地址时,编译器/优化器可以将代码中对 static const int 的每个引用替换为值 3。在这种情况下,它类似于 #define HST_INT_CONSTANT 3,并且没有为该变量分配主机内存。

但是对于float var,即使是static const float,主机内存总是被分配的。由于内核无法直接访问主机内存,因此不会编译带有 static const float 的代码。

对于 C/C++,int 可以比 float 更积极地优化。

你的代码在注释打开时运行,我认为这可以看作是 CUDA C 的一个错误。 static const int 是主机端的东西,设备不应该直接访问它。

关于cuda - CUDA 内核中主机浮点常量的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26443857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com