如何使用 CUDA 将 std::vector<std::string> 复制到 GPU 设备

How to copy std::vector<std::string> to GPU device with CUDA

本文关键字:std 复制 gt GPU 设备 string 何使用 CUDA vector lt      更新时间:2023-10-16

我正在从文件中读取行,并希望通过 GPU 对每一行执行一些计算。

我面临的问题是,到目前为止,我曾经以恒定大小复制一个 int 数组,现在我有一个字符串向量,每个字符串的大小都不同。我正在使用:

std::vector<std::string> lines;

我使用了一个常量大小来复制数组。 像这样:

err = cudaMemcpy(_devArr, tmp, count * sizeof(unsigned int) * 8, cudaMemcpyHostToDevice);

但我不确定我是否完全理解它如何与向量一起工作。如何寻址和复制字符串向量?我可以以某种方式复制它并仍然像带有线程+块索引的数组一样访问它吗?

*使用最新的 CUDA 10.2 和 CUDA RTX 2060 显卡

您需要将字符串平展为包含所有字符串的连续内存块。我的建议是使用两个(总(块来执行此操作,一个包含组合的字符串数据,另一个包含每个字符串的索引。

std::string combined; //Works perfectly fine so long as it is contiguously allocated
std::vector<size_t> indexes; //You *might* be able to use int instead of size_t to save space
for(std::string const& line : lines) {
combined += line;
indexes.emplace_back(combined.size());
}
/* If 'lines' initially consisted of ["Dog", "Cat", "Tree", "Yard"], 'combined' is now
* "DogCatTreeYard", and 'indexes' is now [3, 6, 10, 14].
*/
//I'm hoping I am writing these statements correctly; I don't specifically have CUDA experience
err = cudaMemcpy(_devArr, combined.data(), combined.size(), cudaMemcpyHostToDevice);
err = cudaMemcpy(_devArr2, indexes.data(), indexes.size() * sizeof(size_t), cudaMemcpyHostToDevice);

然后,在设备本身中,您将能够根据需要读取每个字符串。我不熟悉 CUDA 使用的语法,所以我打算用 OpenCL 语法来写这个,但原则应该干净直接地转换为 CUDA;如果我弄错了,有人纠正我。

kernel void main_func(
global char * lines, //combined string data
global ulong * indexes, //indexes telling us the beginning and end of each string
ulong indexes_size, //number of strings being analyzed
global int * results //space to return results back to Host
) {
size_t id = get_global_id(0);//"Which String are we examining?"
if(id >= indexes_size) //Bounds Checking
return;
global char * string; //Beginning of the string
if(id == 0) //First String
string = lines;
else
string = (lines + indexes[id-1]);
global char * string_end = (lines + indexes[id]); //end of the string
for(; string != string_end; string++) {
if(*string == 'A') {
results[id] = 1; //We matched the criteria; we'll put a '1' for this string
return;
}
}
results[id] = 0; //We did not match. We'll put a '0' for this string
}

在初始字符串列表上执行的此代码的结果是,对于任何包含A的字符串,它将得到 1 的结果;如果没有,它将得到 0 的结果。这里的逻辑应该可以干净地转移到 CUDA 使用的特定语法;如果不是,请告诉我。