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

Generating single random number in pyCuda kernel

我见过很多生成随机数数组的方法。但我想生成一个随机数。 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".

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

基本问题是,默认情况下,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, 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 的设备功能。