c++ - 迭代第二个循环,在 CUDA 中减少总和

标签 c++ cuda iteration

我必须将此代码从 C++ 并行化到 CUDA C

  for(ihist = 0; ihist < numhist; ihist++){ 
      for(iwin = 0; iwin<numwin; iwin++){
          denwham[ihist] += (numbinwin[iwin]/g[iwin])*exp(F[iwin]-U[ihist]); 
          }
          Punnorm[ihist] = numwham[ihist]/denwham[ihist];
        }

在 CUDA C 中,使用总和缩减:

extern __shared__ float sdata[];
  int tx = threadIdx.x;
  int i=blockIdx.x;
  int j=blockIdx.y;
  float sum=0.0;
  float temp=0.0;
  temp=U[j];


   if(tx<numwin)
   {
    sum=(numbinwin[tx]/g[tx])*exp(F[tx]- temp); 
    sdata[tx] = sum;
     __syncthreads();  
   }


  for(int offset = blockDim.x / 2;offset > 0;offset >>= 1)
  {
   if(tx < offset)
   {
    // add a partial sum upstream to our own
    sdata[tx] += sdata[tx + offset];
   }
   __syncthreads();
  }

   // finally, thread 0 writes the result
  if(threadIdx.x == 0)
  {
   // note that the result is per-block
   // not per-thread
   denwham[i] = sdata[0];

    for(int k=0;k<numhist;k++)
    Punnorm[k] = numwham[k]/denwham[k];
  }

并以这种方式初始化它:

 int smem_sz = (256)*sizeof(float);
  dim3 Block(numhist,numhist,1);
  NewProbabilitiesKernel<<<Block,256,smem_sz>>>(...);

我的问题是我无法使用 exp 遍历 U,我尝试了以下方法:

a) loop for/while inside the kernel that iterates over U 
b) iterate by thread
c) iterate to block

所有这些尝试导致我在 C++ 代码和代码 cuda 之间得到不同的结果。如果我输入一个常量而不是 U [i],代码工作正常!

你有什么想法可以帮助我吗?

谢谢。

最佳答案

看起来你可以将 U 移出内循环

for(iwin = 0; iwin<numwin; iwin++){
    denwham += numbinwin[iwin] / g[iwin] * exp(F[iwin]); 
}
for(ihist = 0; ihist < numhist; ihist++){ 
    Punnorm[ihist] = numwham[ihist] / denwham * exp(U[ihist]);
}

更新

之后,您可以使用 2 个简单内核而不是 1 个复杂内核来完成任务。

  1. 减少内核计算 denwham;
  2. 用于计算Punnorm的一维变换核;

关于c++ - 迭代第二个循环,在 CUDA 中减少总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19631057/

相关文章:

java - 如何通过引用 Java 中包含数组的 HashMap 来向数组添加值?

java - 循环遍历枚举作为参数

c++ - opencv 3.0 findContours 函数在窗口中不起作用

c++ - g++ undefined reference ,尽管 *.so 文件中存在符号

c++ - 模仿boost lexical_cast操作

compilation - 在Linux下进行Cuda编译时,非常简单的Makefile的外观应该如何

c++ - 带 TTL 的数据结构

c++ - CUDA Visual Profiler 5.0 不生成时间线,Cudadevicereset() 出错

recursion - CUDA支持递归吗?

javascript - 最小化 getElementById/getElementsByClassName 的代码