如何从gpu内存地址创建PyCUDA GPUArray?

时间:2018-07-20 08:26:17

标签: python memory-address pytorch pycuda

我正在使用PyTorch,并希望在PyCUDA的帮助下对Tensor数据进行一些算术运算。我可以通过t获得cuda张量t.data_ptr()的内存地址。我可以以某种方式使用此地址以及我对大小和数据类型的了解来初始化GPUArray吗?我希望避免复制数据,但这也是一种替代方法。

1 个答案:

答案 0 :(得分:2)

事实证明这是可能的。 我们需要一个指针来处理数据,这需要一些附加功能:

class Holder(PointerHolderBase):

    def __init__(self, tensor):
        super().__init__()
        self.tensor = tensor
        self.gpudata = tensor.data_ptr()

    def get_pointer(self):
        return self.tensor.data_ptr()

    def __int__(self):
        return self.__index__()

    # without an __index__ method, arithmetic calls to the GPUArray backed by this pointer fail
    # not sure why, this needs to return some integer, apparently
    def __index__(self):
        return self.gpudata

然后我们可以使用此类实例化GPUArray。该代码使用Reikna数组,它是一个子类,但也应与pycuda数组一起使用。

def tensor_to_gpuarray(tensor, context=pycuda.autoinit.context):
    '''Convert a :class:`torch.Tensor` to a :class:`pycuda.gpuarray.GPUArray`. The underlying
    storage will be shared, so that modifications to the array will reflect in the tensor object.
    Parameters
    ----------
    tensor  :   torch.Tensor
    Returns
    -------
    pycuda.gpuarray.GPUArray
    Raises
    ------
    ValueError
        If the ``tensor`` does not live on the gpu
    '''
    if not tensor.is_cuda:
        raise ValueError('Cannot convert CPU tensor to GPUArray (call `cuda()` on it)')
    else:
        thread = cuda.cuda_api().Thread(context)
    return reikna.cluda.cuda.Array(thread, tensor.shape, dtype=torch_dtype_to_numpy(tensor.dtype), base_data=Holder(tensor))

我们可以返回此代码。我没有找到一种方法来复制数据。

def gpuarray_to_tensor(gpuarray, context=pycuda.autoinit.context):
    '''Convert a :class:`pycuda.gpuarray.GPUArray` to a :class:`torch.Tensor`. The underlying
    storage will NOT be shared, since a new copy must be allocated.
    Parameters
    ----------
    gpuarray  :   pycuda.gpuarray.GPUArray
    Returns
    -------
    torch.Tensor
    '''
    shape = gpuarray.shape
    dtype = gpuarray.dtype
    out_dtype = numpy_dtype_to_torch(dtype)
    out = torch.zeros(shape, dtype=out_dtype).cuda()
    gpuarray_copy = tensor_to_gpuarray(out, context=context)
    byte_size = gpuarray.itemsize * gpuarray.size
    pycuda.driver.memcpy_dtod(gpuarray_copy.gpudata, gpuarray.gpudata, byte_size)
    return out

旧答案

from pycuda.gpuarray import GPUArray


def torch_dtype_to_numpy(dtype):
    dtype_name = str(dtype)[6:]     # remove 'torch.'
    return getattr(np, dtype_name)


def tensor_to_gpuarray(tensor):
    if not tensor.is_cuda:
        raise ValueError('Cannot convert CPU tensor to GPUArray (call `cuda()` on it)')
    else:
        array = GPUArray(tensor.shape, dtype=torch_dtype_to_numpy(tensor.dtype),
                         gpudata=tensor.data_ptr())
        return array.copy()

不幸的是,将int作为gpudata关键字(或pytorch论坛中建议的pycuda.driver.PointerHolderBase的子类型)传递似乎在表面上可行,但是许多操作失败,并且看似无关的错误。复制数组似乎可以将其转换为可用格式。 我认为这与以下事实有关:gpudata成员应该是一个pycuda.driver.DeviceAllocation对象,似乎无法从Python实例化该对象。

现在如何从原始数据返回张量是另一回事。