Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rely on __cuda_array_interface__ for tensor conversions #26

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 2 additions & 29 deletions chainer_pytorch_migration/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,7 @@ def asarray(tensor):
return cupy.ndarray(
tuple(tensor.shape),
dtype=to_numpy_dtype(tensor.dtype))
itemsize = tensor.element_size()
storage = tensor.storage()
memptr = cupy.cuda.MemoryPointer(
cupy.cuda.UnownedMemory(
storage.data_ptr(), storage.size() * itemsize, tensor,
),
tensor.storage_offset() * itemsize,
)
return cupy.ndarray(
tuple(tensor.shape),
dtype=to_numpy_dtype(tensor.dtype),
memptr=memptr,
strides=tuple(s * itemsize for s in tensor.stride()),
)
return cupy.array(tensor.detach(), copy=False)
if dev_type == 'cpu':
return tensor.detach().numpy()
raise ValueError('tensor on device "{}" is not supported', dev_type)
Expand Down Expand Up @@ -78,28 +65,14 @@ def astensor(array):
device=array.device.id
)
return torch.as_tensor(
_ArrayWithCudaArrayInterfaceHavingStrides(array),
array,
device=array.device.id,
)
if isinstance(array, numpy.ndarray):
return torch.from_numpy(array)
raise TypeError('array of type {} is not supported'.format(type(array)))


# Workaround to avoid a bug in converting cupy.ndarray to torch.Tensor via
# __cuda_array_interface__. See: https://github.com/pytorch/pytorch/pull/24947
class _ArrayWithCudaArrayInterfaceHavingStrides:

def __init__(self, array):
self._array = array

@property
def __cuda_array_interface__(self):
d = self._array.__cuda_array_interface__
d['strides'] = self._array.strides
return d


def to_numpy_dtype(torch_dtype):
"""Convert PyTorch dtype to NumPy dtype.

Expand Down