我正在用 CUDA 编写程序,问题如下:
两个矩阵A(n * 128)和B(m * 128)
我取 A 的第一行,然后逐个计算该 vector 与 B 的所有行之间的距离。
我将每个距离的结果写在矩阵 C 的一行上,因此 C 的元素 C(i,j) 包含 A 的第 i 行和 B 的第 j 行之间的距离。
-然后我继续下一行 A。
我是这样实现的: 我有一个由 ( n * m ) 个 block 组成的网格,每个 block 有 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();
}
最佳答案
条件看起来不对:
for (int stride = SIZE/2 ; stride < 0 ; stride >>= 1)
假设你说的SIZE是128,这个是不会执行的。此外,if 语句中的 __synchthread
可能会使整个事情停止
编辑:在阅读了 OP 的评论后,我意识到这是一个语言问题。这是一个片段:
#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;
}
输出是:没有。看看 for loop syntax在 C++ 中,第二部分是条件应该在整个循环期间持续。如果您以错误条件开始,您的循环将永远不会执行。
关于c++ - 计算 CUDA 中 2 个矩阵之间的欧氏距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24064023/