使用numba不能获得与numpy elementwise矩阵乘法相同的值

时间:2017-10-11 07:03:53

标签: python numpy cuda numba

我一直在玩numba并尝试实现一个简单的元素矩阵乘法。使用' vectorize'我得到了与numpy乘法相同的结果,但是当我使用&c 39. cuda.jit'他们不一样。其中许多都是零。我为此提供了最低限度的工作示例。任何有关此问题的帮助将不胜感激。我使用的是numba o.35.0和python 2.7

from __future__ import division
from __future__ import print_function

import numpy as np

from numba import vectorize, cuda, jit

M = 80
N = 40
P = 40

# Set the number of threads in a block
threadsperblock = 32

# Calculate the number of thread blocks in the grid
blockspergrid = (M*N*P + (threadsperblock - 1)) // threadsperblock

@vectorize(['float32(float32,float32)'], target='cuda')
def VectorMult3d(a, b):
   return a*b

@cuda.jit('void(float32[:, :, :], float32[:, :, :], float32[:, :, :])')
def mult_gpu_3d(a, b, c):
  [x, y, z] = cuda.grid(3)
  if x < c.shape[0] and y < c.shape[1] and z < c.shape[2]:
    c[x, y, z] = a[x, y, z] * b[x, y, z]

if __name__ == '__main__':
  A = np.random.normal(size=(M, N, P)).astype(np.float32)
  B = np.random.normal(size=(M, N, P)).astype(np.float32)

  numpy_C = A*B

  A_gpu = cuda.to_device(A)
  B_gpu = cuda.to_device(B)
  C_gpu = cuda.device_array((M,N,P), dtype=np.float32) # cuda.device_array_like(A_gpu)

  mult_gpu_3d[blockspergrid,threadsperblock](A_gpu,B_gpu,C_gpu)

  cudajit_C = C_gpu.copy_to_host()

  print('------- using cuda.jit -------')
  print('Is close?: {}'.format(np.allclose(numpy_C,cudajit_C)))
  print('{} of {} elements are close'.format(np.sum(np.isclose(numpy_C,cudajit_C)), M*N*P))
  print('------- using cuda.jit -------\n')


  vectorize_C_gpu = VectorMult3d(A_gpu, B_gpu)
  vectorize_C = vectorize_C_gpu.copy_to_host()

  print('------- using vectorize -------')
  print('Is close?: {}'.format(np.allclose(numpy_C,vectorize_C)))
  print('{} of {} elements are close'.format(np.sum(np.isclose(numpy_C,vectorize_C)), M*N*P))
  print('------- using vectorize -------\n')

  import numba; print("numba version: "+numba.__version__)

1 个答案:

答案 0 :(得分:2)

以下是调试方法。

考虑一个较小的简化示例:

  • 减少阵列大小,例如(2,3,1)(所以你实际上可以打印这些值并能够阅读它们)
  • 简单且确定的内容,例如&#34;所有的&#34; (比较不同的运行)
  • 用于调试的其他内核参数
from __future__ import (division, print_function)

import numpy as np
from numba import cuda

M = 2
N = 3
P = 1

threadsperblock = 1
blockspergrid = (M * N * P + (threadsperblock - 1)) // threadsperblock


@cuda.jit
def mult_gpu_3d(a, b, c, grid_ran, grid_multed):
    grid = cuda.grid(3)
    x, y, z = grid

    grid_ran[x] = 1

    if (x < c.shape[0]) and (y < c.shape[1]) and (z < c.shape[2]):
        grid_multed[x] = 1
        c[grid] = a[grid] * b[grid]


if __name__ == '__main__':
    A = np.ones((M, N, P), np.int32)
    B = np.ones((M, N, P), np.int32)

    A_gpu = cuda.to_device(A)
    B_gpu = cuda.to_device(B)
    C_gpu = cuda.to_device(np.zeros_like(A))

    # Tells whether thread at index i have ran
    grid_ran = cuda.to_device(np.zeros([blockspergrid], np.int32))

    # Tells whether thread at index i have performed multiplication
    grid_multed = cuda.to_device(np.zeros(blockspergrid, np.int32))

    mult_gpu_3d[blockspergrid, threadsperblock](
        A_gpu, B_gpu, C_gpu, grid_ran, grid_multed)

    print("grid_ran.shape    : ", grid_ran.shape)
    print("grid_multed.shape : ", grid_multed.shape)
    print("C_gpu.shape       : ", C_gpu.shape)

    print("grid_ran          : ", grid_ran.copy_to_host())
    print("grid_multed       : ", grid_multed.copy_to_host())

    C = C_gpu.copy_to_host()
    print("C transpose flat  : ", C.T.flatten())
    print("C                 : \n", C)

输出:

grid_ran.shape    :  (6,)
grid_multed.shape :  (6,)
C_gpu.shape       :  (2, 3, 1)
grid_ran          :  [1 1 1 1 1 1]
grid_multed       :  [1 1 0 0 0 0]
C transpose flat  :  [1 1 0 0 0 0]
C                 : 
 [[[1]
  [0]
  [0]]

 [[1]
  [0]
  [0]]]

您可以看到设备网格形状与数组的形状不对应:网格是平面(M*N*P),而数组都是三维(M, N, P)。也就是说,网格的第一维具有范围0..M*N*P-10..5中的索引,在我的示例中总共6个值),而数组的第一维仅在0..M-1中{{1在我的例子中总计2个值)。这个错误通常导致越界访问,但是您使用条件保护内核,从而减少了违规的线程:

0..1

这一行不允许索引高于if (x <= c.shape[0]) (在我的例子中为M-1)的线程运行(好吧,排序[1]),这就是为什么没有写入值并且你得到很多结果数组中的零。

可能的解决方案:

  • 通常,您可以使用多维内核网格配置,即1的3D矢量而不是标量[2]。
  • 特别是,由于元素乘法是一个map操作而不依赖于数组形状,你可以将所有3个数组展平为1D数组,在1D网格上运行你的内核,然后重新整形结果[3],[ 4]。

参考文献: