Skip to content

Commit

Permalink
Merge pull request #22 from asi1024/zero-size-astensor
Browse files Browse the repository at this point in the history
Fix `cpm.astensor(cupy.ndarray)` for zero-size input
  • Loading branch information
emcastillo authored Mar 5, 2020
2 parents 830713f + 4ef9ac4 commit 01abf44
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion chainer_pytorch_migration/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ def astensor(array):
# If the array is not allocated (empty)
# we just create a new one
if array.data.ptr == 0:
return torch.empty(array.shape, dtype=to_torch_dtype(array.dtype))
return torch.empty(
array.shape,
dtype=to_torch_dtype(array.dtype),
device=array.device.id
)
return torch.as_tensor(
_ArrayWithCudaArrayInterfaceHavingStrides(array),
device=array.device.id,
Expand Down
4 changes: 4 additions & 0 deletions tests/test_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,22 +59,26 @@ def test_astensor_negative_stride():
def test_asarray_empty_cpu():
t = torch.tensor([], dtype=torch.float32)
a = tensor.asarray(t)
assert isinstance(a, numpy.ndarray)


def test_asarray_empty_gpu():
t = torch.tensor([], dtype=torch.float32, device='cuda')
a = tensor.asarray(t)
assert isinstance(a, cupy.ndarray)


def test_astensor_empty_cpu():
a = numpy.array([], dtype=numpy.float32)
t = tensor.astensor(a)
assert t.device.type == 'cpu'


def test_astensor_empty_gpu():
a = cupy.array([], dtype=cupy.float32)
t = tensor.astensor(a)
assert isinstance(t, torch.Tensor)
assert t.device.type == 'cuda'
t += 1
numpy.testing.assert_array_equal(a.get(), t.cpu().numpy())

Expand Down

0 comments on commit 01abf44

Please sign in to comment.