c++ cuda共享内存-结果不一致

t98cgbkg  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(114)

我正在尝试在CUDA中对一个数组进行并行归约求和。目前我传递一个数组,在其中存储每个块中元素的总和。这是我的代码:

#include <cstdlib>
#include <iostream>
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <helper_cuda.h>
#include <host_config.h>
#define THREADS_PER_BLOCK 256
#define CUDA_ERROR_CHECK(ans) { gpuAssert((ans), __FILE__, __LINE__); }

using namespace std;

inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=true)
{
   if (code != cudaSuccess) 
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

struct double3c {
    double x; 
    double y;
    double z;
    __host__ __device__ double3c() : x(0), y(0), z(0) {}
    __host__ __device__ double3c(int x_, int y_, int z_) : x(x_), y(y_), z(z_) {}
    __host__ __device__ double3c& operator+=(const double3c& rhs) { x += rhs.x; y += rhs.y; z += rhs.z;}
    __host__ __device__ double3c& operator/=(const double& rhs) { x /= rhs; y /= rhs; z /= rhs;}

};

class VectorField {
public:
    double3c *data;
    int size_x, size_y, size_z;
    bool is_copy;  

    __host__ VectorField () {}

    __host__ VectorField (int x, int y, int z) {
        size_x = x; size_y = y; size_z = z;
        is_copy = false;
        CUDA_ERROR_CHECK (cudaMalloc(&data, x * y * z * sizeof(double3c))); 
    }

    __host__ VectorField (const VectorField& other) {
        size_x = other.size_x; size_y = other.size_y; size_z = other.size_z;
        this->data = other.data;
        is_copy = true;
    }

    __host__ ~VectorField() {     
        if (!is_copy) CUDA_ERROR_CHECK (cudaFree(data));
    }
};

__global__ void KernelCalculateMeanFieldBlock (VectorField m, double3c* result) {
    __shared__ double3c blockmean[THREADS_PER_BLOCK];    
    int index = threadIdx.x + blockIdx.x * blockDim.x;
    if (index < m.size_x * m.size_y * m.size_z) blockmean[threadIdx.x] = m.data[index] = double3c(0, 1, 0);
    else blockmean[threadIdx.x] = double3c(0,0,0);
    __syncthreads();
    for(int s = THREADS_PER_BLOCK / 2; s > 0; s /= 2) {
        if (threadIdx.x < s) blockmean[threadIdx.x] += blockmean[threadIdx.x + s];
        __syncthreads();
    }

    if(threadIdx.x == 0) result[blockIdx.x] = blockmean[0];   
}

double3c CalculateMeanField (VectorField& m) { 
    int blocknum = (m.size_x * m.size_y * m.size_z - 1) / THREADS_PER_BLOCK + 1;
    double3c *mean = new double3c[blocknum]();
    double3c *cu_mean;
    CUDA_ERROR_CHECK (cudaMalloc(&cu_mean, sizeof(double3c) * blocknum));
    CUDA_ERROR_CHECK (cudaMemset (cu_mean, 0, sizeof(double3c) * blocknum));

        KernelCalculateMeanFieldBlock <<<blocknum, THREADS_PER_BLOCK>>> (m, cu_mean);
        CUDA_ERROR_CHECK (cudaPeekAtLastError());
        CUDA_ERROR_CHECK (cudaDeviceSynchronize());
        CUDA_ERROR_CHECK (cudaMemcpy(mean, cu_mean, sizeof(double3c) * blocknum, cudaMemcpyDeviceToHost));

    CUDA_ERROR_CHECK (cudaFree(cu_mean));
    for (int i = 1; i < blocknum; i++) {mean[0] += mean[i];}
    mean[0] /= m.size_x * m.size_y * m.size_z;
    double3c aux = mean[0];
    delete[] mean;
    return aux;
}


int main() {
    VectorField m(100,100,100);
    double3c sum = CalculateMeanField (m);
    cout <<  sum.x << '\t' << sum.y << '\t' <<sum.z;  

    return 0;
}

编辑

发布了功能代码。用10x10x10个元素构造VectorField可以很好地工作,平均值为1,但是用100x100x100个元素构造它,平均值为0.97(它因运行而异)。这是进行并行缩减的正确方法吗?还是我应该坚持每个块启动一个内核?

jgzswidk

jgzswidk1#

当我在linux上编译你现在拥有的代码时,我得到以下警告:

t614.cu(55): warning: __shared__ memory variable with non-empty constructor or destructor (potential race between threads)

不应忽略此类警告。它与这行代码相关联:

__shared__ double3c blockmean[THREADS_PER_BLOCK];

由于存储在共享内存中的这些对象的初始化(由构造函数)将以某种任意顺序发生,并且在此与也将设置这些值的后续代码之间没有障碍,因此可能会发生 * 不可预知的事情 )。
如果我在代码中插入一个__syncthreads(),将构造函数活动与后续代码隔离,我会得到预期的结果:

__shared__ double3c blockmean[THREADS_PER_BLOCK];    
int index = threadIdx.x + blockIdx.x * blockDim.x;
__syncthreads();  // add this line
if (index < m.size_x * m.size_y * m.size_z) blockmean[threadIdx.x] = m.data[index] = double3c(0, 1, 0);
else blockmean[threadIdx.x] = double3c(0,0,0);
__syncthreads();

然而,这仍然给我们留下了警告。要解决这个问题并使警告消失,可以进行修改,动态分配必要的__shared__大小。将共享内存声明更改为:

extern __shared__ double3c blockmean[];

然后修改你的内核调用:

KernelCalculateMeanFieldBlock <<<blocknum, THREADS_PER_BLOCK, THREADS_PER_BLOCK*sizeof(double3c)>>> (m, cu_mean);

这将消除警告,生成正确的结果,并避免共享内存变量上不必要的构造函数通信。(并且不再需要上面描述的附加__syncthreads()

  • 关于“不可预测的事情”,如果你通过检查生成的SASS(cuobjdump -sass...)* 或PTX*(**)(nvcc -ptx...)来查看后台,你会看到 * 每个线程 * 将 * 整个 * __shared__对象数组初始化为零(默认构造函数的行为)。因此,一些线程(即,warps)可以根据这一行抢先并开始填充共享存储器区域:
if (index < m.size_x * m.size_y * m.size_z) blockmean[threadIdx.x] = m.data[index] = double3c(0, 1, 0);

然后,当其他线程束开始执行时,这些线程将再次清除整个共享内存阵列。这种竞争行为导致不可预测的结果。

**我通常不建议通过检查PTX来判断代码行为,但在这种情况下,它同样具有指导意义。最后的编译阶段不会优化构造函数的行为。

相关问题