在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,&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))
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 silently applies C linkage 将所有代码编译在一个 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,&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))
print(gdata)

这使内核具有 C 链接,但不会触及使用 cuRand 的设备函数。

,

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...