【问题标题】:Element-by-element vector multiplication with CUDA使用 CUDA 进行逐元素向量乘法
【发布时间】:2013-05-29 18:01:57
【问题描述】:

我在 CUDA 中构建了一个基本内核来执行两个复向量的 elementwise 向量-向量乘法。内核代码插入下面(multiplyElementwise)。它工作正常,但由于我注意到其他看似简单的操作(如缩放矢量)在 CUBLAS 或 CULA 等库中进行了优化,我想知道是否可以通过库调用替换我的代码?令我惊讶的是,CUBLAS 和 CULA 都没有这个选项,我试图通过使其中一个向量成为对角矩阵向量乘积的对角线来伪造它,但结果非常慢。

作为最后的手段,我尝试自己优化这段代码(参见下面的multiplyElementwiseFast),将两个向量加载到共享内存中,然后从那里开始工作,但这比我的原始代码慢。

所以我的问题:

  1. 是否有执行元素向量-向量乘法的库?
  2. 如果没有,我可以加速我的代码 (multiplyElementwise) 吗?

任何帮助将不胜感激!

__global__ void multiplyElementwise(cufftComplex* f0, cufftComplex* f1, int size)
{
    const int i = blockIdx.x*blockDim.x + threadIdx.x;
    if (i < size)
    {
        float a, b, c, d;
        a = f0[i].x; 
        b = f0[i].y;
        c = f1[i].x; 
        d = f1[i].y;
        float k;
        k = a * (c + d);
        d =  d * (a + b);
        c =  c * (b - a);
        f0[i].x = k - d;
        f0[i].y = k + c;
    }
}

__global__ void multiplyElementwiseFast(cufftComplex* f0, cufftComplex* f1, int size)
{
    const int i = blockIdx.x*blockDim.x + threadIdx.x;
    if (i < 4*size)
    {
        const int N = 256;
        const int thId = threadIdx.x / 4;
        const int rem4 = threadIdx.x % 4;
        const int i4 = i / 4;

        __shared__ float a[N];
        __shared__ float b[N];
        __shared__ float c[N];
        __shared__ float d[N];
        __shared__ float Re[N];
        __shared__ float Im[N];

        if (rem4 == 0)
        {
            a[thId] = f0[i4].x;
            Re[thId] = 0.f;
        }
        if (rem4 == 1)
        {
            b[thId] = f0[i4].y;
            Im[thId] = 0.f;
        }
        if (rem4 == 2)
            c[thId] = f1[i4].x;
        if (rem4 == 0)
            d[thId] = f1[i4].y;
        __syncthreads();

        if (rem4 == 0)
            atomicAdd(&(Re[thId]), a[thId]*c[thId]);        
        if (rem4 == 1)
            atomicAdd(&(Re[thId]), -b[thId]*d[thId]);
        if (rem4 == 2)
            atomicAdd(&(Im[thId]), b[thId]*c[thId]);
        if (rem4 == 3)
            atomicAdd(&(Im[thId]), a[thId]*d[thId]);
        __syncthreads();

        if (rem4 == 0)
            f0[i4].x = Re[thId];
        if (rem4 == 1)
            f0[i4].y = Im[thId];
    }
}        

【问题讨论】:

  • "elementwise vector-vector multiplication" 你的意思是点积吗?
  • @Benc... 不。对于实向量,点积是元素乘积的总和。
  • @sgar91:如果他正在“乘”复数,他实际上可能想要计算一个倍半线性形式,在这种情况下可以称为内积/点积(参见 this)。我只是想确定他的意图。

标签: cuda complex-numbers cublas


【解决方案1】:

您可以使用 cublasZdgmm。

cublasStatus_t cublasZdgmm(cublasHandle_t handle, cublasSideMode_t mode,
                      int m, int n,
                      const cuDoubleComplex *A, int lda,
                      const cuDoubleComplex *x, int incx,
                      cuDoubleComplex *C, int ldc)

【讨论】:

    【解决方案2】:

    如果您想要实现的是具有复数的简单元素乘积,那么您似乎确实在您的multiplyElementwise 内核中执行了一些额外的步骤来增加寄存器的使用。您尝试计算的是:

    f0[i].x = a*c - b*d;
    f0[i].y = a*d + b*c;
    

    因为(a + ib)*(c + id) = (a*c - b*d) + i(a*d + b*c)。通过使用改进的复数乘法,您可以用 1 次乘法换取 3 次加法和一些额外的寄存器。这是否合理可能取决于您使用的硬件。例如,如果您的硬件支持FMA(融合乘加),那么这种优化可能效率不高。您应该考虑阅读此文档:“Precision & Performance: Floating Point and IEEE 754 Compliance for NVIDIA GPUs”,它还解决了浮点精度问题。

    不过,您应该考虑使用Thrust。这个库提供了许多高级工具来操作主机和设备向量。您可以在此处查看一长串示例:https://github.com/thrust/thrust/tree/master/examples。这将使您的生活更轻松。

    更新代码

    在您的情况下,您可以使用 this example 并将其调整为如下内容:

    #include <thrust/host_vector.h>
    #include <thrust/device_vector.h>
    #include <time.h>
    
    struct ElementWiseProductBasic : public thrust::binary_function<float2,float2,float2>
    {
        __host__ __device__
        float2 operator()(const float2& v1, const float2& v2) const
        {
            float2 res;
            res.x = v1.x * v2.x - v1.y * v2.y;
            res.y = v1.x * v2.y + v1.y * v2.x;
            return res;
        }
    };
    
    /**
     * See: http://www.embedded.com/design/embedded/4007256/Digital-Signal-Processing-Tricks--Fast-multiplication-of-complex-numbers%5D
     */
    struct ElementWiseProductModified : public thrust::binary_function<float2,float2,float2>
    {
        __host__ __device__
        float2 operator()(const float2& v1, const float2& v2) const
        {
            float2 res;
            float a, b, c, d, k;
            a = v1.x;
            b = v1.y;
            c = v2.x;
            d = v2.y;
            k = a * (c + d);
            d =  d * (a + b);
            c =  c * (b - a);
            res.x = k -d;
            res.y = k + c;
            return res;
        }
    };
    
    int get_random_int(int min, int max)
    {
        return min + (rand() % (int)(max - min + 1));
    }
    
    thrust::host_vector<float2> init_vector(const size_t N)
    {
        thrust::host_vector<float2> temp(N);
        for(size_t i = 0; i < N; i++)
        {
            temp[i].x = get_random_int(0, 10);
            temp[i].y = get_random_int(0, 10);
        }
        return temp;
    }
    
    int main(void)
    {
        const size_t N = 100000;
        const bool compute_basic_product    = true;
        const bool compute_modified_product = true;
    
        srand(time(NULL));
    
        thrust::host_vector<float2>   h_A = init_vector(N);
        thrust::host_vector<float2>   h_B = init_vector(N);
        thrust::device_vector<float2> d_A = h_A;
        thrust::device_vector<float2> d_B = h_B;
    
        thrust::host_vector<float2> h_result(N);
        thrust::host_vector<float2> h_result_modified(N);
    
        if (compute_basic_product)
        {
            thrust::device_vector<float2> d_result(N);
    
            thrust::transform(d_A.begin(), d_A.end(),
                              d_B.begin(), d_result.begin(),
                              ElementWiseProductBasic());
            h_result = d_result;
        }
    
        if (compute_modified_product)
        {
            thrust::device_vector<float2> d_result_modified(N);
    
            thrust::transform(d_A.begin(), d_A.end(),
                              d_B.begin(), d_result_modified.begin(),
                              ElementWiseProductModified());
            h_result_modified = d_result_modified;
        }
    
        std::cout << std::fixed;
        for (size_t i = 0; i < 4; i++)
        {
            float2 a = h_A[i];
            float2 b = h_B[i];
    
            std::cout << "(" << a.x << "," << a.y << ")";
            std::cout << " * ";
            std::cout << "(" << b.x << "," << b.y << ")";
    
            if (compute_basic_product)
            {
                float2 prod = h_result[i];
                std::cout << " = ";
                std::cout << "(" << prod.x << "," << prod.y << ")";
            }
    
            if (compute_modified_product)
            {
                float2 prod_modified = h_result_modified[i];
                std::cout << " = ";
                std::cout << "(" << prod_modified.x << "," << prod_modified.y << ")";
            }
            std::cout << std::endl;
        }   
    
        return 0;
    }
    

    这会返回:

    (6.000000,5.000000)  * (0.000000,1.000000)  = (-5.000000,6.000000)
    (3.000000,2.000000)  * (0.000000,4.000000)  = (-8.000000,12.000000)
    (2.000000,10.000000) * (10.000000,4.000000) = (-20.000000,108.000000)
    (4.000000,8.000000)  * (10.000000,9.000000) = (-32.000000,116.000000)
    

    然后,您可以比较两种不同乘法策略的时序,并选择最适合您的硬件的方法。

    【讨论】:

    • 非常感谢,我会研究一下 Thrust 是否可以让它为我工作。以这种“向后”方式计算复杂乘积的原因是我在这里读到 [embedded.com/design/embedded/4007256/… 处理器在加法方面的麻烦比在乘法方面的麻烦少,因此它可能会更快一些。尽管在许多库中很容易找到向量的缩放或两个向量的总和,但这仍然有点奇怪,但元素乘法却不是......无论如何,感谢您的回答!
    • @WVDB:我明白了,我想这是值得比较的,但是这种优化实际上是依赖于硬件的,你需要记住,如果你使用编译器优化,编译器可能会重新排序操作.您可以将时间与nvprof/nvvp 甚至生成的 PTX 代码进行比较,以更好地了解实际情况。
    • @WVDB:我更新了我的答案,以便与 NVIDIA 的分析工具进行比较。
    • @ BenC 目前我正在尝试使用 Nsight 分析我的代码。再次感谢您的中肯建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2018-10-23
    • 1970-01-01
    • 2022-07-06
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多