我想知道在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 ?对于N个列表,每个列表有M个值,如何做到这一点呢?
我使用的术语可能不正确。我可以试着解释我的意思:
我实际上是在尝试生成一个真值表:一个二元真值表看起来像
一个二元真值表看起来像
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)
我不认为这是有效的;功能:
#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), }