gpt4 book ai didi

c++ - cudaMemcpyFromSymbol和cudaMemcpyToSymbol始终返回cudaErrorInvalidSymbol(13)错误

转载 作者:行者123 更新时间:2023-12-02 10:17:59 32 4
gpt4 key购买 nike

我在CUDA C++ API中调用cudaMemcpyFrom(To)Symbol函数时遇到问题。欢迎在块之间存储一些参数的替代方案。下面,我提供了一些(示例)代码,这些代码无法正常运行。

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>
#include <cstdlib>
#include <ctime>

int avgHost(int*, int);

cudaError_t cudaError;

__device__ int getGlobalIdx()
{
int blockId = blockIdx.x + blockIdx.y * gridDim.x + gridDim.x * gridDim.y * blockIdx.z;
int threadId = blockId * (blockDim.x * blockDim.y * blockDim.z) + (threadIdx.z * (blockDim.x * blockDim.y)) + (threadIdx.y * blockDim.x) + threadIdx.x;
return threadId;
}

__device__ int avg;
__device__ int count;
__device__ int sum;

__global__ void avgKernel(const int *arr)
{
auto idx = getGlobalIdx();
count++;
sum += arr[idx];
avg = sum / count;
}


int main(int argc, char ** argv)
{
const int arraySize = 128;
auto arr1 = (int*)__vcrt_malloc_normal(arraySize * sizeof(int));
srand(time(NULL));
for (size_t i = 0; i < arraySize; i++)
{
arr1[i] = rand() % 100;
}
auto hostAvg = avgHost(arr1, arraySize);
fprintf_s(stdout, "AVG: %d", hostAvg);
free(arr1);
return 0;
}

int avgHost(int* arr, int arraySize)
{
int *dArray = nullptr;
cudaSetDevice(0);
cudaError = cudaMemcpyToSymbol((void *)count, (void*)0, sizeof(int), 0, cudaMemcpyHostToDevice);
if (cudaError)
{
fprintf_s(stderr, "%s\t%d\n", cudaGetErrorString(cudaError), __LINE__);
return -1;
}
cudaMalloc((void**)&dArray, arraySize * sizeof(int));
cudaMemcpy(dArray, arr, arraySize * sizeof(int), cudaMemcpyKind::cudaMemcpyHostToDevice);
avgKernel <<<1, arraySize>>> (dArray);
cudaDeviceSynchronize();
int hostResult = -1;
cudaError = cudaMemcpyFromSymbol(&hostResult, (void *)avg, sizeof(int), 0, cudaMemcpyDeviceToHost);
if (cudaError)
{
fprintf_s(stderr, "%s\t%d\n", cudaGetErrorString(cudaError), __LINE__);
}
cudaFree(dArray);
return hostResult;
}

当我启动打印代码系统时

invalid device symbol   55 AVG: -1

C:\Users\Administrator\source\repos\CudaTests\x64\Debug\cudabase.exe
(process 18152) exited with code 0.

有任何想法吗?

最佳答案

删除此行,因为在启动内核之前,设备变量“count”始终为0。

cudaError = cudaMemcpyToSymbol((void *)count, (void*)0, sizeof(int), 0, cudaMemcpyHostToDevice);
if (cudaError)
{
fprintf_s(stderr, "%s\t%d\n", cudaGetErrorString(cudaError), __LINE__);
return -1;
}

编辑
cudaError = cudaMemcpyFromSymbol(&hostResult, (void *)avg, sizeof(int), 0, CudaMemcpyDeviceToHost);

TO
cudaError = cudaMemcpyFromSymbol(&hostResult, avg, sizeof(int), 0, cudaMemcpyDeviceToHost);

(从参数“avg”中删除强制转换)。智能提供错误,但是代码可以编译并运行成功。

关于c++ - cudaMemcpyFromSymbol和cudaMemcpyToSymbol始终返回cudaErrorInvalidSymbol(13)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61286704/

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