在pyCuda内核中生成单个随机数



我见过很多生成随机数数组的方法。但我想生成一个随机数。c++中有rand((这样的函数吗。我不想要一系列随机数字。我只需要在内核中生成一个随机数。有没有生成随机数的内置函数?我已经尝试了下面给定的代码,但它不起作用。

import numpy as np
import pycuda.autoinit
from pycuda.compiler import SourceModule
from pycuda import gpuarray
code = """
#include <curand_kernel.h>
__device__ float getRand()
{
curandState_t s;
curand_init(clock64(), 123456, 0, &s);
return curand_uniform(&s);
}
__global__ void myRand(float *values)
{
values[0] = getRand();
}
"""

mod = SourceModule(code)
myRand = mod.get_function("myRand")
gdata = gpuarray.zeros(2, dtype=np.float32)
myRand(gdata, block=(1,1,1), grid=(1,1,1))
print(gdata)

错误如下:

/usr/local/cuda/bin/../targets/x86_64-linux/include/curand_poisson.h(548): error: this declaration may not have extern "C" linkage
/usr/local/cuda/bin/../targets/x86_64-linux/include/curand_discrete2.h(69): error: this declaration may not have extern "C" linkage
/usr/local/cuda/bin/../targets/x86_64-linux/include/curand_discrete2.h(78): error: this declaration may not have extern "C" linkage
/usr/local/cuda/bin/../targets/x86_64-linux/include/curand_discrete2.h(86): error: this declaration may not have extern "C" linkage
30 errors detected in the compilation of "kernel.cu".

基本问题是,默认情况下,PyCUDA将C链接静默地应用于在SourceModule中编译的所有代码。正如错误所示,cuRand需要C++链接,所以getRand不能有C链接。

您可以通过更改以下两行来解决此问题:

mod = SourceModule(code)
myRand = mod.get_function("myRand")

mod = SourceModule(code, no_extern_c=True)
myRand = mod.get_function("_Z6myRandPf")

这将禁用C链接,但意味着您需要为get_function调用提供C++损坏的名称。您需要查看详细的编译器输出或在PyCUDA之外编译代码才能获得该名称(例如Godbolt(。

或者,你可以这样修改代码:

import numpy as np
import pycuda.autoinit
from pycuda.compiler import SourceModule
from pycuda import gpuarray
code = """
#include <curand_kernel.h>
__device__ float getRand()
{
curandState_t s;
curand_init(clock64(), 123456, 0, &s);
return curand_uniform(&s);
}

extern "C" {
__global__ void myRand(float *values)
{
values[0] = getRand();
}
}
"""

mod = SourceModule(code, no_extern_c=True)
myRand = mod.get_function("myRand")
gdata = gpuarray.zeros(2, dtype=np.float32)
myRand(gdata, block=(1,1,1), grid=(1,1,1))
print(gdata)

这使得内核使用C链接,但不涉及使用cuRand的设备功能。

您可以在python中使用import random。并使用CCD_ 6。通过在函数中定义范围来生成指定范围内的随机数。前random.randint(0,50)

最新更新