【问题标题】:Use of shared memory to reduce computational time of calculations inside CUDA kernel使用共享内存来减少 CUDA 内核内部计算的计算时间
【发布时间】:2015-07-21 13:25:17
【问题描述】:

我有一个大小为 1920 x 1080 的图像。我正在使用三个 CUDA 流从 H2D 传输、处理并从 D2H 传输回来,每个流负责处理总数据的 1/3。通过了解 SM、SP、warp 的概念,我能够优化块的尺寸和每个块的线程数。如果必须在内核中进行简单的计算,则代码可以令人满意地运行(需要 2 毫秒)。下面的简单计算代码从源图像中找到 R、G 和 B 值,然后将这些值放在同一个源图像中。

ptr_source[numChannels*  (iw*y + x) + 0] = ptr_source[numChannels*  (iw*y + x) + 0];
ptr_source[numChannels*  (iw*y + x) + 1] = ptr_source[numChannels*  (iw*y + x) + 1];
ptr_source[numChannels*  (iw*y + x) + 2] = ptr_source[numChannels*  (iw*y + x) + 2];

但是我必须执行 更多计算,这些计算独立于所有其他线程,然后计算时间增加了 6 毫秒,这对我的应用程序来说太多了。我已经尝试在constant memory 中声明最常用的常量值。这些计算的代码如下所示。在该代码中,我再次找到了 R、G 和 B 值。然后,我通过将旧值乘以一些常数来计算 R、G 和 B 的新值,最后我将这些新的 R、G 和 B 值再次放入同一源图像的相应位置。

__constant__ int iw = 1080;
__constant__ int ih = 1920;
__constant__ int numChannels = 3;


__global__ void cudaKernel(unsigned char *ptr_source, int numCudaStreams)
{

    // Calculate our pixel's location
    int x = (blockIdx.x * blockDim.x) + threadIdx.x;
    int y = (blockIdx.y * blockDim.y) + threadIdx.y;

    // Operate only if we are in the correct boundaries
    if (x >= 0 && x < iw && y >= 0 && y < ih / numCudaStreams)
    {

        const int index_b = numChannels*  (iw*y + x) + 0;
        const int index_g = numChannels*  (iw*y + x) + 1;
        const int index_r = numChannels*  (iw*y + x) + 2;

        //GET VALUES: get the R,G and B values from Source image
        unsigned char b_val = ptr_source[index_b];
        unsigned char g_val = ptr_source[index_g];
        unsigned char r_val = ptr_source[index_r];

        float float_r_val = ((1.574090) * (float)r_val + (0.088825) * (float)g_val + (-0.1909)  * (float)b_val);
        float float_g_val = ((-0.344198) * (float)r_val + (1.579802) * (float)g_val + (-1.677604)  * (float)b_val);
        float float_b_val = ((-1.012951) * (float)r_val + (-1.781485) * (float)g_val + (2.404436)  * (float)b_val);


        unsigned char dst_r_val = (float_r_val > 255.0f) ? 255 : static_cast<unsigned char>(float_r_val);
        unsigned char dst_g_val = (float_g_val > 255.0f) ? 255 : static_cast<unsigned char>(float_g_val);
        unsigned char dst_b_val = (float_b_val > 255.0f) ? 255 : static_cast<unsigned char>(float_b_val);

        //PUT VALUES---put the new calculated values of R,G and B
        ptr_source[index_b] = dst_b_val;
        ptr_source[index_g] = dst_g_val;
        ptr_source[index_r] = dst_r_val;

    }
}

问题:我认为将图像段(即ptr_src)传输到共享内存会有所帮助,但我对如何做到这一点感到很困惑。我的意思是,共享内存的范围只有一个块,我如何管理图像段到共享内存的传输。

PS:我的 GPU 是 Quadro K2000,计算 3.0,2 SM,每个 SM 192 SP。

【问题讨论】:

  • 我们遗漏了您的一些实施细节。您是否使用三个流,然后在流之间划分每个颜色通道?此外,在此示例中使用共享内存不会获得任何性能改进,因为所有操作都是在像素级别完成的。事实上,总是渴望优化 nvcc 编译器可能会将计算转移到寄存器中。最后要注意的是,您对全局内存的内存访问模式没有合并,因为连续线程不会访问连续的内存位置。
  • @pQB:我已经更新了我的问题的第二句话。希望,现在我能够澄清 3 个流的使用。
  • 我不确定将图像拆分为三个流是否有任何好处。为什么不让y 维度中的块完成所有工作?尽管如此,关于共享内存的评论仍然是一样的,以及合并的问题。这些改进(合并)可能会缩短执行时间。
  • @pQB:由于并行数据传输和内核执行,三个流肯定使我受益。我没看懂你memory access pattern to global memory is not coalesct because consecutive threads do not access consecutive memory positions.这句话,因为我对这东西不太熟悉。
  • 你确实意识到你在这个内核中有双精度算术,并且可以在不改变你的代码行的情况下获得两倍的免费加速(除了修复双精度常量)......跨度>

标签: c++ cuda


【解决方案1】:

我将添加这段代码,暂时不做太多评论:

const int iw = 1080;
const int ih = 1920;
const int numChannels = 3;

__global__ void cudaKernel3(unsigned char *ptr_source, int n)
{
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    int stride = blockDim.x * gridDim.x;
    uchar3 * p = reinterpret_cast<uchar3 *>(ptr_source);

    for(; idx < n; idx+=stride) {

        uchar3 vin = p[idx];
        unsigned char b_val = vin.x;
        unsigned char g_val = vin.y;
        unsigned char r_val = vin.z;

        float float_r_val = ((1.574090f) * (float)r_val + (0.088825f) * (float)g_val + (-0.1909f)  * (float)b_val);
        float float_g_val = ((-0.344198f) * (float)r_val + (1.579802f) * (float)g_val + (-1.677604f)  * (float)b_val);
        float float_b_val = ((-1.012951f) * (float)r_val + (-1.781485f) * (float)g_val + (2.404436f)  * (float)b_val);

        uchar3 vout;
        vout.x = (unsigned char)fminf(255.f, float_r_val);
        vout.y = (unsigned char)fminf(255.f, float_g_val);
        vout.z = (unsigned char)fminf(255.f, float_b_val);

        p[idx] = vout;
    }
}

// Original kernel with a bit of template magic to conditionally correct
// accidental double precision arithmetic removed for brevity

int main()
{
    const size_t sz = iw * ih * numChannels;
    typedef unsigned char uchar;
    uchar * image = new uchar[sz];

    uchar v = 0;
    for(int i=0; i<sz; i++) {
        image[i] = v;
        v = (++v > 128) ? 0 : v;
    }

    uchar * image_;
    cudaMalloc((void **)&image_, sz);
    cudaMemcpy(image_, image, sz, cudaMemcpyHostToDevice);

    dim3 blocksz(32,32);
    dim3 gridsz(1+iw/blocksz.x, 1+ih/blocksz.y);
    cudaKernel<1><<<gridsz, blocksz>>>(image_, 1);
    cudaDeviceSynchronize();

    cudaMemcpy(image_, image, sz, cudaMemcpyHostToDevice);
    cudaKernel<0><<<gridsz, blocksz>>>(image_, 1);
    cudaDeviceSynchronize();

    cudaMemcpy(image_, image, sz, cudaMemcpyHostToDevice);
    cudaKernel3<<<16, 512>>>(image_, iw * ih);
    cudaDeviceSynchronize();

    cudaDeviceReset();

    return 0;
}

这里的想法是让尽可能多的线程驻留在设备上,并让它们处理整个图像,每个线程发出多个输出。块调度在 CUDA 中非常便宜,但它不是免费的,索引计算和一个线程完成有用工作所需的所有其他“设置”代码也不是免费的。所以这个想法只是将这些成本摊销到许多输出上。因为您的图像只是线性内存,并且您对每个条目执行的操作是完全独立的,所以使用 2D 网格和 2D 索引没有意义。它只是减慢代码速度的附加设置代码。您还将看到矢量类型 (char3) 的使用,该类型应该通过减少每个像素的内存传输数来提高内存吞吐量。

另请注意,在支持双精度的 GPU 上,将编译双精度常量并生成 64 位浮点运算。与单精度相比,执行双精度时性能损失 2 到 12 倍,具体取决于您的 GPU。当我编译您发布的内核并查看 CUDA 7 版本编译器为 sm_30 架构(与您的 GPU 相同)发出的 PTX 时,我在像素计算代码中看到了这一点:

cvt.f64.f32     %fd1, %f4;
mul.f64         %fd2, %fd1, 0d3FF92F78FEEF5EC8;
ld.global.u8    %rs9, [%rd1+1];
cvt.rn.f32.u16  %f5, %rs9;
cvt.f64.f32     %fd3, %f5;
fma.rn.f64      %fd4, %fd3, 0d3FB6BD3C36113405, %fd2;
ld.global.u8    %rs10, [%rd1];
cvt.rn.f32.u16  %f6, %rs10;
cvt.f64.f32     %fd5, %f6;
fma.rn.f64      %fd6, %fd5, 0dBFC86F694467381D, %fd4;
cvt.rn.f32.f64  %f1, %fd6;
mul.f64         %fd7, %fd1, 0dBFD607570C564F98;
fma.rn.f64      %fd8, %fd3, 0d3FF946DE76427C7C, %fd7;
fma.rn.f64      %fd9, %fd5, 0dBFFAD7774ABA3876, %fd8;
cvt.rn.f32.f64  %f2, %fd9;
mul.f64         %fd10, %fd1, 0dBFF0350C1B97353B;
fma.rn.f64      %fd11, %fd3, 0dBFFC80F66A550870, %fd10;
fma.rn.f64      %fd12, %fd5, 0d40033C48F10A99B7, %fd11;
cvt.rn.f32.f64  %f3, %fd12;

请注意,所有内容都升级为 64 位浮点,并且乘法均在 64 位中完成,浮点常量为 IEEE754 双精度格式,然后结果降级为 32 位。这是一个真正的性能成本,您应该小心地通过将浮点常量正确定义为单精度来避免它。

在 GT620M(2 SM Fermi 移动部件,依靠电池运行)上运行时,我们从 nvprof 获得以下配置文件数据

Time(%)      Time     Calls       Avg       Min       Max  Name
 39.44%  17.213ms         1  17.213ms  17.213ms  17.213ms  void cudaKernel<int=1>(unsigned char*, int)
 35.02%  15.284ms         3  5.0947ms  5.0290ms  5.2022ms  [CUDA memcpy HtoD]
 18.51%  8.0770ms         1  8.0770ms  8.0770ms  8.0770ms  void cudaKernel<int=0>(unsigned char*, int)
  7.03%  3.0662ms         1  3.0662ms  3.0662ms  3.0662ms  cudaKernel3(unsigned char*, int)

==5504== API calls:
Time(%)      Time     Calls       Avg       Min       Max  Name
 95.37%  1.01433s         1  1.01433s  1.01433s  1.01433s  cudaMalloc
  3.17%  33.672ms         3  11.224ms  4.8036ms  19.039ms  cudaDeviceSynchronize

  1.29%  13.706ms         3  4.5687ms  4.5423ms  4.5924ms  cudaMemcpy
  0.12%  1.2560ms        83  15.132us     427ns  541.81us  cuDeviceGetAttribute
  0.03%  329.28us         3  109.76us  91.086us  139.41us  cudaLaunch
  0.02%  209.54us         1  209.54us  209.54us  209.54us  cuDeviceGetName
  0.00%  23.520us         1  23.520us  23.520us  23.520us  cuDeviceTotalMem
  0.00%  13.685us         3  4.5610us  2.9930us  7.6980us  cudaConfigureCall
  0.00%  9.4090us         6  1.5680us     428ns  3.4210us  cudaSetupArgument
  0.00%  5.1320us         2  2.5660us  2.5660us  2.5660us  cuDeviceGetCount
  0.00%  2.5660us         2  1.2830us  1.2830us  1.2830us  cuDeviceGet

当在更大的设备上运行时(具有 7 个 SMX 的 GTX 670 Kepler 设备):

==9442== NVPROF is profiling process 9442, command: ./a.out
==9442== Profiling application: ./a.out
==9442== Profiling result:
Time(%)      Time     Calls       Avg       Min       Max  Name
 65.68%  2.6976ms         3  899.19us  784.56us  1.0829ms  [CUDA memcpy HtoD]
 20.84%  856.05us         1  856.05us  856.05us  856.05us  void cudaKernel<int=1>(unsigned char*, int)
  7.90%  324.64us         1  324.64us  324.64us  324.64us  void cudaKernel<int=0>(unsigned char*, int)
  5.58%  229.12us         1  229.12us  229.12us  229.12us  cudaKernel3(unsigned char*, int)

==9442== API calls:
Time(%)      Time     Calls       Avg       Min       Max  Name
 55.88%  45.443ms         1  45.443ms  45.443ms  45.443ms  cudaMalloc
 38.16%  31.038ms         1  31.038ms  31.038ms  31.038ms  cudaDeviceReset
  3.55%  2.8842ms         3  961.40us  812.99us  1.1982ms  cudaMemcpy
  1.92%  1.5652ms         3  521.72us  294.16us  882.27us  cudaDeviceSynchronize
  0.32%  262.49us        83  3.1620us     150ns  110.94us  cuDeviceGetAttribute
  0.09%  74.253us         3  24.751us  15.575us  41.784us  cudaLaunch
  0.03%  22.568us         1  22.568us  22.568us  22.568us  cuDeviceTotalMem
  0.03%  20.815us         1  20.815us  20.815us  20.815us  cuDeviceGetName
  0.01%  7.3900us         6  1.2310us     200ns  5.3890us  cudaSetupArgument
  0.00%  3.6510us         2  1.8250us     674ns  2.9770us  cuDeviceGetCount
  0.00%  3.1440us         3  1.0480us     516ns  1.9410us  cudaConfigureCall
  0.00%  2.1600us         2  1.0800us     985ns  1.1750us  cuDeviceGet

因此,只需在更小和更大的设备上修复基本错误并使用合理的设计模式,就可以大大加快速度。信不信由你。

【讨论】:

  • 使用uchar3 会产生一些问题。对于cudaStreamSynchronize(stream[i]) 行,我收到错误an illegal memory access was encountered。我试图做一些非常简单的事情来确定。如果我使用p[index].x = 0; p[index].y = 0; p[index].z = 255; 在内核中对图像进行更改,则会出现上述错误,而如果我使用以前的方法,即ptr_source[index + 0] = 0; ptr_source[index + 1] = 0; ptr_source[index + 2] = 255;,则会显示预期的 RED 图像。
  • 您的代码中没有流,但正如我提到的,我在代码中使用了三个流,所以我只根据您的建议更改了内核。代码中没有其他问题,因为它能够适用于不同的配置,但只有当我尝试使用 uchar3 * 类型指针处理图像时才会出现错误。
  • 我怎么可能回答你?我怎么知道你写了什么代码?此答案中添加的代码旨在供您学习和理解,而不是剪切和粘贴到您的代码库中。它展示了几个重要的概念(如何处理每个线程的多个输入/输出,如何使用向量类型来提高吞吐量,意外双精度算术的危险)。这不是代码编写或个性化帮助服务。问题和答案旨在使所有人受益,而不仅仅是此时此地的您。想一想。
  • 是的,我完全理解你的意思。我只是问你关于你建议的改变。我的观点只是使用uchar3 * 会在从D2H 复制回结果时引发错误。而unsinged char * 的使用不会引发任何错误。所以,关于正确使用uchar3,我可能需要了解一些事情。现在,我无法更改我原来的问题,因此,如果问题仍然存在,我将通过一个最小的工作示例发布一个关于此问题的问题。
  • 再一次,我并不是建议您更改您的代码。这不是这个答案的重点。我正在以完整示例代码的形式展示您可以从中学习的概念,并用真实世界的分析数据来支持它们。
【解决方案2】:

共享内存对您的情况没有帮助,您的内存访问不是 coaslescent。

您可以尝试以下操作:将您的 char* ptr_source 替换为 uchar3* 应该可能有助于您的线程访问数组中的连续数据。 uchar3 只是意味着:3 个连续的无符号字符。

由于同一线程中的线程同时执行同一指令,您将拥有这种访问模式:

假设您尝试访问地址为 0x3F0000 的内存。

thread 1 copies data at : 0x3F0000 then 0x3F0001 then 0x3F0002

thread 2 copies data at : 0x3F0003 then 0x3F0004 then 0x3F0005

0x3F0000 和 0x3F0003 不连续,因此访问数据的性能会很差。

与 uchar3 一起使用:

thread 1 : 0x3F0000 to 0x3F0002

thread 2 : 0x3F0003 to 0x3F0005

就像每个线程复制连续数据一样,您的内存控制器可以快速复制它。

你也可以替换:

(float_r_val > 255.0f) ? 255 : static_cast<unsigned char>(float_r_val);

float_r_val = fmin(255.0f, float_r_val);

这应该给你一个像这样的内核:

__global__ void cudaKernel(uchar3 *ptr_source, int numCudaStreams)
{

    // Calculate our pixel's location
    int x = (blockIdx.x * blockDim.x) + threadIdx.x;
    int y = (blockIdx.y * blockDim.y) + threadIdx.y;

    // Operate only if we are in the correct boundaries
    if (x >= 0 && x < iw && y >= 0 && y < ih / numCudaStreams)
    {
        const int index =   (iw*y + x);

        uchar3 val = ptr_source)[index];

        float float_r_val = ((1.574090f) * (float)val.x + (0.088825f) * (float)val.y + (-0.1909f)  * (float)b_val.z);
        float float_g_val = ((-0.344198f) * (float)val.x + (1.579802f) * (float)val.y + (-1.677604f)  * (float)b_val.z);
        float float_b_val = ((-1.012951f) * (float)val.x + (-1.781485f) * (float)val.y + (2.404436f)  * (float)b_val.z);

        ptr_source[index] = make_uchar3( fmin(255.0f, float_r_val), fmin(255.0f, float_g_val), fmin(255.0f, float_b_val) );
    }
}

我希望这些更新能提高性能。

【讨论】:

  • uchar3 的使用让我对cudaMemcpy() 感到困惑。我正在使用三个流。 numTripleBytes = image.rows * image.cols;totalMemSize = numTripleBytes * sizeof(uchar3);,每个流的内存段是memSegmentSize = totalMemSize / 3。现在,电话cudaMemcpyAsync(dev_src[j], h_src + (j*memSegmentSize), memSegmentSize, cudaMemcpyHostToDevice, stream[j]); 有一些问题。 j 从 0 到 2 不等,因为我有 3 个流。
  • “有一些问题”是什么意思。实际上totalMemSize应该和以前一样,因为sizeof(uchar3) == 3*sizeof(unsigned char)
  • 通常你应该在你的内核调用中将你的 unsigned char* 转换为 uchar3* 。我已经更新了我的帖子,试图解释什么是联合访问
  • @X3liF:好的,我明天会检查它,然后更新场景。
  • @X3liF:为什么要使用 2D 索引方案呢?这是完全没有必要的,索引开销占总计算负载的很大一部分。
猜你喜欢
  • 2013-02-09
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
相关资源
最近更新 更多