如何将密集的向量转换为CUDA中的稀疏向量

How to convert dense vector to sparse vector in CUDA ?

本文关键字:向量 CUDA 转换      更新时间:2023-10-16

我在GPU内存中有一个大密集向量(不是矩阵):

[1,3,0,0,4,0,0]

并希望将其转换为稀疏格式:

values = [1,3,4];index = [0,1,4]

我知道我可以在cuSPARSE中调用cusparse<t>dense2csc(),但这是为矩阵而设计的,并且可能对向量不有效。还有其他方法吗?或者也许是cuda内核。谢谢

使用thrust::copy_if

int * d_index = [1,3,0,0,4,0,0];
int * d_index_compact;
struct non_negative
{
    __host__ __device__
    bool operator()(const int x)
    {
        return x >= 0;
    }
};

thrust::copy_if(thrust::cuda::par, d_index, d_index + this->vocab_size , d_index_compact, non_negative()); // d_index_compact = [1,3,4];