【问题标题】:How should I do instead of using numpy.vectorize in CuPy?我应该怎么做而不是在 CuPy 中使用 numpy.vectorize?
【发布时间】:2020-02-29 22:38:56
【问题描述】:

我应该如何将定义的函数应用于 cupy.array 而不是 np.vectorize? 有没有在cupy中实现过类似的功能?

我正在用 Python 3.6.9 编写模拟程序。

我想在 GPU(GTX1060,NVIDIA)中使用 CuPy(CUDA10.1 为 6.0.0)进行模拟。

在原始代码中,函数 numpy.vectorize 用于将定义的函数应用于 np.array。但是,相同的功能尚未在 CuPy 中实现。

原始代码(使用numpy)如下:

#For define function
def rate(tmean,x,y,z):
    rate = 1/z/(1 + math.exp(-x*(tmean-y)))
    #DVR<0
    if rate < 0:
        rate = 0
    return rate

#tmean is temperature data(365,100,100) and loaded as np.array
#paras is parameter(3,100,100)
#vectorized
f = np.vectorize(rate)
#roop
for i in range(365):
    #calc developing rate(by function "rate") and accumulate
    dvi[i,:,:] = dvi[i-1,:,:] + f(tmean[i,:,:],paras[0],paras[1],paras[2])

我知道几乎 numpy 的功能已经在 CuPy 中实现了。 所以我改变了

f = np.vectorized(rate) 

f= cp.vectorized(rate)

但是发生了AttributeError。

【问题讨论】:

    标签: python cupy


    【解决方案1】:

    GPU 无法并行化任意 Python 代码。在 NumPy 兼容的操作中编写所有内容,例如

    def rate_(xp, tmean,x,y,z):
        rate = 1/z/(1 + xp.exp(-x*(tmean-y)))
        rate[rate < 0] = 0
        return rate
    
    f = functools.partial(rate_, xp=cupy)
    

    为了加快速度,您可以使用cupy.ElementwiseKernel (https://docs-cupy.chainer.org/en/stable/tutorial/kernel.html),它会为矢量化操作创建单个内核。

    f = cupy.ElementwiseKernel(
        'T tmean, T x, T y, T z',
        'T rate',
        '''
        rate = 1/z/(1 + exp(-x*(tmean-y)));
        // DVR<0
        if (rate < 0) {
            rate = 0;
        }
        '''
    )
    

    要从 Python 代码创建内核,请尝试 cupy.fuse

    @cupy.fuse()
    def f(tmean,x,y,z):
        rate = 1/z/(1 + cupy.exp(-x*(tmean-y)))
        return cupy.where(rate < 0, 0, rate)  # __setitem__ is not fully supported
    

    【讨论】:

      猜你喜欢
      • 2013-02-10
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多