CUDA - 多个内核来计算单个值
嘿,我正在尝试编写一个内核,本质上是在 C 中执行以下操作
float sum = 0.0;
for(int i = 0; i < N; i++){
sum += valueArray[i]*valueArray[i];
}
sum += sum / N;
目前我的内核中有这个,但它没有给出正确的值。
int i0 = blockIdx.x * blockDim.x + threadIdx.x;
for(int i=i0; i<N; i += blockDim.x*gridDim.x){
*d_sum += d_valueArray[i]*d_valueArray[i];
}
*d_sum= __fdividef(*d_sum, N);
用于调用内核的代码是
kernelName<<<64,128>>>(N, d_valueArray, d_sum);
cudaMemcpy(&sum, d_sum, sizeof(float) , cudaMemcpyDeviceToHost);
我认为每个内核都在计算部分和,但最终的除法语句没有考虑每个线程的累积值。每个内核都为 d_sum 生成自己的最终值?
有谁知道我怎样才能有效地做到这一点?也许在线程之间使用共享内存?我对 GPU 编程非常陌生。干杯
Hey, I'm trying to write a kernel to essentially do the following in C
float sum = 0.0;
for(int i = 0; i < N; i++){
sum += valueArray[i]*valueArray[i];
}
sum += sum / N;
At the moment I have this inside my kernel, but it is not giving correct values.
int i0 = blockIdx.x * blockDim.x + threadIdx.x;
for(int i=i0; i<N; i += blockDim.x*gridDim.x){
*d_sum += d_valueArray[i]*d_valueArray[i];
}
*d_sum= __fdividef(*d_sum, N);
The code used to call the kernel is
kernelName<<<64,128>>>(N, d_valueArray, d_sum);
cudaMemcpy(&sum, d_sum, sizeof(float) , cudaMemcpyDeviceToHost);
I think that each kernel is calculating a partial sum, but the final divide statement is not taking into account the accumulated value from each of the threads. Every kernel is producing it's own final value for d_sum?
Does anyone know how could I go about doing this in an efficient way? Maybe using shared memory between threads? I'm very new to GPU programming. Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在从多个线程更新 d_sum 。
请参阅以下 SDK 示例:
http://developer.download.nvidia .com/compute/cuda/sdk/website/samples.html
这是该示例的代码。请注意这是一个两步过程。在尝试累积最终结果之前,先对每个线程块求和,然后对 __syncthreads 求和。
You're updating d_sum from multiple threads.
See the following SDK sample:
http://developer.download.nvidia.com/compute/cuda/sdk/website/samples.html
Here's the code from that sample. Note how it's a two step process. Sum each thread block and then __syncthreads before attempting to accumulate the final result.