【发布时间】:2021-03-27 06:23:22
【问题描述】:
我有一个主机类TestClass,它有一个指向类TestTable 的指针,它的数据存储在GPU 上的浮点数组中。
TestClass 调用访问TestTable 内部数据的内核,以及来自TestClass 的方法GetValue()。
在阅读了很多内容并尝试了几个选项之后,哪些类型说明符用于哪些方法和类以及如何(以及在哪里)初始化TestTable,我觉得我的所有选项最终归结为相同的内存访问错误。因此,我对 Cuda/C++ 工作原理的理解可能不足以正确实现它。我的代码应该如何正确设置?
这是我的main.cu的最小版本的内容:
#include <iostream>
#include <cuda_runtime.h>
#define CUDA_CHECK cuda_check(__FILE__,__LINE__)
inline void cuda_check(std::string file, int line)
{
cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::cout << std::endl
<< file << ", line " << line << ": "
<< cudaGetErrorString(e) << " (" << e << ")" << std::endl;
exit(1);
}
}
class TestTable {
float* vector_;
int num_cells_;
public:
void Init() {
num_cells_ = 1e4;
cudaMallocManaged(&vector_, num_cells_*sizeof(float));
CUDA_CHECK;
}
void Free() {
cudaFree(vector_);
}
__device__
bool UpdateValue(int global_index, float val) {
int index = global_index % num_cells_;
vector_[index] = val;
return false;
}
};
class TestClass {
private:
float value_;
TestTable* test_table_;
public:
TestClass() : value_(1.) {
// test_table_ = new TestTable;
cudaMallocManaged(&test_table_, sizeof(TestTable));
test_table_->Init();
CUDA_CHECK;
}
~TestClass() {
test_table_->Free();
cudaFree(test_table_);
CUDA_CHECK;
}
__host__ __device__
float GetValue() {
return value_;
}
__host__
void RunKernel();
};
__global__
void test_kernel(TestClass* test_class, TestTable* test_table) {
int index = threadIdx.x + blockIdx.x * blockDim.x;
int stride = blockDim.x * gridDim.x;
for (int i = index; i < 1e6; i += stride) {
const float val = test_class->GetValue();
test_table->UpdateValue(i, val);
}
}
__host__
void TestClass::RunKernel() {
test_kernel<<<1,1>>>(this, test_table_);
cudaDeviceSynchronize(); CUDA_CHECK;
}
int main(int argc, char *argv[]) {
TestClass* test_class = new TestClass();
std::cout << "TestClass successfully constructed" << std::endl;
test_class->RunKernel();
std::cout << "Kernel successfully run" << std::endl;
delete test_class;
std::cout << "TestClass successfully destroyed" << std::endl;
return 0;
}
我得到的错误是line 88: an illegal memory access was encountered (700)。
我认为错误在于以下问题之一:
-
TestTable没有使用new正确创建,这可能很糟糕。但是,在TestClass()中取消注释test_table_ = new TestTable;并不能解决问题。 -
test_kernel中的GetValue()不返回有效的浮点变量。如果我用任意浮点数替换它,例如1.f,程序运行无误。但是,在我的代码的真实(不是最小)版本中,GetValue()会在代码库的不同点进行大量计算,因此硬编码不是一种选择。 - 我从不将
TestClass复制到GPU,而是从内核调用它的一个成员函数。我看到这一定会造成麻烦,但我觉得知道在哪里以及如何复制它并不直观。如果我只在内核中调用GetValue()而不重用其结果,则没有错误,因此我的程序似乎可以调用GetValue()而无需将类复制到GPU。
我无法针对我的具体问题提出的可能相关问题:
- Accessing class data members from within cuda kernel - how to design proper host/device interaction? - 这个看起来非常相似,但不知何故我无法将它翻译成我的用例。
- Accessing Class Member in different CUDA kernels - 在这里,我不确定我有两个类相互“交互”这一事实会如何影响解决方案。
- CUDA and Classes - 这个问题对我来说似乎更笼统。
非常感谢任何帮助!
【问题讨论】: