thrust::reduce_by_key() 返回重复的键

问题描述 投票:0回答:1

这是我的代码:

//initialize the device_vector
int size = N;
thrust::device_vector<glm::vec3> value(size);
thrust::device_vector<int> key(size);
//get the device pointer of the device_vector
//so than I can write data to the device_vector in CUDA kernel
glm::vec3 * dv_value_ptr = thrust::raw_pointer_cast(&value[0]);
int* dv_key_ptr = thrust::raw_pointer_cast(&key[0]);
//run the kernel function
dim3 threads(16, 16);
dim3 blocks(iDivUp(m_width, threads.x), iDivUp(m_height, threads.y));
//the size of value and key is packed in dev_data
compute_one_i_all_j <<<blocks, threads >>>(dev_data, dv_key_ptr, dv_value_ptr);
//Finally, reduce the vector by its keys.
thrust::pair<thrust::device_vector<int>::iterator,
      thrust::device_vector<glm::vec3>::iterator> new_last;
new_last = thrust::reduce_by_key(key.begin(), key.end(), value.begin(), output_key.begin(), output_value.begin());
//get the reduced vector size
int new__size = new_last.first - output_key.begin();

完成所有这些代码后,我将

output_key
写入文件。我在文件中得到很多重复的键,如下所示:

所以,

reduce_by_key()
似乎不起作用。
附言。 CUDA内核只写了部分
key
s和
value
s,所以在内核之后
key
value
中的一些元素保持不变(可能是0)。

c++ cuda reduce thrust
1个回答
2
投票

如文档中所述:

对于

[keys_first, keys_last)
范围内的每组连续键,
reduce_by_key
将组的第一个元素复制到 keys_output。使用加号减少范围内的相应值,并将结果复制到 values_output。

每组相等的连续键会减少

所以首先你必须重新排列所有的键和值,这样所有具有相同键的元素都是相邻的。最简单的方法是使用

sort_by_key
.

thrust::sort_by_key(key.begin(), key.end(), value.begin())
new_last = thrust::reduce_by_key(key.begin(), key.end(), value.begin(), output_key.begin(), output_value.begin());
© www.soinside.com 2019 - 2024. All rights reserved.