gpt4 book ai didi

cuda - 在 GPU 上使用 CUDA 生成笛卡尔积

转载 作者:行者123 更新时间:2023-12-04 18:10:02 27 4
gpt4 key购买 nike

我想知道一种在 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)

最佳答案

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

#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), }

关于cuda - 在 GPU 上使用 CUDA 生成笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196321/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com