【问题标题】:Computing Euclidean distances between 2 matrices in CUDA在 CUDA 中计算两个矩阵之间的欧几里得距离
【发布时间】:2014-06-05 15:17:44
【问题描述】:

我正在用 CUDA 编写程序,问题如下:

  • 两个矩阵 A (n * 128) 和 B (m * 128)

  • 我取 A 的第一行,并逐一计算该向量与 B 的所有行之间的距离。

  • 我将每个距离的结果写在矩阵C的一行上,所以C的元素C(i,j)包含A的i行和B的j行之间的距离。

-然后我继续下一行 A。

我是这样实现的: 我有一个由 ( n * m ) 个块组成的网格,每个块有 128 个线程。 ( 1 * 128 )。

程序正在编译,但问题是它没有给出好的距离。 我不知道哪里错了...

PS:我有 CUDA 6.0 和 NVIDIA GTX 650(计算能力 3.0)

 __global__ void EuclidianDistances( float *A, float *B , float *C , int n , int m)
{
    // SIZE is equal to 128
__shared__ float accumResult[SIZE];
__shared__ float sA[SIZE];
__shared__ float sB[SIZE];

    // MAPPING
int bx = blockIdx.x;  // n
int by = blockIdx.y;  // m
int ty = threadIdx.y; // 128
int tx = threadIdx.x; // 1


sA[ty] = A [bx * SIZE + ty];
sB[ty] = B [by * SIZE + ty];
__syncthreads();


accumResult[ty] = (sA[ty] - sB[ty])*(sA[ty] - sB[ty]);
__syncthreads();


// Parallel tree-reduction
for (int stride = SIZE/2 ; stride < 0 ; stride >>= 1)
    if (ty < stride)
    {
        accumResult[ty] += accumResult [stride + ty];
          __syncthreads();
    }

    // Writing results to output matrix
if ((threadIdx.y == 0))
    C [bx * m + by] = accumResult[ty];
       __syncthreads();
}

【问题讨论】:

  • (ty &lt; pas),这是什么pas?将__syncthreads(); 放在if 语句中取决于threadIdx 对我来说看起来很危险。
  • 另外:条件似乎不对:for (int stride = SIZE/2 ; stride &lt; 0 ; stride &gt;&gt;= 1)
  • @Levans:对不起,passtride。我刚刚更正了。

标签: c++ cuda


【解决方案1】:

条件看起来不对:

for (int stride = SIZE/2 ; stride < 0 ; stride >>= 1)

如你所说,假设 SIZE 为 128,这将不会被执行。此外,if 语句中的 __synchthread 可能会拖延整个事情


编辑:在阅读了 OP 的 cmets 之后,我意识到这是一个语言问题.. 这是一个 sn-p:

#include <iostream>
using namespace std;

int main() {

    int SIZE = 128;

    for (int stride = SIZE/2 ; stride < 0 ; stride >>= 1)
        cout << "Hello I'm running" << endl;



    return 0;
}

http://ideone.com/AyhXYF

输出是:什么都没有。看看 C++ 中的for loop syntax,第二部分是应该在整个循环期间持续的条件。如果你从一个错误的条件开始,你的循环永远不会被执行。

【讨论】:

  • 我刚刚将pas 更改为stride。抱歉,是我的错。那么为什么条件不对呢?
  • @Jeb11 他的回答仍然有效,你不是说stride &gt; 0 而不是stride &lt; 0 吗?
  • @Levans 现在正在与stride &gt; 0 合作,谢谢。我想我要删除这个帖子,解决方案很明显..
  • @Marco A. 我刚刚接受了你的回答。我会把我的问题留在网上;)
  • 这可能是一个不同的问题,但您可能会看看您的瓶颈在哪里(即内存或计算)。 Nsight 可以在这方面提供帮助
猜你喜欢
  • 2018-06-14
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 2014-08-15
  • 2018-03-14
  • 1970-01-01
相关资源
最近更新 更多