4

我想知道一种在 GPU 上使用 CUDA 生成笛卡尔积的方法。
简单案例:我们有两个列表:

 A = {0.0, 0.1, 0.2}   B = {0.0, 0.1, 0.2}
 A x B = C = { {0.0, 0.0}, {0.0, 0.1}, {0.0, 0.2}, {0.1, 0.0}, {0.1, 0.1} ...}

如何在 GPU 中生成(列表列表)C?对于每个具有 M 值的 N 个列表,如何做到这一点。

我使用的术语可能不正确。我可以尝试解释我的意思:
我实际上是在尝试生成一个真值表:二进制真值表看起来像

二进制真值表看起来像

A     B
0     0
0     1
1     0
1     1

其中 A 有两个值 {0, 1},B 有 {0, 1}。在我的情况下,A 和 B 有两个以上的值,对于初学者来说,有 31 个值(0 - 30)。对于集合 A 中的每个值,集合 B 中有 31 个值,我需要枚举它们并将它们存储在内存中。

除此之外,我需要将算法扩展到 N 个列表而不是 2 个列表(A 和 B)

4

1 回答 1

1

我不认为这是有效的。只是功能:

#include <thrust/device_vector.h>
#include <thrust/pair.h>
#include <thrust/copy.h>
#include <iterator>

__global__ void cartesian_product(const int *a, size_t a_size,
                                  const int *b, size_t b_size,
                                  thrust::pair<int,int> *c)
{
  unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x;

  if(idx < a_size * b_size)
  {
    unsigned int a_idx = idx / a_size;
    unsigned int b_idx = idx % a_size;

    c[idx] = thrust::make_pair(a[a_idx], b[b_idx]);
  }
}

int main()
{
  thrust::device_vector<int> a(3);
  a[0] = 0; a[1] = 1; a[2] = 2;

  thrust::device_vector<int> b(3);
  b[0] = 0; b[1] = 1; b[2] = 2;

  thrust::device_vector<thrust::pair<int,int> > c(a.size() * b.size());

  unsigned int block_size = 256;
  unsigned int num_blocks = (c.size() + (block_size - 1)) / block_size;

  cartesian_product<<<num_blocks, block_size>>>(thrust::raw_pointer_cast(a.data()), a.size(),
                                                thrust::raw_pointer_cast(b.data()), b.size(),
                                                thrust::raw_pointer_cast(c.data()));

  std::cout << "a: { ";
  thrust::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, ", "));
  std::cout << "}" << std::endl;

  std::cout << "b: { ";
  thrust::copy(b.begin(), b.end(), std::ostream_iterator<int>(std::cout, ", "));
  std::cout << "}" << std::endl;

  std::cout << "c: { ";
  for(unsigned int i = 0; i < c.size(); ++i)
  {
    thrust::pair<int,int> x = c[i];
    std::cout << "(" << x.first << ", " << x.second << "), ";
  }
  std::cout << "}" << std::endl;

  return 0;
}

程序的输出:

$ nvcc cartesian_product.cu -run
a: { 0, 1, 2, }
b: { 0, 1, 2, }
c: { (0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), }
于 2013-04-24T20:12:00.357 回答